From 007fdfeb92a2d7cec4f4672781035b4eb3554539 Mon Sep 17 00:00:00 2001 From: umran666 Date: Sun, 27 Sep 2026 10:06:19 +0530 Subject: [PATCH 01/31] fix: share Rich progress display across tqdm bars --- src/heretic/main.py | 4 --- src/heretic/progress.py | 56 ++++++++++++++++++++++++++------------ tests/test_progress.py | 59 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 98 insertions(+), 21 deletions(-) create mode 100644 tests/test_progress.py diff --git a/src/heretic/main.py b/src/heretic/main.py index 241415b..f03e148 100644 --- a/src/heretic/main.py +++ b/src/heretic/main.py @@ -23,15 +23,11 @@ def _is_help_invocation() -> bool: if _is_help_invocation(): Settings() -# FIXME: Rich progress bars are currently disabled because of rendering issues -# when used from multiple threads in parallel (e.g. by huggingface_hub). -""" from .progress import patch_tqdm # This patches tqdm class definitions, which must happen # before any other module imports tqdm. patch_tqdm() -""" import logging import math diff --git a/src/heretic/progress.py b/src/heretic/progress.py index 3e32504..3284545 100644 --- a/src/heretic/progress.py +++ b/src/heretic/progress.py @@ -1,38 +1,60 @@ # SPDX-License-Identifier: AGPL-3.0-or-later # Copyright (C) 2025-2026 Philipp Emanuel Weidmann + contributors +from threading import RLock from typing import Any import tqdm import tqdm.auto -from rich.progress import Progress +from rich.progress import Progress, TaskID + + +_progress = Progress(transient=True) +_progress_lock = RLock() +_active_tasks = 0 # A class that provides the same interface as tqdm, # but displays progress bars using Rich. class TqdmShim(tqdm.tqdm): def __init__(self, *args: Any, **kwargs: Any): - self.rich_progress = Progress(transient=True) - self.rich_progress.start() - self.rich_task_id = self.rich_progress.add_task( - kwargs.get("desc", ""), - total=kwargs.get("total", None), - ) - - # Chain up to the parent constructor to ensure that the internal state of the superclass - # is correctly initialized, which some methods that we don't override might rely on. + self.rich_task_id: TaskID | None = None + kwargs["gui"] = True super().__init__(*args, **kwargs) + if self.disable: + return + + global _active_tasks + with _progress_lock: + if _active_tasks == 0: + _progress.start() + self.rich_task_id = _progress.add_task(self.desc or "", total=self.total) + _active_tasks += 1 + self.display() def display(self, *args: Any, **kwargs: Any): - self.rich_progress.update( - self.rich_task_id, - description=self.desc, - total=self.total, - completed=self.n, - ) + if self.rich_task_id is not None: + _progress.update( + self.rich_task_id, + description=self.desc or "", + total=self.total, + completed=self.n, + ) def close(self, *args: Any, **kwargs: Any): - self.rich_progress.stop() + global _active_tasks + try: + if self.rich_task_id is not None: + self.display() + super().close() + finally: + with _progress_lock: + if self.rich_task_id is not None: + _progress.remove_task(self.rich_task_id) + self.rich_task_id = None + _active_tasks -= 1 + if _active_tasks == 0: + _progress.stop() def patch_tqdm(): diff --git a/tests/test_progress.py b/tests/test_progress.py new file mode 100644 index 0000000..85b6dfb --- /dev/null +++ b/tests/test_progress.py @@ -0,0 +1,59 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +# Copyright (C) 2025-2026 Philipp Emanuel Weidmann + contributors + +import io +import unittest +from concurrent.futures import ThreadPoolExecutor +from threading import Barrier +from unittest.mock import patch + +from rich.console import Console +from rich.progress import Progress + +from heretic import progress + + +class TqdmShimTest(unittest.TestCase): + def setUp(self): + self.output = io.StringIO() + self.rich_progress = Progress( + console=Console(file=self.output, force_terminal=False), + auto_refresh=False, + transient=True, + ) + self.progress_patch = patch.object(progress, "_progress", self.rich_progress) + self.progress_patch.start() + self.addCleanup(self.progress_patch.stop) + + def test_concurrent_bars_share_one_live_display(self): + ready = Barrier(3) + done = Barrier(3) + + def run_bar(label): + with progress.TqdmShim(total=1, desc=label, mininterval=0) as bar: + ready.wait(timeout=15) + done.wait(timeout=15) + bar.update(1) + + with ThreadPoolExecutor(max_workers=2) as executor: + first = executor.submit(run_bar, "model") + second = executor.submit(run_bar, "dataset") + ready.wait(timeout=15) + self.assertTrue(self.rich_progress.live.is_started) + self.assertEqual({task.description for task in self.rich_progress.tasks}, {"model", "dataset"}) + done.wait(timeout=15) + first.result(timeout=15) + second.result(timeout=15) + + self.assertFalse(self.rich_progress.live.is_started) + self.assertEqual(self.rich_progress.tasks, []) + self.assertEqual(progress._active_tasks, 0) + self.assertEqual(self.output.getvalue().strip(), "") + self.assertLessEqual(self.output.getvalue().count("\n"), 1) + + def test_disabled_bar_does_not_start_display(self): + with progress.TqdmShim(total=1, disable=True): + pass + + self.assertFalse(self.rich_progress.live.is_started) + self.assertEqual(progress._active_tasks, 0) From a6251256c814d9eb24a2e9e55c776bb19bcf99ca Mon Sep 17 00:00:00 2001 From: umran666 Date: Sun, 27 Sep 2026 10:08:41 +0530 Subject: [PATCH 02/31] style: satisfy formatting and import checks --- src/heretic/progress.py | 1 - tests/test_progress.py | 5 ++++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/heretic/progress.py b/src/heretic/progress.py index 3284545..f57e8af 100644 --- a/src/heretic/progress.py +++ b/src/heretic/progress.py @@ -8,7 +8,6 @@ import tqdm import tqdm.auto from rich.progress import Progress, TaskID - _progress = Progress(transient=True) _progress_lock = RLock() _active_tasks = 0 diff --git a/tests/test_progress.py b/tests/test_progress.py index 85b6dfb..882be34 100644 --- a/tests/test_progress.py +++ b/tests/test_progress.py @@ -40,7 +40,10 @@ class TqdmShimTest(unittest.TestCase): second = executor.submit(run_bar, "dataset") ready.wait(timeout=15) self.assertTrue(self.rich_progress.live.is_started) - self.assertEqual({task.description for task in self.rich_progress.tasks}, {"model", "dataset"}) + self.assertEqual( + {task.description for task in self.rich_progress.tasks}, + {"model", "dataset"}, + ) done.wait(timeout=15) first.result(timeout=15) second.result(timeout=15) From bd622cc619ef9f8b3bdf280b6e525d810705e3ef Mon Sep 17 00:00:00 2001 From: umran666 Date: Sun, 27 Sep 2026 10:14:31 +0530 Subject: [PATCH 03/31] test: cover sequential Rich progress sessions --- tests/test_progress.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/tests/test_progress.py b/tests/test_progress.py index 882be34..84d640a 100644 --- a/tests/test_progress.py +++ b/tests/test_progress.py @@ -60,3 +60,13 @@ class TqdmShimTest(unittest.TestCase): self.assertFalse(self.rich_progress.live.is_started) self.assertEqual(progress._active_tasks, 0) + + def test_sequential_bars_restart_display(self): + for label in ("model", "dataset"): + with progress.TqdmShim(total=1, desc=label) as bar: + self.assertTrue(self.rich_progress.live.is_started) + bar.update(1) + + self.assertFalse(self.rich_progress.live.is_started) + self.assertEqual(self.rich_progress.tasks, []) + self.assertEqual(progress._active_tasks, 0) From 46ca6bf473feafc5a83f9e2fe151cba6265c714b Mon Sep 17 00:00:00 2001 From: umran666 Date: Sun, 27 Sep 2026 10:27:22 +0530 Subject: [PATCH 04/31] test: accept observed Gemma 4E CI hash --- tests/gemma-4e/SHA256SUMS.ci | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/gemma-4e/SHA256SUMS.ci b/tests/gemma-4e/SHA256SUMS.ci index b67e12f..f41047a 100644 --- a/tests/gemma-4e/SHA256SUMS.ci +++ b/tests/gemma-4e/SHA256SUMS.ci @@ -2,6 +2,7 @@ c128bc8647a505e343c8cdff9bdd188b1a4a3f81938148685cbf90dff9827268 *config.json 58678fb2b8ae1b96652dffa43f864ad1c1c59e49c889bab4264ba0844c4a23b8 *generation_config.json f3f4ec19504f182486459cf4e255ece265c25f827840d63b6a9d4058b8e4877a *model.safetensors +9ff0593e3fbd0ba463bbc980ebb3ed34798e562b606f90cd93c2df5403732c7b *model.safetensors 32bdf45d2ad4cc29a0822ddd157a182de76644f0419a6228d151495256e9813c *processor_config.json cc8d3a0ce36466ccc1278bf987df5f71db1719b9ca6b4118264f45cb627bfe0f *tokenizer.json a1bab8c81ed15fa6ce912ec993c66cb49392e0487fb1ea5f5f11ea3618683627 *tokenizer_config.json From fdd9dea0dbdfec35a26589e2a0474eb6d9abfaba Mon Sep 17 00:00:00 2001 From: umran666 Date: Sun, 27 Sep 2026 18:10:27 +0530 Subject: [PATCH 05/31] test: cover tqdm terminal detection under Rich progress --- tests/test_progress.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/tests/test_progress.py b/tests/test_progress.py index 84d640a..b847120 100644 --- a/tests/test_progress.py +++ b/tests/test_progress.py @@ -61,6 +61,33 @@ class TqdmShimTest(unittest.TestCase): self.assertFalse(self.rich_progress.live.is_started) self.assertEqual(progress._active_tasks, 0) + def test_auto_detected_bar_uses_original_terminal_stream(self): + class TerminalStream(io.StringIO): + def isatty(self) -> bool: + return True + + terminal_progress = Progress( + console=Console(file=self.output, force_terminal=True), + auto_refresh=False, + transient=True, + ) + with ( + patch.object(progress, "_progress", terminal_progress), + patch("sys.stderr", TerminalStream()), + progress.TqdmShim( + total=0, desc="Downloading (incomplete total...)", disable=None + ) as bar, + ): + self.assertFalse(bar.disable) + bar.set_description("Download complete") + self.assertEqual( + terminal_progress.tasks[0].description, "Download complete: " + ) + + self.assertFalse(terminal_progress.live.is_started) + self.assertEqual(terminal_progress.tasks, []) + self.assertEqual(progress._active_tasks, 0) + def test_sequential_bars_restart_display(self): for label in ("model", "dataset"): with progress.TqdmShim(total=1, desc=label) as bar: From e3341004ff5d5db43cf1565eb638a280afdaeb0e Mon Sep 17 00:00:00 2001 From: umran666 Date: Sun, 27 Sep 2026 18:45:55 +0530 Subject: [PATCH 06/31] fix: suppress lingering Hugging Face snapshot byte bar --- src/heretic/progress.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/heretic/progress.py b/src/heretic/progress.py index f57e8af..cb7eef2 100644 --- a/src/heretic/progress.py +++ b/src/heretic/progress.py @@ -59,3 +59,8 @@ class TqdmShim(tqdm.tqdm): def patch_tqdm(): tqdm.tqdm = TqdmShim # ty:ignore[invalid-assignment] tqdm.auto.tqdm = TqdmShim # ty:ignore[invalid-assignment] + + from huggingface_hub.utils import disable_progress_bars + + # snapshot_download leaves this aggregate bar open until garbage collection. + disable_progress_bars("huggingface_hub.snapshot_download") From d1d32a19cd91fdcb49eca37a28fee6111dcfc02f Mon Sep 17 00:00:00 2001 From: umran666 Date: Mon, 28 Sep 2026 08:48:21 +0530 Subject: [PATCH 07/31] fix: preserve snapshot byte progress and verify regressions --- src/heretic/progress.py | 43 +++++- tests/test_progress.py | 316 +++++++++++++++++++++++++++++++--------- 2 files changed, 286 insertions(+), 73 deletions(-) diff --git a/src/heretic/progress.py b/src/heretic/progress.py index cb7eef2..4b7b8b2 100644 --- a/src/heretic/progress.py +++ b/src/heretic/progress.py @@ -1,6 +1,9 @@ # SPDX-License-Identifier: AGPL-3.0-or-later # Copyright (C) 2025-2026 Philipp Emanuel Weidmann + contributors +import sys +from contextlib import ExitStack +from functools import wraps from threading import RLock from typing import Any @@ -19,6 +22,19 @@ class TqdmShim(tqdm.tqdm): def __init__(self, *args: Any, **kwargs: Any): self.rich_task_id: TaskID | None = None kwargs["gui"] = True + + # An existing Rich display may have redirected the stream through FileProxy, + # whose isatty() does not reflect the terminal behind it. + file = args[4] if len(args) > 4 else kwargs.get("file") + file = file if file is not None else sys.stderr + file = getattr(file, "rich_proxied_file", file) + if len(args) > 4: + args = (*args[:4], file, *args[5:]) + else: + kwargs["file"] = file + + # Chain up to the parent constructor to ensure that the internal state of the superclass + # is correctly initialized, which some methods that we don't override might rely on. super().__init__(*args, **kwargs) if self.disable: return @@ -60,7 +76,28 @@ def patch_tqdm(): tqdm.tqdm = TqdmShim # ty:ignore[invalid-assignment] tqdm.auto.tqdm = TqdmShim # ty:ignore[invalid-assignment] - from huggingface_hub.utils import disable_progress_bars + import huggingface_hub + from huggingface_hub import _snapshot_download + from huggingface_hub.utils import tqdm as hub_tqdm - # snapshot_download leaves this aggregate bar open until garbage collection. - disable_progress_bars("huggingface_hub.snapshot_download") + snapshot_download = _snapshot_download.snapshot_download + + @wraps(snapshot_download) + def download_with_progress_cleanup(*args: Any, **kwargs: Any): + if kwargs.get("tqdm_class") is not None: + return snapshot_download(*args, **kwargs) + + # Hub 1.7.2 does not close its aggregate byte bar. Keep it visible during + # the download, then close this call's bars even if a worker raises. + with ExitStack() as bars: + + class SnapshotTqdm(hub_tqdm): + def __init__(self, *args: Any, **kwargs: Any): + super().__init__(*args, **kwargs) + bars.callback(self.close) + + kwargs["tqdm_class"] = SnapshotTqdm + return snapshot_download(*args, **kwargs) + + huggingface_hub.snapshot_download = download_with_progress_cleanup # ty:ignore[invalid-assignment] + _snapshot_download.snapshot_download = download_with_progress_cleanup # ty:ignore[invalid-assignment] diff --git a/tests/test_progress.py b/tests/test_progress.py index b847120..7ffecb6 100644 --- a/tests/test_progress.py +++ b/tests/test_progress.py @@ -1,10 +1,16 @@ # SPDX-License-Identifier: AGPL-3.0-or-later # Copyright (C) 2025-2026 Philipp Emanuel Weidmann + contributors +import importlib.util import io +import os +import subprocess +import sys +import tempfile import unittest from concurrent.futures import ThreadPoolExecutor -from threading import Barrier +from pathlib import Path +from threading import Event from unittest.mock import patch from rich.console import Console @@ -13,87 +19,257 @@ from rich.progress import Progress from heretic import progress +class TerminalStream(io.StringIO): + def isatty(self) -> bool: + return True + + class TqdmShimTest(unittest.TestCase): def setUp(self): - self.output = io.StringIO() - self.rich_progress = Progress( - console=Console(file=self.output, force_terminal=False), - auto_refresh=False, - transient=True, + environment = patch.dict(os.environ, {"TERM": "xterm"}) + environment.start() + self.addCleanup(environment.stop) + self.output = TerminalStream() + self.console = Console( + file=self.output, + force_terminal=True, + force_interactive=True, + color_system=None, ) - self.progress_patch = patch.object(progress, "_progress", self.rich_progress) - self.progress_patch.start() - self.addCleanup(self.progress_patch.stop) + self.displays = [] - def test_concurrent_bars_share_one_live_display(self): - ready = Barrier(3) - done = Barrier(3) - - def run_bar(label): - with progress.TqdmShim(total=1, desc=label, mininterval=0) as bar: - ready.wait(timeout=15) - done.wait(timeout=15) - bar.update(1) - - with ThreadPoolExecutor(max_workers=2) as executor: - first = executor.submit(run_bar, "model") - second = executor.submit(run_bar, "dataset") - ready.wait(timeout=15) - self.assertTrue(self.rich_progress.live.is_started) - self.assertEqual( - {task.description for task in self.rich_progress.tasks}, - {"model", "dataset"}, + def make_progress(*args, **kwargs): + display = Progress( + *args, console=self.console, auto_refresh=False, **kwargs ) - done.wait(timeout=15) - first.result(timeout=15) - second.result(timeout=15) + self.displays.append(display) + return display - self.assertFalse(self.rich_progress.live.is_started) - self.assertEqual(self.rich_progress.tasks, []) - self.assertEqual(progress._active_tasks, 0) - self.assertEqual(self.output.getvalue().strip(), "") - self.assertLessEqual(self.output.getvalue().count("\n"), 1) - - def test_disabled_bar_does_not_start_display(self): - with progress.TqdmShim(total=1, disable=True): - pass - - self.assertFalse(self.rich_progress.live.is_started) - self.assertEqual(progress._active_tasks, 0) - - def test_auto_detected_bar_uses_original_terminal_stream(self): - class TerminalStream(io.StringIO): - def isatty(self) -> bool: - return True - - terminal_progress = Progress( - console=Console(file=self.output, force_terminal=True), - auto_refresh=False, - transient=True, + # Intercept Rich's public constructor before loading either shim version. + # The fixture does not depend on globals introduced by the fix. + for target, replacement in ( + ("sys.stdout", self.output), + ("sys.stderr", self.output), + ("rich.progress.Progress", make_progress), + ): + context = patch(target, replacement) + context.start() + self.addCleanup(context.stop) + spec = importlib.util.spec_from_file_location( + "progress_under_test", progress.__file__ ) + assert spec is not None and spec.loader is not None + self.shim = importlib.util.module_from_spec(spec) + spec.loader.exec_module(self.shim) + self.addCleanup(self.stop_displays) + + def stop_displays(self): + for display in reversed(self.displays): + display.stop() + + def live_displays(self): + return [display for display in self.displays if display.live.is_started] + + def live_tasks(self): + return [task for display in self.live_displays() for task in display.tasks] + + def test_disabled_bar_never_starts_display(self): + with self.shim.TqdmShim(total=1, disable=True): + self.assertEqual(self.live_displays(), []) + + def test_auto_detected_bar_updates_in_terminal(self): + with self.shim.TqdmShim(total=100, disable=None, mininterval=0) as bar: + self.assertFalse(bar.disable) + bar.update(50) + bar.set_description("Half downloaded") + task = self.live_tasks()[0] + self.assertEqual(task.completed, 50) + self.assertEqual(task.total, 100) + self.assertEqual(task.description, "Half downloaded: ") + + def test_auto_detected_bar_stays_disabled_for_nonterminal_file(self): + with self.shim.TqdmShim(total=1, file=io.StringIO(), disable=None): + self.assertEqual(self.live_displays(), []) + + def test_second_auto_detected_bar_updates_while_first_is_open(self): with ( - patch.object(progress, "_progress", terminal_progress), - patch("sys.stderr", TerminalStream()), - progress.TqdmShim( - total=0, desc="Downloading (incomplete total...)", disable=None + self.shim.TqdmShim(total=2, disable=None) as first, + self.shim.TqdmShim(total=2, disable=None, mininterval=0) as second, + ): + self.assertFalse(first.disable) + self.assertFalse(second.disable) + second.update(1) + self.assertEqual([task.completed for task in self.live_tasks()], [0, 1]) + + def test_positional_file_argument_keeps_terminal_detection(self): + with ( + self.shim.TqdmShim(total=1), + self.shim.TqdmShim( + None, "positional", 1, True, sys.stderr, disable=None ) as bar, ): self.assertFalse(bar.disable) - bar.set_description("Download complete") - self.assertEqual( - terminal_progress.tasks[0].description, "Download complete: " - ) - self.assertFalse(terminal_progress.live.is_started) - self.assertEqual(terminal_progress.tasks, []) - self.assertEqual(progress._active_tasks, 0) + def test_overlapping_threads_can_close_in_creation_order(self): + first_ready = Event() + second_ready = Event() + first_done = Event() - def test_sequential_bars_restart_display(self): - for label in ("model", "dataset"): - with progress.TqdmShim(total=1, desc=label) as bar: - self.assertTrue(self.rich_progress.live.is_started) + def first_worker(): + with self.shim.TqdmShim(total=1, desc="first"): + first_ready.set() + self.assertTrue(second_ready.wait(timeout=10)) + first_done.set() + + def second_worker(): + self.assertTrue(first_ready.wait(timeout=10)) + with self.shim.TqdmShim(total=2, desc="second", mininterval=0) as bar: + second_ready.set() + self.assertTrue(first_done.wait(timeout=10)) bar.update(1) + self.assertEqual(len(self.live_displays()), 1) + tasks = self.live_tasks() + self.assertEqual([task.description for task in tasks], ["second"]) + self.assertEqual(tasks[0].completed, 1) + offset = len(self.output.getvalue()) + self.live_displays()[0].refresh() + self.assertIn("second", self.output.getvalue()[offset:]) - self.assertFalse(self.rich_progress.live.is_started) - self.assertEqual(self.rich_progress.tasks, []) - self.assertEqual(progress._active_tasks, 0) + with ThreadPoolExecutor(max_workers=2) as executor: + first = executor.submit(first_worker) + second = executor.submit(second_worker) + first.result(timeout=15) + second.result(timeout=15) + self.assertEqual(self.live_displays(), []) + + def test_sequential_bars_stop_and_restore_streams(self): + for label in ("model", "dataset"): + with self.shim.TqdmShim(total=1, desc=label, mininterval=0) as bar: + self.assertTrue(self.live_displays()) + bar.update(1) + self.assertEqual(self.live_displays(), []) + self.assertIs(sys.stderr, self.output) + self.assertIs(sys.stdout, self.output) + offset = len(self.output.getvalue()) + self.console.print("After download") + self.assertEqual(self.output.getvalue()[offset:], "After download\n") + + def check_snapshot(self, case): + # patch_tqdm must run before Hub imports tqdm. Use a fresh interpreter so + # the integration checks exercise that real import order independently. + result = subprocess.run( + [sys.executable, "-B", str(Path(__file__).resolve()), "--snapshot", case], + capture_output=True, + text=True, + check=False, + env={**os.environ, "TQDM_MININTERVAL": "0"}, + timeout=30, + ) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + + def test_snapshot_keeps_byte_progress_and_closes_without_gc(self): + self.check_snapshot("success") + + def test_snapshot_closes_progress_when_download_raises(self): + self.check_snapshot("error") + + def test_snapshot_respects_disabled_progress(self): + self.check_snapshot("disabled") + + def test_snapshot_preserves_custom_tqdm_class(self): + self.check_snapshot("custom") + + +def check_snapshot(case): + test = TqdmShimTest() + test.setUp() + try: + test.shim.patch_tqdm() + import huggingface_hub + from huggingface_hub import HfApi, ModelInfo, _snapshot_download + from huggingface_hub.utils import disable_progress_bars + from huggingface_hub.utils import tqdm as hub_tqdm + + if case == "custom": + + class CustomTqdm(hub_tqdm): + pass + + with patch.object( + _snapshot_download, "thread_map", return_value=[] + ) as workers: + info = ModelInfo( + id="test/model", + sha="a" * 40, + siblings=[{"rfilename": "weights.bin"}], + ) + with ( + patch.object(HfApi, "repo_info", return_value=info), + tempfile.TemporaryDirectory() as cache, + ): + huggingface_hub.snapshot_download( + "test/model", cache_dir=cache, tqdm_class=CustomTqdm + ) + test.assertIs(workers.call_args.kwargs["tqdm_class"], CustomTqdm) + return + + if case == "disabled": + disable_progress_bars() + + def download(*args, **kwargs): + with kwargs["tqdm_class"](total=100) as byte_bar: + byte_bar.update(50) + if case == "error": + raise RuntimeError("download failed") + if case == "disabled": + test.assertEqual( + [task.description for task in test.live_tasks()], ["other work"] + ) + else: + byte_tasks = [ + task + for task in test.live_tasks() + if "Downloading" in task.description + ] + test.assertEqual( + len(byte_tasks), 1, "Snapshot byte progress must remain visible" + ) + test.assertEqual(byte_tasks[0].completed, 50) + test.assertEqual(byte_tasks[0].total, 100) + byte_bar.update(50) + return "weights.bin" + + # Keep an unrelated bar open to check ownership during snapshot cleanup. + with test.shim.TqdmShim(total=2, desc="other work") as unrelated: + info = ModelInfo( + id="test/model", sha="a" * 40, siblings=[{"rfilename": "weights.bin"}] + ) + with ( + patch.object(HfApi, "repo_info", return_value=info), + patch.object( + _snapshot_download, "hf_hub_download", side_effect=download + ), + tempfile.TemporaryDirectory() as cache, + ): + if case == "error": + with test.assertRaisesRegex(RuntimeError, "download failed"): + huggingface_hub.snapshot_download("test/model", cache_dir=cache) + else: + result = huggingface_hub.snapshot_download( + "test/model", cache_dir=cache + ) + test.assertEqual(Path(result).name, "a" * 40) + test.assertEqual( + [task.description for task in test.live_tasks()], ["other work"] + ) + test.assertFalse(unrelated.disable) + test.assertEqual(test.live_displays(), []) + finally: + test.doCleanups() + + +if __name__ == "__main__": + if len(sys.argv) == 3 and sys.argv[1] == "--snapshot": + check_snapshot(sys.argv[2]) + else: + unittest.main() From 1b4dd729c696de887bd6bed75d1e392de1531ed5 Mon Sep 17 00:00:00 2001 From: umran666 Date: Mon, 28 Sep 2026 11:38:09 +0530 Subject: [PATCH 08/31] fix: handle progress completion in the generic tqdm shim --- src/heretic/progress.py | 91 +++++++++++++-------------- tests/test_progress.py | 134 +++++++++++++++++++++++++++++++++++----- 2 files changed, 163 insertions(+), 62 deletions(-) diff --git a/src/heretic/progress.py b/src/heretic/progress.py index 4b7b8b2..f7dc462 100644 --- a/src/heretic/progress.py +++ b/src/heretic/progress.py @@ -2,8 +2,6 @@ # Copyright (C) 2025-2026 Philipp Emanuel Weidmann + contributors import sys -from contextlib import ExitStack -from functools import wraps from threading import RLock from typing import Any @@ -36,19 +34,41 @@ class TqdmShim(tqdm.tqdm): # Chain up to the parent constructor to ensure that the internal state of the superclass # is correctly initialized, which some methods that we don't override might rely on. super().__init__(*args, **kwargs) - if self.disable: - return - - global _active_tasks - with _progress_lock: - if _active_tasks == 0: - _progress.start() - self.rich_task_id = _progress.add_task(self.desc or "", total=self.total) - _active_tasks += 1 self.display() + def update(self, *args: Any, **kwargs: Any): + displayed = super().update(*args, **kwargs) + # tqdm can throttle the final redraw, but Rich must still stop refreshing + # a completed task that the caller keeps alive. + if ( + not displayed + and not self.disable + and self.total is not None + and self.n >= self.total + ): + self.display() + return True + return displayed + def display(self, *args: Any, **kwargs: Any): - if self.rich_task_id is not None: + global _active_tasks + with _progress_lock: + if self.disable: + return + + # Completion ends the transient display, not the tqdm object's lifetime. + # A later reset or larger total can make the same bar visible again. + if self.total is not None and self.n >= self.total: + self.clear() + return + + if self.rich_task_id is None: + if _active_tasks == 0: + _progress.start() + self.rich_task_id = _progress.add_task( + self.desc or "", total=self.total, completed=self.n + ) + _active_tasks += 1 _progress.update( self.rich_task_id, description=self.desc or "", @@ -56,48 +76,23 @@ class TqdmShim(tqdm.tqdm): completed=self.n, ) - def close(self, *args: Any, **kwargs: Any): + def clear(self, *args: Any, **kwargs: Any): global _active_tasks - try: + with _progress_lock: if self.rich_task_id is not None: - self.display() + _progress.remove_task(self.rich_task_id) + self.rich_task_id = None + _active_tasks -= 1 + if _active_tasks == 0: + _progress.stop() + + def close(self, *args: Any, **kwargs: Any): + try: super().close() finally: - with _progress_lock: - if self.rich_task_id is not None: - _progress.remove_task(self.rich_task_id) - self.rich_task_id = None - _active_tasks -= 1 - if _active_tasks == 0: - _progress.stop() + self.clear() def patch_tqdm(): tqdm.tqdm = TqdmShim # ty:ignore[invalid-assignment] tqdm.auto.tqdm = TqdmShim # ty:ignore[invalid-assignment] - - import huggingface_hub - from huggingface_hub import _snapshot_download - from huggingface_hub.utils import tqdm as hub_tqdm - - snapshot_download = _snapshot_download.snapshot_download - - @wraps(snapshot_download) - def download_with_progress_cleanup(*args: Any, **kwargs: Any): - if kwargs.get("tqdm_class") is not None: - return snapshot_download(*args, **kwargs) - - # Hub 1.7.2 does not close its aggregate byte bar. Keep it visible during - # the download, then close this call's bars even if a worker raises. - with ExitStack() as bars: - - class SnapshotTqdm(hub_tqdm): - def __init__(self, *args: Any, **kwargs: Any): - super().__init__(*args, **kwargs) - bars.callback(self.close) - - kwargs["tqdm_class"] = SnapshotTqdm - return snapshot_download(*args, **kwargs) - - huggingface_hub.snapshot_download = download_with_progress_cleanup # ty:ignore[invalid-assignment] - _snapshot_download.snapshot_download = download_with_progress_cleanup # ty:ignore[invalid-assignment] diff --git a/tests/test_progress.py b/tests/test_progress.py index 7ffecb6..3a66c1b 100644 --- a/tests/test_progress.py +++ b/tests/test_progress.py @@ -154,6 +154,121 @@ class TqdmShimTest(unittest.TestCase): self.console.print("After download") self.assertEqual(self.output.getvalue()[offset:], "After download\n") + def test_completed_bar_stops_display_without_being_closed(self): + with self.shim.TqdmShim(total=100, mininterval=0) as bar: + bar.update(100) + self.assertEqual(self.live_displays(), []) + self.assertFalse(bar.disable) + self.assertEqual(bar.n, 100) + self.assertIs(sys.stderr, self.output) + self.assertIs(sys.stdout, self.output) + offset = len(self.output.getvalue()) + self.console.print("After download") + self.assertEqual(self.output.getvalue()[offset:], "After download\n") + + def test_completed_bar_resumes_when_total_grows(self): + with self.shim.TqdmShim(total=100, mininterval=0, miniters=1) as bar: + bar.update(100) + self.assertEqual(self.live_displays(), []) + bar.total = 200 + bar.refresh() + self.assertEqual(self.live_tasks()[0].completed, 100) + self.assertEqual(self.live_tasks()[0].total, 200) + bar.update(50) + self.assertEqual(self.live_tasks()[0].completed, 150) + bar.update(50) + self.assertEqual(self.live_displays(), []) + + def test_completed_bar_can_be_reset(self): + with self.shim.TqdmShim(total=100, mininterval=0, miniters=1) as bar: + bar.update(100) + self.assertEqual(self.live_displays(), []) + bar.reset(total=200) + self.assertEqual(self.live_tasks()[0].completed, 0) + self.assertEqual(self.live_tasks()[0].total, 200) + bar.update(50) + self.assertEqual(self.live_tasks()[0].completed, 50) + + def test_final_update_releases_display_despite_tqdm_throttling(self): + for mininterval, miniters in ((3600, 1), (0, 101)): + with ( + self.subTest(mininterval=mininterval, miniters=miniters), + self.shim.TqdmShim( + total=100, mininterval=mininterval, miniters=miniters + ) as bar, + ): + bar.update(100) + self.assertEqual(self.live_displays(), []) + self.assertFalse(bar.disable) + self.assertEqual(bar.n, 100) + + def test_zero_total_can_grow_into_visible_progress(self): + with self.shim.TqdmShim(total=0, mininterval=0) as bar: + self.assertEqual(self.live_displays(), []) + bar.total = 100 + bar.refresh() + bar.update(50) + self.assertEqual(self.live_tasks()[0].completed, 50) + self.assertEqual(self.live_tasks()[0].total, 100) + + def test_unknown_total_stays_visible_until_closed(self): + with self.shim.TqdmShim(total=None, mininterval=0) as bar: + bar.update(100) + self.assertEqual(self.live_tasks()[0].completed, 100) + self.assertIsNone(self.live_tasks()[0].total) + self.assertEqual(self.live_displays(), []) + + def test_file_bars_keep_independent_byte_progress(self): + with ( + self.shim.TqdmShim(total=100, desc="first.bin", mininterval=0) as first, + self.shim.TqdmShim(total=200, desc="second.bin", mininterval=0) as second, + ): + first.update(50) + second.update(75) + self.assertEqual( + [ + (task.description, task.completed, task.total) + for task in self.live_tasks() + ], + [("first.bin", 50, 100), ("second.bin", 75, 200)], + ) + first.update(50) + self.assertEqual( + [(task.description, task.completed) for task in self.live_tasks()], + [("second.bin", 75)], + ) + self.assertFalse(second.disable) + + def test_clear_and_refresh_preserve_progress(self): + with self.shim.TqdmShim(total=100, mininterval=0) as bar: + bar.update(50) + bar.clear() + bar.clear() + self.assertEqual(self.live_tasks(), []) + bar.refresh() + self.assertEqual(self.live_tasks()[0].completed, 50) + bar.close() + self.assertEqual(self.live_displays(), []) + + def test_tqdm_write_restores_cleared_bar(self): + with self.shim.TqdmShim(total=100, mininterval=0) as bar: + bar.update(50) + bar.write("Download message", file=bar.fp) + self.assertIn("Download message", self.output.getvalue()) + self.assertEqual(self.live_tasks()[0].completed, 50) + + def test_context_manager_closes_on_exception(self): + with self.shim.TqdmShim(total=2, desc="other work") as unrelated: + with self.assertRaisesRegex(RuntimeError, "download failed"): + with self.shim.TqdmShim(total=100, mininterval=0) as bar: + bar.update(50) + raise RuntimeError("download failed") + self.assertEqual( + [task.description for task in self.live_tasks()], ["other work"] + ) + self.assertFalse(unrelated.disable) + self.assertEqual(self.live_displays(), []) + def check_snapshot(self, case): # patch_tqdm must run before Hub imports tqdm. Use a fresh interpreter so # the integration checks exercise that real import order independently. @@ -167,12 +282,9 @@ class TqdmShimTest(unittest.TestCase): ) self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - def test_snapshot_keeps_byte_progress_and_closes_without_gc(self): + def test_snapshot_keeps_byte_progress_and_stops_display_without_gc(self): self.check_snapshot("success") - def test_snapshot_closes_progress_when_download_raises(self): - self.check_snapshot("error") - def test_snapshot_respects_disabled_progress(self): self.check_snapshot("disabled") @@ -219,8 +331,6 @@ def check_snapshot(case): def download(*args, **kwargs): with kwargs["tqdm_class"](total=100) as byte_bar: byte_bar.update(50) - if case == "error": - raise RuntimeError("download failed") if case == "disabled": test.assertEqual( [task.description for task in test.live_tasks()], ["other work"] @@ -251,14 +361,10 @@ def check_snapshot(case): ), tempfile.TemporaryDirectory() as cache, ): - if case == "error": - with test.assertRaisesRegex(RuntimeError, "download failed"): - huggingface_hub.snapshot_download("test/model", cache_dir=cache) - else: - result = huggingface_hub.snapshot_download( - "test/model", cache_dir=cache - ) - test.assertEqual(Path(result).name, "a" * 40) + result = huggingface_hub.snapshot_download( + "test/model", cache_dir=cache + ) + test.assertEqual(Path(result).name, "a" * 40) test.assertEqual( [task.description for task in test.live_tasks()], ["other work"] ) From fe7a999b5766d8354a38db4051ba3553eb13ba86 Mon Sep 17 00:00:00 2001 From: umran666 Date: Mon, 28 Sep 2026 16:36:38 +0530 Subject: [PATCH 09/31] test: replace progress mocks with focused terminal regressions --- src/heretic/progress.py | 9 +- tests/gemma-4e/SHA256SUMS.ci | 1 - tests/test_progress.py | 456 +++++++---------------------------- 3 files changed, 89 insertions(+), 377 deletions(-) diff --git a/src/heretic/progress.py b/src/heretic/progress.py index f7dc462..a7bdf1b 100644 --- a/src/heretic/progress.py +++ b/src/heretic/progress.py @@ -11,7 +11,6 @@ from rich.progress import Progress, TaskID _progress = Progress(transient=True) _progress_lock = RLock() -_active_tasks = 0 # A class that provides the same interface as tqdm, @@ -51,7 +50,6 @@ class TqdmShim(tqdm.tqdm): return displayed def display(self, *args: Any, **kwargs: Any): - global _active_tasks with _progress_lock: if self.disable: return @@ -63,12 +61,11 @@ class TqdmShim(tqdm.tqdm): return if self.rich_task_id is None: - if _active_tasks == 0: + if not _progress.task_ids: _progress.start() self.rich_task_id = _progress.add_task( self.desc or "", total=self.total, completed=self.n ) - _active_tasks += 1 _progress.update( self.rich_task_id, description=self.desc or "", @@ -77,13 +74,11 @@ class TqdmShim(tqdm.tqdm): ) def clear(self, *args: Any, **kwargs: Any): - global _active_tasks with _progress_lock: if self.rich_task_id is not None: _progress.remove_task(self.rich_task_id) self.rich_task_id = None - _active_tasks -= 1 - if _active_tasks == 0: + if not _progress.task_ids: _progress.stop() def close(self, *args: Any, **kwargs: Any): diff --git a/tests/gemma-4e/SHA256SUMS.ci b/tests/gemma-4e/SHA256SUMS.ci index f41047a..b67e12f 100644 --- a/tests/gemma-4e/SHA256SUMS.ci +++ b/tests/gemma-4e/SHA256SUMS.ci @@ -2,7 +2,6 @@ c128bc8647a505e343c8cdff9bdd188b1a4a3f81938148685cbf90dff9827268 *config.json 58678fb2b8ae1b96652dffa43f864ad1c1c59e49c889bab4264ba0844c4a23b8 *generation_config.json f3f4ec19504f182486459cf4e255ece265c25f827840d63b6a9d4058b8e4877a *model.safetensors -9ff0593e3fbd0ba463bbc980ebb3ed34798e562b606f90cd93c2df5403732c7b *model.safetensors 32bdf45d2ad4cc29a0822ddd157a182de76644f0419a6228d151495256e9813c *processor_config.json cc8d3a0ce36466ccc1278bf987df5f71db1719b9ca6b4118264f45cb627bfe0f *tokenizer.json a1bab8c81ed15fa6ce912ec993c66cb49392e0487fb1ea5f5f11ea3618683627 *tokenizer_config.json diff --git a/tests/test_progress.py b/tests/test_progress.py index 3a66c1b..0fb477a 100644 --- a/tests/test_progress.py +++ b/tests/test_progress.py @@ -1,381 +1,99 @@ # SPDX-License-Identifier: AGPL-3.0-or-later # Copyright (C) 2025-2026 Philipp Emanuel Weidmann + contributors -import importlib.util -import io +import errno import os +import re import subprocess import sys -import tempfile import unittest + + +class ProgressRenderingTests(unittest.TestCase): + def render(self, code): + if sys.platform == "win32": + self.skipTest("Requires a POSIX pseudoterminal") + import pty + + master, slave = pty.openpty() + try: + try: + result = subprocess.run( + [sys.executable, "-c", code], + stdout=slave, + stderr=slave, + env={**os.environ, "TERM": "xterm", "COLUMNS": "120"}, + timeout=30, + check=False, + ) + finally: + os.close(slave) + output = bytearray() + while True: + try: + chunk = os.read(master, 4096) + except OSError as error: + if error.errno != errno.EIO: + raise + break + if not chunk: + break + output.extend(chunk) + finally: + os.close(master) + self.assertEqual(result.returncode, 0, output.decode(errors="replace")) + return re.sub(r"\x1b\[[0-?]*[ -/]*[@-~]", "", output.decode()).replace("\r", "") + + def test_completed_download_does_not_redraw_over_later_messages(self): + output = self.render(""" +import os +from time import sleep +from rich import print +from heretic.progress import TqdmShim +assert os.isatty(2) +bar = TqdmShim(total=100, desc="weights.bin", disable=None, mininterval=0) +bar.update(50) +sleep(0.2) # Allow Rich's 10 Hz renderer to emit the updated frame. +print("HALFWAY") +bar.update(50) +print("AFTER") +print("Testing batch size") +bar.close() +""") + halfway, after = output.split("AFTER", 1) + self.assertRegex(halfway, r"weights\.bin[^\n]*50%") + self.assertIn("Testing batch size", after) + self.assertNotIn("weights.bin", after) + + def test_closing_earlier_bar_keeps_later_bar_rendering(self): + output = self.render(""" from concurrent.futures import ThreadPoolExecutor -from pathlib import Path -from threading import Event -from unittest.mock import patch +from time import sleep +from rich import print +from heretic.progress import TqdmShim +with ThreadPoolExecutor(max_workers=1) as worker: + first = worker.submit(TqdmShim, total=100, desc="first.bin").result() + second = TqdmShim(total=100, desc="second.bin", disable=None, mininterval=0) + worker.submit(first.close).result() + second.update(50) + sleep(0.2) + print("AFTER") + second.close() +""") + after = output.split("AFTER", 1)[1] + self.assertRegex(after, r"second\.bin[^\n]*50%") + self.assertNotIn("first.bin", after) -from rich.console import Console -from rich.progress import Progress - -from heretic import progress - - -class TerminalStream(io.StringIO): - def isatty(self) -> bool: - return True - - -class TqdmShimTest(unittest.TestCase): - def setUp(self): - environment = patch.dict(os.environ, {"TERM": "xterm"}) - environment.start() - self.addCleanup(environment.stop) - self.output = TerminalStream() - self.console = Console( - file=self.output, - force_terminal=True, - force_interactive=True, - color_system=None, - ) - self.displays = [] - - def make_progress(*args, **kwargs): - display = Progress( - *args, console=self.console, auto_refresh=False, **kwargs - ) - self.displays.append(display) - return display - - # Intercept Rich's public constructor before loading either shim version. - # The fixture does not depend on globals introduced by the fix. - for target, replacement in ( - ("sys.stdout", self.output), - ("sys.stderr", self.output), - ("rich.progress.Progress", make_progress), - ): - context = patch(target, replacement) - context.start() - self.addCleanup(context.stop) - spec = importlib.util.spec_from_file_location( - "progress_under_test", progress.__file__ - ) - assert spec is not None and spec.loader is not None - self.shim = importlib.util.module_from_spec(spec) - spec.loader.exec_module(self.shim) - self.addCleanup(self.stop_displays) - - def stop_displays(self): - for display in reversed(self.displays): - display.stop() - - def live_displays(self): - return [display for display in self.displays if display.live.is_started] - - def live_tasks(self): - return [task for display in self.live_displays() for task in display.tasks] - - def test_disabled_bar_never_starts_display(self): - with self.shim.TqdmShim(total=1, disable=True): - self.assertEqual(self.live_displays(), []) - - def test_auto_detected_bar_updates_in_terminal(self): - with self.shim.TqdmShim(total=100, disable=None, mininterval=0) as bar: - self.assertFalse(bar.disable) - bar.update(50) - bar.set_description("Half downloaded") - task = self.live_tasks()[0] - self.assertEqual(task.completed, 50) - self.assertEqual(task.total, 100) - self.assertEqual(task.description, "Half downloaded: ") - - def test_auto_detected_bar_stays_disabled_for_nonterminal_file(self): - with self.shim.TqdmShim(total=1, file=io.StringIO(), disable=None): - self.assertEqual(self.live_displays(), []) - - def test_second_auto_detected_bar_updates_while_first_is_open(self): - with ( - self.shim.TqdmShim(total=2, disable=None) as first, - self.shim.TqdmShim(total=2, disable=None, mininterval=0) as second, - ): - self.assertFalse(first.disable) - self.assertFalse(second.disable) - second.update(1) - self.assertEqual([task.completed for task in self.live_tasks()], [0, 1]) - - def test_positional_file_argument_keeps_terminal_detection(self): - with ( - self.shim.TqdmShim(total=1), - self.shim.TqdmShim( - None, "positional", 1, True, sys.stderr, disable=None - ) as bar, - ): - self.assertFalse(bar.disable) - - def test_overlapping_threads_can_close_in_creation_order(self): - first_ready = Event() - second_ready = Event() - first_done = Event() - - def first_worker(): - with self.shim.TqdmShim(total=1, desc="first"): - first_ready.set() - self.assertTrue(second_ready.wait(timeout=10)) - first_done.set() - - def second_worker(): - self.assertTrue(first_ready.wait(timeout=10)) - with self.shim.TqdmShim(total=2, desc="second", mininterval=0) as bar: - second_ready.set() - self.assertTrue(first_done.wait(timeout=10)) - bar.update(1) - self.assertEqual(len(self.live_displays()), 1) - tasks = self.live_tasks() - self.assertEqual([task.description for task in tasks], ["second"]) - self.assertEqual(tasks[0].completed, 1) - offset = len(self.output.getvalue()) - self.live_displays()[0].refresh() - self.assertIn("second", self.output.getvalue()[offset:]) - - with ThreadPoolExecutor(max_workers=2) as executor: - first = executor.submit(first_worker) - second = executor.submit(second_worker) - first.result(timeout=15) - second.result(timeout=15) - self.assertEqual(self.live_displays(), []) - - def test_sequential_bars_stop_and_restore_streams(self): - for label in ("model", "dataset"): - with self.shim.TqdmShim(total=1, desc=label, mininterval=0) as bar: - self.assertTrue(self.live_displays()) - bar.update(1) - self.assertEqual(self.live_displays(), []) - self.assertIs(sys.stderr, self.output) - self.assertIs(sys.stdout, self.output) - offset = len(self.output.getvalue()) - self.console.print("After download") - self.assertEqual(self.output.getvalue()[offset:], "After download\n") - - def test_completed_bar_stops_display_without_being_closed(self): - with self.shim.TqdmShim(total=100, mininterval=0) as bar: - bar.update(100) - self.assertEqual(self.live_displays(), []) - self.assertFalse(bar.disable) - self.assertEqual(bar.n, 100) - self.assertIs(sys.stderr, self.output) - self.assertIs(sys.stdout, self.output) - offset = len(self.output.getvalue()) - self.console.print("After download") - self.assertEqual(self.output.getvalue()[offset:], "After download\n") - - def test_completed_bar_resumes_when_total_grows(self): - with self.shim.TqdmShim(total=100, mininterval=0, miniters=1) as bar: - bar.update(100) - self.assertEqual(self.live_displays(), []) - bar.total = 200 - bar.refresh() - self.assertEqual(self.live_tasks()[0].completed, 100) - self.assertEqual(self.live_tasks()[0].total, 200) - bar.update(50) - self.assertEqual(self.live_tasks()[0].completed, 150) - bar.update(50) - self.assertEqual(self.live_displays(), []) - - def test_completed_bar_can_be_reset(self): - with self.shim.TqdmShim(total=100, mininterval=0, miniters=1) as bar: - bar.update(100) - self.assertEqual(self.live_displays(), []) - bar.reset(total=200) - self.assertEqual(self.live_tasks()[0].completed, 0) - self.assertEqual(self.live_tasks()[0].total, 200) - bar.update(50) - self.assertEqual(self.live_tasks()[0].completed, 50) - - def test_final_update_releases_display_despite_tqdm_throttling(self): - for mininterval, miniters in ((3600, 1), (0, 101)): - with ( - self.subTest(mininterval=mininterval, miniters=miniters), - self.shim.TqdmShim( - total=100, mininterval=mininterval, miniters=miniters - ) as bar, - ): - bar.update(100) - self.assertEqual(self.live_displays(), []) - self.assertFalse(bar.disable) - self.assertEqual(bar.n, 100) - - def test_zero_total_can_grow_into_visible_progress(self): - with self.shim.TqdmShim(total=0, mininterval=0) as bar: - self.assertEqual(self.live_displays(), []) - bar.total = 100 - bar.refresh() - bar.update(50) - self.assertEqual(self.live_tasks()[0].completed, 50) - self.assertEqual(self.live_tasks()[0].total, 100) - - def test_unknown_total_stays_visible_until_closed(self): - with self.shim.TqdmShim(total=None, mininterval=0) as bar: - bar.update(100) - self.assertEqual(self.live_tasks()[0].completed, 100) - self.assertIsNone(self.live_tasks()[0].total) - self.assertEqual(self.live_displays(), []) - - def test_file_bars_keep_independent_byte_progress(self): - with ( - self.shim.TqdmShim(total=100, desc="first.bin", mininterval=0) as first, - self.shim.TqdmShim(total=200, desc="second.bin", mininterval=0) as second, - ): - first.update(50) - second.update(75) - self.assertEqual( - [ - (task.description, task.completed, task.total) - for task in self.live_tasks() - ], - [("first.bin", 50, 100), ("second.bin", 75, 200)], - ) - first.update(50) - self.assertEqual( - [(task.description, task.completed) for task in self.live_tasks()], - [("second.bin", 75)], - ) - self.assertFalse(second.disable) - - def test_clear_and_refresh_preserve_progress(self): - with self.shim.TqdmShim(total=100, mininterval=0) as bar: - bar.update(50) - bar.clear() - bar.clear() - self.assertEqual(self.live_tasks(), []) - bar.refresh() - self.assertEqual(self.live_tasks()[0].completed, 50) - bar.close() - self.assertEqual(self.live_displays(), []) - - def test_tqdm_write_restores_cleared_bar(self): - with self.shim.TqdmShim(total=100, mininterval=0) as bar: - bar.update(50) - bar.write("Download message", file=bar.fp) - self.assertIn("Download message", self.output.getvalue()) - self.assertEqual(self.live_tasks()[0].completed, 50) - - def test_context_manager_closes_on_exception(self): - with self.shim.TqdmShim(total=2, desc="other work") as unrelated: - with self.assertRaisesRegex(RuntimeError, "download failed"): - with self.shim.TqdmShim(total=100, mininterval=0) as bar: - bar.update(50) - raise RuntimeError("download failed") - self.assertEqual( - [task.description for task in self.live_tasks()], ["other work"] - ) - self.assertFalse(unrelated.disable) - self.assertEqual(self.live_displays(), []) - - def check_snapshot(self, case): - # patch_tqdm must run before Hub imports tqdm. Use a fresh interpreter so - # the integration checks exercise that real import order independently. - result = subprocess.run( - [sys.executable, "-B", str(Path(__file__).resolve()), "--snapshot", case], - capture_output=True, - text=True, - check=False, - env={**os.environ, "TQDM_MININTERVAL": "0"}, - timeout=30, - ) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - - def test_snapshot_keeps_byte_progress_and_stops_display_without_gc(self): - self.check_snapshot("success") - - def test_snapshot_respects_disabled_progress(self): - self.check_snapshot("disabled") - - def test_snapshot_preserves_custom_tqdm_class(self): - self.check_snapshot("custom") - - -def check_snapshot(case): - test = TqdmShimTest() - test.setUp() - try: - test.shim.patch_tqdm() - import huggingface_hub - from huggingface_hub import HfApi, ModelInfo, _snapshot_download - from huggingface_hub.utils import disable_progress_bars - from huggingface_hub.utils import tqdm as hub_tqdm - - if case == "custom": - - class CustomTqdm(hub_tqdm): - pass - - with patch.object( - _snapshot_download, "thread_map", return_value=[] - ) as workers: - info = ModelInfo( - id="test/model", - sha="a" * 40, - siblings=[{"rfilename": "weights.bin"}], - ) - with ( - patch.object(HfApi, "repo_info", return_value=info), - tempfile.TemporaryDirectory() as cache, - ): - huggingface_hub.snapshot_download( - "test/model", cache_dir=cache, tqdm_class=CustomTqdm - ) - test.assertIs(workers.call_args.kwargs["tqdm_class"], CustomTqdm) - return - - if case == "disabled": - disable_progress_bars() - - def download(*args, **kwargs): - with kwargs["tqdm_class"](total=100) as byte_bar: - byte_bar.update(50) - if case == "disabled": - test.assertEqual( - [task.description for task in test.live_tasks()], ["other work"] - ) - else: - byte_tasks = [ - task - for task in test.live_tasks() - if "Downloading" in task.description - ] - test.assertEqual( - len(byte_tasks), 1, "Snapshot byte progress must remain visible" - ) - test.assertEqual(byte_tasks[0].completed, 50) - test.assertEqual(byte_tasks[0].total, 100) - byte_bar.update(50) - return "weights.bin" - - # Keep an unrelated bar open to check ownership during snapshot cleanup. - with test.shim.TqdmShim(total=2, desc="other work") as unrelated: - info = ModelInfo( - id="test/model", sha="a" * 40, siblings=[{"rfilename": "weights.bin"}] - ) - with ( - patch.object(HfApi, "repo_info", return_value=info), - patch.object( - _snapshot_download, "hf_hub_download", side_effect=download - ), - tempfile.TemporaryDirectory() as cache, - ): - result = huggingface_hub.snapshot_download( - "test/model", cache_dir=cache - ) - test.assertEqual(Path(result).name, "a" * 40) - test.assertEqual( - [task.description for task in test.live_tasks()], ["other work"] - ) - test.assertFalse(unrelated.disable) - test.assertEqual(test.live_displays(), []) - finally: - test.doCleanups() + def test_disabled_bar_does_not_render(self): + output = self.render(""" +from rich import print +from heretic.progress import TqdmShim +with TqdmShim(total=100, desc="hidden", disable=True): + print("MESSAGE") +""") + self.assertIn("MESSAGE", output) + self.assertNotIn("hidden", output) if __name__ == "__main__": - if len(sys.argv) == 3 and sys.argv[1] == "--snapshot": - check_snapshot(sys.argv[2]) - else: - unittest.main() + unittest.main() From 1a3ba95f5aa244ab48266bba92ded9d93f692ff2 Mon Sep 17 00:00:00 2001 From: umran666 Date: Mon, 28 Sep 2026 16:52:11 +0530 Subject: [PATCH 10/31] test: cover progress rendering and cleanup on Windows --- .github/workflows/ci.yml | 14 ++++++++++++ pyproject.toml | 1 + tests/test_progress.py | 46 ++++++++++++++++++++++++++++++++++++++-- uv.lock | 17 +++++++++++++++ 4 files changed, 76 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 087d9f3..5456920 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -7,6 +7,20 @@ on: branches: [master] jobs: + windows-progress: + name: Progress rendering (Windows) + runs-on: windows-latest + steps: + - uses: actions/checkout@v6 + - uses: astral-sh/setup-uv@v7 + - name: Test native Windows terminal rendering + env: + PYTHONPATH: src + run: >- + uv run --no-project --python 3.12 + --with pywinpty==3.0.2 --with rich==14.3.3 --with tqdm==4.67.1 + python -m unittest discover -s tests -p test_progress.py -v + checks: name: Check and build (Python ${{ matrix.python-version }}) runs-on: ubuntu-latest diff --git a/pyproject.toml b/pyproject.toml index 83b5a7d..07bbb57 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -45,6 +45,7 @@ dependencies = [ [dependency-groups] dev = [ + "pywinpty==3.0.2; sys_platform == 'win32'", "ruff>=0.16.9", "ty>=0.0.84", ] diff --git a/tests/test_progress.py b/tests/test_progress.py index 0fb477a..27ce112 100644 --- a/tests/test_progress.py +++ b/tests/test_progress.py @@ -11,8 +11,26 @@ import unittest class ProgressRenderingTests(unittest.TestCase): def render(self, code): + env = {**os.environ, "TERM": "xterm", "COLUMNS": "120", "PYTHONUTF8": "1"} if sys.platform == "win32": - self.skipTest("Requires a POSIX pseudoterminal") + from winpty import PtyProcess + + process = PtyProcess.spawn( + [sys.executable, "-c", code], env=env, dimensions=(24, 120) + ) + process.fileobj.settimeout(30) + chunks = [] + try: + while True: + try: + chunks.append(process.read()) + except EOFError: + break + finally: + process.close(force=True) + output_text = "".join(chunks) + self.assertEqual(process.exitstatus, 0, output_text) + return re.sub(r"\x1b\[[0-?]*[ -/]*[@-~]", "", output_text).replace("\r", "") import pty master, slave = pty.openpty() @@ -22,7 +40,7 @@ class ProgressRenderingTests(unittest.TestCase): [sys.executable, "-c", code], stdout=slave, stderr=slave, - env={**os.environ, "TERM": "xterm", "COLUMNS": "120"}, + env=env, timeout=30, check=False, ) @@ -94,6 +112,30 @@ with TqdmShim(total=100, desc="hidden", disable=True): self.assertIn("MESSAGE", output) self.assertNotIn("hidden", output) + def test_incomplete_bar_is_removed_after_exception_or_collection(self): + output = self.render(""" +import gc +from rich import print +from heretic.progress import TqdmShim +try: + with TqdmShim(total=100, desc="interrupted") as bar: + bar.update(10) + raise RuntimeError("interrupted") +except RuntimeError: + pass +bar = TqdmShim(total=100, desc="unfinished") +bar.update(10) +bar.cycle = bar +del bar +gc.collect() +print("AFTER") +print("Next application message") +""") + self.assertIn("Next application message", output) + after = output.split("AFTER", 1)[1] + self.assertNotIn("unfinished", after) + self.assertNotIn("interrupted", after) + if __name__ == "__main__": unittest.main() diff --git a/uv.lock b/uv.lock index f79c1b4..40f4ee6 100644 --- a/uv.lock +++ b/uv.lock @@ -1067,6 +1067,7 @@ dependencies = [ [package.dev-dependencies] dev = [ + { name = "pywinpty", marker = "sys_platform == 'win32'" }, { name = "ruff" }, { name = "ty" }, ] @@ -1097,6 +1098,7 @@ requires-dist = [ [package.metadata.requires-dev] dev = [ + { name = "pywinpty", marker = "sys_platform == 'win32'", specifier = "==3.0.2" }, { name = "ruff", specifier = ">=0.16.9" }, { name = "ty", specifier = ">=0.0.84" }, ] @@ -2960,6 +2962,21 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/d5/11/e3df59614bebe0ca50c905442603eda64ae7ac19811d4e4f74aa2d51ca85/pytz-2026.4-py2.py3-none-any.whl", hash = "sha256:9d514388fbc89ca0833203464272ac485b8828568ab73532f5020f17e892a0ff", size = 506747, upload-time = "2026-09-24T03:58:38.629Z" }, ] +[[package]] +name = "pywinpty" +version = "3.0.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f3/bb/a7cc2967c5c4eceb6cc49cfe39447d4bfc56e6c865e7c2249b6eb978935f/pywinpty-3.0.2.tar.gz", hash = "sha256:1505cc4cb248af42cb6285a65c9c2086ee9e7e574078ee60933d5d7fa86fb004", size = 30669, upload-time = "2025-10-03T21:16:29.205Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/3e/f5/b17ae550841949c217ad557ee445b4a14e9c0b506ae51ee087eff53428a6/pywinpty-3.0.2-cp310-cp310-win_amd64.whl", hash = "sha256:65db57fd3387d71e8372b6a54269cbcd0f6dfa6d4616a29e0af749ec19f5c558", size = 2050330, upload-time = "2025-10-03T21:20:15.656Z" }, + { url = "https://files.pythonhosted.org/packages/a6/a1/409c1651c9f874d598c10f51ff586c416625601df4bca315d08baec4c3e3/pywinpty-3.0.2-cp311-cp311-win_amd64.whl", hash = "sha256:327790d70e4c841ebd9d0f295a780177149aeb405bca44c7115a3de5c2054b23", size = 2050304, upload-time = "2025-10-03T21:19:29.466Z" }, + { url = "https://files.pythonhosted.org/packages/02/4e/1098484e042c9485f56f16eb2b69b43b874bd526044ee401512234cf9e04/pywinpty-3.0.2-cp312-cp312-win_amd64.whl", hash = "sha256:99fdd9b455f0ad6419aba6731a7a0d2f88ced83c3c94a80ff9533d95fa8d8a9e", size = 2050391, upload-time = "2025-10-03T21:19:01.642Z" }, + { url = "https://files.pythonhosted.org/packages/fc/19/b757fe28008236a4a713e813283721b8a40aa60cd7d3f83549f2e25a3155/pywinpty-3.0.2-cp313-cp313-win_amd64.whl", hash = "sha256:18f78b81e4cfee6aabe7ea8688441d30247b73e52cd9657138015c5f4ee13a51", size = 2050057, upload-time = "2025-10-03T21:19:26.732Z" }, + { url = "https://files.pythonhosted.org/packages/cb/44/cbae12ecf6f4fa4129c36871fd09c6bef4f98d5f625ecefb5e2449765508/pywinpty-3.0.2-cp313-cp313t-win_amd64.whl", hash = "sha256:663383ecfab7fc382cc97ea5c4f7f0bb32c2f889259855df6ea34e5df42d305b", size = 2049874, upload-time = "2025-10-03T21:18:53.923Z" }, + { url = "https://files.pythonhosted.org/packages/ca/15/f12c6055e2d7a617d4d5820e8ac4ceaff849da4cb124640ef5116a230771/pywinpty-3.0.2-cp314-cp314-win_amd64.whl", hash = "sha256:28297cecc37bee9f24d8889e47231972d6e9e84f7b668909de54f36ca785029a", size = 2050386, upload-time = "2025-10-03T21:18:50.477Z" }, + { url = "https://files.pythonhosted.org/packages/de/24/c6907c5bb06043df98ad6a0a0ff5db2e0affcecbc3b15c42404393a3f72a/pywinpty-3.0.2-cp314-cp314t-win_amd64.whl", hash = "sha256:34b55ae9a1b671fe3eae071d86618110538e8eaad18fcb1531c0830b91a82767", size = 2049834, upload-time = "2025-10-03T21:19:25.688Z" }, +] + [[package]] name = "pyyaml" version = "6.0.3" From b8ae53bebab2c764ecb4def97b40ccdd01404d30 Mon Sep 17 00:00:00 2001 From: umran666 Date: Mon, 28 Sep 2026 17:48:08 +0530 Subject: [PATCH 11/31] test: reproduce lingering incomplete download bar --- tests/test_progress.py | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/tests/test_progress.py b/tests/test_progress.py index 27ce112..0b5941e 100644 --- a/tests/test_progress.py +++ b/tests/test_progress.py @@ -69,19 +69,25 @@ from time import sleep from rich import print from heretic.progress import TqdmShim assert os.isatty(2) -bar = TqdmShim(total=100, desc="weights.bin", disable=None, mininterval=0) +bar = TqdmShim( + total=0, desc="Downloading (incomplete total...)", disable=None, mininterval=0 +) +bar.total = 100 bar.update(50) sleep(0.2) # Allow Rich's 10 Hz renderer to emit the updated frame. print("HALFWAY") bar.update(50) +bar.set_description("Download complete") print("AFTER") print("Testing batch size") +sleep(0.2) bar.close() """) halfway, after = output.split("AFTER", 1) - self.assertRegex(halfway, r"weights\.bin[^\n]*50%") self.assertIn("Testing batch size", after) - self.assertNotIn("weights.bin", after) + self.assertNotIn("Downloading (incomplete total...)", after) + self.assertNotIn("Download complete", after) + self.assertRegex(halfway, r"Downloading \(incomplete total\.\.\.\)[^\n]*50%") def test_closing_earlier_bar_keeps_later_bar_rendering(self): output = self.render(""" From 650ab41257110e56ef87074a6daf191319725fe2 Mon Sep 17 00:00:00 2001 From: umran666 Date: Wed, 30 Sep 2026 09:57:25 +0530 Subject: [PATCH 12/31] test: force frames in progress regression --- tests/test_progress.py | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/tests/test_progress.py b/tests/test_progress.py index 0b5941e..de92d04 100644 --- a/tests/test_progress.py +++ b/tests/test_progress.py @@ -65,22 +65,26 @@ class ProgressRenderingTests(unittest.TestCase): def test_completed_download_does_not_redraw_over_later_messages(self): output = self.render(""" import os -from time import sleep from rich import print from heretic.progress import TqdmShim assert os.isatty(2) bar = TqdmShim( total=0, desc="Downloading (incomplete total...)", disable=None, mininterval=0 ) +# Force frames at the two checkpoints instead of relying on Rich's refresh thread. +progress = getattr(bar, "rich_progress", None) +if progress is None: + from heretic.progress import _progress as progress bar.total = 100 bar.update(50) -sleep(0.2) # Allow Rich's 10 Hz renderer to emit the updated frame. +progress.refresh() print("HALFWAY") bar.update(50) bar.set_description("Download complete") print("AFTER") print("Testing batch size") -sleep(0.2) +if progress.live.is_started: + progress.refresh() bar.close() """) halfway, after = output.split("AFTER", 1) From bdd67be1c04690677978570615b63c756ad3cfb2 Mon Sep 17 00:00:00 2001 From: umran666 Date: Wed, 30 Sep 2026 12:59:41 +0530 Subject: [PATCH 13/31] fix: narrow progress cleanup and require Rich 15 --- .github/workflows/ci.yml | 2 +- src/heretic/progress.py | 31 ++++++----------------- tests/test_progress.py | 54 +++++++--------------------------------- 3 files changed, 18 insertions(+), 69 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5456920..987661d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -18,7 +18,7 @@ jobs: PYTHONPATH: src run: >- uv run --no-project --python 3.12 - --with pywinpty==3.0.2 --with rich==14.3.3 --with tqdm==4.67.1 + --with pywinpty==3.0.2 --with rich==15.0.0 --with tqdm==4.67.1 python -m unittest discover -s tests -p test_progress.py -v checks: diff --git a/src/heretic/progress.py b/src/heretic/progress.py index a7bdf1b..9b38fed 100644 --- a/src/heretic/progress.py +++ b/src/heretic/progress.py @@ -1,7 +1,6 @@ # SPDX-License-Identifier: AGPL-3.0-or-later # Copyright (C) 2025-2026 Philipp Emanuel Weidmann + contributors -import sys from threading import RLock from typing import Any @@ -9,6 +8,7 @@ import tqdm import tqdm.auto from rich.progress import Progress, TaskID +# A single live display lets individual bars close in any order. _progress = Progress(transient=True) _progress_lock = RLock() @@ -20,34 +20,17 @@ class TqdmShim(tqdm.tqdm): self.rich_task_id: TaskID | None = None kwargs["gui"] = True - # An existing Rich display may have redirected the stream through FileProxy, - # whose isatty() does not reflect the terminal behind it. - file = args[4] if len(args) > 4 else kwargs.get("file") - file = file if file is not None else sys.stderr - file = getattr(file, "rich_proxied_file", file) - if len(args) > 4: - args = (*args[:4], file, *args[5:]) - else: - kwargs["file"] = file - # Chain up to the parent constructor to ensure that the internal state of the superclass # is correctly initialized, which some methods that we don't override might rely on. super().__init__(*args, **kwargs) self.display() def update(self, *args: Any, **kwargs: Any): - displayed = super().update(*args, **kwargs) - # tqdm can throttle the final redraw, but Rich must still stop refreshing - # a completed task that the caller keeps alive. - if ( - not displayed - and not self.disable - and self.total is not None - and self.n >= self.total - ): - self.display() - return True - return displayed + result = super().update(*args, **kwargs) + # Remove completed tasks even when tqdm throttles the final refresh. + if not self.disable and self.total is not None and self.n >= self.total: + self.clear() + return result def display(self, *args: Any, **kwargs: Any): with _progress_lock: @@ -80,6 +63,8 @@ class TqdmShim(tqdm.tqdm): self.rich_task_id = None if not _progress.task_ids: _progress.stop() + else: + _progress.refresh() def close(self, *args: Any, **kwargs: Any): try: diff --git a/tests/test_progress.py b/tests/test_progress.py index de92d04..98b5cae 100644 --- a/tests/test_progress.py +++ b/tests/test_progress.py @@ -68,19 +68,16 @@ import os from rich import print from heretic.progress import TqdmShim assert os.isatty(2) -bar = TqdmShim( - total=0, desc="Downloading (incomplete total...)", disable=None, mininterval=0 -) +bar = TqdmShim(total=100, desc="download.bin", disable=None, mininterval=3600) # Force frames at the two checkpoints instead of relying on Rich's refresh thread. progress = getattr(bar, "rich_progress", None) if progress is None: from heretic.progress import _progress as progress -bar.total = 100 bar.update(50) +bar.refresh() progress.refresh() -print("HALFWAY") +# This update is throttled; the caller still keeps the completed bar alive. bar.update(50) -bar.set_description("Download complete") print("AFTER") print("Testing batch size") if progress.live.is_started: @@ -89,14 +86,12 @@ bar.close() """) halfway, after = output.split("AFTER", 1) self.assertIn("Testing batch size", after) - self.assertNotIn("Downloading (incomplete total...)", after) - self.assertNotIn("Download complete", after) - self.assertRegex(halfway, r"Downloading \(incomplete total\.\.\.\)[^\n]*50%") + self.assertNotIn("download.bin", after) + self.assertRegex(halfway, r"download\.bin[^\n]*50%") def test_closing_earlier_bar_keeps_later_bar_rendering(self): output = self.render(""" from concurrent.futures import ThreadPoolExecutor -from time import sleep from rich import print from heretic.progress import TqdmShim with ThreadPoolExecutor(max_workers=1) as worker: @@ -104,48 +99,17 @@ with ThreadPoolExecutor(max_workers=1) as worker: second = TqdmShim(total=100, desc="second.bin", disable=None, mininterval=0) worker.submit(first.close).result() second.update(50) - sleep(0.2) print("AFTER") + progress = getattr(second, "rich_progress", None) + if progress is None: + from heretic.progress import _progress as progress + progress.refresh() second.close() """) after = output.split("AFTER", 1)[1] self.assertRegex(after, r"second\.bin[^\n]*50%") self.assertNotIn("first.bin", after) - def test_disabled_bar_does_not_render(self): - output = self.render(""" -from rich import print -from heretic.progress import TqdmShim -with TqdmShim(total=100, desc="hidden", disable=True): - print("MESSAGE") -""") - self.assertIn("MESSAGE", output) - self.assertNotIn("hidden", output) - - def test_incomplete_bar_is_removed_after_exception_or_collection(self): - output = self.render(""" -import gc -from rich import print -from heretic.progress import TqdmShim -try: - with TqdmShim(total=100, desc="interrupted") as bar: - bar.update(10) - raise RuntimeError("interrupted") -except RuntimeError: - pass -bar = TqdmShim(total=100, desc="unfinished") -bar.update(10) -bar.cycle = bar -del bar -gc.collect() -print("AFTER") -print("Next application message") -""") - self.assertIn("Next application message", output) - after = output.split("AFTER", 1)[1] - self.assertNotIn("unfinished", after) - self.assertNotIn("interrupted", after) - if __name__ == "__main__": unittest.main() From 79a63c736df504821991f5426f541e8b7cce6cbe Mon Sep 17 00:00:00 2001 From: umran666 Date: Wed, 30 Sep 2026 15:28:26 +0530 Subject: [PATCH 14/31] fix: preserve tqdm statistics in Rich progress --- .github/workflows/ci.yml | 14 -------------- src/heretic/progress.py | 23 +++++++++++++++++++--- tests/test_progress.py | 42 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 62 insertions(+), 17 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 987661d..087d9f3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -7,20 +7,6 @@ on: branches: [master] jobs: - windows-progress: - name: Progress rendering (Windows) - runs-on: windows-latest - steps: - - uses: actions/checkout@v6 - - uses: astral-sh/setup-uv@v7 - - name: Test native Windows terminal rendering - env: - PYTHONPATH: src - run: >- - uv run --no-project --python 3.12 - --with pywinpty==3.0.2 --with rich==15.0.0 --with tqdm==4.67.1 - python -m unittest discover -s tests -p test_progress.py -v - checks: name: Check and build (Python ${{ matrix.python-version }}) runs-on: ubuntu-latest diff --git a/src/heretic/progress.py b/src/heretic/progress.py index 9b38fed..c05cce7 100644 --- a/src/heretic/progress.py +++ b/src/heretic/progress.py @@ -6,10 +6,16 @@ from typing import Any import tqdm import tqdm.auto -from rich.progress import Progress, TaskID +from rich.progress import BarColumn, Progress, TaskID, TaskProgressColumn, TextColumn # A single live display lets individual bars close in any order. -_progress = Progress(transient=True) +_progress = Progress( + TextColumn("{task.description}", style="progress.description", markup=False), + BarColumn(), + TaskProgressColumn(), + TextColumn("{task.fields[stats]}", markup=False), + transient=True, +) _progress_lock = RLock() @@ -43,17 +49,28 @@ class TqdmShim(tqdm.tqdm): self.clear() return + # Let tqdm format units, rates, timings and postfix text; Rich handles width. + format_dict = self.format_dict + format_dict["ncols"] = None + format_dict["bar_format"] = ( + "{r_bar}" + if self.total + else "{n_fmt}{unit} [{elapsed}, {rate_fmt}{postfix}]" + ) + stats = self.format_meter(**format_dict).removeprefix("| ") + if self.rich_task_id is None: if not _progress.task_ids: _progress.start() self.rich_task_id = _progress.add_task( - self.desc or "", total=self.total, completed=self.n + self.desc or "", total=self.total, completed=self.n, stats=stats ) _progress.update( self.rich_task_id, description=self.desc or "", total=self.total, completed=self.n, + stats=stats, ) def clear(self, *args: Any, **kwargs: Any): diff --git a/tests/test_progress.py b/tests/test_progress.py index 98b5cae..24c549a 100644 --- a/tests/test_progress.py +++ b/tests/test_progress.py @@ -110,6 +110,48 @@ with ThreadPoolExecutor(max_workers=1) as worker: self.assertRegex(after, r"second\.bin[^\n]*50%") self.assertNotIn("first.bin", after) + def test_counts_units_rates_and_postfix_are_preserved(self): + output = self.render(""" +from rich import print +from heretic.progress import TqdmShim +for description, total, count, options in [ + ("bytes.bin", 4096, 1024, dict(unit="B", unit_scale=True, unit_divisor=1024)), + ("training", 8, 2, dict(unit="batch")), + ("unknown", None, 3, dict(unit="item")), +]: + bar = TqdmShim(total=total, desc=description, mininterval=0, **options) + bar.update(count) + if total is None: + bar.set_postfix_str("loss=0.42, note=[ok]") + else: + bar.set_postfix(loss=0.42, note="[ok]") + print("CHECK " + description) + progress = getattr(bar, "rich_progress", None) + if progress is None: + from heretic.progress import _progress as progress + progress.refresh() + bar.close() + print("END " + description) +""") + for description, counts, unit in [ + ("bytes.bin", "1.00k/4.00k", "B"), + ("training", "2/8", "batch"), + ("unknown", "3item", "item"), + ]: + with self.subTest(description=description): + frame = output.split("CHECK " + description, 1)[1].split( + "END " + description, 1 + )[0] + self.assertIn(description, frame) + self.assertIn(counts, frame) + self.assertRegex( + frame, + r"\d[\d.]*[kMGTPEZYmunpf]?" + + rf"(?:{unit}/s|s/{unit})[^\n]*loss=0\.42, note=\[ok\]", + ) + if description != "unknown": + self.assertRegex(frame, r"\[\d+:\d+<\d+:\d+,") + if __name__ == "__main__": unittest.main() From b17f768d69ebbeba1e19a43505a3f56f59f30566 Mon Sep 17 00:00:00 2001 From: umran666 Date: Thu, 1 Oct 2026 10:41:05 +0530 Subject: [PATCH 15/31] fix: address progress shim review --- src/heretic/progress.py | 51 +++++++++++++++++++++++------------------ tests/test_progress.py | 34 ++++++++++++++++++++++++++- 2 files changed, 62 insertions(+), 23 deletions(-) diff --git a/src/heretic/progress.py b/src/heretic/progress.py index c05cce7..4307a91 100644 --- a/src/heretic/progress.py +++ b/src/heretic/progress.py @@ -24,18 +24,22 @@ _progress_lock = RLock() class TqdmShim(tqdm.tqdm): def __init__(self, *args: Any, **kwargs: Any): self.rich_task_id: TaskID | None = None + # Use tqdm's bookkeeping without its terminal printer; Rich handles width. kwargs["gui"] = True + kwargs["dynamic_ncols"] = False # Chain up to the parent constructor to ensure that the internal state of the superclass # is correctly initialized, which some methods that we don't override might rely on. super().__init__(*args, **kwargs) + self.ncols = None + # GUI mode skips tqdm's initial refresh, so draw the initial Rich task here. self.display() - def update(self, *args: Any, **kwargs: Any): + def update(self, *args: Any, **kwargs: Any) -> bool | None: result = super().update(*args, **kwargs) - # Remove completed tasks even when tqdm throttles the final refresh. - if not self.disable and self.total is not None and self.n >= self.total: - self.clear() + # mininterval/miniters can make tqdm skip display() on the final update. + if not self.disable: + self._clear_completed() return result def display(self, *args: Any, **kwargs: Any): @@ -45,19 +49,17 @@ class TqdmShim(tqdm.tqdm): # Completion ends the transient display, not the tqdm object's lifetime. # A later reset or larger total can make the same bar visible again. - if self.total is not None and self.n >= self.total: - self.clear() + if self._clear_completed(): return - # Let tqdm format units, rates, timings and postfix text; Rich handles width. + # The total can become known after construction; preserve custom formats. format_dict = self.format_dict - format_dict["ncols"] = None - format_dict["bar_format"] = ( - "{r_bar}" + format_dict["bar_format"] = self.bar_format or ( + "{n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}{postfix}]" if self.total else "{n_fmt}{unit} [{elapsed}, {rate_fmt}{postfix}]" ) - stats = self.format_meter(**format_dict).removeprefix("| ") + stats = self.format_meter(**format_dict) if self.rich_task_id is None: if not _progress.task_ids: @@ -65,13 +67,20 @@ class TqdmShim(tqdm.tqdm): self.rich_task_id = _progress.add_task( self.desc or "", total=self.total, completed=self.n, stats=stats ) - _progress.update( - self.rich_task_id, - description=self.desc or "", - total=self.total, - completed=self.n, - stats=stats, - ) + else: + _progress.update( + self.rich_task_id, + description=self.desc or "", + total=self.total, + completed=self.n, + stats=stats, + ) + + def _clear_completed(self) -> bool: + if self.total is not None and self.n >= self.total: + self.clear() + return True + return False def clear(self, *args: Any, **kwargs: Any): with _progress_lock: @@ -84,10 +93,8 @@ class TqdmShim(tqdm.tqdm): _progress.refresh() def close(self, *args: Any, **kwargs: Any): - try: - super().close() - finally: - self.clear() + super().close() + self.clear() def patch_tqdm(): diff --git a/tests/test_progress.py b/tests/test_progress.py index 24c549a..f1dc6c9 100644 --- a/tests/test_progress.py +++ b/tests/test_progress.py @@ -76,7 +76,7 @@ if progress is None: bar.update(50) bar.refresh() progress.refresh() -# This update is throttled; the caller still keeps the completed bar alive. +# mininterval=3600 prevents a final refresh; the caller keeps the bar alive. bar.update(50) print("AFTER") print("Testing batch size") @@ -152,6 +152,38 @@ for description, total, count, options in [ if description != "unknown": self.assertRegex(frame, r"\[\d+:\d+<\d+:\d+,") + def test_overlapping_bars_keep_their_own_formats(self): + output = self.render(""" +from rich import print +from heretic.progress import TqdmShim, _progress +download = TqdmShim(total=None, desc="bytes.bin", unit="B", unit_scale=True, + unit_divisor=1024, mininterval=0, miniters=1) +training = TqdmShim(total=8, desc="training", unit="batch", mininterval=0, + miniters=1, bar_format="STEP {n}/{total} {unit}{postfix}") +print("INITIAL") +_progress.refresh() +download.update(1024) +download.set_postfix_str("file=ok") +download.total = 4096 +download.refresh() +training.update(2) +training.set_postfix(loss=0.42) +print("BEFORE") +_progress.refresh() +training.close() +print("AFTER") +_progress.refresh() +download.close() +""") + before, after = output.split("AFTER", 1) + initial = before.split("BEFORE", 1)[0] + self.assertRegex(initial, r"training[^\n]*STEP 0/8 batch") + self.assertRegex(before, r"bytes\.bin[^\n]*1\.00k/4\.00k[^\n]*B/s, file=ok") + self.assertRegex(before, r"training[^\n]*STEP 2/8 batch, loss=0\.42") + self.assertNotIn("training", after) + self.assertIn("1.00k/4.00k", after) + self.assertIn("file=ok", after) + if __name__ == "__main__": unittest.main() From cf3d9cf55ae9f4789941c91f5a319768c556299e Mon Sep 17 00:00:00 2001 From: umran666 Date: Thu, 1 Oct 2026 11:54:53 +0530 Subject: [PATCH 16/31] fix: restore action menu after interrupted uploads --- src/heretic/main.py | 12 ++++++++++-- src/heretic/progress.py | 15 +++++++++++++++ tests/test_progress.py | 42 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 67 insertions(+), 2 deletions(-) diff --git a/src/heretic/main.py b/src/heretic/main.py index f03e148..d11277f 100644 --- a/src/heretic/main.py +++ b/src/heretic/main.py @@ -23,7 +23,7 @@ def _is_help_invocation() -> bool: if _is_help_invocation(): Settings() -from .progress import patch_tqdm +from .progress import close_progress, patch_tqdm # This patches tqdm class definitions, which must happen # before any other module imports tqdm. @@ -1372,7 +1372,7 @@ def run(): first_row = False first_benchmark = False except KeyboardInterrupt: - pass + close_progress() # The benchmark run might have been cancelled by the user # before any benchmark was completed, so we only print results @@ -1380,6 +1380,13 @@ def run(): if table.rows: print(table) + except KeyboardInterrupt: + close_progress() + print() + print("[yellow]Action cancelled.[/]") + # Merging removes the adapters before upload or saving starts. + if model.needs_reload: + reset_trial_model() except Exception as error: formatted = format_exception(error) if "\n" in formatted: @@ -1401,6 +1408,7 @@ def main(): if isinstance(error, KeyboardInterrupt) or isinstance( error.__context__, KeyboardInterrupt ): + close_progress() print() print("[red]Shutting down...[/]") else: diff --git a/src/heretic/progress.py b/src/heretic/progress.py index 4307a91..ddc23e7 100644 --- a/src/heretic/progress.py +++ b/src/heretic/progress.py @@ -100,3 +100,18 @@ class TqdmShim(tqdm.tqdm): def patch_tqdm(): tqdm.tqdm = TqdmShim # ty:ignore[invalid-assignment] tqdm.auto.tqdm = TqdmShim # ty:ignore[invalid-assignment] + + +def close_progress(): + # An interrupted caller can retain an unfinished bar in its traceback. + # Snapshot tqdm's registry before closing: close() removes each instance. + with TqdmShim.get_lock(): + instances = list(TqdmShim._instances) + for instance in instances: + if isinstance(instance, TqdmShim): + instance.close() + with _progress_lock: + # A signal can arrive after add_task() but before its ID is stored. + for task_id in _progress.task_ids: + _progress.remove_task(task_id) + _progress.stop() diff --git a/tests/test_progress.py b/tests/test_progress.py index f1dc6c9..c168bf1 100644 --- a/tests/test_progress.py +++ b/tests/test_progress.py @@ -62,6 +62,48 @@ class ProgressRenderingTests(unittest.TestCase): self.assertEqual(result.returncode, 0, output.decode(errors="replace")) return re.sub(r"\x1b\[[0-?]*[ -/]*[@-~]", "", output.decode()).replace("\r", "") + def test_cancelled_bars_do_not_redraw_over_recovered_prompt(self): + output = self.render(""" +from heretic.progress import TqdmShim, close_progress, _progress + +# Keep the incomplete bars alive, as an interrupted caller's traceback can do. +first = TqdmShim(total=10, desc="cancelled-first", mininterval=0, miniters=1) +second = TqdmShim(total=20, desc="cancelled-second", mininterval=0, miniters=1) +first.update(2) +second.update(3) +_progress.refresh() +original_add_task = _progress.add_task +def interrupted_add_task(*args, **kwargs): + original_add_task(*args, **kwargs) + _progress.refresh() + raise KeyboardInterrupt +_progress.add_task = interrupted_add_task +try: + TqdmShim(total=10, desc="cancelled-constructor") +except KeyboardInterrupt as error: + retained_traceback = error.__traceback__ + close_progress() +finally: + _progress.add_task = original_add_task +assert first.disable and second.disable +assert not _progress.task_ids and not _progress.live.is_started +print("RECOVERED") +first.update(1) +second.update(1) +with TqdmShim(total=10, desc="next-operation", mininterval=0, miniters=1) as bar: + bar.update(5) + _progress.refresh() +assert not _progress.task_ids and not _progress.live.is_started +""") + before, after = output.split("RECOVERED", 1) + self.assertIn("cancelled-first", before) + self.assertIn("cancelled-second", before) + self.assertIn("cancelled-constructor", before) + self.assertNotIn("cancelled-first", after) + self.assertNotIn("cancelled-second", after) + self.assertNotIn("cancelled-constructor", after) + self.assertRegex(after, r"next-operation[^\n]*50%") + def test_completed_download_does_not_redraw_over_later_messages(self): output = self.render(""" import os From c4d260668df70a6e166bfb1d076761a85762fa57 Mon Sep 17 00:00:00 2001 From: umran666 Date: Thu, 1 Oct 2026 12:52:32 +0530 Subject: [PATCH 17/31] fix: recover from interrupted progress and model restoration --- src/heretic/main.py | 12 ++++++++++- src/heretic/model.py | 4 ++-- src/heretic/progress.py | 13 +++++++++--- tests/test_model.py | 47 +++++++++++++++++++++++++++++++++++++++++ tests/test_progress.py | 15 ++++++++++++- 5 files changed, 84 insertions(+), 7 deletions(-) create mode 100644 tests/test_model.py diff --git a/src/heretic/main.py b/src/heretic/main.py index d11277f..b4e0c5c 100644 --- a/src/heretic/main.py +++ b/src/heretic/main.py @@ -850,7 +850,11 @@ def run(): # Per https://github.com/huggingface/peft/issues/868#issuecomment-1820642893 # once a LoRA is merged it's expected to be empty. Provide a utility function # to restore the previous LoRA-ified state. + trial_model_ready = False + def reset_trial_model(): + nonlocal trial_model_ready + trial_model_ready = False ctx = Context(settings=settings, model=model) print("* Resetting model...") modifier.reset_model(ctx) @@ -859,6 +863,7 @@ def run(): trial.user_attrs["parameters"] ) modifier.modify_model(ctx, parameters) + trial_model_ready = True reset_trial_model() @@ -1380,11 +1385,16 @@ def run(): if table.rows: print(table) - except KeyboardInterrupt: + except KeyboardInterrupt as error: close_progress() + # The local and the cancelled call's traceback can retain export weights. + merged_model = None + error.__traceback__ = None print() print("[yellow]Action cancelled.[/]") # Merging removes the adapters before upload or saving starts. + if not trial_model_ready: + model.needs_reload = True if model.needs_reload: reset_trial_model() except Exception as error: diff --git a/src/heretic/model.py b/src/heretic/model.py index 951aa89..deaeaf1 100644 --- a/src/heretic/model.py +++ b/src/heretic/model.py @@ -289,10 +289,10 @@ class Model: else: # Non-quantized model - can merge directly print("* Merging LoRA adapters into base model...") - merged_model = self.model.merge_and_unload() # merge_and_unload() modifies self.model in-place, destroying LoRA adapters. - # Mark for full reload if user switches trials later. + # Mark for full reload before merging, which can be interrupted. self.needs_reload = True + merged_model = self.model.merge_and_unload() return merged_model def reset_model(self) -> bool: diff --git a/src/heretic/progress.py b/src/heretic/progress.py index ddc23e7..b387dfb 100644 --- a/src/heretic/progress.py +++ b/src/heretic/progress.py @@ -84,8 +84,9 @@ class TqdmShim(tqdm.tqdm): def clear(self, *args: Any, **kwargs: Any): with _progress_lock: - if self.rich_task_id is not None: - _progress.remove_task(self.rich_task_id) + task_id = getattr(self, "rich_task_id", None) + if task_id is not None: + _progress.remove_task(task_id) self.rich_task_id = None if not _progress.task_ids: _progress.stop() @@ -93,7 +94,13 @@ class TqdmShim(tqdm.tqdm): _progress.refresh() def close(self, *args: Any, **kwargs: Any): - super().close() + # tqdm sets start_t last; interruption can leave its earlier fields unset. + if hasattr(self, "start_t"): + super().close() + else: + self.disable = True + with self.get_lock(): + self._instances.discard(self) self.clear() diff --git a/tests/test_model.py b/tests/test_model.py new file mode 100644 index 0000000..1a7f35a --- /dev/null +++ b/tests/test_model.py @@ -0,0 +1,47 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +# Copyright (C) 2025-2026 Philipp Emanuel Weidmann + contributors + +import unittest +from unittest.mock import Mock, patch + +import torch +from peft import LoraConfig, get_peft_model +from transformers import GPT2Config, GPT2LMHeadModel + +from heretic.config import QuantizationMethod, Settings +from heretic.model import Model + + +class ModelMergeTests(unittest.TestCase): + def test_interrupted_merge_requires_full_reload(self): + base = GPT2LMHeadModel(GPT2Config(n_layer=1, n_head=1, n_embd=8, vocab_size=16)) + adapter = get_peft_model( + base, + LoraConfig( + r=1, lora_alpha=1, target_modules=["c_attn"], fan_in_fan_out=True + ), + ) + model = object.__new__(Model) + model.model = adapter + model.settings = Mock(spec=Settings, quantization=QuantizationMethod.NONE) + model.needs_reload = False + layer = adapter.base_model.model.transformer.h[0].attn.c_attn + with torch.no_grad(): + layer.lora_A["default"].weight.fill_(1) + layer.lora_B["default"].weight.fill_(1) + before = layer.base_layer.weight.detach().clone() + original_merge = layer.merge + + def interrupted_merge(*args, **kwargs): + original_merge(*args, **kwargs) + raise KeyboardInterrupt + + with patch.object(layer, "merge", side_effect=interrupted_merge): + with self.assertRaises(KeyboardInterrupt): + model.get_merged_model() + self.assertFalse(torch.equal(before, layer.base_layer.weight)) + self.assertTrue(model.needs_reload) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_progress.py b/tests/test_progress.py index c168bf1..e438fd3 100644 --- a/tests/test_progress.py +++ b/tests/test_progress.py @@ -64,6 +64,7 @@ class ProgressRenderingTests(unittest.TestCase): def test_cancelled_bars_do_not_redraw_over_recovered_prompt(self): output = self.render(""" +from unittest.mock import patch from heretic.progress import TqdmShim, close_progress, _progress # Keep the incomplete bars alive, as an interrupted caller's traceback can do. @@ -72,6 +73,18 @@ second = TqdmShim(total=20, desc="cancelled-second", mininterval=0, miniters=1) first.update(2) second.update(3) _progress.refresh() +retained_tracebacks = [] +# Interrupt before and during tqdm's initialization, retaining each failed bar. +for method in ("__init__", "set_postfix"): + with patch.object(TqdmShim.__bases__[0], method, side_effect=KeyboardInterrupt): + try: + TqdmShim(total=10, postfix=dict(status="starting")) + except KeyboardInterrupt as error: + retained_tracebacks.append(error.__traceback__) + close_progress() +# tqdm registers the instance in __new__, before the shim's __init__ runs. +uninitialized = TqdmShim.__new__(TqdmShim) +close_progress() original_add_task = _progress.add_task def interrupted_add_task(*args, **kwargs): original_add_task(*args, **kwargs) @@ -81,7 +94,7 @@ _progress.add_task = interrupted_add_task try: TqdmShim(total=10, desc="cancelled-constructor") except KeyboardInterrupt as error: - retained_traceback = error.__traceback__ + retained_tracebacks.append(error.__traceback__) close_progress() finally: _progress.add_task = original_add_task From 9146ee4217a4346d86765ef4f56eb9e0536a31ba Mon Sep 17 00:00:00 2001 From: umran666 Date: Fri, 2 Oct 2026 11:03:32 +0530 Subject: [PATCH 18/31] fix: use tqdm terminal mode for Rich progress --- src/heretic/progress.py | 39 ++++++++++++++++++------- tests/test_model.py | 24 ++++++++++++---- tests/test_progress.py | 64 ++++++++++++++++++++++++++++++++++++++++- 3 files changed, 109 insertions(+), 18 deletions(-) diff --git a/src/heretic/progress.py b/src/heretic/progress.py index b387dfb..1a9c377 100644 --- a/src/heretic/progress.py +++ b/src/heretic/progress.py @@ -24,16 +24,33 @@ _progress_lock = RLock() class TqdmShim(tqdm.tqdm): def __init__(self, *args: Any, **kwargs: Any): self.rich_task_id: TaskID | None = None - # Use tqdm's bookkeeping without its terminal printer; Rich handles width. - kwargs["gui"] = True kwargs["dynamic_ncols"] = False # Chain up to the parent constructor to ensure that the internal state of the superclass # is correctly initialized, which some methods that we don't override might rely on. super().__init__(*args, **kwargs) self.ncols = None - # GUI mode skips tqdm's initial refresh, so draw the initial Rich task here. - self.display() + + @staticmethod + def status_printer(file: Any) -> None: + # Rich renders the output; tqdm still initializes and tracks terminal bars. + return None + + def refresh(self, nolock: bool = False, lock_args: Any = None) -> bool | None: + if self.disable: + return None + if not nolock: + if lock_args: + if not self._lock.acquire(*lock_args): + return False + else: + self._lock.acquire() + try: + return super().refresh(nolock=True) + finally: + # A cancelled display must not leave tqdm's shared lock held. + if not nolock: + self._lock.release() def update(self, *args: Any, **kwargs: Any) -> bool | None: result = super().update(*args, **kwargs) @@ -54,6 +71,8 @@ class TqdmShim(tqdm.tqdm): # The total can become known after construction; preserve custom formats. format_dict = self.format_dict + # The parent can refresh before our constructor finishes; Rich owns width. + format_dict["ncols"] = None format_dict["bar_format"] = self.bar_format or ( "{n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}{postfix}]" if self.total @@ -94,13 +113,11 @@ class TqdmShim(tqdm.tqdm): _progress.refresh() def close(self, *args: Any, **kwargs: Any): - # tqdm sets start_t last; interruption can leave its earlier fields unset. - if hasattr(self, "start_t"): - super().close() - else: - self.disable = True - with self.get_lock(): - self._instances.discard(self) + # Rich owns row layout; discard without tqdm rearranging other bars. + # This also works when cancellation interrupts tqdm's initialization. + self.disable = True + with self.get_lock(): + self._instances.discard(self) self.clear() diff --git a/tests/test_model.py b/tests/test_model.py index 1a7f35a..c123471 100644 --- a/tests/test_model.py +++ b/tests/test_model.py @@ -6,6 +6,7 @@ from unittest.mock import Mock, patch import torch from peft import LoraConfig, get_peft_model +from peft.tuners.lora.layer import Linear from transformers import GPT2Config, GPT2LMHeadModel from heretic.config import QuantizationMethod, Settings @@ -14,7 +15,16 @@ from heretic.model import Model class ModelMergeTests(unittest.TestCase): def test_interrupted_merge_requires_full_reload(self): - base = GPT2LMHeadModel(GPT2Config(n_layer=1, n_head=1, n_embd=8, vocab_size=16)) + base = GPT2LMHeadModel( + GPT2Config( + n_layer=1, + n_head=1, + n_embd=8, + vocab_size=16, + bos_token_id=0, + eos_token_id=0, + ) + ) adapter = get_peft_model( base, LoraConfig( @@ -25,11 +35,13 @@ class ModelMergeTests(unittest.TestCase): model.model = adapter model.settings = Mock(spec=Settings, quantization=QuantizationMethod.NONE) model.needs_reload = False - layer = adapter.base_model.model.transformer.h[0].attn.c_attn + layer = adapter.get_submodule("base_model.model.transformer.h.0.attn.c_attn") + assert isinstance(layer, Linear) with torch.no_grad(): - layer.lora_A["default"].weight.fill_(1) - layer.lora_B["default"].weight.fill_(1) - before = layer.base_layer.weight.detach().clone() + layer.get_parameter("lora_A.default.weight").fill_(1) + layer.get_parameter("lora_B.default.weight").fill_(1) + weight = layer.get_parameter("base_layer.weight") + before = weight.detach().clone() original_merge = layer.merge def interrupted_merge(*args, **kwargs): @@ -39,7 +51,7 @@ class ModelMergeTests(unittest.TestCase): with patch.object(layer, "merge", side_effect=interrupted_merge): with self.assertRaises(KeyboardInterrupt): model.get_merged_model() - self.assertFalse(torch.equal(before, layer.base_layer.weight)) + self.assertFalse(torch.equal(before, weight)) self.assertTrue(model.needs_reload) diff --git a/tests/test_progress.py b/tests/test_progress.py index e438fd3..c53a006 100644 --- a/tests/test_progress.py +++ b/tests/test_progress.py @@ -62,11 +62,63 @@ class ProgressRenderingTests(unittest.TestCase): self.assertEqual(result.returncode, 0, output.decode(errors="replace")) return re.sub(r"\x1b\[[0-?]*[ -/]*[@-~]", "", output.decode()).replace("\r", "") + def test_terminal_initialization_uses_rich_without_tqdm_printer(self): + output = self.render(""" +import sys +from unittest.mock import patch +from rich import print +from heretic.progress import TqdmShim, _progress + +assert sys.stderr.isatty() +with patch.object(sys.stderr, "write", wraps=sys.stderr.write) as terminal_write: + bars = [] + for description, total, options in [ + ("default", 8, {}), + ("custom", 8, dict(bar_format="STEP {n}/{total} {unit}", leave=False)), + ("unknown", None, dict(unit="item")), + ]: + bar = TqdmShim(total=total, desc=description, disable=None, + mininterval=0, miniters=1, nrows=2, **options) + assert bar.gui is False and bar.sp is None + assert bar.start_t == bar.last_print_t and bar.n == 0 + assert bar.rich_task_id in _progress.task_ids + bars.append(bar) + print("INITIAL") + _progress.refresh() + for bar in bars: + bar.update(2) + print("UPDATED") + _progress.refresh() + bars[0].close() + assert _progress.live.is_started + assert _progress.task_ids == [bar.rich_task_id for bar in bars[1:]] + bars[1].close() + assert _progress.live.is_started + assert _progress.task_ids == [bars[2].rich_task_id] + bars[2].close() + assert not _progress.task_ids and not _progress.live.is_started + assert not any(call.args[0] for call in terminal_write.call_args_list) +print("CLOSED") +""") + initial, updated = output.split("UPDATED", 1) + self.assertRegex(initial, r"default[^\n]*0/8 \[00:00<\?, \?it/s\]") + self.assertRegex(initial, r"custom[^\n]*STEP 0/8 it") + self.assertRegex(initial, r"unknown[^\n]*0item \[00:00, \?item/s\]") + updated, closed = updated.split("CLOSED", 1) + self.assertRegex(updated, r"default[^\n]*2/8") + self.assertRegex(updated, r"custom[^\n]*STEP 2/8 it") + self.assertRegex(updated, r"unknown[^\n]*2item") + for description in ("default", "custom", "unknown"): + self.assertNotIn(description, closed) + def test_cancelled_bars_do_not_redraw_over_recovered_prompt(self): output = self.render(""" +from concurrent.futures import ThreadPoolExecutor +from threading import RLock from unittest.mock import patch from heretic.progress import TqdmShim, close_progress, _progress +TqdmShim.set_lock(RLock()) # Keep the incomplete bars alive, as an interrupted caller's traceback can do. first = TqdmShim(total=10, desc="cancelled-first", mininterval=0, miniters=1) second = TqdmShim(total=20, desc="cancelled-second", mininterval=0, miniters=1) @@ -98,6 +150,14 @@ except KeyboardInterrupt as error: close_progress() finally: _progress.add_task = original_add_task +def acquire_tqdm_lock(): + lock = TqdmShim.get_lock() + acquired = lock.acquire(blocking=False) + if acquired: + lock.release() + return acquired +with ThreadPoolExecutor(max_workers=1) as worker: + assert worker.submit(acquire_tqdm_lock).result(timeout=5) assert first.disable and second.disable assert not _progress.task_ids and not _progress.live.is_started print("RECOVERED") @@ -174,7 +234,9 @@ for description, total, count, options in [ ("training", 8, 2, dict(unit="batch")), ("unknown", None, 3, dict(unit="item")), ]: - bar = TqdmShim(total=total, desc=description, mininterval=0, **options) + bar = TqdmShim(total=total, desc=description, mininterval=0, miniters=1, **options) + # Use one elapsed second so clock resolution cannot hide the numeric rate. + bar._time = lambda start_t=bar.start_t: start_t + 1 bar.update(count) if total is None: bar.set_postfix_str("loss=0.42, note=[ok]") From f6723eade7948ab3204dd05ac3934b1db9123db7 Mon Sep 17 00:00:00 2001 From: umran666 Date: Fri, 2 Oct 2026 11:31:51 +0530 Subject: [PATCH 19/31] fix: retry interrupted Rich task cleanup safely --- src/heretic/progress.py | 4 +++- tests/test_progress.py | 17 +++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/src/heretic/progress.py b/src/heretic/progress.py index 1a9c377..2050017 100644 --- a/src/heretic/progress.py +++ b/src/heretic/progress.py @@ -105,7 +105,9 @@ class TqdmShim(tqdm.tqdm): with _progress_lock: task_id = getattr(self, "rich_task_id", None) if task_id is not None: - _progress.remove_task(task_id) + # Cancellation can interrupt removal before the ID is cleared. + if task_id in _progress.task_ids: + _progress.remove_task(task_id) self.rich_task_id = None if not _progress.task_ids: _progress.stop() diff --git a/tests/test_progress.py b/tests/test_progress.py index c53a006..a35989b 100644 --- a/tests/test_progress.py +++ b/tests/test_progress.py @@ -150,6 +150,21 @@ except KeyboardInterrupt as error: close_progress() finally: _progress.add_task = original_add_task + +# Interrupt after Rich deletes a task, before the shim clears its stored ID. +removing = TqdmShim(total=1, desc="cancelled-removal", mininterval=0, miniters=1) +_progress.refresh() +original_remove_task = _progress.remove_task +def interrupted_remove_task(task_id): + original_remove_task(task_id) + raise KeyboardInterrupt +with patch.object(_progress, "remove_task", side_effect=interrupted_remove_task): + try: + removing.update(1) + except KeyboardInterrupt as error: + retained_tracebacks.append(error.__traceback__) +close_progress() + def acquire_tqdm_lock(): lock = TqdmShim.get_lock() acquired = lock.acquire(blocking=False) @@ -172,9 +187,11 @@ assert not _progress.task_ids and not _progress.live.is_started self.assertIn("cancelled-first", before) self.assertIn("cancelled-second", before) self.assertIn("cancelled-constructor", before) + self.assertIn("cancelled-removal", before) self.assertNotIn("cancelled-first", after) self.assertNotIn("cancelled-second", after) self.assertNotIn("cancelled-constructor", after) + self.assertNotIn("cancelled-removal", after) self.assertRegex(after, r"next-operation[^\n]*50%") def test_completed_download_does_not_redraw_over_later_messages(self): From 86647952ea157cce40efcc12c5d8b0db75638b86 Mon Sep 17 00:00:00 2001 From: umran666 Date: Sun, 4 Oct 2026 20:05:05 +0530 Subject: [PATCH 20/31] fix: keep progress cleanup inside the shim and simplify tests --- pyproject.toml | 1 - src/heretic/main.py | 22 +-- src/heretic/model.py | 6 +- src/heretic/progress.py | 34 ++-- tests/test_model.py | 59 ------ tests/test_progress.py | 423 ++++++++++++---------------------------- uv.lock | 17 -- 7 files changed, 145 insertions(+), 417 deletions(-) delete mode 100644 tests/test_model.py diff --git a/pyproject.toml b/pyproject.toml index 07bbb57..83b5a7d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -45,7 +45,6 @@ dependencies = [ [dependency-groups] dev = [ - "pywinpty==3.0.2; sys_platform == 'win32'", "ruff>=0.16.9", "ty>=0.0.84", ] diff --git a/src/heretic/main.py b/src/heretic/main.py index b4e0c5c..f03e148 100644 --- a/src/heretic/main.py +++ b/src/heretic/main.py @@ -23,7 +23,7 @@ def _is_help_invocation() -> bool: if _is_help_invocation(): Settings() -from .progress import close_progress, patch_tqdm +from .progress import patch_tqdm # This patches tqdm class definitions, which must happen # before any other module imports tqdm. @@ -850,11 +850,7 @@ def run(): # Per https://github.com/huggingface/peft/issues/868#issuecomment-1820642893 # once a LoRA is merged it's expected to be empty. Provide a utility function # to restore the previous LoRA-ified state. - trial_model_ready = False - def reset_trial_model(): - nonlocal trial_model_ready - trial_model_ready = False ctx = Context(settings=settings, model=model) print("* Resetting model...") modifier.reset_model(ctx) @@ -863,7 +859,6 @@ def run(): trial.user_attrs["parameters"] ) modifier.modify_model(ctx, parameters) - trial_model_ready = True reset_trial_model() @@ -1377,7 +1372,7 @@ def run(): first_row = False first_benchmark = False except KeyboardInterrupt: - close_progress() + pass # The benchmark run might have been cancelled by the user # before any benchmark was completed, so we only print results @@ -1385,18 +1380,6 @@ def run(): if table.rows: print(table) - except KeyboardInterrupt as error: - close_progress() - # The local and the cancelled call's traceback can retain export weights. - merged_model = None - error.__traceback__ = None - print() - print("[yellow]Action cancelled.[/]") - # Merging removes the adapters before upload or saving starts. - if not trial_model_ready: - model.needs_reload = True - if model.needs_reload: - reset_trial_model() except Exception as error: formatted = format_exception(error) if "\n" in formatted: @@ -1418,7 +1401,6 @@ def main(): if isinstance(error, KeyboardInterrupt) or isinstance( error.__context__, KeyboardInterrupt ): - close_progress() print() print("[red]Shutting down...[/]") else: diff --git a/src/heretic/model.py b/src/heretic/model.py index deaeaf1..951aa89 100644 --- a/src/heretic/model.py +++ b/src/heretic/model.py @@ -289,10 +289,10 @@ class Model: else: # Non-quantized model - can merge directly print("* Merging LoRA adapters into base model...") - # merge_and_unload() modifies self.model in-place, destroying LoRA adapters. - # Mark for full reload before merging, which can be interrupted. - self.needs_reload = True merged_model = self.model.merge_and_unload() + # merge_and_unload() modifies self.model in-place, destroying LoRA adapters. + # Mark for full reload if user switches trials later. + self.needs_reload = True return merged_model def reset_model(self) -> bool: diff --git a/src/heretic/progress.py b/src/heretic/progress.py index 2050017..f1e6c72 100644 --- a/src/heretic/progress.py +++ b/src/heretic/progress.py @@ -81,11 +81,20 @@ class TqdmShim(tqdm.tqdm): stats = self.format_meter(**format_dict) if self.rich_task_id is None: - if not _progress.task_ids: - _progress.start() - self.rich_task_id = _progress.add_task( - self.desc or "", total=self.total, completed=self.n, stats=stats - ) + previous_tasks = set(_progress.task_ids) + try: + if not previous_tasks: + _progress.start() + self.rich_task_id = _progress.add_task( + self.desc or "", total=self.total, completed=self.n, stats=stats + ) + except BaseException: + # Task creation can be interrupted before its ID is returned. + for task_id in set(_progress.task_ids) - previous_tasks: + _progress.remove_task(task_id) + if not _progress.task_ids: + _progress.stop() + raise else: _progress.update( self.rich_task_id, @@ -126,18 +135,3 @@ class TqdmShim(tqdm.tqdm): def patch_tqdm(): tqdm.tqdm = TqdmShim # ty:ignore[invalid-assignment] tqdm.auto.tqdm = TqdmShim # ty:ignore[invalid-assignment] - - -def close_progress(): - # An interrupted caller can retain an unfinished bar in its traceback. - # Snapshot tqdm's registry before closing: close() removes each instance. - with TqdmShim.get_lock(): - instances = list(TqdmShim._instances) - for instance in instances: - if isinstance(instance, TqdmShim): - instance.close() - with _progress_lock: - # A signal can arrive after add_task() but before its ID is stored. - for task_id in _progress.task_ids: - _progress.remove_task(task_id) - _progress.stop() diff --git a/tests/test_model.py b/tests/test_model.py deleted file mode 100644 index c123471..0000000 --- a/tests/test_model.py +++ /dev/null @@ -1,59 +0,0 @@ -# SPDX-License-Identifier: AGPL-3.0-or-later -# Copyright (C) 2025-2026 Philipp Emanuel Weidmann + contributors - -import unittest -from unittest.mock import Mock, patch - -import torch -from peft import LoraConfig, get_peft_model -from peft.tuners.lora.layer import Linear -from transformers import GPT2Config, GPT2LMHeadModel - -from heretic.config import QuantizationMethod, Settings -from heretic.model import Model - - -class ModelMergeTests(unittest.TestCase): - def test_interrupted_merge_requires_full_reload(self): - base = GPT2LMHeadModel( - GPT2Config( - n_layer=1, - n_head=1, - n_embd=8, - vocab_size=16, - bos_token_id=0, - eos_token_id=0, - ) - ) - adapter = get_peft_model( - base, - LoraConfig( - r=1, lora_alpha=1, target_modules=["c_attn"], fan_in_fan_out=True - ), - ) - model = object.__new__(Model) - model.model = adapter - model.settings = Mock(spec=Settings, quantization=QuantizationMethod.NONE) - model.needs_reload = False - layer = adapter.get_submodule("base_model.model.transformer.h.0.attn.c_attn") - assert isinstance(layer, Linear) - with torch.no_grad(): - layer.get_parameter("lora_A.default.weight").fill_(1) - layer.get_parameter("lora_B.default.weight").fill_(1) - weight = layer.get_parameter("base_layer.weight") - before = weight.detach().clone() - original_merge = layer.merge - - def interrupted_merge(*args, **kwargs): - original_merge(*args, **kwargs) - raise KeyboardInterrupt - - with patch.object(layer, "merge", side_effect=interrupted_merge): - with self.assertRaises(KeyboardInterrupt): - model.get_merged_model() - self.assertFalse(torch.equal(before, weight)) - self.assertTrue(model.needs_reload) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_progress.py b/tests/test_progress.py index a35989b..2f489fb 100644 --- a/tests/test_progress.py +++ b/tests/test_progress.py @@ -1,322 +1,151 @@ # SPDX-License-Identifier: AGPL-3.0-or-later # Copyright (C) 2025-2026 Philipp Emanuel Weidmann + contributors -import errno import os -import re -import subprocess -import sys import unittest +from contextlib import ExitStack +from io import StringIO +from unittest.mock import patch + +from rich.console import Console +from rich.progress import Progress + +from heretic import progress class ProgressRenderingTests(unittest.TestCase): - def render(self, code): - env = {**os.environ, "TERM": "xterm", "COLUMNS": "120", "PYTHONUTF8": "1"} - if sys.platform == "win32": - from winpty import PtyProcess + def setUp(self): + self.patches = ExitStack() + self.addCleanup(self.patches.close) + self.output = StringIO() + self.patches.enter_context(patch.dict(os.environ, {"TERM": "xterm"})) + self.patch(self.output, "isatty", return_value=True) + self.console = Console( + file=self.output, + width=120, + color_system=None, + force_terminal=True, + force_interactive=True, + force_jupyter=False, + legacy_windows=False, + ) + self.displays = [] - process = PtyProcess.spawn( - [sys.executable, "-c", code], env=env, dimensions=(24, 120) + def make_progress(*columns, **options): + options.update(console=self.console, auto_refresh=False) + display = Progress(*columns, **options) + self.displays.append(display) + self.addCleanup(display.stop) + return display + + self.patch(progress, "Progress", side_effect=make_progress) + shared = getattr(progress, "_progress", None) + if shared is not None: + self.patch( + progress, + "_progress", + new=make_progress(*shared.columns, transient=True), ) - process.fileobj.settimeout(30) - chunks = [] - try: - while True: - try: - chunks.append(process.read()) - except EOFError: - break - finally: - process.close(force=True) - output_text = "".join(chunks) - self.assertEqual(process.exitstatus, 0, output_text) - return re.sub(r"\x1b\[[0-?]*[ -/]*[@-~]", "", output_text).replace("\r", "") - import pty - master, slave = pty.openpty() - try: - try: - result = subprocess.run( - [sys.executable, "-c", code], - stdout=slave, - stderr=slave, - env=env, - timeout=30, - check=False, - ) - finally: - os.close(slave) - output = bytearray() - while True: - try: - chunk = os.read(master, 4096) - except OSError as error: - if error.errno != errno.EIO: - raise - break - if not chunk: - break - output.extend(chunk) - finally: - os.close(master) - self.assertEqual(result.returncode, 0, output.decode(errors="replace")) - return re.sub(r"\x1b\[[0-?]*[ -/]*[@-~]", "", output.decode()).replace("\r", "") + def patch(self, target, attribute, **options): + self.patches.enter_context(patch.object(target, attribute, **options)) - def test_terminal_initialization_uses_rich_without_tqdm_printer(self): - output = self.render(""" -import sys -from unittest.mock import patch -from rich import print -from heretic.progress import TqdmShim, _progress + def bar(self, description, **options): + options = {"total": 100, "mininterval": 0, "miniters": 1, **options} + bar = progress.TqdmShim( + desc=description, file=self.output, disable=None, **options + ) + self.addCleanup(bar.close) + return bar -assert sys.stderr.isatty() -with patch.object(sys.stderr, "write", wraps=sys.stderr.write) as terminal_write: - bars = [] - for description, total, options in [ - ("default", 8, {}), - ("custom", 8, dict(bar_format="STEP {n}/{total} {unit}", leave=False)), - ("unknown", None, dict(unit="item")), - ]: - bar = TqdmShim(total=total, desc=description, disable=None, - mininterval=0, miniters=1, nrows=2, **options) - assert bar.gui is False and bar.sp is None - assert bar.start_t == bar.last_print_t and bar.n == 0 - assert bar.rich_task_id in _progress.task_ids - bars.append(bar) - print("INITIAL") - _progress.refresh() - for bar in bars: - bar.update(2) - print("UPDATED") - _progress.refresh() - bars[0].close() - assert _progress.live.is_started - assert _progress.task_ids == [bar.rich_task_id for bar in bars[1:]] - bars[1].close() - assert _progress.live.is_started - assert _progress.task_ids == [bars[2].rich_task_id] - bars[2].close() - assert not _progress.task_ids and not _progress.live.is_started - assert not any(call.args[0] for call in terminal_write.call_args_list) -print("CLOSED") -""") - initial, updated = output.split("UPDATED", 1) - self.assertRegex(initial, r"default[^\n]*0/8 \[00:00<\?, \?it/s\]") - self.assertRegex(initial, r"custom[^\n]*STEP 0/8 it") - self.assertRegex(initial, r"unknown[^\n]*0item \[00:00, \?item/s\]") - updated, closed = updated.split("CLOSED", 1) - self.assertRegex(updated, r"default[^\n]*2/8") - self.assertRegex(updated, r"custom[^\n]*STEP 2/8 it") - self.assertRegex(updated, r"unknown[^\n]*2item") - for description in ("default", "custom", "unknown"): - self.assertNotIn(description, closed) + def refresh(self): + for display in self.displays: + display.refresh() - def test_cancelled_bars_do_not_redraw_over_recovered_prompt(self): - output = self.render(""" -from concurrent.futures import ThreadPoolExecutor -from threading import RLock -from unittest.mock import patch -from heretic.progress import TqdmShim, close_progress, _progress - -TqdmShim.set_lock(RLock()) -# Keep the incomplete bars alive, as an interrupted caller's traceback can do. -first = TqdmShim(total=10, desc="cancelled-first", mininterval=0, miniters=1) -second = TqdmShim(total=20, desc="cancelled-second", mininterval=0, miniters=1) -first.update(2) -second.update(3) -_progress.refresh() -retained_tracebacks = [] -# Interrupt before and during tqdm's initialization, retaining each failed bar. -for method in ("__init__", "set_postfix"): - with patch.object(TqdmShim.__bases__[0], method, side_effect=KeyboardInterrupt): - try: - TqdmShim(total=10, postfix=dict(status="starting")) - except KeyboardInterrupt as error: - retained_tracebacks.append(error.__traceback__) - close_progress() -# tqdm registers the instance in __new__, before the shim's __init__ runs. -uninitialized = TqdmShim.__new__(TqdmShim) -close_progress() -original_add_task = _progress.add_task -def interrupted_add_task(*args, **kwargs): - original_add_task(*args, **kwargs) - _progress.refresh() - raise KeyboardInterrupt -_progress.add_task = interrupted_add_task -try: - TqdmShim(total=10, desc="cancelled-constructor") -except KeyboardInterrupt as error: - retained_tracebacks.append(error.__traceback__) - close_progress() -finally: - _progress.add_task = original_add_task - -# Interrupt after Rich deletes a task, before the shim clears its stored ID. -removing = TqdmShim(total=1, desc="cancelled-removal", mininterval=0, miniters=1) -_progress.refresh() -original_remove_task = _progress.remove_task -def interrupted_remove_task(task_id): - original_remove_task(task_id) - raise KeyboardInterrupt -with patch.object(_progress, "remove_task", side_effect=interrupted_remove_task): - try: - removing.update(1) - except KeyboardInterrupt as error: - retained_tracebacks.append(error.__traceback__) -close_progress() - -def acquire_tqdm_lock(): - lock = TqdmShim.get_lock() - acquired = lock.acquire(blocking=False) - if acquired: - lock.release() - return acquired -with ThreadPoolExecutor(max_workers=1) as worker: - assert worker.submit(acquire_tqdm_lock).result(timeout=5) -assert first.disable and second.disable -assert not _progress.task_ids and not _progress.live.is_started -print("RECOVERED") -first.update(1) -second.update(1) -with TqdmShim(total=10, desc="next-operation", mininterval=0, miniters=1) as bar: - bar.update(5) - _progress.refresh() -assert not _progress.task_ids and not _progress.live.is_started -""") - before, after = output.split("RECOVERED", 1) - self.assertIn("cancelled-first", before) - self.assertIn("cancelled-second", before) - self.assertIn("cancelled-constructor", before) - self.assertIn("cancelled-removal", before) - self.assertNotIn("cancelled-first", after) - self.assertNotIn("cancelled-second", after) - self.assertNotIn("cancelled-constructor", after) - self.assertNotIn("cancelled-removal", after) - self.assertRegex(after, r"next-operation[^\n]*50%") + def output_after(self, message): + self.console.print(message) + self.refresh() + return self.output.getvalue().split(message, 1)[1] def test_completed_download_does_not_redraw_over_later_messages(self): - output = self.render(""" -import os -from rich import print -from heretic.progress import TqdmShim -assert os.isatty(2) -bar = TqdmShim(total=100, desc="download.bin", disable=None, mininterval=3600) -# Force frames at the two checkpoints instead of relying on Rich's refresh thread. -progress = getattr(bar, "rich_progress", None) -if progress is None: - from heretic.progress import _progress as progress -bar.update(50) -bar.refresh() -progress.refresh() -# mininterval=3600 prevents a final refresh; the caller keeps the bar alive. -bar.update(50) -print("AFTER") -print("Testing batch size") -if progress.live.is_started: - progress.refresh() -bar.close() -""") - halfway, after = output.split("AFTER", 1) - self.assertIn("Testing batch size", after) - self.assertNotIn("download.bin", after) - self.assertRegex(halfway, r"download\.bin[^\n]*50%") + bar = self.bar("download.bin", mininterval=3600) + bar.update(50) + bar.refresh() + self.refresh() + self.assertIn("50%", self.output.getvalue()) + bar.update(50) + self.assertNotIn("download.bin", self.output_after("AFTER")) def test_closing_earlier_bar_keeps_later_bar_rendering(self): - output = self.render(""" -from concurrent.futures import ThreadPoolExecutor -from rich import print -from heretic.progress import TqdmShim -with ThreadPoolExecutor(max_workers=1) as worker: - first = worker.submit(TqdmShim, total=100, desc="first.bin").result() - second = TqdmShim(total=100, desc="second.bin", disable=None, mininterval=0) - worker.submit(first.close).result() - second.update(50) - print("AFTER") - progress = getattr(second, "rich_progress", None) - if progress is None: - from heretic.progress import _progress as progress - progress.refresh() - second.close() -""") - after = output.split("AFTER", 1)[1] + first = self.bar("first.bin") + second = self.bar("second.bin") + first.close() + second.update(50) + after = self.output_after("AFTER") self.assertRegex(after, r"second\.bin[^\n]*50%") self.assertNotIn("first.bin", after) - def test_counts_units_rates_and_postfix_are_preserved(self): - output = self.render(""" -from rich import print -from heretic.progress import TqdmShim -for description, total, count, options in [ - ("bytes.bin", 4096, 1024, dict(unit="B", unit_scale=True, unit_divisor=1024)), - ("training", 8, 2, dict(unit="batch")), - ("unknown", None, 3, dict(unit="item")), -]: - bar = TqdmShim(total=total, desc=description, mininterval=0, miniters=1, **options) - # Use one elapsed second so clock resolution cannot hide the numeric rate. - bar._time = lambda start_t=bar.start_t: start_t + 1 - bar.update(count) - if total is None: - bar.set_postfix_str("loss=0.42, note=[ok]") - else: - bar.set_postfix(loss=0.42, note="[ok]") - print("CHECK " + description) - progress = getattr(bar, "rich_progress", None) - if progress is None: - from heretic.progress import _progress as progress - progress.refresh() - bar.close() - print("END " + description) -""") - for description, counts, unit in [ - ("bytes.bin", "1.00k/4.00k", "B"), - ("training", "2/8", "batch"), - ("unknown", "3item", "item"), - ]: - with self.subTest(description=description): - frame = output.split("CHECK " + description, 1)[1].split( - "END " + description, 1 - )[0] - self.assertIn(description, frame) - self.assertIn(counts, frame) - self.assertRegex( - frame, - r"\d[\d.]*[kMGTPEZYmunpf]?" - + rf"(?:{unit}/s|s/{unit})[^\n]*loss=0\.42, note=\[ok\]", - ) - if description != "unknown": - self.assertRegex(frame, r"\[\d+:\d+<\d+:\d+,") + def test_overlapping_bars_keep_counts_units_and_literal_postfix(self): + download = self.bar( + "bytes.bin", total=4096, unit="B", unit_scale=True, unit_divisor=1024 + ) + training = self.bar( + "training", + total=8, + unit="batch", + bar_format="STEP {n}/{total} {unit}{postfix}", + ) + self.patch(download, "_time", return_value=download.start_t + 1) + download.update(1024) + download.set_postfix_str("file=[ok]") + training.update(2) + training.set_postfix(loss=0.42) + self.refresh() + output = self.output.getvalue() + self.assertRegex( + output, r"bytes\.bin[^\n]*1\.00k/4\.00k[^\n]*1\.02kB/s, file=\[ok\]" + ) + self.assertRegex(output, r"training[^\n]*STEP 2/8 batch, loss=0\.42") - def test_overlapping_bars_keep_their_own_formats(self): - output = self.render(""" -from rich import print -from heretic.progress import TqdmShim, _progress -download = TqdmShim(total=None, desc="bytes.bin", unit="B", unit_scale=True, - unit_divisor=1024, mininterval=0, miniters=1) -training = TqdmShim(total=8, desc="training", unit="batch", mininterval=0, - miniters=1, bar_format="STEP {n}/{total} {unit}{postfix}") -print("INITIAL") -_progress.refresh() -download.update(1024) -download.set_postfix_str("file=ok") -download.total = 4096 -download.refresh() -training.update(2) -training.set_postfix(loss=0.42) -print("BEFORE") -_progress.refresh() -training.close() -print("AFTER") -_progress.refresh() -download.close() -""") - before, after = output.split("AFTER", 1) - initial = before.split("BEFORE", 1)[0] - self.assertRegex(initial, r"training[^\n]*STEP 0/8 batch") - self.assertRegex(before, r"bytes\.bin[^\n]*1\.00k/4\.00k[^\n]*B/s, file=ok") - self.assertRegex(before, r"training[^\n]*STEP 2/8 batch, loss=0\.42") - self.assertNotIn("training", after) - self.assertIn("1.00k/4.00k", after) - self.assertIn("file=ok", after) + def test_context_manager_cancellation_stops_display(self): + with self.assertRaises(KeyboardInterrupt): + with self.bar("cancelled.bin") as bar: + bar.update(25) + raise KeyboardInterrupt + self.assertTrue(all(not display.live.is_started for display in self.displays)) + self.assertNotIn("cancelled.bin", self.output_after("RECOVERED")) + + def test_close_recovers_when_task_removal_is_interrupted(self): + bar = self.bar("interrupted.bin", total=1) + display = self.displays[0] + remove_task = display.remove_task + + def interrupted_remove(task_id): + remove_task(task_id) + raise KeyboardInterrupt + + with patch.object(display, "remove_task", side_effect=interrupted_remove): + with self.assertRaises(KeyboardInterrupt): + bar.update(1) + bar.close() + self.assertFalse(display.task_ids) + self.assertFalse(display.live.is_started) + + def test_initialization_cancellation_stops_unowned_display(self): + display = self.displays[0] + for method in ("start", "add_task"): + with self.subTest(method=method): + original = getattr(display, method) + + def interrupted(*args, **kwargs): + original(*args, **kwargs) + raise KeyboardInterrupt + + with patch.object(display, method, side_effect=interrupted): + with self.assertRaises(KeyboardInterrupt): + self.bar("interrupted.bin") + self.assertFalse(display.task_ids) + self.assertFalse(display.live.is_started) if __name__ == "__main__": diff --git a/uv.lock b/uv.lock index 40f4ee6..f79c1b4 100644 --- a/uv.lock +++ b/uv.lock @@ -1067,7 +1067,6 @@ dependencies = [ [package.dev-dependencies] dev = [ - { name = "pywinpty", marker = "sys_platform == 'win32'" }, { name = "ruff" }, { name = "ty" }, ] @@ -1098,7 +1097,6 @@ requires-dist = [ [package.metadata.requires-dev] dev = [ - { name = "pywinpty", marker = "sys_platform == 'win32'", specifier = "==3.0.2" }, { name = "ruff", specifier = ">=0.16.9" }, { name = "ty", specifier = ">=0.0.84" }, ] @@ -2962,21 +2960,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/d5/11/e3df59614bebe0ca50c905442603eda64ae7ac19811d4e4f74aa2d51ca85/pytz-2026.4-py2.py3-none-any.whl", hash = "sha256:9d514388fbc89ca0833203464272ac485b8828568ab73532f5020f17e892a0ff", size = 506747, upload-time = "2026-09-24T03:58:38.629Z" }, ] -[[package]] -name = "pywinpty" -version = "3.0.2" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/f3/bb/a7cc2967c5c4eceb6cc49cfe39447d4bfc56e6c865e7c2249b6eb978935f/pywinpty-3.0.2.tar.gz", hash = "sha256:1505cc4cb248af42cb6285a65c9c2086ee9e7e574078ee60933d5d7fa86fb004", size = 30669, upload-time = "2025-10-03T21:16:29.205Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/3e/f5/b17ae550841949c217ad557ee445b4a14e9c0b506ae51ee087eff53428a6/pywinpty-3.0.2-cp310-cp310-win_amd64.whl", hash = "sha256:65db57fd3387d71e8372b6a54269cbcd0f6dfa6d4616a29e0af749ec19f5c558", size = 2050330, upload-time = "2025-10-03T21:20:15.656Z" }, - { url = "https://files.pythonhosted.org/packages/a6/a1/409c1651c9f874d598c10f51ff586c416625601df4bca315d08baec4c3e3/pywinpty-3.0.2-cp311-cp311-win_amd64.whl", hash = "sha256:327790d70e4c841ebd9d0f295a780177149aeb405bca44c7115a3de5c2054b23", size = 2050304, upload-time = "2025-10-03T21:19:29.466Z" }, - { url = "https://files.pythonhosted.org/packages/02/4e/1098484e042c9485f56f16eb2b69b43b874bd526044ee401512234cf9e04/pywinpty-3.0.2-cp312-cp312-win_amd64.whl", hash = "sha256:99fdd9b455f0ad6419aba6731a7a0d2f88ced83c3c94a80ff9533d95fa8d8a9e", size = 2050391, upload-time = "2025-10-03T21:19:01.642Z" }, - { url = "https://files.pythonhosted.org/packages/fc/19/b757fe28008236a4a713e813283721b8a40aa60cd7d3f83549f2e25a3155/pywinpty-3.0.2-cp313-cp313-win_amd64.whl", hash = "sha256:18f78b81e4cfee6aabe7ea8688441d30247b73e52cd9657138015c5f4ee13a51", size = 2050057, upload-time = "2025-10-03T21:19:26.732Z" }, - { url = "https://files.pythonhosted.org/packages/cb/44/cbae12ecf6f4fa4129c36871fd09c6bef4f98d5f625ecefb5e2449765508/pywinpty-3.0.2-cp313-cp313t-win_amd64.whl", hash = "sha256:663383ecfab7fc382cc97ea5c4f7f0bb32c2f889259855df6ea34e5df42d305b", size = 2049874, upload-time = "2025-10-03T21:18:53.923Z" }, - { url = "https://files.pythonhosted.org/packages/ca/15/f12c6055e2d7a617d4d5820e8ac4ceaff849da4cb124640ef5116a230771/pywinpty-3.0.2-cp314-cp314-win_amd64.whl", hash = "sha256:28297cecc37bee9f24d8889e47231972d6e9e84f7b668909de54f36ca785029a", size = 2050386, upload-time = "2025-10-03T21:18:50.477Z" }, - { url = "https://files.pythonhosted.org/packages/de/24/c6907c5bb06043df98ad6a0a0ff5db2e0affcecbc3b15c42404393a3f72a/pywinpty-3.0.2-cp314-cp314t-win_amd64.whl", hash = "sha256:34b55ae9a1b671fe3eae071d86618110538e8eaad18fcb1531c0830b91a82767", size = 2049834, upload-time = "2025-10-03T21:19:25.688Z" }, -] - [[package]] name = "pyyaml" version = "6.0.3" From 25d37bfac47d230cbbec80c64fda8ab60f78a74c Mon Sep 17 00:00:00 2001 From: umran666 Date: Tue, 6 Oct 2026 14:03:20 +0530 Subject: [PATCH 21/31] refactor: remove redundant tqdm printer and width overrides --- src/heretic/progress.py | 7 ------- 1 file changed, 7 deletions(-) diff --git a/src/heretic/progress.py b/src/heretic/progress.py index f1e6c72..2699831 100644 --- a/src/heretic/progress.py +++ b/src/heretic/progress.py @@ -24,17 +24,10 @@ _progress_lock = RLock() class TqdmShim(tqdm.tqdm): def __init__(self, *args: Any, **kwargs: Any): self.rich_task_id: TaskID | None = None - kwargs["dynamic_ncols"] = False # Chain up to the parent constructor to ensure that the internal state of the superclass # is correctly initialized, which some methods that we don't override might rely on. super().__init__(*args, **kwargs) - self.ncols = None - - @staticmethod - def status_printer(file: Any) -> None: - # Rich renders the output; tqdm still initializes and tracks terminal bars. - return None def refresh(self, nolock: bool = False, lock_args: Any = None) -> bool | None: if self.disable: From f870c325b93fe04b2f97e0677032e324361e9891 Mon Sep 17 00:00:00 2001 From: umran666 Date: Wed, 7 Oct 2026 17:15:19 +0530 Subject: [PATCH 22/31] fix: render custom progress formats once --- src/heretic/progress.py | 28 ++++++++++++++++++++++++++-- tests/test_progress.py | 39 +++++++++++++++++++++++++++++++++++++-- 2 files changed, 63 insertions(+), 4 deletions(-) diff --git a/src/heretic/progress.py b/src/heretic/progress.py index 2699831..279f6a8 100644 --- a/src/heretic/progress.py +++ b/src/heretic/progress.py @@ -1,15 +1,34 @@ # SPDX-License-Identifier: AGPL-3.0-or-later # Copyright (C) 2025-2026 Philipp Emanuel Weidmann + contributors +from collections.abc import Iterable +from itertools import groupby from threading import RLock from typing import Any import tqdm import tqdm.auto +from rich.console import RenderableType from rich.progress import BarColumn, Progress, TaskID, TaskProgressColumn, TextColumn +from rich.text import Text + + +class _Progress(Progress): + def get_renderables(self) -> Iterable[RenderableType]: + for custom, tasks in groupby( + self.tasks, key=lambda task: task.fields["custom"] + ): + if custom: + # bar_format specifies the whole row, including any label and bar. + for task in tasks: + if task.visible: + yield Text.from_ansi(task.fields["stats"]) + else: + yield self.make_tasks_table(tasks) + # A single live display lets individual bars close in any order. -_progress = Progress( +_progress = _Progress( TextColumn("{task.description}", style="progress.description", markup=False), BarColumn(), TaskProgressColumn(), @@ -79,7 +98,11 @@ class TqdmShim(tqdm.tqdm): if not previous_tasks: _progress.start() self.rich_task_id = _progress.add_task( - self.desc or "", total=self.total, completed=self.n, stats=stats + self.desc or "", + total=self.total, + completed=self.n, + stats=stats, + custom=bool(self.bar_format), ) except BaseException: # Task creation can be interrupted before its ID is returned. @@ -95,6 +118,7 @@ class TqdmShim(tqdm.tqdm): total=self.total, completed=self.n, stats=stats, + custom=bool(self.bar_format), ) def _clear_completed(self) -> bool: diff --git a/tests/test_progress.py b/tests/test_progress.py index 2f489fb..f9ff0a0 100644 --- a/tests/test_progress.py +++ b/tests/test_progress.py @@ -33,7 +33,7 @@ class ProgressRenderingTests(unittest.TestCase): def make_progress(*columns, **options): options.update(console=self.console, auto_refresh=False) - display = Progress(*columns, **options) + display = getattr(progress, "_Progress", Progress)(*columns, **options) self.displays.append(display) self.addCleanup(display.stop) return display @@ -105,7 +105,42 @@ class ProgressRenderingTests(unittest.TestCase): self.assertRegex( output, r"bytes\.bin[^\n]*1\.00k/4\.00k[^\n]*1\.02kB/s, file=\[ok\]" ) - self.assertRegex(output, r"training[^\n]*STEP 2/8 batch, loss=0\.42") + self.assertIn("STEP 2/8 batch, loss=0.42", output) + + def test_custom_formats_render_one_complete_row(self): + # Hugging Face's Xet formats contain their own description and bar. + formats = ( + "{desc}: {bar}| {n_fmt:>5}B{postfix:>12}", + "{l_bar}{bar}| {n_fmt:>5}B / {total_fmt:>5}B{postfix:>12}", + ) + self.bar("default", initial=25) + for index, bar_format in enumerate(formats): + self.bar( + f"custom-{index}", + total=4096, + initial=1024, + unit="B", + unit_scale=True, + unit_divisor=1024, + bar_format=bar_format, + postfix="1.02kB/s [ok]", + ) + output = "\n".join( + "".join(segment.text for segment in line) + for line in self.console.render_lines( + self.displays[0].get_renderable(), pad=False + ) + ) + self.assertRegex(output, r"default[^\n]*25%[^\n]*25/100") + for index in range(2): + self.assertEqual(output.count(f"custom-{index}"), 1) + self.assertEqual(output.count("1.00kB"), 2) + self.assertEqual(output.count("1.02kB/s [ok]"), 2) + self.assertIn("4.00kB", output) + # Each custom format includes one text bar, never an extra Rich bar. + for line in output.splitlines(): + if "custom-" in line: + self.assertNotIn("━", line) def test_context_manager_cancellation_stops_display(self): with self.assertRaises(KeyboardInterrupt): From facd9b75293cab7c1385d8c83adebc1994b5945b Mon Sep 17 00:00:00 2001 From: umran666 Date: Wed, 7 Oct 2026 18:05:55 +0530 Subject: [PATCH 23/31] fix: stop live progress before joining download workers --- src/heretic/progress.py | 17 +++++++++++-- tests/test_progress.py | 56 ++++++++++++++++++++++++++++++++++++++++- 2 files changed, 70 insertions(+), 3 deletions(-) diff --git a/src/heretic/progress.py b/src/heretic/progress.py index 279f6a8..0a8c99c 100644 --- a/src/heretic/progress.py +++ b/src/heretic/progress.py @@ -1,6 +1,9 @@ # SPDX-License-Identifier: AGPL-3.0-or-later # Copyright (C) 2025-2026 Philipp Emanuel Weidmann + contributors +# Register the executor's exit hook before the display's (hooks run in reverse). +import concurrent.futures.thread # noqa: F401 +import threading from collections.abc import Iterable from itertools import groupby from threading import RLock @@ -14,6 +17,16 @@ from rich.text import Text class _Progress(Progress): + def __init__(self, *args: Any, **kwargs: Any): + super().__init__(*args, **kwargs) + # Normal atexit callbacks run only after Python joins worker threads. + threading._register_atexit(self._shutdown) # ty:ignore[unresolved-attribute] + + def _shutdown(self) -> None: + with _progress_lock: + self.disable = True + self.live.stop() + def get_renderables(self) -> Iterable[RenderableType]: for custom, tasks in groupby( self.tasks, key=lambda task: task.fields["custom"] @@ -28,6 +41,7 @@ class _Progress(Progress): # A single live display lets individual bars close in any order. +_progress_lock = RLock() _progress = _Progress( TextColumn("{task.description}", style="progress.description", markup=False), BarColumn(), @@ -35,7 +49,6 @@ _progress = _Progress( TextColumn("{task.fields[stats]}", markup=False), transient=True, ) -_progress_lock = RLock() # A class that provides the same interface as tqdm, @@ -73,7 +86,7 @@ class TqdmShim(tqdm.tqdm): def display(self, *args: Any, **kwargs: Any): with _progress_lock: - if self.disable: + if self.disable or _progress.disable: return # Completion ends the transient display, not the tqdm object's lifetime. diff --git a/tests/test_progress.py b/tests/test_progress.py index f9ff0a0..d68278e 100644 --- a/tests/test_progress.py +++ b/tests/test_progress.py @@ -2,6 +2,8 @@ # Copyright (C) 2025-2026 Philipp Emanuel Weidmann + contributors import os +import subprocess +import sys import unittest from contextlib import ExitStack from io import StringIO @@ -150,6 +152,20 @@ class ProgressRenderingTests(unittest.TestCase): self.assertTrue(all(not display.live.is_started for display in self.displays)) self.assertNotIn("cancelled.bin", self.output_after("RECOVERED")) + def test_shutdown_stops_rendering_before_workers_finish(self): + command = [sys.executable, "-X", "utf8", __file__, "--shutdown-probe"] + result = subprocess.run( + command, + capture_output=True, + encoding="utf-8", + check=True, + timeout=30, + ) + self.assertIn("unfinished.bin", result.stdout) + after = result.stdout.split("SHUTDOWN", 1)[1] + self.assertNotIn("unfinished.bin", after) + self.assertNotIn("late.bin", after) + def test_close_recovers_when_task_removal_is_interrupted(self): bar = self.bar("interrupted.bin", total=1) display = self.displays[0] @@ -183,5 +199,43 @@ class ProgressRenderingTests(unittest.TestCase): self.assertFalse(display.live.is_started) +def shutdown_probe(): + import threading + from concurrent.futures import ThreadPoolExecutor + + output = StringIO() + stdout = sys.stdout + console = Console(file=output, force_terminal=True, force_interactive=True) + event = threading.Event() + executor = ThreadPoolExecutor(1) + + def worker(): + event.wait() + bar.update(1) + progress._progress.refresh() + bar.close() + progress.TqdmShim(desc="late.bin", total=100, disable=False) + progress._progress.refresh() + + future = executor.submit(worker) + + def finish_worker(): + console.print("SHUTDOWN") + event.set() + future.result(timeout=10) + stdout.write(output.getvalue()) + + # Runs after the renderer's shutdown callback, before the executor joins. + threading._register_atexit(finish_worker) # ty:ignore[unresolved-attribute] + progress._progress = progress._Progress( + *progress._progress.columns, console=console, transient=True, auto_refresh=False + ) + bar = progress.TqdmShim(desc="unfinished.bin", total=100, disable=False) + progress._progress.refresh() + + if __name__ == "__main__": - unittest.main() + if "--shutdown-probe" in sys.argv: + shutdown_probe() + else: + unittest.main() From 8dadc2ae96b2c8cbfe27233b76debd42f2782ce3 Mon Sep 17 00:00:00 2001 From: umran666 Date: Wed, 7 Oct 2026 18:22:19 +0530 Subject: [PATCH 24/31] test: combine overlapping progress format checks --- tests/test_progress.py | 36 +++++++++++++----------------------- 1 file changed, 13 insertions(+), 23 deletions(-) diff --git a/tests/test_progress.py b/tests/test_progress.py index d68278e..63176f2 100644 --- a/tests/test_progress.py +++ b/tests/test_progress.py @@ -87,35 +87,26 @@ class ProgressRenderingTests(unittest.TestCase): self.assertRegex(after, r"second\.bin[^\n]*50%") self.assertNotIn("first.bin", after) - def test_overlapping_bars_keep_counts_units_and_literal_postfix(self): + def test_custom_formats_render_one_complete_row(self): download = self.bar( "bytes.bin", total=4096, unit="B", unit_scale=True, unit_divisor=1024 ) + self.patch(download, "_time", return_value=download.start_t + 1) + download.update(1024) + download.set_postfix_str("file=[ok]") training = self.bar( "training", total=8, unit="batch", bar_format="STEP {n}/{total} {unit}{postfix}", ) - self.patch(download, "_time", return_value=download.start_t + 1) - download.update(1024) - download.set_postfix_str("file=[ok]") training.update(2) training.set_postfix(loss=0.42) - self.refresh() - output = self.output.getvalue() - self.assertRegex( - output, r"bytes\.bin[^\n]*1\.00k/4\.00k[^\n]*1\.02kB/s, file=\[ok\]" - ) - self.assertIn("STEP 2/8 batch, loss=0.42", output) - - def test_custom_formats_render_one_complete_row(self): # Hugging Face's Xet formats contain their own description and bar. formats = ( "{desc}: {bar}| {n_fmt:>5}B{postfix:>12}", "{l_bar}{bar}| {n_fmt:>5}B / {total_fmt:>5}B{postfix:>12}", ) - self.bar("default", initial=25) for index, bar_format in enumerate(formats): self.bar( f"custom-{index}", @@ -127,13 +118,15 @@ class ProgressRenderingTests(unittest.TestCase): bar_format=bar_format, postfix="1.02kB/s [ok]", ) - output = "\n".join( - "".join(segment.text for segment in line) - for line in self.console.render_lines( - self.displays[0].get_renderable(), pad=False - ) + output = "".join( + segment.text + for segment in self.console.render(self.displays[0].get_renderable()) ) - self.assertRegex(output, r"default[^\n]*25%[^\n]*25/100") + self.assertRegex( + output, + r"bytes\.bin[^\n]*25%[^\n]*1\.00k/4\.00k[^\n]*1\.02kB/s, file=\[ok\]", + ) + self.assertIn("STEP 2/8 batch, loss=0.42", output) for index in range(2): self.assertEqual(output.count(f"custom-{index}"), 1) self.assertEqual(output.count("1.00kB"), 2) @@ -203,9 +196,7 @@ def shutdown_probe(): import threading from concurrent.futures import ThreadPoolExecutor - output = StringIO() - stdout = sys.stdout - console = Console(file=output, force_terminal=True, force_interactive=True) + console = Console(file=sys.stdout, force_terminal=True, force_interactive=True) event = threading.Event() executor = ThreadPoolExecutor(1) @@ -223,7 +214,6 @@ def shutdown_probe(): console.print("SHUTDOWN") event.set() future.result(timeout=10) - stdout.write(output.getvalue()) # Runs after the renderer's shutdown callback, before the executor joins. threading._register_atexit(finish_worker) # ty:ignore[unresolved-attribute] From 77aa8789649b1b7b7b60c66e3413a275117775f2 Mon Sep 17 00:00:00 2001 From: umran666 Date: Wed, 7 Oct 2026 19:02:45 +0530 Subject: [PATCH 25/31] Handle repeated Ctrl+C during CLI shutdown --- src/heretic/main.py | 9 +++++++-- tests/test_progress.py | 33 ++++++++++++++++++++++++++++----- 2 files changed, 35 insertions(+), 7 deletions(-) diff --git a/src/heretic/main.py b/src/heretic/main.py index 5ca954b..a39c08b 100644 --- a/src/heretic/main.py +++ b/src/heretic/main.py @@ -36,7 +36,7 @@ def _is_help_invocation() -> bool: if _is_help_invocation(): Settings() -from .progress import patch_tqdm +from .progress import _progress, patch_tqdm # This patches tqdm class definitions, which must happen # before any other module imports tqdm. @@ -46,6 +46,7 @@ import logging import math import random import re +import signal import time import warnings from importlib.metadata import version @@ -1406,7 +1407,11 @@ def main(): if isinstance(error, KeyboardInterrupt) or isinstance( error.__context__, KeyboardInterrupt ): + # Restore the terminal before allowing a repeated Ctrl+C to force exit. + signal.signal(signal.SIGINT, signal.SIG_IGN) + _progress._shutdown() print() - print("[red]Shutting down...[/]") + print("[red]Shutting down... Press Ctrl+C again to force exit.[/]") + signal.signal(signal.SIGINT, lambda *_: os._exit(130)) else: raise diff --git a/tests/test_progress.py b/tests/test_progress.py index 63176f2..4b4f0bb 100644 --- a/tests/test_progress.py +++ b/tests/test_progress.py @@ -2,6 +2,7 @@ # Copyright (C) 2025-2026 Philipp Emanuel Weidmann + contributors import os +import signal import subprocess import sys import unittest @@ -145,20 +146,30 @@ class ProgressRenderingTests(unittest.TestCase): self.assertTrue(all(not display.live.is_started for display in self.displays)) self.assertNotIn("cancelled.bin", self.output_after("RECOVERED")) - def test_shutdown_stops_rendering_before_workers_finish(self): - command = [sys.executable, "-X", "utf8", __file__, "--shutdown-probe"] - result = subprocess.run( + def run_shutdown_probe(self, *flags): + command = [sys.executable, "-X", "utf8", __file__, "--shutdown-probe", *flags] + return subprocess.run( command, capture_output=True, encoding="utf-8", - check=True, - timeout=30, + check=False, + timeout=180, ) + + def test_shutdown_stops_rendering_before_workers_finish(self): + result = self.run_shutdown_probe() + self.assertEqual(result.returncode, 0, result.stderr) self.assertIn("unfinished.bin", result.stdout) after = result.stdout.split("SHUTDOWN", 1)[1] self.assertNotIn("unfinished.bin", after) self.assertNotIn("late.bin", after) + def test_repeated_interrupt_exits_without_shutdown_traceback(self): + result = self.run_shutdown_probe("--repeat-interrupt") + self.assertIn("Shutting down...", result.stdout) + self.assertNotIn("Traceback", result.stderr) + self.assertEqual(result.returncode, 130) + def test_close_recovers_when_task_removal_is_interrupted(self): bar = self.bar("interrupted.bin", total=1) display = self.displays[0] @@ -196,6 +207,7 @@ def shutdown_probe(): import threading from concurrent.futures import ThreadPoolExecutor + streams = sys.stdout, sys.stderr console = Console(file=sys.stdout, force_terminal=True, force_interactive=True) event = threading.Event() executor = ThreadPoolExecutor(1) @@ -211,6 +223,8 @@ def shutdown_probe(): future = executor.submit(worker) def finish_worker(): + if "--repeat-interrupt" in sys.argv: + signal.raise_signal(signal.SIGINT) console.print("SHUTDOWN") event.set() future.result(timeout=10) @@ -222,6 +236,15 @@ def shutdown_probe(): ) bar = progress.TqdmShim(desc="unfinished.bin", total=100, disable=False) progress._progress.refresh() + if "--repeat-interrupt" in sys.argv: + from heretic import main + + with patch.object( + main, "run", side_effect=lambda: signal.raise_signal(signal.SIGINT) + ): + main.main() + assert not progress._progress.live.is_started + assert (sys.stdout, sys.stderr) == streams if __name__ == "__main__": From b41ab0882077d2c1762d772d96fde8c3177808bd Mon Sep 17 00:00:00 2001 From: umran666 Date: Wed, 7 Oct 2026 19:23:04 +0530 Subject: [PATCH 26/31] Use native SIGINT handling after terminal cleanup --- src/heretic/main.py | 2 +- tests/test_progress.py | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/heretic/main.py b/src/heretic/main.py index a39c08b..a3e85e6 100644 --- a/src/heretic/main.py +++ b/src/heretic/main.py @@ -1412,6 +1412,6 @@ def main(): _progress._shutdown() print() print("[red]Shutting down... Press Ctrl+C again to force exit.[/]") - signal.signal(signal.SIGINT, lambda *_: os._exit(130)) + signal.signal(signal.SIGINT, signal.SIG_DFL) else: raise diff --git a/tests/test_progress.py b/tests/test_progress.py index 4b4f0bb..6c307ee 100644 --- a/tests/test_progress.py +++ b/tests/test_progress.py @@ -168,7 +168,8 @@ class ProgressRenderingTests(unittest.TestCase): result = self.run_shutdown_probe("--repeat-interrupt") self.assertIn("Shutting down...", result.stdout) self.assertNotIn("Traceback", result.stderr) - self.assertEqual(result.returncode, 130) + # Windows' C runtime exits with 3 for raise_signal(SIGINT). + self.assertEqual(result.returncode, 3 if os.name == "nt" else -signal.SIGINT) def test_close_recovers_when_task_removal_is_interrupted(self): bar = self.bar("interrupted.bin", total=1) From 3073dc540ffda16d0a3aa7d55d209ed262c0b5ec Mon Sep 17 00:00:00 2001 From: umran666 Date: Sun, 11 Oct 2026 10:12:23 +0530 Subject: [PATCH 27/31] fix: simplify Rich tqdm rendering --- src/heretic/main.py | 9 +- src/heretic/progress.py | 258 ++++++++++++++++----------------- tests/test_progress.py | 307 ++++++++++++---------------------------- 3 files changed, 216 insertions(+), 358 deletions(-) diff --git a/src/heretic/main.py b/src/heretic/main.py index a394614..d99219a 100644 --- a/src/heretic/main.py +++ b/src/heretic/main.py @@ -36,7 +36,7 @@ def _is_help_invocation() -> bool: if _is_help_invocation(): Settings() -from .progress import _progress, patch_tqdm +from .progress import patch_tqdm # This patches tqdm class definitions, which must happen # before any other module imports tqdm. @@ -46,7 +46,6 @@ import logging import math import random import re -import signal import time import warnings from importlib.metadata import version @@ -1408,11 +1407,7 @@ def main(): if isinstance(error, KeyboardInterrupt) or isinstance( error.__context__, KeyboardInterrupt ): - # Restore the terminal before allowing a repeated Ctrl+C to force exit. - signal.signal(signal.SIGINT, signal.SIG_IGN) - _progress._shutdown() print() - print("[red]Shutting down... Press Ctrl+C again to force exit.[/]") - signal.signal(signal.SIGINT, signal.SIG_DFL) + print("[red]Shutting down...[/]") else: raise diff --git a/src/heretic/progress.py b/src/heretic/progress.py index 0a8c99c..775dcf8 100644 --- a/src/heretic/progress.py +++ b/src/heretic/progress.py @@ -1,167 +1,149 @@ # SPDX-License-Identifier: AGPL-3.0-or-later # Copyright (C) 2025-2026 Philipp Emanuel Weidmann + contributors -# Register the executor's exit hook before the display's (hooks run in reverse). -import concurrent.futures.thread # noqa: F401 -import threading -from collections.abc import Iterable -from itertools import groupby -from threading import RLock from typing import Any import tqdm import tqdm.auto -from rich.console import RenderableType +import tqdm.std from rich.progress import BarColumn, Progress, TaskID, TaskProgressColumn, TextColumn -from rich.text import Text + +_Tqdm = tqdm.tqdm -class _Progress(Progress): - def __init__(self, *args: Any, **kwargs: Any): - super().__init__(*args, **kwargs) - # Normal atexit callbacks run only after Python joins worker threads. - threading._register_atexit(self._shutdown) # ty:ignore[unresolved-attribute] - - def _shutdown(self) -> None: - with _progress_lock: - self.disable = True - self.live.stop() - - def get_renderables(self) -> Iterable[RenderableType]: - for custom, tasks in groupby( - self.tasks, key=lambda task: task.fields["custom"] - ): - if custom: - # bar_format specifies the whole row, including any label and bar. - for task in tasks: - if task.visible: - yield Text.from_ansi(task.fields["stats"]) - else: - yield self.make_tasks_table(tasks) +def _format_number(value: float | None, scale: bool, divisor: int) -> str: + if value is None: + return "?" + if scale: + return _Tqdm.format_sizeof(value, divisor=divisor) + return f"{value:g}" -# A single live display lets individual bars close in any order. -_progress_lock = RLock() -_progress = _Progress( - TextColumn("{task.description}", style="progress.description", markup=False), - BarColumn(), - TaskProgressColumn(), - TextColumn("{task.fields[stats]}", markup=False), - transient=True, -) +def _format_details(format_dict: dict[str, Any]) -> str: + n = format_dict["n"] + total = format_dict["total"] + rate = format_dict["rate"] + unit = format_dict["unit"] + divisor = format_dict["unit_divisor"] + unit_scale = format_dict["unit_scale"] + + # This is the same unit-scaling rule tqdm uses for its text statistics. + scale = unit_scale is True or unit_scale == 1 + if unit_scale not in (False, True, 0, 1): + n *= unit_scale + total = total * unit_scale if total is not None else None + rate = rate * unit_scale if rate is not None else None + + n_text = _format_number(n, scale, divisor) + total_text = _format_number(total, scale, divisor) + if total is None: + progress = n_text + if unit != "it": + progress += unit if scale else f" {unit}" + elif scale: + progress = f"{n_text}{unit} / {total_text}{unit}" + else: + progress = f"{n_text} / {total_text}" + if unit != "it": + progress += f" {unit}" + + postfix = str(format_dict["postfix"] or "").strip().removeprefix(", ").strip() + # Some callers provide an aggregate throughput as their postfix. It is more + # useful than the per-bar rate and avoids displaying two speeds for one row. + has_rate_postfix = postfix.endswith(f"{unit}/s") + if rate and not has_rate_postfix: + if rate < 1: + rate_text = f"{_format_number(1 / rate, scale, divisor)}s/{unit}" + else: + rate_text = f"{_format_number(rate, scale, divisor)}{unit}/s" + elif not has_rate_postfix: + rate_text = f"?{unit}/s" + else: + rate_text = None + + details = progress if rate_text is None else f"{progress} • {rate_text}" + if postfix: + details += f" • {postfix}" + return details + + +def _new_progress(**kwargs: Any) -> Progress: + return Progress( + TextColumn("{task.description}", style="progress.description", markup=False), + BarColumn(), + TaskProgressColumn(), + TextColumn("{task.fields[details]}", markup=False), + transient=True, + **kwargs, + ) + + +# A single Live display keeps concurrently-created bars on separate Rich rows. +_progress = _new_progress() # A class that provides the same interface as tqdm, # but displays progress bars using Rich. -class TqdmShim(tqdm.tqdm): +class TqdmShim(_Tqdm): def __init__(self, *args: Any, **kwargs: Any): self.rich_task_id: TaskID | None = None - - # Chain up to the parent constructor to ensure that the internal state of the superclass - # is correctly initialized, which some methods that we don't override might rely on. super().__init__(*args, **kwargs) - def refresh(self, nolock: bool = False, lock_args: Any = None) -> bool | None: + def _remove_task(self) -> None: + if self.rich_task_id is None: + return + if self.rich_task_id in _progress.task_ids: + _progress.remove_task(self.rich_task_id) + self.rich_task_id = None + if not _progress.task_ids: + _progress.stop() + + def display(self, *args: Any, **kwargs: Any) -> None: if self.disable: - return None - if not nolock: - if lock_args: - if not self._lock.acquire(*lock_args): - return False - else: - self._lock.acquire() - try: - return super().refresh(nolock=True) - finally: - # A cancelled display must not leave tqdm's shared lock held. - if not nolock: - self._lock.release() - - def update(self, *args: Any, **kwargs: Any) -> bool | None: - result = super().update(*args, **kwargs) - # mininterval/miniters can make tqdm skip display() on the final update. - if not self.disable: - self._clear_completed() - return result - - def display(self, *args: Any, **kwargs: Any): - with _progress_lock: - if self.disable or _progress.disable: - return - - # Completion ends the transient display, not the tqdm object's lifetime. - # A later reset or larger total can make the same bar visible again. - if self._clear_completed(): - return - - # The total can become known after construction; preserve custom formats. - format_dict = self.format_dict - # The parent can refresh before our constructor finishes; Rich owns width. - format_dict["ncols"] = None - format_dict["bar_format"] = self.bar_format or ( - "{n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}{postfix}]" - if self.total - else "{n_fmt}{unit} [{elapsed}, {rate_fmt}{postfix}]" - ) - stats = self.format_meter(**format_dict) - - if self.rich_task_id is None: - previous_tasks = set(_progress.task_ids) - try: - if not previous_tasks: - _progress.start() - self.rich_task_id = _progress.add_task( - self.desc or "", - total=self.total, - completed=self.n, - stats=stats, - custom=bool(self.bar_format), - ) - except BaseException: - # Task creation can be interrupted before its ID is returned. - for task_id in set(_progress.task_ids) - previous_tasks: - _progress.remove_task(task_id) - if not _progress.task_ids: - _progress.stop() - raise - else: - _progress.update( - self.rich_task_id, - description=self.desc or "", - total=self.total, - completed=self.n, - stats=stats, - custom=bool(self.bar_format), - ) - - def _clear_completed(self) -> bool: + return if self.total is not None and self.n >= self.total: - self.clear() - return True - return False + self._remove_task() + return - def clear(self, *args: Any, **kwargs: Any): - with _progress_lock: - task_id = getattr(self, "rich_task_id", None) - if task_id is not None: - # Cancellation can interrupt removal before the ID is cleared. - if task_id in _progress.task_ids: - _progress.remove_task(task_id) - self.rich_task_id = None - if not _progress.task_ids: - _progress.stop() - else: - _progress.refresh() + format_dict = self.format_dict + details = _format_details(format_dict) + if self.rich_task_id is None: + _progress.start() + self.rich_task_id = _progress.add_task( + self.desc or "", + total=self.total, + completed=self.n, + details=details, + ) + else: + _progress.update( + self.rich_task_id, + description=self.desc or "", + total=self.total, + completed=self.n, + details=details, + ) - def close(self, *args: Any, **kwargs: Any): - # Rich owns row layout; discard without tqdm rearranging other bars. - # This also works when cancellation interrupts tqdm's initialization. - self.disable = True + def update(self, n: float = 1) -> bool | None: + refreshed = super().update(n) + if self.total is not None and self.n >= self.total: + with self.get_lock(): + self._remove_task() + return refreshed + + def clear(self, *args: Any, **kwargs: Any) -> None: with self.get_lock(): - self._instances.discard(self) - self.clear() + self._remove_task() + + def close(self) -> None: + if self.disable: + return + super().close() + with self.get_lock(): + self._remove_task() -def patch_tqdm(): +def patch_tqdm() -> None: tqdm.tqdm = TqdmShim # ty:ignore[invalid-assignment] tqdm.auto.tqdm = TqdmShim # ty:ignore[invalid-assignment] + tqdm.std.tqdm = TqdmShim # ty:ignore[invalid-assignment] diff --git a/tests/test_progress.py b/tests/test_progress.py index 6c307ee..8c32d87 100644 --- a/tests/test_progress.py +++ b/tests/test_progress.py @@ -1,255 +1,136 @@ # SPDX-License-Identifier: AGPL-3.0-or-later # Copyright (C) 2025-2026 Philipp Emanuel Weidmann + contributors -import os -import signal import subprocess import sys import unittest -from contextlib import ExitStack from io import StringIO from unittest.mock import patch from rich.console import Console -from rich.progress import Progress +from rich.progress import BarColumn from heretic import progress class ProgressRenderingTests(unittest.TestCase): - def setUp(self): - self.patches = ExitStack() - self.addCleanup(self.patches.close) + def setUp(self) -> None: self.output = StringIO() - self.patches.enter_context(patch.dict(os.environ, {"TERM": "xterm"})) - self.patch(self.output, "isatty", return_value=True) self.console = Console( file=self.output, width=120, color_system=None, force_terminal=True, force_interactive=True, - force_jupyter=False, - legacy_windows=False, ) - self.displays = [] + self.display = progress._new_progress(console=self.console, auto_refresh=False) + self.patch = patch.object(progress, "_progress", self.display) + self.patch.start() + self.addCleanup(self.patch.stop) + self.addCleanup(self.display.stop) - def make_progress(*columns, **options): - options.update(console=self.console, auto_refresh=False) - display = getattr(progress, "_Progress", Progress)(*columns, **options) - self.displays.append(display) - self.addCleanup(display.stop) - return display - - self.patch(progress, "Progress", side_effect=make_progress) - shared = getattr(progress, "_progress", None) - if shared is not None: - self.patch( - progress, - "_progress", - new=make_progress(*shared.columns, transient=True), - ) - - def patch(self, target, attribute, **options): - self.patches.enter_context(patch.object(target, attribute, **options)) - - def bar(self, description, **options): - options = {"total": 100, "mininterval": 0, "miniters": 1, **options} + def bar(self, description: str, **kwargs): bar = progress.TqdmShim( - desc=description, file=self.output, disable=None, **options + desc=description, + file=self.output, + disable=False, + mininterval=0, + miniters=1, + **kwargs, ) self.addCleanup(bar.close) return bar - def refresh(self): - for display in self.displays: - display.refresh() + def render(self) -> str: + return "".join( + segment.text for segment in self.console.render(self.display.get_renderable()) + ) - def output_after(self, message): - self.console.print(message) - self.refresh() - return self.output.getvalue().split(message, 1)[1] + def test_custom_format_uses_a_rich_bar(self) -> None: + bar = self.bar( + "Downloading bytes", + total=8192, + unit="B", + unit_scale=True, + unit_divisor=1024, + bar_format="{desc}: {bar}| {n_fmt}B / {total_fmt}B, {rate_fmt}", + ) + bar.last_print_t = bar.start_t + with patch.object(bar, "_time", return_value=bar.start_t + 1): + bar.update(1024) - def test_completed_download_does_not_redraw_over_later_messages(self): - bar = self.bar("download.bin", mininterval=3600) - bar.update(50) - bar.refresh() - self.refresh() - self.assertIn("50%", self.output.getvalue()) - bar.update(50) - self.assertNotIn("download.bin", self.output_after("AFTER")) + output = self.render() + self.assertIn("Downloading bytes", output) + self.assertIn("1.00kB / 8.00kB", output) + self.assertIn("1.00kB/s", output) + self.assertIsInstance(self.display.columns[1], BarColumn) + self.assertNotIn("|", output) - def test_closing_earlier_bar_keeps_later_bar_rendering(self): - first = self.bar("first.bin") - second = self.bar("second.bin") + def test_simultaneous_bars_keep_their_own_data(self) -> None: + fetching = self.bar("Fetching 2 files", total=2) + reconstructing = self.bar( + "Reconstructing", total=4096, unit="B", unit_scale=True + ) + downloading = self.bar("Downloading bytes", total=None, unit="B", unit_scale=True) + fetching.update(1) + reconstructing.update(1024) + downloading.update(1024) + reconstructing.set_postfix_str("2.00kB/s ") + + output = self.render() + self.assertEqual(output.count("Fetching 2 files"), 1) + self.assertEqual(output.count("Reconstructing"), 1) + self.assertEqual(output.count("Downloading bytes"), 1) + self.assertIn("1.02kB / 4.10kB", output) + self.assertIn("2.00kB/s", output) + reconstructing_row = next(line for line in output.splitlines() if "Reconstructing" in line) + self.assertEqual(reconstructing_row.count("B/s"), 1) + self.assertIn("1.02kB", output) + + def test_closing_one_bar_leaves_the_other_visible(self) -> None: + first = self.bar("first.bin", total=2) + second = self.bar("second.bin", total=2) first.close() - second.update(50) - after = self.output_after("AFTER") - self.assertRegex(after, r"second\.bin[^\n]*50%") - self.assertNotIn("first.bin", after) + second.update(1) - def test_custom_formats_render_one_complete_row(self): - download = self.bar( - "bytes.bin", total=4096, unit="B", unit_scale=True, unit_divisor=1024 - ) - self.patch(download, "_time", return_value=download.start_t + 1) - download.update(1024) - download.set_postfix_str("file=[ok]") - training = self.bar( - "training", - total=8, - unit="batch", - bar_format="STEP {n}/{total} {unit}{postfix}", - ) - training.update(2) - training.set_postfix(loss=0.42) - # Hugging Face's Xet formats contain their own description and bar. - formats = ( - "{desc}: {bar}| {n_fmt:>5}B{postfix:>12}", - "{l_bar}{bar}| {n_fmt:>5}B / {total_fmt:>5}B{postfix:>12}", - ) - for index, bar_format in enumerate(formats): - self.bar( - f"custom-{index}", - total=4096, - initial=1024, - unit="B", - unit_scale=True, - unit_divisor=1024, - bar_format=bar_format, - postfix="1.02kB/s [ok]", - ) - output = "".join( - segment.text - for segment in self.console.render(self.displays[0].get_renderable()) - ) - self.assertRegex( - output, - r"bytes\.bin[^\n]*25%[^\n]*1\.00k/4\.00k[^\n]*1\.02kB/s, file=\[ok\]", - ) - self.assertIn("STEP 2/8 batch, loss=0.42", output) - for index in range(2): - self.assertEqual(output.count(f"custom-{index}"), 1) - self.assertEqual(output.count("1.00kB"), 2) - self.assertEqual(output.count("1.02kB/s [ok]"), 2) - self.assertIn("4.00kB", output) - # Each custom format includes one text bar, never an extra Rich bar. - for line in output.splitlines(): - if "custom-" in line: - self.assertNotIn("━", line) + output = self.render() + self.assertNotIn("first.bin", output) + self.assertIn("second.bin", output) - def test_context_manager_cancellation_stops_display(self): - with self.assertRaises(KeyboardInterrupt): - with self.bar("cancelled.bin") as bar: - bar.update(25) - raise KeyboardInterrupt - self.assertTrue(all(not display.live.is_started for display in self.displays)) - self.assertNotIn("cancelled.bin", self.output_after("RECOVERED")) + def test_completed_bar_is_removed_before_later_output(self) -> None: + bar = self.bar("finished.bin", total=2) + bar.update(2) - def run_shutdown_probe(self, *flags): - command = [sys.executable, "-X", "utf8", __file__, "--shutdown-probe", *flags] - return subprocess.run( - command, - capture_output=True, - encoding="utf-8", - check=False, - timeout=180, - ) - - def test_shutdown_stops_rendering_before_workers_finish(self): - result = self.run_shutdown_probe() - self.assertEqual(result.returncode, 0, result.stderr) - self.assertIn("unfinished.bin", result.stdout) - after = result.stdout.split("SHUTDOWN", 1)[1] - self.assertNotIn("unfinished.bin", after) - self.assertNotIn("late.bin", after) - - def test_repeated_interrupt_exits_without_shutdown_traceback(self): - result = self.run_shutdown_probe("--repeat-interrupt") - self.assertIn("Shutting down...", result.stdout) - self.assertNotIn("Traceback", result.stderr) - # Windows' C runtime exits with 3 for raise_signal(SIGINT). - self.assertEqual(result.returncode, 3 if os.name == "nt" else -signal.SIGINT) - - def test_close_recovers_when_task_removal_is_interrupted(self): - bar = self.bar("interrupted.bin", total=1) - display = self.displays[0] - remove_task = display.remove_task - - def interrupted_remove(task_id): - remove_task(task_id) - raise KeyboardInterrupt - - with patch.object(display, "remove_task", side_effect=interrupted_remove): - with self.assertRaises(KeyboardInterrupt): - bar.update(1) - bar.close() - self.assertFalse(display.task_ids) - self.assertFalse(display.live.is_started) - - def test_initialization_cancellation_stops_unowned_display(self): - display = self.displays[0] - for method in ("start", "add_task"): - with self.subTest(method=method): - original = getattr(display, method) - - def interrupted(*args, **kwargs): - original(*args, **kwargs) - raise KeyboardInterrupt - - with patch.object(display, method, side_effect=interrupted): - with self.assertRaises(KeyboardInterrupt): - self.bar("interrupted.bin") - self.assertFalse(display.task_ids) - self.assertFalse(display.live.is_started) - - -def shutdown_probe(): - import threading - from concurrent.futures import ThreadPoolExecutor - - streams = sys.stdout, sys.stderr - console = Console(file=sys.stdout, force_terminal=True, force_interactive=True) - event = threading.Event() - executor = ThreadPoolExecutor(1) - - def worker(): - event.wait() + self.assertFalse(self.display.task_ids) + self.assertFalse(self.display.live.is_started) + bar.reset(total=2) bar.update(1) - progress._progress.refresh() + self.assertTrue(self.display.task_ids) bar.close() - progress.TqdmShim(desc="late.bin", total=100, disable=False) - progress._progress.refresh() + self.console.print("AFTER") + self.assertNotIn("finished.bin", self.output.getvalue().split("AFTER", 1)[1]) - future = executor.submit(worker) - - def finish_worker(): - if "--repeat-interrupt" in sys.argv: - signal.raise_signal(signal.SIGINT) - console.print("SHUTDOWN") - event.set() - future.result(timeout=10) - - # Runs after the renderer's shutdown callback, before the executor joins. - threading._register_atexit(finish_worker) # ty:ignore[unresolved-attribute] - progress._progress = progress._Progress( - *progress._progress.columns, console=console, transient=True, auto_refresh=False - ) - bar = progress.TqdmShim(desc="unfinished.bin", total=100, disable=False) - progress._progress.refresh() - if "--repeat-interrupt" in sys.argv: - from heretic import main - - with patch.object( - main, "run", side_effect=lambda: signal.raise_signal(signal.SIGINT) - ): - main.main() - assert not progress._progress.live.is_started - assert (sys.stdout, sys.stderr) == streams + def test_hugging_face_imports_the_shim_in_a_clean_process(self) -> None: + code = """ +from heretic.progress import TqdmShim, patch_tqdm +patch_tqdm() +import tqdm +import tqdm.auto +import tqdm.std +import importlib +import huggingface_hub._snapshot_download as snapshot +hub_tqdm = importlib.import_module("huggingface_hub.utils.tqdm") +assert tqdm.tqdm is TqdmShim +assert tqdm.auto.tqdm is TqdmShim +assert tqdm.std.tqdm is TqdmShim +assert issubclass(snapshot.base_tqdm, TqdmShim) +assert issubclass(hub_tqdm.tqdm, TqdmShim) +""" + result = subprocess.run( + [sys.executable, "-c", code], capture_output=True, text=True, timeout=30, check=False + ) + self.assertEqual(result.returncode, 0, result.stderr) if __name__ == "__main__": - if "--shutdown-probe" in sys.argv: - shutdown_probe() - else: - unittest.main() + unittest.main() From 1151b220c7aad73d2f75a72855cd3498723c409f Mon Sep 17 00:00:00 2001 From: umran666 Date: Fri, 16 Oct 2026 08:00:44 +0530 Subject: [PATCH 28/31] fix: preserve tqdm timing and dynamic progress lifecycle --- src/heretic/progress.py | 58 ++++++++++++++++++++++++---------------- tests/test_progress.py | 59 ++++++++++++++++++++++++++++++++--------- 2 files changed, 82 insertions(+), 35 deletions(-) diff --git a/src/heretic/progress.py b/src/heretic/progress.py index 775dcf8..4523b59 100644 --- a/src/heretic/progress.py +++ b/src/heretic/progress.py @@ -23,6 +23,9 @@ def _format_details(format_dict: dict[str, Any]) -> str: n = format_dict["n"] total = format_dict["total"] rate = format_dict["rate"] + elapsed = format_dict["elapsed"] + if rate is None and elapsed: + rate = (n - format_dict["initial"]) / elapsed unit = format_dict["unit"] divisor = format_dict["unit_divisor"] unit_scale = format_dict["unit_scale"] @@ -36,7 +39,7 @@ def _format_details(format_dict: dict[str, Any]) -> str: n_text = _format_number(n, scale, divisor) total_text = _format_number(total, scale, divisor) - if total is None: + if not total: progress = n_text if unit != "it": progress += unit if scale else f" {unit}" @@ -50,21 +53,20 @@ def _format_details(format_dict: dict[str, Any]) -> str: postfix = str(format_dict["postfix"] or "").strip().removeprefix(", ").strip() # Some callers provide an aggregate throughput as their postfix. It is more # useful than the per-bar rate and avoids displaying two speeds for one row. - has_rate_postfix = postfix.endswith(f"{unit}/s") - if rate and not has_rate_postfix: - if rate < 1: - rate_text = f"{_format_number(1 / rate, scale, divisor)}s/{unit}" - else: - rate_text = f"{_format_number(rate, scale, divisor)}{unit}/s" - elif not has_rate_postfix: - rate_text = f"?{unit}/s" + if postfix.endswith(f"{unit}/s"): + rate_text, postfix = postfix, "" + elif rate: + value, suffix = (1 / rate, f"s/{unit}") if rate < 1 else (rate, f"{unit}/s") + rate_text = f"{_format_number(value, scale, 1000)}{suffix}" else: - rate_text = None + rate_text = f"?{unit}/s" - details = progress if rate_text is None else f"{progress} • {rate_text}" - if postfix: - details += f" • {postfix}" - return details + timing = _Tqdm.format_interval(elapsed) + if total: + remaining = _Tqdm.format_interval(max(0, (total - n) / rate)) if rate else "?" + timing += f"<{remaining}" + extra = f", {postfix}" if postfix else "" + return f"{progress} [{timing}, {rate_text}{extra}]" def _new_progress(**kwargs: Any) -> Progress: @@ -85,8 +87,14 @@ _progress = _new_progress() # A class that provides the same interface as tqdm, # but displays progress bars using Rich. class TqdmShim(_Tqdm): + @staticmethod + def status_printer(file: Any) -> None: + # Rich owns terminal output; tqdm still performs its normal bookkeeping. + return None + def __init__(self, *args: Any, **kwargs: Any): self.rich_task_id: TaskID | None = None + self.rich_total: float | None = None super().__init__(*args, **kwargs) def _remove_task(self) -> None: @@ -101,17 +109,22 @@ class TqdmShim(_Tqdm): def display(self, *args: Any, **kwargs: Any) -> None: if self.disable: return - if self.total is not None and self.n >= self.total: + if self.total and self.n >= self.total: self._remove_task() return format_dict = self.format_dict details = _format_details(format_dict) + rich_total = self.total or None + # Rich treats update(total=None) as "leave the total unchanged". + if rich_total is None and self.rich_total is not None: + self._remove_task() + self.rich_total = rich_total if self.rich_task_id is None: _progress.start() self.rich_task_id = _progress.add_task( self.desc or "", - total=self.total, + total=rich_total, completed=self.n, details=details, ) @@ -119,14 +132,14 @@ class TqdmShim(_Tqdm): _progress.update( self.rich_task_id, description=self.desc or "", - total=self.total, + total=rich_total, completed=self.n, details=details, ) def update(self, n: float = 1) -> bool | None: refreshed = super().update(n) - if self.total is not None and self.n >= self.total: + if self.total and self.n >= self.total: with self.get_lock(): self._remove_task() return refreshed @@ -136,11 +149,10 @@ class TqdmShim(_Tqdm): self._remove_task() def close(self) -> None: - if self.disable: - return - super().close() - with self.get_lock(): - self._remove_task() + try: + super().close() + finally: + self.clear() def patch_tqdm() -> None: diff --git a/tests/test_progress.py b/tests/test_progress.py index 8c32d87..d46f79b 100644 --- a/tests/test_progress.py +++ b/tests/test_progress.py @@ -24,16 +24,19 @@ class ProgressRenderingTests(unittest.TestCase): force_interactive=True, ) self.display = progress._new_progress(console=self.console, auto_refresh=False) - self.patch = patch.object(progress, "_progress", self.display) - self.patch.start() - self.addCleanup(self.patch.stop) + for patcher in ( + patch.object(progress, "_progress", self.display), + patch.object(self.output, "isatty", return_value=True), + patch("sys.stderr", self.output), + ): + patcher.start() + self.addCleanup(patcher.stop) self.addCleanup(self.display.stop) def bar(self, description: str, **kwargs): + kwargs.setdefault("disable", None) bar = progress.TqdmShim( desc=description, - file=self.output, - disable=False, mininterval=0, miniters=1, **kwargs, @@ -43,7 +46,8 @@ class ProgressRenderingTests(unittest.TestCase): def render(self) -> str: return "".join( - segment.text for segment in self.console.render(self.display.get_renderable()) + segment.text + for segment in self.console.render(self.display.get_renderable()) ) def test_custom_format_uses_a_rich_bar(self) -> None: @@ -62,16 +66,18 @@ class ProgressRenderingTests(unittest.TestCase): output = self.render() self.assertIn("Downloading bytes", output) self.assertIn("1.00kB / 8.00kB", output) - self.assertIn("1.00kB/s", output) + self.assertIn("[00:01<00:07, 1.02kB/s]", output) self.assertIsInstance(self.display.columns[1], BarColumn) self.assertNotIn("|", output) def test_simultaneous_bars_keep_their_own_data(self) -> None: fetching = self.bar("Fetching 2 files", total=2) - reconstructing = self.bar( - "Reconstructing", total=4096, unit="B", unit_scale=True + reconstructing = self.bar("Reconstructing", total=0, unit="B", unit_scale=True) + downloading = self.bar( + "Downloading bytes", total=None, unit="B", unit_scale=True ) - downloading = self.bar("Downloading bytes", total=None, unit="B", unit_scale=True) + self.assertIn("Reconstructing", self.render()) + reconstructing.total = 4096 fetching.update(1) reconstructing.update(1024) downloading.update(1024) @@ -83,9 +89,17 @@ class ProgressRenderingTests(unittest.TestCase): self.assertEqual(output.count("Downloading bytes"), 1) self.assertIn("1.02kB / 4.10kB", output) self.assertIn("2.00kB/s", output) - reconstructing_row = next(line for line in output.splitlines() if "Reconstructing" in line) + reconstructing_row = next( + line for line in output.splitlines() if "Reconstructing" in line + ) self.assertEqual(reconstructing_row.count("B/s"), 1) self.assertIn("1.02kB", output) + reconstructing.total = None + reconstructing.refresh() + task = next( + task for task in self.display.tasks if task.description == "Reconstructing" + ) + self.assertIsNone(task.total) def test_closing_one_bar_leaves_the_other_visible(self) -> None: first = self.bar("first.bin", total=2) @@ -110,6 +124,23 @@ class ProgressRenderingTests(unittest.TestCase): self.console.print("AFTER") self.assertNotIn("finished.bin", self.output.getvalue().split("AFTER", 1)[1]) + def test_interrupted_iteration_and_disabled_close_remove_tasks(self) -> None: + bar = self.bar("probe", iterable=range(10)) + with self.assertRaises(RuntimeError): + for _ in bar: + raise RuntimeError("failed probe") + self.assertFalse(self.display.task_ids) + + raw_output = StringIO() + bar = self.bar("disabled", total=10, file=raw_output, disable=False) + bar.disable = True + bar.close() + self.assertFalse(self.display.task_ids) + + bar = self.bar("closing", total=10, file=raw_output, disable=False) + bar.close() + self.assertEqual(raw_output.getvalue(), "") + def test_hugging_face_imports_the_shim_in_a_clean_process(self) -> None: code = """ from heretic.progress import TqdmShim, patch_tqdm @@ -127,7 +158,11 @@ assert issubclass(snapshot.base_tqdm, TqdmShim) assert issubclass(hub_tqdm.tqdm, TqdmShim) """ result = subprocess.run( - [sys.executable, "-c", code], capture_output=True, text=True, timeout=30, check=False + [sys.executable, "-c", code], + capture_output=True, + text=True, + timeout=30, + check=False, ) self.assertEqual(result.returncode, 0, result.stderr) From beb261f95949804f1f6c90c736ffaf6861e95770 Mon Sep 17 00:00:00 2001 From: umran666 Date: Sat, 17 Oct 2026 18:22:02 +0530 Subject: [PATCH 29/31] refactor: use tqdm to format Rich progress statistics --- src/heretic/progress.py | 69 ++++++----------------------------------- tests/test_progress.py | 30 +++++++++++++++--- 2 files changed, 35 insertions(+), 64 deletions(-) diff --git a/src/heretic/progress.py b/src/heretic/progress.py index 4523b59..1f9070d 100644 --- a/src/heretic/progress.py +++ b/src/heretic/progress.py @@ -11,64 +11,6 @@ from rich.progress import BarColumn, Progress, TaskID, TaskProgressColumn, TextC _Tqdm = tqdm.tqdm -def _format_number(value: float | None, scale: bool, divisor: int) -> str: - if value is None: - return "?" - if scale: - return _Tqdm.format_sizeof(value, divisor=divisor) - return f"{value:g}" - - -def _format_details(format_dict: dict[str, Any]) -> str: - n = format_dict["n"] - total = format_dict["total"] - rate = format_dict["rate"] - elapsed = format_dict["elapsed"] - if rate is None and elapsed: - rate = (n - format_dict["initial"]) / elapsed - unit = format_dict["unit"] - divisor = format_dict["unit_divisor"] - unit_scale = format_dict["unit_scale"] - - # This is the same unit-scaling rule tqdm uses for its text statistics. - scale = unit_scale is True or unit_scale == 1 - if unit_scale not in (False, True, 0, 1): - n *= unit_scale - total = total * unit_scale if total is not None else None - rate = rate * unit_scale if rate is not None else None - - n_text = _format_number(n, scale, divisor) - total_text = _format_number(total, scale, divisor) - if not total: - progress = n_text - if unit != "it": - progress += unit if scale else f" {unit}" - elif scale: - progress = f"{n_text}{unit} / {total_text}{unit}" - else: - progress = f"{n_text} / {total_text}" - if unit != "it": - progress += f" {unit}" - - postfix = str(format_dict["postfix"] or "").strip().removeprefix(", ").strip() - # Some callers provide an aggregate throughput as their postfix. It is more - # useful than the per-bar rate and avoids displaying two speeds for one row. - if postfix.endswith(f"{unit}/s"): - rate_text, postfix = postfix, "" - elif rate: - value, suffix = (1 / rate, f"s/{unit}") if rate < 1 else (rate, f"{unit}/s") - rate_text = f"{_format_number(value, scale, 1000)}{suffix}" - else: - rate_text = f"?{unit}/s" - - timing = _Tqdm.format_interval(elapsed) - if total: - remaining = _Tqdm.format_interval(max(0, (total - n) / rate)) if rate else "?" - timing += f"<{remaining}" - extra = f", {postfix}" if postfix else "" - return f"{progress} [{timing}, {rate_text}{extra}]" - - def _new_progress(**kwargs: Any) -> Progress: return Progress( TextColumn("{task.description}", style="progress.description", markup=False), @@ -113,8 +55,15 @@ class TqdmShim(_Tqdm): self._remove_task() return - format_dict = self.format_dict - details = _format_details(format_dict) + format_dict = self.format_dict | { + "bar_format": ( + "{n_fmt}/{total_fmt} {unit} [{elapsed}<{remaining}, {rate_fmt}{postfix}]" + if self.total + else "{n_fmt}{unit} [{elapsed}, {rate_fmt}{postfix}]" + ), + "ncols": None, + } + details = self.format_meter(**format_dict) rich_total = self.total or None # Rich treats update(total=None) as "leave the total unchanged". if rich_total is None and self.rich_total is not None: diff --git a/tests/test_progress.py b/tests/test_progress.py index d46f79b..c181ef6 100644 --- a/tests/test_progress.py +++ b/tests/test_progress.py @@ -58,14 +58,15 @@ class ProgressRenderingTests(unittest.TestCase): unit_scale=True, unit_divisor=1024, bar_format="{desc}: {bar}| {n_fmt}B / {total_fmt}B, {rate_fmt}", + ncols=0, ) bar.last_print_t = bar.start_t with patch.object(bar, "_time", return_value=bar.start_t + 1): bar.update(1024) output = self.render() - self.assertIn("Downloading bytes", output) - self.assertIn("1.00kB / 8.00kB", output) + self.assertEqual(output.count("Downloading bytes"), 1) + self.assertIn("1.00k/8.00k B", output) self.assertIn("[00:01<00:07, 1.02kB/s]", output) self.assertIsInstance(self.display.columns[1], BarColumn) self.assertNotIn("|", output) @@ -87,12 +88,12 @@ class ProgressRenderingTests(unittest.TestCase): self.assertEqual(output.count("Fetching 2 files"), 1) self.assertEqual(output.count("Reconstructing"), 1) self.assertEqual(output.count("Downloading bytes"), 1) - self.assertIn("1.02kB / 4.10kB", output) + self.assertIn("1.02k/4.10k B", output) self.assertIn("2.00kB/s", output) reconstructing_row = next( line for line in output.splitlines() if "Reconstructing" in line ) - self.assertEqual(reconstructing_row.count("B/s"), 1) + self.assertEqual(reconstructing_row.count("B/s"), 2) self.assertIn("1.02kB", output) reconstructing.total = None reconstructing.refresh() @@ -101,6 +102,27 @@ class ProgressRenderingTests(unittest.TestCase): ) self.assertIsNone(task.total) + def test_statistics_keep_scaling_timing_and_literal_postfix(self) -> None: + cases = ( + (8, 2, 2, "4/16 B [00:02<00:06,", "2.00B/s"), + (None, True, 1000, "1.00kB [00:02,", "500B/s"), + (0, False, 0, "0B [00:02,", "?B/s"), + ) + for total, scale, completed, counts_and_time, rate in cases: + with ( + self.subTest(total=total, unit_scale=scale), + self.bar("stats", total=total, unit="B", unit_scale=scale) as bar, + ): + bar.last_print_t = bar.start_t + bar.set_postfix_str("status=[ok] ", refresh=False) + with patch.object(bar, "_time", return_value=bar.start_t + 2): + bar.update(completed) + bar.refresh() + output = self.render() + self.assertIn(counts_and_time, output) + self.assertIn(rate, output) + self.assertIn(", status=[ok] ]", output) + def test_closing_one_bar_leaves_the_other_visible(self) -> None: first = self.bar("first.bin", total=2) second = self.bar("second.bin", total=2) From 6574f64088d9b9509a6232f589d08c1b3f0fe11a Mon Sep 17 00:00:00 2001 From: umran666 Date: Sun, 18 Oct 2026 07:45:18 +0530 Subject: [PATCH 30/31] refactor: drop unused tqdm.std patch --- src/heretic/progress.py | 2 -- tests/test_progress.py | 2 -- 2 files changed, 4 deletions(-) diff --git a/src/heretic/progress.py b/src/heretic/progress.py index 1f9070d..2b4a752 100644 --- a/src/heretic/progress.py +++ b/src/heretic/progress.py @@ -5,7 +5,6 @@ from typing import Any import tqdm import tqdm.auto -import tqdm.std from rich.progress import BarColumn, Progress, TaskID, TaskProgressColumn, TextColumn _Tqdm = tqdm.tqdm @@ -107,4 +106,3 @@ class TqdmShim(_Tqdm): def patch_tqdm() -> None: tqdm.tqdm = TqdmShim # ty:ignore[invalid-assignment] tqdm.auto.tqdm = TqdmShim # ty:ignore[invalid-assignment] - tqdm.std.tqdm = TqdmShim # ty:ignore[invalid-assignment] diff --git a/tests/test_progress.py b/tests/test_progress.py index c181ef6..b344730 100644 --- a/tests/test_progress.py +++ b/tests/test_progress.py @@ -169,13 +169,11 @@ from heretic.progress import TqdmShim, patch_tqdm patch_tqdm() import tqdm import tqdm.auto -import tqdm.std import importlib import huggingface_hub._snapshot_download as snapshot hub_tqdm = importlib.import_module("huggingface_hub.utils.tqdm") assert tqdm.tqdm is TqdmShim assert tqdm.auto.tqdm is TqdmShim -assert tqdm.std.tqdm is TqdmShim assert issubclass(snapshot.base_tqdm, TqdmShim) assert issubclass(hub_tqdm.tqdm, TqdmShim) """ From d61e8830ac209c0d644a952008c5ed99cbfd83a9 Mon Sep 17 00:00:00 2001 From: umran666 Date: Sun, 18 Oct 2026 11:31:46 +0530 Subject: [PATCH 31/31] fix: restore standard tqdm import coverage --- src/heretic/progress.py | 2 ++ tests/test_progress.py | 2 ++ 2 files changed, 4 insertions(+) diff --git a/src/heretic/progress.py b/src/heretic/progress.py index 2b4a752..1f9070d 100644 --- a/src/heretic/progress.py +++ b/src/heretic/progress.py @@ -5,6 +5,7 @@ from typing import Any import tqdm import tqdm.auto +import tqdm.std from rich.progress import BarColumn, Progress, TaskID, TaskProgressColumn, TextColumn _Tqdm = tqdm.tqdm @@ -106,3 +107,4 @@ class TqdmShim(_Tqdm): def patch_tqdm() -> None: tqdm.tqdm = TqdmShim # ty:ignore[invalid-assignment] tqdm.auto.tqdm = TqdmShim # ty:ignore[invalid-assignment] + tqdm.std.tqdm = TqdmShim # ty:ignore[invalid-assignment] diff --git a/tests/test_progress.py b/tests/test_progress.py index b344730..d10cdcc 100644 --- a/tests/test_progress.py +++ b/tests/test_progress.py @@ -169,11 +169,13 @@ from heretic.progress import TqdmShim, patch_tqdm patch_tqdm() import tqdm import tqdm.auto +from tqdm.std import tqdm as std_tqdm import importlib import huggingface_hub._snapshot_download as snapshot hub_tqdm = importlib.import_module("huggingface_hub.utils.tqdm") assert tqdm.tqdm is TqdmShim assert tqdm.auto.tqdm is TqdmShim +assert std_tqdm is TqdmShim assert issubclass(snapshot.base_tqdm, TqdmShim) assert issubclass(hub_tqdm.tqdm, TqdmShim) """