Skip to content

read_storage() - filter by name pattern #1285

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from

Conversation

dmpetrov
Copy link
Member

@dmpetrov dmpetrov commented Aug 10, 2025

NOT READY YET because I don't like pattern=.. approach. Figuring our if the pattern could be fit into storage string.

Closes #1283 pattern only: dc.read_storage("s3://bkt/dir", pattern="*.jpg") or dc.read_storage("s3://bkt/dir", pattern=["*.jpg", "*.png"])

Summary by Sourcery

Add support for file name pattern filtering to read_storage

New Features:

  • Introduce optional pattern parameter in read_storage to filter input files by glob patterns
  • Implement _apply_pattern_filtering helper to apply single or multiple glob filters on a DataChain

Enhancements:

  • Update read_storage to apply the pattern filter before returning the chain

Documentation:

  • Enhance read_storage docstring with usage examples for single and multiple patterns

Tests:

  • Add unit tests for _apply_pattern_filtering covering matching, non-matching, empty, and None patterns

@dmpetrov dmpetrov marked this pull request as draft August 10, 2025 01:47
Copy link
Contributor

sourcery-ai bot commented Aug 10, 2025

Reviewer's Guide

Adds optional pattern-based file filtering to read_storage by introducing a helper that builds glob filters, updates the function API and documentation, and accompanies the feature with comprehensive unit tests.

Class diagram for updated read_storage and _apply_pattern_filtering

classDiagram
    class DataChain {
        +filter(expr)
    }
    class C {
        +glob(pattern)
    }
    class _apply_pattern_filtering {
        +_apply_pattern_filtering(chain: DataChain, pattern: Union[str, list[str]], column: str) DataChain
    }
    class read_storage {
        +read_storage(uri, ..., pattern=None, ...) DataChain
    }
    read_storage --> _apply_pattern_filtering : uses
    _apply_pattern_filtering --> DataChain : filters
    _apply_pattern_filtering --> C : builds filter expressions
Loading

Flow diagram for pattern-based filtering in read_storage

flowchart TD
    A[User calls read_storage with pattern argument] --> B[read_storage processes storage_chain]
    B --> C[_apply_pattern_filtering applies glob filters]
    C --> D[Filtered DataChain returned]
    B -->|No pattern| D
Loading

File-Level Changes

Change Details Files
Implement pattern-based filtering helper
  • Introduce _apply_pattern_filtering with glob-based filter construction
  • Handle no-pattern case by returning original chain
  • Combine multiple patterns with OR logic
src/datachain/lib/dc/storage.py
Extend read_storage to support pattern filtering
  • Add optional pattern parameter to signature
  • Integrate _apply_pattern_filtering at end of function
  • Update docstring to include pattern description and examples
src/datachain/lib/dc/storage.py
Add unit tests for pattern filtering
  • Test single and multiple pattern scenarios
  • Verify no-filter and empty-list behaviors
  • Check non-matching pattern returns zero results
tests/unit/lib/test_datachain.py

Assessment against linked issues

Issue Objective Addressed Explanation
#1283 Implement a shortcut in read_storage() to filter files by name patterns using a 'patterns' (plural) argument, supporting both single pattern strings and lists.
#1283 Support globstar-based filtering in read_storage(), allowing users to specify patterns like 's3://mybkt/dir1/dir2/**/*.mp3' for file selection.

Possibly linked issues


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

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

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

  • Make sure you import typing.Union and the C helper for column construction in storage.py so that _apply_pattern_filtering compiles without errors.
  • Consider applying the pattern filter to each individual chain before merging multiple URIs to reduce intermediate result sizes and improve efficiency.
  • The glob logic always prepends a wildcard, which can lead to double-wildcard patterns when the user already includes '*'; consider normalizing or documenting this behavior to avoid confusion.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- Make sure you import typing.Union and the C helper for column construction in storage.py so that _apply_pattern_filtering compiles without errors.
- Consider applying the pattern filter to each individual chain before merging multiple URIs to reduce intermediate result sizes and improve efficiency.
- The glob logic always prepends a wildcard, which can lead to double-wildcard patterns when the user already includes '*'; consider normalizing or documenting this behavior to avoid confusion.

## Individual Comments

### Comment 1
<location> `src/datachain/lib/dc/storage.py:43` </location>
<code_context>
+    pattern_list = pattern if isinstance(pattern, list) else [pattern]
+    filters = []
+
+    for pattern_item in pattern_list:
+        filters.append(C(f"{column}.path").glob(f"*{pattern_item}"))
+
+    combined_filter = filters[0]
</code_context>

<issue_to_address>
Pattern matching may be too permissive for certain use cases.

Consider whether using `*{pattern_item}` could unintentionally match more files than intended, especially if user-supplied patterns already include wildcards.
</issue_to_address>

<suggested_fix>
<<<<<<< SEARCH
    for pattern_item in pattern_list:
        filters.append(C(f"{column}.path").glob(f"*{pattern_item}"))
=======
    for pattern_item in pattern_list:
        # If the pattern already contains glob wildcards, use as-is
        if any(char in pattern_item for char in ["*", "?", "["]):
            glob_pattern = pattern_item
        else:
            glob_pattern = f"*{pattern_item}*"
        filters.append(C(f"{column}.path").glob(glob_pattern))
>>>>>>> REPLACE

</suggested_fix>

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 on lines +43 to +44
for pattern_item in pattern_list:
filters.append(C(f"{column}.path").glob(f"*{pattern_item}"))
Copy link
Contributor

Choose a reason for hiding this comment

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

suggestion: Pattern matching may be too permissive for certain use cases.

Consider whether using *{pattern_item} could unintentionally match more files than intended, especially if user-supplied patterns already include wildcards.

Suggested change
for pattern_item in pattern_list:
filters.append(C(f"{column}.path").glob(f"*{pattern_item}"))
for pattern_item in pattern_list:
# If the pattern already contains glob wildcards, use as-is
if any(char in pattern_item for char in ["*", "?", "["]):
glob_pattern = pattern_item
else:
glob_pattern = f"*{pattern_item}*"
filters.append(C(f"{column}.path").glob(glob_pattern))

Comment on lines +41 to +45
filters = []

for pattern_item in pattern_list:
filters.append(C(f"{column}.path").glob(f"*{pattern_item}"))

Copy link
Contributor

Choose a reason for hiding this comment

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

suggestion (code-quality): Convert for loop into list comprehension (list-comprehension)

Suggested change
filters = []
for pattern_item in pattern_list:
filters.append(C(f"{column}.path").glob(f"*{pattern_item}"))
filters = [
C(f"{column}.path").glob(f"*{pattern_item}")
for pattern_item in pattern_list
]

Copy link

cloudflare-workers-and-pages bot commented Aug 10, 2025

Deploying datachain-documentation with  Cloudflare Pages  Cloudflare Pages

Latest commit: 5798e9a
Status: ✅  Deploy successful!
Preview URL: https://1eea906f.datachain-documentation.pages.dev
Branch Preview URL: https://feature-pattern-based-filter.datachain-documentation.pages.dev

View logs

Copy link

codecov bot commented Aug 10, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 88.80%. Comparing base (f25a736) to head (5798e9a).

Additional details and impacted files

Impacted file tree graph

@@           Coverage Diff           @@
##             main    #1285   +/-   ##
=======================================
  Coverage   88.79%   88.80%           
=======================================
  Files         153      153           
  Lines       14055    14067   +12     
  Branches     1980     1983    +3     
=======================================
+ Hits        12480    12492   +12     
  Misses       1113     1113           
  Partials      462      462           
Flag Coverage Δ
datachain 88.73% <100.00%> (+<0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
src/datachain/lib/dc/storage.py 100.00% <100.00%> (ø)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

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.

Filename filter shortcut in read_storage()
1 participant