Incremental engine for long horizon agents π Star if you like it!
Rust agentic-data-frameworkaiai-agentschange-data-capturecodebase-intelligencecontext-engineeringdata-engineeringdata-indexingdata-processingetlhelp-wantedindexingknowledge-graphllmlong-horizon-agentpythonragreal-timerustsemantic-search
fix(connectors): object store walkers honor excluded directories (#2822)
Jiangzhoubb7f18bbde2d
diff --git a/docs/src/content/docs/common_resources/data_types.mdx b/docs/src/content/docs/common_resources/data_types.mdxindex d1baf0f1..68f8ebe4 100644--- a/docs/src/content/docs/common_resources/data_types.mdx+++ b/docs/src/content/docs/common_resources/data_types.mdx@@ -299,7 +299,7 @@ let files = walk_dir(sourcedir)**Parameters:**- `included_patterns` β Glob patterns ([globset](https://docs.rs/globset) syntax) for files to include. Use `**/*.ext` to match at any depth. <Lang only="python">If `None`, all files are included.</Lang><Lang only="rust">An empty list includes all files.</Lang>-- `excluded_patterns` β Glob patterns ([globset](https://docs.rs/globset) syntax) for files/directories to exclude. Excluded directories are not traversed. A pattern prefixed with `!` negates the exclusion for matching paths (see below).+- `excluded_patterns` β Glob patterns ([globset](https://docs.rs/globset) syntax) for files/directories to exclude. Excluded directories are not traversed. In an object store (Amazon S3, Azure Blob Storage, OCI Object Storage), the folders of an object's key are its directories: excluding `logs` skips `logs/2024/a.txt`. A pattern prefixed with `!` negates the exclusion for matching paths (see below).:::notePatterns use [globset](https://docs.rs/globset) semantics: `*.py` matches only in the root directory; use `**/*.py` to match at any depth.diff --git a/python/cocoindex/connectorkits/_object_store.py b/python/cocoindex/connectorkits/_object_store.pyindex 8998db64..e1655e8c 100644--- a/python/cocoindex/connectorkits/_object_store.py+++ b/python/cocoindex/connectorkits/_object_store.py@@ -10,7 +10,7 @@ from __future__ import annotationsfrom abc import abstractmethodfrom pathlib import PurePath-from cocoindex.resources.file import FilePath+from cocoindex.resources.file import FilePath, FilePathMatcherdef folder_prefix(prefix: str) -> str:@@ -35,6 +35,19 @@ def relative_key(object_key: str, folder: str) -> str | None:return object_key[len(folder) :]+def is_key_included(path_matcher: FilePathMatcher, rel_key: str) -> bool:+ """Return whether ``path_matcher`` includes the object with item key ``rel_key``.++ The key is matched as a file, and each folder above it as a directory, so an+ excluded directory excludes every object under it, as in a directory walk.+ """+ path = PurePath(rel_key)+ # The last parent is "." (or the root), which names no folder of the key.+ return path_matcher.is_file_included(path) and all(+ path_matcher.is_dir_included(parent) for parent in path.parents[:-1]+ )++class ObjectStoreFilePath(FilePath[str]):"""File path of an object in an object store.diff --git a/python/cocoindex/connectors/amazon_s3/_source.py b/python/cocoindex/connectors/amazon_s3/_source.pyindex e44b2892..181dc38a 100644--- a/python/cocoindex/connectors/amazon_s3/_source.py+++ b/python/cocoindex/connectors/amazon_s3/_source.py@@ -34,6 +34,7 @@ except ImportError as e:from cocoindex.connectorkits._object_store import (ObjectStoreFilePath,folder_prefix,+ is_key_included,relative_key,)from cocoindex.resources import file@@ -314,7 +315,7 @@ class S3Walker:continue# Apply path matcher- if not self._path_matcher.is_file_included(PurePath(rel_key)):+ if not is_key_included(self._path_matcher, rel_key):continueobj_size: int = obj["Size"]diff --git a/python/cocoindex/connectors/azure_blob/_source.py b/python/cocoindex/connectors/azure_blob/_source.pyindex b83a4c88..37e3eb7e 100644--- a/python/cocoindex/connectors/azure_blob/_source.py+++ b/python/cocoindex/connectors/azure_blob/_source.py@@ -20,6 +20,7 @@ from urllib.parse import urlparsefrom cocoindex.connectorkits._object_store import (ObjectStoreFilePath,folder_prefix,+ is_key_included,relative_key,)from cocoindex.resources import file@@ -282,7 +283,7 @@ class AzureBlobWalker:if relative_name is None:continue- if not self._path_matcher.is_file_included(PurePath(relative_name)):+ if not is_key_included(self._path_matcher, relative_name):continueblob_size = int(blob.size)diff --git a/python/cocoindex/connectors/oci_object_storage/_source.py b/python/cocoindex/connectors/oci_object_storage/_source.pyindex b839765c..617a2058 100644--- a/python/cocoindex/connectors/oci_object_storage/_source.py+++ b/python/cocoindex/connectors/oci_object_storage/_source.py@@ -52,6 +52,7 @@ from cocoindex.connectorkits import SingleWatcherGuardfrom cocoindex.connectorkits._object_store import (ObjectStoreFilePath,folder_prefix,+ is_key_included,relative_key,)from cocoindex.resources import file@@ -306,9 +307,7 @@ class OCIWalker:Shared by the scan and live events, so both key an object the same way."""rel_key = relative_key(object_name, self._folder)- if rel_key is None or not self._path_matcher.is_file_included(- PurePath(rel_key)- ):+ if rel_key is None or not is_key_included(self._path_matcher, rel_key):return Nonereturn rel_keydiff --git a/python/tests/common/object_store_exclusions.py b/python/tests/common/object_store_exclusions.pynew file mode 100644index 00000000..fbdf9856--- /dev/null+++ b/python/tests/common/object_store_exclusions.py@@ -0,0 +1,67 @@+"""Cases for how the object store sources (S3, Azure Blob, OCI) treat excluded directories.++An object store has flat keys, yet a directory that ``excluded_patterns`` excludes+must exclude every object under it, as it does in a directory walk.+"""++from __future__ import annotations++import pytest++# Object keys to store; the cases below list some of them.+EXCLUSION_TEST_KEYS = (+ "visible.txt",+ "ignored.txt",+ "ignored/deep/hidden.txt",+ "outer/kept.txt",+ "outer/ignored/hidden.txt",+ ".github/workflows/ci.yml",+ ".cache/x.txt",+)++# (prefix, excluded_patterns, item keys listed)+EXCLUDED_DIRECTORY_CASES = [+ # The key `ignored/deep/hidden.txt` matches no pattern: its folder excludes it.+ pytest.param(+ "",+ ["ignored"],+ [+ ".cache/x.txt",+ ".github/workflows/ci.yml",+ "ignored.txt",+ "outer/ignored/hidden.txt",+ "outer/kept.txt",+ "visible.txt",+ ],+ id="top-level",+ ),+ pytest.param(+ "",+ ["outer/ignored"],+ [+ ".cache/x.txt",+ ".github/workflows/ci.yml",+ "ignored.txt",+ "ignored/deep/hidden.txt",+ "outer/kept.txt",+ "visible.txt",+ ],+ id="nested",+ ),+ # Patterns match the key below the prefix folder.+ pytest.param("outer", ["ignored"], ["kept.txt"], id="below-prefix"),+ # A negation keeps the folder it carves out of an exclusion.+ pytest.param(+ "",+ ["**/.*", "!**/.github/**"],+ [+ ".github/workflows/ci.yml",+ "ignored.txt",+ "ignored/deep/hidden.txt",+ "outer/ignored/hidden.txt",+ "outer/kept.txt",+ "visible.txt",+ ],+ id="negation",+ ),+]diff --git a/python/tests/connectors/test_amazon_s3.py b/python/tests/connectors/test_amazon_s3.pyindex bc44ca86..0e67e1dc 100644--- a/python/tests/connectors/test_amazon_s3.py+++ b/python/tests/connectors/test_amazon_s3.py@@ -13,6 +13,10 @@ from aiomoto import mock_awsfrom cocoindex.connectors import amazon_s3from cocoindex.resources.file import PatternFilePathMatcher+from tests.common.object_store_exclusions import (+ EXCLUDED_DIRECTORY_CASES,+ EXCLUSION_TEST_KEYS,+)@pytest_asyncio.fixture@@ -168,6 +172,32 @@ class TestAsyncListObjects:assert isinstance(items[0][1], amazon_s3.S3File)+ ("prefix", "excluded_patterns", "expected"), EXCLUDED_DIRECTORY_CASES+)+async def test_excluded_directory_excludes_the_objects_under_it(+ prefix: str, excluded_patterns: list[str], expected: list[str]+) -> None:+ async with mock_aws():+ sync_client = boto3.client("s3", region_name="us-east-1")+ sync_client.create_bucket(Bucket="exclusion-test")+ for key in EXCLUSION_TEST_KEYS:+ sync_client.put_object(Bucket="exclusion-test", Key=key, Body=b"x")++ session = aiobotocore.session.get_session()+ async with session.create_client("s3", region_name="us-east-1") as client:+ walker = amazon_s3.list_objects(+ client,+ "exclusion-test",+ prefix=prefix,+ path_matcher=PatternFilePathMatcher(+ excluded_patterns=excluded_patterns+ ),+ )+ assert sorted([key async for key, _ in walker.items()]) == expected++# ---------------------------------------------------------------------------# S3File (async) tests# ---------------------------------------------------------------------------diff --git a/python/tests/connectors/test_azure_blob.py b/python/tests/connectors/test_azure_blob.pyindex e0db01ee..ac88b19b 100644--- a/python/tests/connectors/test_azure_blob.py+++ b/python/tests/connectors/test_azure_blob.py@@ -11,6 +11,10 @@ import pytestfrom cocoindex.connectors import azure_blobfrom cocoindex.resources.file import PatternFilePathMatcher+from tests.common.object_store_exclusions import (+ EXCLUDED_DIRECTORY_CASES,+ EXCLUSION_TEST_KEYS,+)_NOW = datetime(2026, 1, 2, 3, 4, 5, tzinfo=timezone.utc)@@ -189,6 +193,22 @@ class TestAsyncListBlobs:assert items[1][0] == "nested.json"assert isinstance(items[0][1], azure_blob.AzureBlobFile)+ @pytest.mark.parametrize(+ ("prefix", "excluded_patterns", "expected"), EXCLUDED_DIRECTORY_CASES+ )+ async def test_excluded_directory_excludes_the_blobs_under_it(+ self, prefix: str, excluded_patterns: list[str], expected: list[str]+ ) -> None:+ container_client = _FakeContainerClient(+ dict.fromkeys(EXCLUSION_TEST_KEYS, b"x")+ )+ walker = azure_blob.list_blobs(+ container_client,+ prefix=prefix,+ path_matcher=PatternFilePathMatcher(excluded_patterns=excluded_patterns),+ )+ assert sorted([key async for key, _ in walker.items()]) == expected+@pytest.mark.asyncioclass TestAzureBlobFile:diff --git a/python/tests/connectors/test_oci_object_storage.py b/python/tests/connectors/test_oci_object_storage.pyindex 0a97b902..0b2212c2 100644--- a/python/tests/connectors/test_oci_object_storage.py+++ b/python/tests/connectors/test_oci_object_storage.py@@ -207,6 +207,10 @@ from cocoindex.connectors.oci_object_storage._source import ( # noqa: E402_SCAN_VERSION_KEY,)from cocoindex.resources.file import PatternFilePathMatcher # noqa: E402+from tests.common.object_store_exclusions import ( # noqa: E402+ EXCLUDED_DIRECTORY_CASES,+ EXCLUSION_TEST_KEYS,+)def _live_items(walker: OCIWalker) -> LiveMapView[str, OCIFile]:@@ -1212,6 +1216,48 @@ async def test_oci_live_events_use_scan_keys(await watch_task+ ("prefix", "excluded_patterns", "expected"), EXCLUDED_DIRECTORY_CASES+)+async def test_oci_excluded_directory_excludes_the_objects_under_it(+ oci_client: MockObjectStorageClient,+ prefix: str,+ excluded_patterns: list[str],+ expected: list[str],+) -> None:+ """The scan and live events both skip the objects under an excluded directory."""+ for name in EXCLUSION_TEST_KEYS:+ oci_client.put(name, b"x")+ stream = _ManualLiveStream()+ walker = list_objects(+ oci_client,+ "ns",+ "bucket",+ prefix=prefix,+ path_matcher=PatternFilePathMatcher(excluded_patterns=excluded_patterns),+ live_stream=stream,+ )+ items = _live_items(walker)+ assert sorted([key async for key, _ in items]) == expected++ sub = _MockMapSubscriber()+ watch_task = asyncio.create_task(items.watch(sub)) # type: ignore[arg-type]+ await _drive_to_ready(stream, sub)++ for name in EXCLUSION_TEST_KEYS:+ await stream.send_event(_event("ns", "bucket", name))+ assert sorted(key for key, _ in sub.updates) == expected++ for name in EXCLUSION_TEST_KEYS:+ oci_client.remove(name)+ await stream.send_event(_event("ns", "bucket", name))+ assert sorted(sub.deletes) == expected++ stream.end()+ await watch_task++def test_oci_file_path_identity_includes_namespace_and_bucket() -> None:paths = [OCIFilePath("ns", "b1", "x.txt", object_name="x.txt"),diff --git a/rust/sdk/cocoindex/src/connectors/amazon_s3.rs b/rust/sdk/cocoindex/src/connectors/amazon_s3.rsindex b891e228..15863718 100644--- a/rust/sdk/cocoindex/src/connectors/amazon_s3.rs+++ b/rust/sdk/cocoindex/src/connectors/amazon_s3.rs@@ -33,6 +33,7 @@ use serde::{Deserialize, Serialize};/// depending on `aws-sdk-s3` directly.pub use aws_sdk_s3;+use crate::connectors::object_store::is_key_included;use crate::error::{Error, Result};use crate::resources::file::{FileContentCache, FileLike, FileMetadata, FilePath, FilePathMatcher, FileSourceItem,@@ -469,10 +470,7 @@ impl S3Walker {continue;};let size = obj.size().unwrap_or(0).max(0) as u64;- if !self- .path_matcher- .is_file_included(&PathBuf::from(&relative_key))- {+ if !is_key_included(&*self.path_matcher, &relative_key) {continue;}if self.max_file_size.is_some_and(|max| size > max) {@@ -657,4 +655,25 @@ mod tests {assert!(!matcher.is_file_included(&PathBuf::from("a/b.txt")));assert!(!matcher.is_file_included(&PathBuf::from("skip/b.md")));}++ // An excluded directory excludes the objects under it, matched below the prefix.+ #[test]+ fn excluded_directory_excludes_the_objects_under_it() {+ let matcher = PatternFilePathMatcher::new(+ std::iter::empty::<&str>(),+ ["ignored", "outer/ignored", "**/.*", "!**/.github/**"],+ )+ .unwrap();+ let listed = |prefix: &str, key: &str| {+ relative_key(prefix, key).is_some_and(|rel| is_key_included(&matcher, &rel))+ };+ assert!(!listed("data/", "data/ignored/deep/hidden.txt"));+ assert!(!listed("data/", "data/outer/ignored/hidden.txt"));+ assert!(!listed("data/", "data/.cache/x.txt"));+ assert!(listed("data/", "data/.github/workflows/ci.yml"));+ assert!(listed("data/", "data/outer/kept.txt"));+ assert!(listed("data/", "data/visible.txt"));+ // The prefix's own folders are not matched.+ assert!(listed("ignored/", "ignored/visible.txt"));+ }}diff --git a/rust/sdk/cocoindex/src/connectors/azure_blob.rs b/rust/sdk/cocoindex/src/connectors/azure_blob.rsindex 53f01c3e..f8dbafd4 100644--- a/rust/sdk/cocoindex/src/connectors/azure_blob.rs+++ b/rust/sdk/cocoindex/src/connectors/azure_blob.rs@@ -62,6 +62,7 @@ use reqwest::{Method, StatusCode};use serde::{Deserialize, Serialize};use sha2::Sha256;+use crate::connectors::object_store::is_key_included;use crate::error::{Error, Result};use crate::resources::file::{FileContentCache, FileLike, FileMetadata, FilePath, FilePathMatcher, FileSourceItem,@@ -1219,7 +1220,7 @@ impl AzureBlobWalker {let Some(relative) = relative_key(&blob_name, &self.folder) else {continue;};- if !self.path_matcher.is_file_included(&PathBuf::from(relative)) {+ if !is_key_included(&*self.path_matcher, relative) {continue;}let size = blob.properties.content_length;@@ -1328,6 +1329,7 @@ struct ListedBlobProperties {#[cfg(test)]mod tests {use super::*;+ use crate::resources::file::PatternFilePathMatcher;#[test]fn folder_prefix_names_a_folder() {@@ -1347,6 +1349,27 @@ mod tests {assert_eq!(relative_key("docsa.md", "docs/"), None);}+ // An excluded directory excludes the blobs under it, matched below the folder.+ #[test]+ fn excluded_directory_excludes_the_blobs_under_it() {+ let matcher = PatternFilePathMatcher::new(+ std::iter::empty::<&str>(),+ ["ignored", "outer/ignored", "**/.*", "!**/.github/**"],+ )+ .unwrap();+ let listed = |blob_name: &str, folder: &str| {+ relative_key(blob_name, folder).is_some_and(|rel| is_key_included(&matcher, rel))+ };+ assert!(!listed("docs/ignored/deep/hidden.txt", "docs/"));+ assert!(!listed("docs/outer/ignored/hidden.txt", "docs/"));+ assert!(!listed("docs/.cache/x.txt", "docs/"));+ assert!(listed("docs/.github/workflows/ci.yml", "docs/"));+ assert!(listed("docs/outer/kept.txt", "docs/"));+ assert!(listed("docs/visible.txt", "docs/"));+ // The folder's own path is not matched.+ assert!(listed("ignored/visible.txt", "ignored/"));+ }+#[test]fn account_name_comes_from_host_or_path() {let name = |url: &str| account_name_of(&reqwest::Url::parse(url).unwrap());diff --git a/rust/sdk/cocoindex/src/connectors/mod.rs b/rust/sdk/cocoindex/src/connectors/mod.rsindex 8ee4203c..2f6dd2ce 100644--- a/rust/sdk/cocoindex/src/connectors/mod.rs+++ b/rust/sdk/cocoindex/src/connectors/mod.rs@@ -22,6 +22,12 @@ pub mod kafka;pub mod lancedb;#[cfg(feature = "neo4j")]pub mod neo4j;+#[cfg(any(+ feature = "amazon_s3",+ feature = "azure_blob",+ feature = "oci_object_storage"+))]+mod object_store;#[cfg(feature = "oci_object_storage")]pub mod oci_object_storage;#[cfg(any(feature = "kafka", feature = "iggy"))]diff --git a/rust/sdk/cocoindex/src/connectors/object_store.rs b/rust/sdk/cocoindex/src/connectors/object_store.rsnew file mode 100644index 00000000..4ac94450--- /dev/null+++ b/rust/sdk/cocoindex/src/connectors/object_store.rs@@ -0,0 +1,54 @@+//! Key handling the object store sources (Amazon S3, Azure Blob, OCI) share.++use std::path::Path;++use crate::resources::file::FilePathMatcher;++/// Whether `matcher` includes the object with item key `key`, a path relative+/// to the listed folder. The key is matched as a file, and each folder above it+/// as a directory, so an excluded directory excludes every object under it, as+/// in a directory walk.+pub(crate) fn is_key_included(matcher: &dyn FilePathMatcher, key: &str) -> bool {+ matcher.is_file_included(Path::new(key))+ && key+ .match_indices('/')+ .map(|(end, _)| &key[..end])+ // An empty segment (`a//b`, `/b`) names no further folder.+ .filter(|dir| !dir.is_empty() && !dir.ends_with('/'))+ .all(|dir| matcher.is_dir_included(Path::new(dir)))+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::resources::file::PatternFilePathMatcher;++ #[test]+ fn key_is_included_only_when_no_folder_above_it_is_excluded() {+ let m = PatternFilePathMatcher::new(std::iter::empty::<&str>(), ["ignored", "a/ignored"])+ .unwrap();+ // The file matches no pattern: its folder is what excludes it.+ assert!(m.is_file_included(Path::new("ignored/deep/hidden.txt")));+ assert!(!is_key_included(&m, "ignored/deep/hidden.txt"));+ assert!(!is_key_included(&m, "a/ignored/hidden.txt"));+ assert!(is_key_included(&m, "a/kept.txt"));+ assert!(is_key_included(&m, "b/ignored.txt"));+ // An empty segment names no folder.+ assert!(is_key_included(&m, "/visible.txt"));+ assert!(!is_key_included(&m, "ignored//hidden.txt"));++ // A negation keeps its folders traversable, so it keeps the key.+ let negated = PatternFilePathMatcher::new(+ std::iter::empty::<&str>(),+ ["dir1/**", "!dir1/dir2/a.yml"],+ )+ .unwrap();+ assert!(is_key_included(&negated, "dir1/dir2/a.yml"));+ assert!(!is_key_included(&negated, "dir1/dir2/b.yml"));++ // Include patterns apply to the key alone, never to its folders.+ let include_only = PatternFilePathMatcher::include(["**/*.md"]).unwrap();+ assert!(is_key_included(&include_only, "a/b/c.md"));+ assert!(!is_key_included(&include_only, "a/b/c.txt"));+ }+}diff --git a/rust/sdk/cocoindex/src/connectors/oci_object_storage.rs b/rust/sdk/cocoindex/src/connectors/oci_object_storage.rsindex ee70ee1c..e7d53571 100644--- a/rust/sdk/cocoindex/src/connectors/oci_object_storage.rs+++ b/rust/sdk/cocoindex/src/connectors/oci_object_storage.rs@@ -51,6 +51,7 @@ use serde::{Deserialize, Serialize};use sha1::Sha1;use sha2::{Digest, Sha256};+use crate::connectors::object_store::is_key_included;use crate::error::{Error, Result};use crate::live_component::{LiveComponentOperator, LiveMapFeed, LiveMapSubscriber, LiveMapView, LiveStream,@@ -1306,10 +1307,7 @@ impl OciWalker {continue;};let size = obj.size.unwrap_or(0);- if !self- .path_matcher- .is_file_included(&PathBuf::from(&relative_key))- {+ if !is_key_included(&*self.path_matcher, &relative_key) {continue;}if self.max_file_size.is_some_and(|max| size > max) {@@ -1540,10 +1538,7 @@ impl OciLiveWalker {let Some(relative_key) = relative_key(&self.prefix, &object_name) else {return Ok(ReadyHandle::immediate());};- if !self- .path_matcher- .is_file_included(&PathBuf::from(&relative_key))- {+ if !is_key_included(&*self.path_matcher, &relative_key) {return Ok(ReadyHandle::immediate());}// Re-read: the live object state wins over the event type.@@ -1934,4 +1929,25 @@ mod tests {assert!(!matcher.is_file_included(&PathBuf::from("a/b.txt")));assert!(!matcher.is_file_included(&PathBuf::from("skip/b.md")));}++ // An excluded directory excludes the objects under it, matched below the prefix.+ #[test]+ fn excluded_directory_excludes_the_objects_under_it() {+ let matcher = PatternFilePathMatcher::new(+ std::iter::empty::<&str>(),+ ["ignored", "outer/ignored", "**/.*", "!**/.github/**"],+ )+ .unwrap();+ let listed = |prefix: &str, name: &str| {+ relative_key(prefix, name).is_some_and(|rel| is_key_included(&matcher, &rel))+ };+ assert!(!listed("data/", "data/ignored/deep/hidden.txt"));+ assert!(!listed("data/", "data/outer/ignored/hidden.txt"));+ assert!(!listed("data/", "data/.cache/x.txt"));+ assert!(listed("data/", "data/.github/workflows/ci.yml"));+ assert!(listed("data/", "data/outer/kept.txt"));+ assert!(listed("data/", "data/visible.txt"));+ // The prefix's own folders are not matched.+ assert!(listed("ignored/", "ignored/visible.txt"));+ }}