Skip to content

Add num_workers argument to extract_archive()#184

Closed
hagenw wants to merge 5 commits into
mainfrom
archive-num-workers-2
Closed

Add num_workers argument to extract_archive()#184
hagenw wants to merge 5 commits into
mainfrom
archive-num-workers-2

Conversation

@hagenw

@hagenw hagenw commented Nov 11, 2025

Copy link
Copy Markdown
Member

This speeds up extracting of archives containing multiple files by adding a num_workers argument.

image

Summary by Sourcery

Enable configurable parallel extraction in extract_archive by introducing a num_workers parameter, refactoring member extraction, and adding tests to ensure multi-threaded behavior matches sequential results.

New Features:

  • Add num_workers parameter to extract_archive to enable parallel extraction of archive members
  • Support parallel extraction of ZIP and TAR archives using multiple workers

Enhancements:

  • Refactor extraction logic into per-member helper functions and unify sequential and parallel flows
  • Allow num_workers=None to default to CPU count multiplied by 5 for optimal parallelism

Documentation:

  • Update extract_archive docstring to describe the new num_workers argument

Tests:

  • Introduce parameterized tests verifying multi-threaded extraction yields identical results to single-threaded extraction for ZIP and TAR archives

@sourcery-ai

sourcery-ai Bot commented Nov 11, 2025

Copy link
Copy Markdown
Contributor

Reviewer's Guide

This PR extends extract_archive() to support parallel extraction by introducing a num_workers parameter, refactoring extraction into per-member helper functions, and dispatching tasks via run_tasks, plus new tests to validate multi-threaded behavior.

Sequence diagram for parallel extraction in extract_archive()

sequenceDiagram
participant Caller
participant "extract_archive()"
participant "run_tasks()"
participant "extract_zip_member()"
participant "extract_tar_member()"

Caller->>"extract_archive()": Call with num_workers > 1
alt ZIP archive
    "extract_archive()"->>"run_tasks()": Dispatch extract_zip_member for each file
    "run_tasks()"->>"extract_zip_member()": Extract file (parallel)
else TAR archive
    "extract_archive()"->>"run_tasks()": Dispatch extract_tar_member for each file
    "run_tasks()"->>"extract_tar_member()": Extract file (parallel)
end
"extract_archive()"-->>Caller: Return list of extracted files
Loading

Class diagram for updated extract_archive() and helpers

classDiagram
class extract_archive {
    +keep_archive: bool
    +verbose: bool
    +num_workers: int | None
    +extract_zip(archive: str) list
    +extract_tar(archive: str) list
}
class extract_zip_member {
    +member
}
class extract_tar_member {
    +member
}
class run_tasks {
    +func
    +params
    +num_workers
    +progress_bar
    +task_description
}
extract_archive o-- extract_zip_member
extract_archive o-- extract_tar_member
extract_archive ..> run_tasks
Loading

File-Level Changes

Change Details Files
Add num_workers parameter and update docstring
  • Add num_workers to extract_archive signature
  • Document behavior, defaults, and performance note in docstring
audeer/core/io.py
Refactor extraction to support sequential and parallel modes
  • Define extract_zip_member and extract_tar_member helpers
  • Branch extract_zip and extract_tar on num_workers
  • Use run_tasks for parallel extraction with progress_bar
audeer/core/io.py
Add multithreaded extraction tests
  • Parametrize tests for zip and tar.gz archives
  • Compare single-threaded vs multi-threaded outputs
  • Assert file existence and content consistency
tests/test_io.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

@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:

  • The extract_zip_member and extract_tar_member functions reopen the archive for every file, which can be inefficient—consider opening the archive once and sharing it across worker threads or batching extractions.
  • The num_workers=None pathway isn’t actually implemented—None is passed directly to run_tasks, so you should default it to CPU count * 5 (as documented) or validate/normalize the parameter before use.
  • Archive extraction should sanitize member paths to prevent directory traversal attacks (e.g., stripping leading ‘..’), especially when unpacking untrusted archives.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The `extract_zip_member` and `extract_tar_member` functions reopen the archive for every file, which can be inefficient—consider opening the archive once and sharing it across worker threads or batching extractions.
- The `num_workers=None` pathway isn’t actually implemented—None is passed directly to `run_tasks`, so you should default it to CPU count * 5 (as documented) or validate/normalize the parameter before use.
- Archive extraction should sanitize member paths to prevent directory traversal attacks (e.g., stripping leading ‘..’), especially when unpacking untrusted archives.

## Individual Comments

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

+    def extract_zip_member(member):
+        """Extract a single member from a ZIP archive."""
+        with zipfile.ZipFile(archive, "r") as zf:
+            zf.extract(member, destination)
+
</code_context>

<issue_to_address>
**issue (performance):** Repeated opening of the archive file for each member may impact performance.

Opening the archive file for each extraction can add overhead and reduce parallelization efficiency. Refactor to open the archive once and share the handle if possible, or clarify in documentation if this approach is necessary for thread safety.
</issue_to_address>

### Comment 2
<location> `audeer/core/io.py:370` </location>
<code_context>
+            # Sequential extraction with progress bar
             for member in progress_bar(members, desc=desc, disable=disable):
-                zf.extract(member, destination)
-            return [m.filename for m in members]
+                extract_zip_member(member)
+        else:
</code_context>

<issue_to_address>
**issue:** Inconsistent return value for ZIP and TAR extraction.

Standardize the return value between extract_zip and extract_tar to avoid confusion for downstream consumers, particularly when handling directories or special files.
</issue_to_address>

### Comment 3
<location> `tests/test_io.py:1632-1641` </location>
<code_context>
+def test_extract_archive_multithread(tmpdir, archive_type):
</code_context>

<issue_to_address>
**suggestion (testing):** Missing test for num_workers=None and num_workers > number of files.

Please add tests for num_workers=None and for cases where num_workers is greater than the number of files to fully cover the argument's logic.
</issue_to_address>

### Comment 4
<location> `tests/test_io.py:1637-1641` </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 5
<location> `tests/test_io.py:1668-1680` </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 Outdated
Comment thread audeer/core/io.py
@codecov

codecov Bot commented Nov 11, 2025

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.0%. Comparing base (e0339c2) to head (ab87223).
⚠️ Report is 1 commits behind head on main.

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.

@hagenw

hagenw commented Jan 8, 2026

Copy link
Copy Markdown
Member Author

Closing in favor of #186

@hagenw hagenw closed this Jan 8, 2026
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