Skip to content

Multithreading archive extraction#186

Closed
hagenw wants to merge 2 commits into
mainfrom
g-archive-multithreading
Closed

Multithreading archive extraction#186
hagenw wants to merge 2 commits into
mainfrom
g-archive-multithreading

Conversation

@hagenw

@hagenw hagenw commented Nov 19, 2025

Copy link
Copy Markdown
Member

Alternative implementation to #184.

This adds the num_workers argument to audeer.extract_archive() and audeer.extract_archives().

Benchmark

I run a benchmark on a 1GB ZIP file containing 1000 files, the results are

num_workers Time (s)
1 1.5
10 2.0

We do not really get any speedup by using multithreading for extracting the archive.

Summary by Sourcery

Enable parallel extraction of ZIP and TAR archives by adding a num_workers parameter to extract_archive and extract_archives.

New Features:

  • Add num_workers argument to extract_archive to split and extract archive members in parallel.
  • Add num_workers argument to extract_archives to concurrently extract multiple archives.

Enhancements:

  • Refactor extract_zip and extract_tar to accept optional member lists for chunked extraction.
  • Introduce extract_chunk helper and integrate run_tasks for concurrent extraction workflows.

Tests:

  • Add tests for multithreaded extraction of ZIP and TAR archives and for extracting multiple archives with num_workers > 1.

@sourcery-ai

sourcery-ai Bot commented Nov 19, 2025

Copy link
Copy Markdown
Contributor

Reviewer's Guide

Introduces a num_workers option to enable parallel ZIP/TAR extraction by chunking archive members and dispatching tasks, with refactored extract functions and accompanying tests.

Sequence diagram for parallel extraction of archive chunks

sequenceDiagram
    participant Caller
    participant extract_archive
    participant run_tasks
    participant extract_chunk
    Caller->>extract_archive: call with num_workers > 1
    extract_archive->>run_tasks: dispatch extract_chunk tasks for each chunk
    run_tasks->>extract_chunk: extract chunk (parallel)
    extract_chunk-->>run_tasks: return extracted files
    run_tasks-->>extract_archive: return all files
    extract_archive-->>Caller: return file list
Loading

Class diagram for updated archive extraction functions

classDiagram
    class extract_archive {
        +extract_archive(archive, destination, keep_archive, verbose, num_workers)
        +extract_zip(archive, members=None)
        +extract_tar(archive, members=None)
        +extract_chunk(archive, members, destination, extension)
    }
    class extract_archives {
        +extract_archives(archives, destination, keep_archive, verbose, num_workers)
    }
    extract_archives --> extract_archive : uses
    extract_archive o-- extract_zip : calls
    extract_archive o-- extract_tar : calls
    extract_archive o-- extract_chunk : calls
    extract_archive o-- run_tasks : uses
    extract_archive o-- flatten_list : uses
Loading

Flow diagram for multithreaded archive extraction process

flowchart TD
    A["extract_archive() called with num_workers > 1"] --> B["Determine archive type (ZIP/TAR)"]
    B --> C["List archive members"]
    C --> D["Split members into chunks"]
    D --> E["Dispatch extract_chunk tasks via run_tasks"]
    E --> F["Flatten results and return file list"]
Loading

File-Level Changes

Change Details Files
Add num_workers argument and update docstrings
  • Include num_workers parameter in extract_archive and extract_archives signatures
  • Describe parallel extraction behavior in function docstrings
audeer/core/io.py
Refactor extract_zip and extract_tar to accept optional member lists
  • Add members parameter to both functions
  • Conditional logic to retrieve default members or specific members
audeer/core/io.py
Implement parallel extraction workflow
  • Introduce extract_chunk helper to dispatch based on extension
  • Chunk member lists evenly and assemble task parameters
  • Use run_tasks with progress bar and flatten_list to collect results
audeer/core/io.py
Propagate num_workers through extract_archives
  • Pass num_workers to each extract_archive call in batch extraction loop
audeer/core/io.py
Add tests for multithreaded extraction
  • Verify parallel extraction for ZIP and TAR archives
  • Test extract_archives with multiple archives and overlapping filenames
tests/test_io_multithread.py

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@codecov

codecov Bot commented Nov 19, 2025

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.0%. Comparing base (44b85bd) to head (7c17826).

Additional details and impacted files
Files with missing lines Coverage Δ
audeer/core/io.py 100.0% <100.0%> (ø)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey there - I've reviewed your changes - here's some feedback:

  • Add validation to ensure num_workers is at least 1 and raise a clear error for invalid or zero/negative values.
  • Remove the duplicated keep_archive entry in the docstrings and streamline the description for the new num_workers parameter.
  • Parallel extraction splits members into contiguous chunks which can change output order and imbalance work; consider preserving original ordering in the flattened result or using round-robin assignment for better load distribution.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Add validation to ensure num_workers is at least 1 and raise a clear error for invalid or zero/negative values.
- Remove the duplicated keep_archive entry in the docstrings and streamline the description for the new num_workers parameter.
- Parallel extraction splits members into contiguous chunks which can change output order and imbalance work; consider preserving original ordering in the flattened result or using round-robin assignment for better load distribution.

## Individual Comments

### Comment 1
<location> `audeer/core/io.py:376-377` </location>
<code_context>
     disable = not verbose

-    def extract_zip(archive: str) -> list:
+    def extract_zip(
+        archive: str,
+        members: Sequence[str] | None = None,
+    ) -> list:
</code_context>

<issue_to_address>
**suggestion:** Type annotation for members parameter could be more precise.

Since `members` can be a sequence of either member names or ZipInfo objects, update the annotation to reflect this for better clarity and type safety.

Suggested implementation:

```python
    def extract_zip(
        archive: str,
        members: Sequence[str | zipfile.ZipInfo] | None = None,
    ) -> list:

```

If `zipfile` is not already imported at the top of the file, add:
```python
import zipfile
```
</issue_to_address>

### Comment 2
<location> `audeer/core/io.py:389-377` </location>
<code_context>
             return [m.filename for m in members]

-    def extract_tar(archive: str) -> list:
+    def extract_tar(
+        archive: str,
+        members: Sequence[str] | None = None,
+    ) -> list:
</code_context>

<issue_to_address>
**issue (bug_risk):** Potential exception risk with tf.getmember(m) if member does not exist.

If a member name is missing from the archive, tf.getmember(m) will raise a KeyError. Please handle this exception or clarify the expected behavior.
</issue_to_address>

### Comment 3
<location> `tests/test_io_multithread.py:6-10` </location>
<code_context>
+import audeer
+
+
+def test_extract_archive_multithread(tmpdir):
+    root = audeer.mkdir(tmpdir, "root")
+    # Create a bunch of files
+    files = [f"file_{i}.txt" for i in range(10)]
+    for file in files:
+        audeer.touch(root, file)
+
</code_context>

<issue_to_address>
**suggestion (testing):** Missing test for num_workers=1 (sequential extraction).

Add a test for num_workers=1 to verify sequential extraction matches multithreaded behavior.
</issue_to_address>

### Comment 4
<location> `tests/test_io_multithread.py:31-10` </location>
<code_context>
+        assert os.path.exists(os.path.join(destination, file))
+
+
+def test_extract_tar_multithread(tmpdir):
+    root = audeer.mkdir(tmpdir, "root")
+    files = [f"file_{i}.txt" for i in range(10)]
+    for file in files:
+        audeer.touch(root, file)
+
</code_context>

<issue_to_address>
**suggestion (testing):** No test for extracting archives with zero files.

Add a test for extracting an empty archive with num_workers > 1 to ensure the function returns an empty list and handles the case correctly.
</issue_to_address>

### Comment 5
<location> `tests/test_io_multithread.py:10-11` </location>
<code_context>

</code_context>

<issue_to_address>
**issue (code-quality):** Avoid loops in tests. ([`no-loop-in-tests`](https://docs.sourcery.ai/Reference/Rules-and-In-Line-Suggestions/Python/Default-Rules/no-loop-in-tests))

<details><summary>Explanation</summary>Avoid complex code, like loops, in test functions.

Google's software engineering guidelines says:
"Clear tests are trivially correct upon inspection"
To reach that avoid complex code in tests:
* loops
* conditionals

Some ways to fix this:

* Use parametrized tests to get rid of the loop.
* Move the complex logic into helpers.
* Move the complex part into pytest fixtures.

> Complexity is most often introduced in the form of logic. Logic is defined via the imperative parts of programming languages such as operators, loops, and conditionals. When a piece of code contains logic, you need to do a bit of mental computation to determine its result instead of just reading it off of the screen. It doesn't take much logic to make a test more difficult to reason about.

Software Engineering at Google / [Don't Put Logic in Tests](https://abseil.io/resources/swe-book/html/ch12.html#donapostrophet_put_logic_in_tests)
</details>
</issue_to_address>

### Comment 6
<location> `tests/test_io_multithread.py:27-28` </location>
<code_context>

</code_context>

<issue_to_address>
**issue (code-quality):** Avoid loops in tests. ([`no-loop-in-tests`](https://docs.sourcery.ai/Reference/Rules-and-In-Line-Suggestions/Python/Default-Rules/no-loop-in-tests))

<details><summary>Explanation</summary>Avoid complex code, like loops, in test functions.

Google's software engineering guidelines says:
"Clear tests are trivially correct upon inspection"
To reach that avoid complex code in tests:
* loops
* conditionals

Some ways to fix this:

* Use parametrized tests to get rid of the loop.
* Move the complex logic into helpers.
* Move the complex part into pytest fixtures.

> Complexity is most often introduced in the form of logic. Logic is defined via the imperative parts of programming languages such as operators, loops, and conditionals. When a piece of code contains logic, you need to do a bit of mental computation to determine its result instead of just reading it off of the screen. It doesn't take much logic to make a test more difficult to reason about.

Software Engineering at Google / [Don't Put Logic in Tests](https://abseil.io/resources/swe-book/html/ch12.html#donapostrophet_put_logic_in_tests)
</details>
</issue_to_address>

### Comment 7
<location> `tests/test_io_multithread.py:34-35` </location>
<code_context>

</code_context>

<issue_to_address>
**issue (code-quality):** Avoid loops in tests. ([`no-loop-in-tests`](https://docs.sourcery.ai/Reference/Rules-and-In-Line-Suggestions/Python/Default-Rules/no-loop-in-tests))

<details><summary>Explanation</summary>Avoid complex code, like loops, in test functions.

Google's software engineering guidelines says:
"Clear tests are trivially correct upon inspection"
To reach that avoid complex code in tests:
* loops
* conditionals

Some ways to fix this:

* Use parametrized tests to get rid of the loop.
* Move the complex logic into helpers.
* Move the complex part into pytest fixtures.

> Complexity is most often introduced in the form of logic. Logic is defined via the imperative parts of programming languages such as operators, loops, and conditionals. When a piece of code contains logic, you need to do a bit of mental computation to determine its result instead of just reading it off of the screen. It doesn't take much logic to make a test more difficult to reason about.

Software Engineering at Google / [Don't Put Logic in Tests](https://abseil.io/resources/swe-book/html/ch12.html#donapostrophet_put_logic_in_tests)
</details>
</issue_to_address>

### Comment 8
<location> `tests/test_io_multithread.py:50-51` </location>
<code_context>

</code_context>

<issue_to_address>
**issue (code-quality):** Avoid loops in tests. ([`no-loop-in-tests`](https://docs.sourcery.ai/Reference/Rules-and-In-Line-Suggestions/Python/Default-Rules/no-loop-in-tests))

<details><summary>Explanation</summary>Avoid complex code, like loops, in test functions.

Google's software engineering guidelines says:
"Clear tests are trivially correct upon inspection"
To reach that avoid complex code in tests:
* loops
* conditionals

Some ways to fix this:

* Use parametrized tests to get rid of the loop.
* Move the complex logic into helpers.
* Move the complex part into pytest fixtures.

> Complexity is most often introduced in the form of logic. Logic is defined via the imperative parts of programming languages such as operators, loops, and conditionals. When a piece of code contains logic, you need to do a bit of mental computation to determine its result instead of just reading it off of the screen. It doesn't take much logic to make a test more difficult to reason about.

Software Engineering at Google / [Don't Put Logic in Tests](https://abseil.io/resources/swe-book/html/ch12.html#donapostrophet_put_logic_in_tests)
</details>
</issue_to_address>

### Comment 9
<location> `tests/test_io_multithread.py:57-58` </location>
<code_context>

</code_context>

<issue_to_address>
**issue (code-quality):** Avoid loops in tests. ([`no-loop-in-tests`](https://docs.sourcery.ai/Reference/Rules-and-In-Line-Suggestions/Python/Default-Rules/no-loop-in-tests))

<details><summary>Explanation</summary>Avoid complex code, like loops, in test functions.

Google's software engineering guidelines says:
"Clear tests are trivially correct upon inspection"
To reach that avoid complex code in tests:
* loops
* conditionals

Some ways to fix this:

* Use parametrized tests to get rid of the loop.
* Move the complex logic into helpers.
* Move the complex part into pytest fixtures.

> Complexity is most often introduced in the form of logic. Logic is defined via the imperative parts of programming languages such as operators, loops, and conditionals. When a piece of code contains logic, you need to do a bit of mental computation to determine its result instead of just reading it off of the screen. It doesn't take much logic to make a test more difficult to reason about.

Software Engineering at Google / [Don't Put Logic in Tests](https://abseil.io/resources/swe-book/html/ch12.html#donapostrophet_put_logic_in_tests)
</details>
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread audeer/core/io.py
Comment thread audeer/core/io.py
Comment thread tests/test_io_multithread.py Outdated
Comment on lines +6 to +10
def test_extract_archive_multithread(tmpdir):
root = audeer.mkdir(tmpdir, "root")
# Create a bunch of files
files = [f"file_{i}.txt" for i in range(10)]
for file in files:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (testing): Missing test for num_workers=1 (sequential extraction).

Add a test for num_workers=1 to verify sequential extraction matches multithreaded behavior.

Comment thread audeer/core/io.py Outdated
Comment thread audeer/core/io.py Outdated
@hagenw

hagenw commented Jan 9, 2026

Copy link
Copy Markdown
Member Author

Adding multi-threading to archive extraction does not provide any speedups.

Instead we should consider extracting archives in parallel (#187) or when downloading the archive from a backend use streaming ZIP extraction to extract the archive while downloading (audeering/audbackend#279).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant