From fcc67509c419251847ed2a2b65c038ffb81f97da Mon Sep 17 00:00:00 2001 From: pawank925 <229111348+pawank925@users.noreply.github.com> Date: Wed, 4 Nov 2026 23:02:31 +0530 Subject: [PATCH] Fix hang when a ZIM creation is abandoned before finishing libzim cannot cancel a creation and its worker threads call back into Python to read item content. Abandoning a Creator before finishing left those threads waiting for the GIL while the interpreter held it and joined them from the libzim destructor, deadlocking the process exit. Finish the creation with the GIL released so the workers can drain, then remove the resulting ZIM. This now happens when finishing after an error and, through an atexit sweep, when the creator is neither finished nor collected before the interpreter exits. Closes #300 --- CHANGELOG.md | 1 + src/zimscraperlib/zim/creator.py | 68 ++++++++++++++++++------ tests/zim/test_zim_creator.py | 89 ++++++++++++++++++++++++++++++++ 3 files changed, 141 insertions(+), 17 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cc54d0fc..f4316a75 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed - Patch vendored `wombat.js` so `fetch()` converts POST to GET like `XMLHttpRequest` already does, fixing YouTube embedded player video playback (#379, webrecorder/wombat#242) +- Stop a `zim.Creator` abandoned before finishing (e.g. after an item path duplication) from hanging forever at garbage collection or interpreter exit: its libzim worker threads are now drained with the GIL released and the partially written ZIM is removed (#300) ## [5.5.1] - 2026-10-30 diff --git a/src/zimscraperlib/zim/creator.py b/src/zimscraperlib/zim/creator.py index c6dfd5b7..e07c055c 100644 --- a/src/zimscraperlib/zim/creator.py +++ b/src/zimscraperlib/zim/creator.py @@ -14,11 +14,13 @@ - content stored on object - can be used to store a filepath and content read from it (not stored)""" +import atexit import io import logging import pathlib import re import weakref +from contextlib import suppress from types import TracebackType import libzim.writer # pyright: ignore[reportMissingModuleSource] @@ -85,18 +87,14 @@ def mimetype_for( class Creator(libzim.writer.Creator): """libzim.writer.Creator subclass - Note: due to the lack of a cancel() method in the libzim itself, it is not possible - to stop a zim creation process. Should an error occur in your code, a Zim file - with up-to-that-moment content will be created at destination. + Note: libzim has no cancel() method, so a ZIM creation cannot be stopped. + When an error occurs while adding an item, this class prevents the creation + from completing and discards the ZIM: the output file is removed as soon as + the creator is finished, garbage-collected or the interpreter exits. + Since libzim can only stop its worker threads by running its finalization, + this cleanup takes as long as finishing the creation would. - To prevent this (creating an unwanted ZIM file) from happening, - a workaround is in place. It prevents the libzim from finishing its process. - While it results in no ZIM file being created, it also results in - the zim temp folder to be left on disk and very frequently leads to - a segmentation fault at garbage collection (on exit mostly). - - Meaning you should exit right after an exception in your code (during zim creation) - Use workaround_nocancel=False to disable the workaround. + Use workaround_nocancel=False to let libzim finish the ZIM despite the error. By default, all metadata are validated for compliance with openZIM specification and conventions. Set metdata.APPLY_RECOMMENDATIONS to False to disable this validation @@ -118,6 +116,7 @@ def __init__( self.__indexing_value: bool = False self.can_finish = True self._finish_called = False + self._creation_started = False self.set_mainpath(main_path) @@ -128,6 +127,7 @@ def __init__( self.workaround_nocancel = workaround_nocancel self.ignore_duplicates = ignore_duplicates + _live_creators.add(self) def config_indexing( self, @@ -242,6 +242,7 @@ def start(self): logger.debug(f"Metadata: Tags has been set with '{ftindex_tag}'") super().__enter__() + self._creation_started = True for metadata in self._metadata.values(): if isinstance(metadata, IllustrationBasedMetadata): @@ -434,7 +435,7 @@ def add_item( # pyright: ignore[reportIncompatibleMethodOverride] raise exc except Exception: if self.workaround_nocancel: - self.can_finish = False # pragma: no cover + self.can_finish = False raise def add_redirect( @@ -464,7 +465,7 @@ def add_redirect( raise exc except Exception: if self.workaround_nocancel: - self.can_finish = False # pragma: no cover + self.can_finish = False raise def finish( @@ -474,14 +475,41 @@ def finish( ___: TracebackType | None = None, ): """Triggers finalization of ZIM creation and create final ZIM file.""" - if not getattr(self, "can_finish", False): + if getattr(self, "_finish_called", False): + return + self._finish_called = True + _live_creators.discard(self) + if getattr(self, "can_finish", False): + super().__exit__(None, None, None) return - # finishing an already-finished creator makes libzim raise a RuntimeError; - # make this a no-op instead of calling into libzim again + self._drain_and_discard() + + def _abandon(self) -> None: if getattr(self, "_finish_called", False): return self._finish_called = True - super().__exit__(None, None, None) + _live_creators.discard(self) + self._drain_and_discard() + + def _drain_and_discard(self) -> None: + if not getattr(self, "_creation_started", False): + return + try: + with suppress(RuntimeError): + super().__exit__(None, None, None) + finally: + if self.filename.is_file(): + self.filename.unlink(missing_ok=True) + + def __del__(self) -> None: + with suppress(Exception): + self._abandon() + + @staticmethod + def _abandon_live_creators() -> None: + for creator in list(_live_creators): + with suppress(Exception): + creator._abandon() def __enter__(self): self.start() @@ -494,3 +522,9 @@ def __exit__( exc_tb: TracebackType | None = None, ): self.finish(exc_type, exc_val, exc_tb) + + +_live_creators: weakref.WeakSet[Creator] = weakref.WeakSet() + + +atexit.register(Creator._abandon_live_creators) # pyright: ignore[reportPrivateUsage] diff --git a/tests/zim/test_zim_creator.py b/tests/zim/test_zim_creator.py index dc7888b2..2fad9323 100644 --- a/tests/zim/test_zim_creator.py +++ b/tests/zim/test_zim_creator.py @@ -1,4 +1,5 @@ import datetime as dt +import gc import io import logging import pathlib @@ -7,6 +8,7 @@ import subprocess import sys import tempfile +import textwrap import time from types import NoneType from typing import Any, NamedTuple @@ -16,6 +18,7 @@ import pytest from libzim.writer import Compression # pyright: ignore[reportMissingModuleSource] +import zimscraperlib.zim.creator as creator_module from zimscraperlib.constants import UTF8 from zimscraperlib.download import save_large_file, stream_file from zimscraperlib.filesystem import delete_callback @@ -669,6 +672,92 @@ def test_ignore_duplicates(tmp_path: pathlib.Path): creator.add_redirect(path="B", target_path="C") +def test_duplicate_error_discards_zim(tmp_path: pathlib.Path): + fpath = tmp_path / "test.zim" + with Creator(fpath, "").config_dev_metadata() as creator: + creator.add_item_for(path="A", content="A") + with pytest.raises(RuntimeError, match="existing dirent's title"): + creator.add_item_for(path="A", content="A2") + assert not fpath.exists() + + +def test_garbage_collected_creation_discards_zim(tmp_path: pathlib.Path): + fpath = tmp_path / "test.zim" + creator = Creator(fpath, "").config_dev_metadata() + creator.start() + creator.add_item_for(path="A", content="A") + del creator + gc.collect() + assert not fpath.exists() + + +def test_duplicate_on_filled_cluster_terminates(tmp_path: pathlib.Path): + script = tmp_path / "repro.py" + fpath = tmp_path / "tests.zim" + script.write_text( + textwrap.dedent( + """ + import sys + from pathlib import Path + + from zimscraperlib.zim import Creator, metadata + + creator = Creator( + Path(sys.argv[1]), "index.html" + ).config_metadata(std_metadata=metadata.DEFAULT_DEV_ZIM_METADATA) + creator.start() + creator.add_item_for( + "index.html", "Main Page", content="Main", is_front=True + ) + for i in range(10): + creator.add_item_for(f"content{i}", content="P" * 1000000) + creator.add_item_for("conflict", content="Foo") + creator.add_item_for("conflict", content="Bar") + """ + ) + ) + result = subprocess.run( + [sys.executable, str(script), str(fpath)], + capture_output=True, + timeout=60, + check=False, + ) + assert result.returncode != 0 + assert b"existing dirent's title" in result.stderr + assert not fpath.exists() + + +def test_atexit_sweep_discards_unfinished_creation(tmp_path: pathlib.Path): + fpath = tmp_path / "test.zim" + live_creators = creator_module._live_creators # pyright: ignore[reportPrivateUsage] + creator = Creator(fpath, "").config_dev_metadata() + creator.start() + creator.add_item_for(path="A", content="A") + with pytest.raises(RuntimeError, match="existing dirent's title"): + creator.add_item_for(path="A", content="A2") + # neither finish() nor garbage collection ran: the creation is still live + assert creator in live_creators + + Creator._abandon_live_creators() # pyright: ignore[reportPrivateUsage] + + assert not fpath.exists() + assert creator not in live_creators + + +def test_without_workaround_keeps_zim_on_duplicate(tmp_path: pathlib.Path): + fpath = tmp_path / "test.zim" + with Creator( + fpath, "welcome", workaround_nocancel=False + ).config_dev_metadata() as creator: + creator.add_item_for(path="welcome", content="first") + with pytest.raises(RuntimeError, match="existing dirent's title"): + creator.add_item_for(path="welcome", content="second") + with pytest.raises(RuntimeError, match="existing dirent's title"): + creator.add_redirect(path="welcome", target_path="other") + reader = Archive(fpath) + assert bytes(reader.get_item("welcome").content) == b"first" + + def test_without_metadata(tmp_path: pathlib.Path): with pytest.raises(ValueError, match=r"Mandatory metadata are not all set\."): Creator(tmp_path, "").start()