diff --git a/src/aibs_informatics_core/models/data_sync.py b/src/aibs_informatics_core/models/data_sync.py index b5885c9..3390ba2 100644 --- a/src/aibs_informatics_core/models/data_sync.py +++ b/src/aibs_informatics_core/models/data_sync.py @@ -5,6 +5,7 @@ "PutJSONToFileResponse", "GetJSONFromFileRequest", "GetJSONFromFileResponse", + "DataSyncFilterConfig", "DataSyncTask", "DataSyncConfig", "DataSyncRequest", @@ -16,12 +17,14 @@ ] from pathlib import Path +from re import Pattern from pydantic import Field, JsonValue, model_validator from aibs_informatics_core.models.aws.efs import EFSPath from aibs_informatics_core.models.aws.s3 import S3KeyPrefix, S3Path from aibs_informatics_core.models.base import PydanticBaseModel +from aibs_informatics_core.utils.filters import compile_patterns from aibs_informatics_core.utils.json import JSON @@ -61,12 +64,103 @@ class GetJSONFromFileResponse(JSONContent): pass +class DataSyncFilterConfig(PydanticBaseModel): + """Include/exclude filters restricting which files a data sync moves. + + Patterns follow the shared contract in + :mod:`aibs_informatics_core.utils.filters`: they are regular expressions + (not globs) matched with ``fullmatch`` against the path *relative to* the + filter root, and exclude patterns take precedence over include patterns. + An absent or empty ``include`` includes everything. + + Attributes: + include: Optional regex pattern(s) for files to include. + If multiple patterns, includes files matching any pattern. + exclude: Optional regex pattern(s) for files to exclude. + Exclude patterns take precedence over include patterns. + """ + + include: str | list[str] | None = None + exclude: str | list[str] | None = None + + @classmethod + def from_patterns( + cls, + include: str | list[str] | None = None, + exclude: str | list[str] | None = None, + ) -> "DataSyncFilterConfig | None": + """Build a config from raw patterns, or ``None`` when nothing is filtered. + + The single definition of "are these filters actually filtering anything". Empty + counts as absent -- ``None``, ``""`` and ``[]`` all yield ``None`` rather than a + config that matches everything. + + That distinction is load-bearing for callers that branch on whether filters are + present. ``DemandExecutionParameters.sanitize_serialized_params`` serializes a + resolvable one way when it has filters and another way when it does not, and the + result feeds an execution hash -- so an empty-but-present config must not read as + "filtered", or it would change the hash while filtering nothing. + + Callers holding raw ``include``/``exclude`` should route through here rather than + writing the emptiness check themselves; it has already been written two different + ways in this codebase. + + Args: + include: Optional regex pattern(s) for files to include. + exclude: Optional regex pattern(s) for files to exclude. + + Returns: + A config, or ``None`` if neither argument carries a pattern. + """ + if not include and not exclude: + return None + return cls(include=include, exclude=exclude) + + # Deliberately plain properties, not cached_property. This model is mutable, and a + # cached compile would go stale the moment `include`/`exclude` changed -- leaving the + # config serializing one set of patterns while filtering by another. The staleness + # also survives `model_copy(update=...)`, which copies the populated instance __dict__ + # along with the fields, so freezing the model would not close that path either. + # Recompiling is cheap: `re.compile` keeps its own module-level cache. + @property + def include_patterns(self) -> list[Pattern] | None: + return compile_patterns(self.include) + + @property + def exclude_patterns(self) -> list[Pattern] | None: + return compile_patterns(self.exclude) + + class DataSyncTask(PydanticBaseModel): - """Defines source and destination paths for a data sync operation.""" + """Defines source and destination paths for a data sync operation. + + Attributes: + source_path: Path to sync data from. + destination_path: Path to sync data to. + source_path_prefix: Optional S3 key prefix scoping the source. + filter_config: Optional include/exclude filters describing *what* to + move. Filters live on the task rather than the config because they + change the set of data transferred, not how the transfer runs. + filter_root: Root that filter patterns are matched relative to. + **Internal plumbing -- set by the prepare handler, never by users.** + The distributed sync workflow splits a sync of ``s3://b/run1/`` into + sub-requests rooted at ``s3://b/run1/sampleA/``. Each sub-request + re-lists from its own root, so patterns written against ``run1/`` + would silently stop matching. Sub-requests therefore carry the + original root here. + + ``None`` means "not set" rather than a resolved default: this model + applies no fallback, and consumers are expected to treat ``None`` as + "anchor to ``source_path``". Resolving it here instead would + materialize the source path into the serialized task, which + ``to_dict()`` currently omits while the field is ``None``. + """ source_path: S3Path | EFSPath | Path destination_path: S3Path | EFSPath | Path source_path_prefix: S3KeyPrefix | None = None + filter_config: DataSyncFilterConfig | None = None + filter_root: str | None = None class RemoteToLocalConfig(PydanticBaseModel): @@ -80,10 +174,40 @@ class RemoteToLocalConfig(PydanticBaseModel): class DataSyncConfig(PydanticBaseModel): - """Configuration options for data sync operations.""" + """Configuration options for data sync operations. + + Attributes: + max_concurrency: Maximum number of concurrent transfer operations. + retain_source_data: Whether to keep the source data after syncing. + delete: Whether the sync deletes destination paths that are not present + in the (filtered) source -- i.e. whether the destination is made to + *mirror* the source rather than merely receive from it. + + .. warning:: + **This interacts destructively with** + :class:`DataSyncFilterConfig`. Filters narrow what the sync + considers to be "the source", so with ``delete=True`` any file + already at the destination that the filters exclude is treated + as unexpected and **deleted**. Syncing a filtered subset into a + directory that holds an earlier unfiltered copy will therefore + remove the non-matching files. + + This is deliberately *not* guarded by validation -- ``delete`` + is the gate, and mirroring remains a legitimate use of a + filtered sync. Callers that pass a ``filter_config`` are + expected to pass ``delete=False`` unless they specifically want + the destination mirrored to the filtered subset. + require_lock: Whether to acquire a lock on the destination path. + force: Whether to transfer regardless of existing destination content. + size_only: Whether to compare only file sizes when deciding to transfer. + fail_if_missing: Whether to raise if the source path does not exist. + include_detailed_response: Whether to compute detailed transfer metrics. + remote_to_local_config: Options specific to remote-to-local syncs. + """ max_concurrency: int = 25 retain_source_data: bool = True + delete: bool = True require_lock: bool = False force: bool = False size_only: bool = False @@ -97,10 +221,17 @@ class DataSyncRequest(DataSyncConfig, DataSyncTask): # type: ignore[misc] @property def config(self) -> DataSyncConfig: - """Extract the configuration portion of this request.""" + """Extract the configuration portion of this request. + + Note: + Fields are enumerated by hand -- any field added to + :class:`DataSyncConfig` must be added here too, or it will be + silently dropped. + """ return DataSyncConfig( max_concurrency=self.max_concurrency, retain_source_data=self.retain_source_data, + delete=self.delete, require_lock=self.require_lock, force=self.force, size_only=self.size_only, @@ -111,11 +242,19 @@ def config(self) -> DataSyncConfig: @property def task(self) -> DataSyncTask: - """Extract the task portion of this request.""" + """Extract the task portion of this request. + + Note: + Fields are enumerated by hand -- any field added to + :class:`DataSyncTask` must be added here too, or it will be + silently dropped. + """ return DataSyncTask( source_path=self.source_path, destination_path=self.destination_path, source_path_prefix=self.source_path_prefix, + filter_config=self.filter_config, + filter_root=self.filter_root, ) diff --git a/src/aibs_informatics_core/utils/file_operations.py b/src/aibs_informatics_core/utils/file_operations.py index 93db614..dbd91f8 100644 --- a/src/aibs_informatics_core/utils/file_operations.py +++ b/src/aibs_informatics_core/utils/file_operations.py @@ -18,7 +18,6 @@ import hashlib import logging import os -import re import shutil import tarfile import tempfile @@ -32,6 +31,7 @@ from re import Pattern from typing import Literal, Union, cast +from aibs_informatics_core.utils.filters import filter_paths from aibs_informatics_core.utils.os_operations import find_all_paths ArchiveFile = Union[tarfile.TarFile, zipfile.ZipFile] @@ -358,40 +358,33 @@ def find_paths( ) -> list[str]: """Find paths that match criteria + Patterns follow the shared filter contract in + :mod:`aibs_informatics_core.utils.filters`: they are regexes matched with + ``fullmatch`` against the path **relative to** ``root``, and excludes take + precedence over includes. + Args: root (Union[str, Path]): root path include_dirs (bool, optional): whether to include directories. Defaults to True. include_files (bool, optional): whether to include files. Defaults to True. - includes (Sequence[str], optional): list of regex patterns to include. Defaults to all. - excludes (Sequence[str], optional): list of regex patterns to exclude. Defaults to None. + includes (Sequence[Pattern | str], optional): regex patterns, already compiled + or not, to include. Defaults to all. + excludes (Sequence[Pattern | str], optional): regex patterns, already compiled + or not, to exclude. Defaults to None. Returns: - list of paths matching criteria + list of paths matching criteria, each prefixed with ``root`` as given -- an + absolute ``root`` yields absolute paths, a relative one yields relative paths. + Patterns are matched against the path relative to ``root`` either way. """ - paths_to_return = [] paths = find_all_paths(root, include_dirs=include_dirs, include_files=include_files) if not includes and not excludes: return paths - include_patterns = [re.compile(include) for include in includes or [r".*"]] - exclude_patterns = [re.compile(exclude) for exclude in excludes or []] - - for path in paths: - target_path = path # if check_absolute_path else strip_path_root(root=root, path=path) - # First check exclude patterns - for exclude_pattern in exclude_patterns: - if exclude_pattern.fullmatch(target_path): - break - else: - # Now check include patterns - for include_pattern in include_patterns: - if include_pattern.fullmatch(target_path): - paths_to_return.append(path) - break - return paths_to_return + return filter_paths(paths, root=root, include=includes, exclude=excludes) def get_path_with_root(path: str | Path, root: str | Path) -> str: diff --git a/src/aibs_informatics_core/utils/filters.py b/src/aibs_informatics_core/utils/filters.py new file mode 100644 index 0000000..be2f024 --- /dev/null +++ b/src/aibs_informatics_core/utils/filters.py @@ -0,0 +1,185 @@ +"""Shared include/exclude path filtering. + +This module defines the single filtering contract used across data sync +(local, S3, and EFS listings). Historically each call site rolled its own +variation -- some matched against the relative path, some against the full +absolute path, some used :meth:`re.Pattern.match` and some +:meth:`re.Pattern.fullmatch`. That meant a pattern such as ``sample/.*`` +filtered under S3 and silently did nothing under a local root. + +The contract implemented here is: + +- Patterns are **regular expressions** (not glob patterns). +- A pattern is matched with :meth:`re.Pattern.fullmatch`, so it must describe + the *entire* path, not a fragment of it. Use ``.*`` explicitly to match a + fragment (e.g. ``.*\\.bam``). +- Paths are matched **relative to a supplied root**, so patterns are portable + across the absolute location the data happens to live at. +- **Exclude wins over include**: a path matching any exclude pattern is dropped + regardless of the include patterns. +- An absent or empty ``include`` includes everything. +""" + +__all__ = [ + "AnyPath", + "Patterns", + "compile_patterns", + "get_relative_path", + "path_matches_filters", + "filter_paths", +] + +import re +from collections.abc import Iterable, Sequence +from os.path import basename +from pathlib import Path +from re import Pattern +from typing import TypeAlias, TypeVar + +Patterns: TypeAlias = str | Pattern | Sequence[str | Pattern] | None + +#: Filtering never rewrites the paths it is given, so callers get back exactly the type they +#: passed in. Bound (rather than constrained) so that ``str`` subclasses such as +#: :class:`~aibs_informatics_core.models.aws.s3.S3Path` survive a round trip as themselves +#: instead of being widened to ``str``. +AnyPath = TypeVar("AnyPath", bound=str | Path) + + +def compile_patterns(patterns: Patterns) -> list[Pattern] | None: + """Normalize pattern input into a list of compiled regex patterns. + + Accepts a single pattern or a sequence of patterns, either as strings or + as already-compiled :class:`re.Pattern` objects. + + Args: + patterns: Pattern(s) to compile. May be ``None`` or empty. + + Returns: + A list of compiled patterns, or ``None`` if no patterns were given. + """ + if not patterns: + return None + if isinstance(patterns, (str, Pattern)): + patterns = [patterns] + return [p if isinstance(p, Pattern) else re.compile(p) for p in patterns] + + +def get_relative_path(path: str | Path, root: str | Path | None = None) -> str: + """Get the path relative to the filter root, as a string. + + This is intentionally string prefix based rather than :mod:`pathlib` based + so that it works unchanged for URI style paths (e.g. ``s3://bucket/key``), + which :class:`pathlib.Path` would mangle by collapsing ``//``. + + Args: + path: The path to relativize. + root: The root to relativize against. If ``None``, ``path`` is returned + unchanged (i.e. it is assumed to already be relative). + + Returns: + The path relative to ``root``. If ``path`` *is* ``root`` -- which + happens when the sync source is a single file or object -- the base + name is returned, so that patterns still have something to match. If + ``path`` does not live under ``root`` at all, it is returned unchanged. + """ + str_path = str(path) + if root is None: + return str_path + + str_root = str(root).rstrip("/") + if not str_root: + return str_path.lstrip("/") + if str_path == str_root: + return basename(str_path) + prefix = f"{str_root}/" + if str_path.startswith(prefix): + return str_path[len(prefix) :] + return str_path + + +def path_matches_filters( + path: str | Path, + root: str | Path | None = None, + include: Patterns = None, + exclude: Patterns = None, +) -> bool: + """Check whether a path passes the include/exclude filters. + + See the module docstring for the full contract. In short: patterns are + regexes matched with ``fullmatch`` against ``path`` relative to ``root``, + exclude wins over include, and an empty include includes everything. + + Args: + path: The path to test. + root: Root that ``path`` is matched relative to. If ``None``, ``path`` + is matched as given. + include: Pattern(s) a path must match to be kept. Defaults to all. + exclude: Pattern(s) that drop a path. Takes precedence over ``include``. + + Returns: + True if the path should be kept. + """ + include_patterns = compile_patterns(include) + exclude_patterns = compile_patterns(exclude) + if include_patterns is None and exclude_patterns is None: + return True + return _matches( + get_relative_path(path, root), + include_patterns=include_patterns, + exclude_patterns=exclude_patterns, + ) + + +def filter_paths( + paths: Iterable[AnyPath], + root: str | Path | None = None, + include: Patterns = None, + exclude: Patterns = None, +) -> list[AnyPath]: + """Filter an iterable of paths with the include/exclude filters. + + Equivalent to calling :func:`path_matches_filters` for each path, but the + patterns are only compiled once. + + This selects from ``paths`` without rewriting them, so the element type is + preserved: pass :class:`~pathlib.Path` objects and get ``Path`` objects + back, pass :class:`~aibs_informatics_core.models.aws.s3.S3Path` objects and + get ``S3Path`` objects back. Only the *matching* is done on strings. + + Args: + paths: The paths to filter. + root: Root that each path is matched relative to. If ``None``, paths + are matched as given. + include: Pattern(s) a path must match to be kept. Defaults to all. + exclude: Pattern(s) that drop a path. Takes precedence over ``include``. + + Returns: + The paths that passed the filters, in their original order and of the + same type they were passed in as. + """ + include_patterns = compile_patterns(include) + exclude_patterns = compile_patterns(exclude) + if include_patterns is None and exclude_patterns is None: + return list(paths) + return [ + path + for path in paths + if _matches( + get_relative_path(path, root), + include_patterns=include_patterns, + exclude_patterns=exclude_patterns, + ) + ] + + +def _matches( + relative_path: str, + include_patterns: list[Pattern] | None, + exclude_patterns: list[Pattern] | None, +) -> bool: + """Apply compiled patterns to an already relativized path.""" + if exclude_patterns and any(p.fullmatch(relative_path) for p in exclude_patterns): + return False + if not include_patterns: + return True + return any(p.fullmatch(relative_path) for p in include_patterns) diff --git a/src/aibs_informatics_core/utils/tools/strtools.py b/src/aibs_informatics_core/utils/tools/strtools.py index 3041e53..9134a74 100644 --- a/src/aibs_informatics_core/utils/tools/strtools.py +++ b/src/aibs_informatics_core/utils/tools/strtools.py @@ -1,5 +1,6 @@ __all__ = [ "camelcase", + "condense_str", "is_prefixed", "is_suffixed", "lowercase", @@ -13,6 +14,77 @@ import stringcase +from aibs_informatics_core.utils.hashing import sha256_hexdigest + +#: Hex characters of hash appended by :func:`condense_str` when shortening. 8 hex +#: characters is 32 bits, ample for disambiguating names within a single namespace. +DEFAULT_CONDENSE_HASH_LENGTH = 8 + + +def condense_str( + value: str, + max_length: int, + delimiter: str = "-", + hash_length: int = DEFAULT_CONDENSE_HASH_LENGTH, +) -> str: + """Shorten a string to a maximum length while keeping it unique and readable. + + For names that must fit a downstream length limit -- generated AWS resource names + being the motivating case -- where plain truncation would risk collisions. + + A value that already fits is returned **unchanged**. That matters: condensing has + to be a no-op for names already within budget, or adopting this helper somewhere + would silently rename every existing resource. + + A value that does not fit keeps as much of its readable prefix as possible and is + suffixed with ``delimiter`` plus a hash of the **whole original value**. Hashing + the original rather than the discarded tail means two values sharing a long common + prefix still condense to different results. + + The result is deterministic: the same input always condenses to the same output. + Callers depend on that -- a name that changed between runs would, for example, + register a new AWS Batch job definition revision every time. + + Args: + value: The string to condense. + max_length: Maximum length of the result. Must leave room for the hash suffix + plus at least one character of prefix. + delimiter: Separator placed between the truncated prefix and the hash suffix. + hash_length: Number of hex characters of hash to append. + + Returns: + ``value`` if it already fits within ``max_length``, otherwise + ````, of exactly ``max_length`` characters. + + Raises: + ValueError: If ``hash_length`` is not positive, or if ``max_length`` is too + small to fit the suffix plus at least one prefix character. Truncating + without a hash would silently invite collisions, so this is an error + rather than a quiet fallback. + + Examples: + >>> condense_str("short-name", max_length=24) + 'short-name' + >>> condense_str("a" * 40, max_length=24) + 'aaaaaaaaaaaaaaa-e4bcc900' + """ + if hash_length <= 0: + raise ValueError(f"hash_length must be positive, got {hash_length}") + + if len(value) <= max_length: + return value + + suffix_length = len(delimiter) + hash_length + if max_length <= suffix_length: + raise ValueError( + f"Cannot condense to max_length={max_length}: the {suffix_length} character " + f"suffix (delimiter {delimiter!r} + {hash_length} hash chars) leaves no room " + f"for a prefix. Raise max_length or lower hash_length." + ) + + prefix = value[: max_length - suffix_length] + return f"{prefix}{delimiter}{sha256_hexdigest(value)[:hash_length]}" + def is_prefixed(value: str, prefix: str) -> bool: """Check whether a string starts with the given prefix. diff --git a/test/aibs_informatics_core/models/test_data_sync.py b/test/aibs_informatics_core/models/test_data_sync.py index 9359a21..08156b3 100644 --- a/test/aibs_informatics_core/models/test_data_sync.py +++ b/test/aibs_informatics_core/models/test_data_sync.py @@ -1,17 +1,22 @@ +import re from pathlib import Path +from pytest import mark, param + from aibs_informatics_core.models.aws.s3 import S3KeyPrefix, S3Path from aibs_informatics_core.models.data_sync import ( BatchDataSyncRequest, BatchDataSyncResponse, BatchDataSyncResult, DataSyncConfig, + DataSyncFilterConfig, DataSyncRequest, DataSyncResult, DataSyncTask, JSONContent, JSONReference, PrepareBatchDataSyncResponse, + RemoteToLocalConfig, ) S3_URI = S3Path.build(bucket_name="bucket", key="key") @@ -136,6 +141,7 @@ def test__BatchDataSyncRequest__to_dict(): "force": False, "size_only": False, "retain_source_data": True, + "delete": True, "include_detailed_response": False, "remote_to_local_config": {"use_custom_tmp_dir": False}, }, @@ -185,6 +191,7 @@ def test__PrepareBatchDataSyncResponse__to_dict(): "force": False, "size_only": False, "retain_source_data": True, + "delete": True, "include_detailed_response": False, "remote_to_local_config": {"use_custom_tmp_dir": False}, }, @@ -286,3 +293,241 @@ def test__BatchDataSyncResult__increment_counts(): assert result.failed_requests_count == 3 # Total requests count should now be 2 (from successful) + 3 (from failed) = 5 assert result.total_requests_count == 5 + + +def test__DataSyncFilterConfig__defaults_to_no_filters(): + config = DataSyncFilterConfig() + assert config.include is None + assert config.exclude is None + assert config.include_patterns is None + assert config.exclude_patterns is None + + +def test__DataSyncFilterConfig__compiles_single_pattern(): + config = DataSyncFilterConfig(include=r".*\.bam", exclude=r".*\.bai") + assert [p.pattern for p in config.include_patterns] == [r".*\.bam"] + assert [p.pattern for p in config.exclude_patterns] == [r".*\.bai"] + + +def test__DataSyncFilterConfig__compiles_pattern_list(): + config = DataSyncFilterConfig(include=[r".*\.bam", r".*\.vcf"], exclude=[]) + assert [p.pattern for p in config.include_patterns] == [r".*\.bam", r".*\.vcf"] + assert config.exclude_patterns is None + + +def test__DataSyncFilterConfig__round_trip(): + config = DataSyncFilterConfig(include=[r"s1/.*"], exclude=r".*\.bam") + model_dict = config.to_dict() + assert model_dict == {"include": [r"s1/.*"], "exclude": r".*\.bam"} + assert DataSyncFilterConfig.from_dict(model_dict) == config + + +def test__DataSyncFilterConfig__pattern_properties_do_not_leak_into_serialization(): + # The pattern accessors are derived, not fields: keep them out of to_dict() and equality. + config = DataSyncFilterConfig(include=r"s1/.*") + assert config.include_patterns is not None + assert config.exclude_patterns is None + assert config.to_dict() == {"include": r"s1/.*"} + assert config == DataSyncFilterConfig(include=r"s1/.*") + + +def test__DataSyncFilterConfig__patterns_track_mutation(): + # These are plain properties rather than cached_property precisely so this holds. With a + # cache, the config would serialize one set of patterns while filtering by another. + config = DataSyncFilterConfig(include=r"s1/.*") + assert config.include_patterns == [re.compile(r"s1/.*")] + + config.include = r"s2/.*" + assert config.include_patterns == [re.compile(r"s2/.*")] + assert config.to_dict() == {"include": r"s2/.*"} + + +def test__DataSyncFilterConfig__patterns_track_model_copy_update(): + # model_copy copies the instance __dict__, so a populated cache would survive the update + # here even on a frozen model -- which is why freezing alone would not have fixed this. + config = DataSyncFilterConfig(include=r"s1/.*", exclude=r".*\.bam") + assert config.include_patterns == [re.compile(r"s1/.*")] # warm any cache first + + copied = config.model_copy(update={"include": r"s2/.*"}) + assert copied.include_patterns == [re.compile(r"s2/.*")] + assert copied.exclude_patterns == [re.compile(r".*\.bam")] + + +def test__DataSyncTask__round_trip__with_filter_config(): + task = DataSyncTask( + source_path=S3_URI, + destination_path=S3_URI, + filter_config=DataSyncFilterConfig(include=r"s1/.*"), + filter_root=str(S3_URI), + ) + model_dict = task.to_dict() + assert model_dict["filter_config"] == {"include": r"s1/.*"} + assert model_dict["filter_root"] == str(S3_URI) + assert DataSyncTask.from_dict(model_dict) == task + + +def test__DataSyncTask__round_trip__without_filter_config(): + task = DataSyncTask(source_path=S3_URI, destination_path=S3_URI) + model_dict = task.to_dict() + assert "filter_config" not in model_dict + assert "filter_root" not in model_dict + assert DataSyncTask.from_dict(model_dict) == task + + +def test__DataSyncRequest__round_trip__with_filter_config(): + request = DataSyncRequest( + source_path=S3_URI, + destination_path=S3_URI, + filter_config=DataSyncFilterConfig(include=[r"s1/.*"], exclude=r".*\.bam"), + filter_root=str(S3_URI), + delete=False, + ) + model_dict = request.to_dict() + assert model_dict["filter_config"] == {"include": [r"s1/.*"], "exclude": r".*\.bam"} + assert model_dict["delete"] is False + assert DataSyncRequest.from_dict(model_dict) == request + + +def test__DataSyncRequest__round_trip__without_filter_config(): + request = DataSyncRequest(source_path=S3_URI, destination_path=S3_URI) + model_dict = request.to_dict() + assert "filter_config" not in model_dict + assert model_dict["delete"] is True + assert DataSyncRequest.from_dict(model_dict) == request + + +def test__DataSyncRequest__config_carries_every_config_field(): + # The config property enumerates fields by hand, so new fields are silently dropped + # unless added. Every field is set to a non-default value to catch that. + request = DataSyncRequest( + source_path=S3_URI, + destination_path=S3_URI, + max_concurrency=1, + retain_source_data=False, + delete=False, + require_lock=True, + force=True, + size_only=True, + fail_if_missing=False, + include_detailed_response=True, + remote_to_local_config=RemoteToLocalConfig(use_custom_tmp_dir=True), + ) + config = request.config + for field_name in DataSyncConfig.model_fields: + assert getattr(config, field_name) == getattr(request, field_name), field_name + + +def test__DataSyncRequest__task_carries_every_task_field(): + request = DataSyncRequest( + source_path=S3_URI, + destination_path=S3_URI, + source_path_prefix=S3KeyPrefix("prefix"), + filter_config=DataSyncFilterConfig(include=r"s1/.*", exclude=r".*\.bam"), + filter_root=str(S3_URI), + ) + task = request.task + for field_name in DataSyncTask.model_fields: + assert getattr(task, field_name) == getattr(request, field_name), field_name + + +def test__BatchDataSyncRequest__from_dict__flattened_request_with_filter_config(): + # A single flattened DataSyncRequest -- including a nested filter_config -- is still + # recognized by _handle_single_flattened_request and wrapped into a batch. + single_request = { + "source_path": str(S3_URI), + "destination_path": str(S3_URI), + "filter_config": {"include": [r"s1/.*"], "exclude": r".*\.bam"}, + "filter_root": str(S3_URI), + "delete": False, + } + actual = BatchDataSyncRequest.from_dict(single_request) + assert actual.requests == [DataSyncRequest.from_dict(single_request)] + assert actual.requests[0].filter_config == DataSyncFilterConfig( + include=[r"s1/.*"], exclude=r".*\.bam" + ) + assert actual.requests[0].filter_root == str(S3_URI) + assert actual.requests[0].delete is False + + +def test__BatchDataSyncRequest__round_trip__with_filter_config(): + # This is the seam the SFN Map state crosses -- filters must survive it. + request = BatchDataSyncRequest( + requests=[ + DataSyncRequest( + source_path=S3_URI, + destination_path=S3_URI, + filter_config=DataSyncFilterConfig(include=r"s1/.*"), + filter_root=str(S3_URI), + delete=False, + ), + ], + ) + assert BatchDataSyncRequest.from_dict(request.to_dict()) == request + + +def test__PrepareBatchDataSyncResponse__round_trip__with_filter_config(): + response = PrepareBatchDataSyncResponse( + requests=[ + BatchDataSyncRequest( + requests=[ + DataSyncRequest( + source_path=S3_URI, + destination_path=S3_URI, + filter_config=DataSyncFilterConfig( + include=[r"s1/.*"], exclude=[r".*\.bam"] + ), + filter_root=str(S3_URI), + delete=False, + ), + ], + ), + ], + ) + assert PrepareBatchDataSyncResponse.from_dict(response.to_dict()) == response + + +@mark.parametrize( + "include, exclude, expected_present", + [ + param(None, None, False, id="both None"), + param("", "", False, id="both empty strings"), + param([], [], False, id="both empty lists"), + param([], None, False, id="empty list and None"), + param(r"a.*", None, True, id="include only"), + param(None, r"b.*", True, id="exclude only"), + param([r"a.*"], [r"b.*"], True, id="both"), + ], +) +def test__DataSyncFilterConfig__from_patterns(include, exclude, expected_present): + # One definition of "are these filters actually filtering anything". Empty must read + # as absent: callers branch on presence, and one of them (sanitize_serialized_params) + # feeds an execution hash, so an empty-but-present config would change the hash while + # filtering nothing. + config = DataSyncFilterConfig.from_patterns(include=include, exclude=exclude) + assert (config is not None) == expected_present + if config is not None: + assert config.include == include + assert config.exclude == exclude + + +def test__DataSyncFilterConfig__fields_are_mirrored_by_hand_elsewhere(): + """Fail loudly if DataSyncFilterConfig grows a field. + + ResolvableBase and ResolvableJobParam carry `include`/`exclude` as their own flat + fields and adapt them via `from_patterns`, rather than nesting this model. That keeps + the demand execution models from depending on the data sync schema, at the cost of a + hand-maintained mirror: a new field added here would be silently absent there, and a + value-comparing test would stay green. + + If this fails, a field was added. Either mirror it in + `models/demand_execution/resolvables.py::ResolvableBase` and + `models/demand_execution/job_param.py::ResolvableJobParam` (and thread it through + `from_patterns` and `from_resolvable`), or take it as the signal to switch those + models to a nested `filter_config: DataSyncFilterConfig` field. + + If you do switch: `PydanticBaseModel` sets `extra="ignore"`, so payloads still using + the flat keys would be accepted with their filters SILENTLY DROPPED. That migration + needs a `model_validator(mode="before")` that either folds the flat keys into the + nested config or rejects them outright -- never a bare field swap. + """ + assert set(DataSyncFilterConfig.model_fields) == {"include", "exclude"} diff --git a/test/aibs_informatics_core/utils/test_file_operations.py b/test/aibs_informatics_core/utils/test_file_operations.py index a37c8ac..3e49ca8 100644 --- a/test/aibs_informatics_core/utils/test_file_operations.py +++ b/test/aibs_informatics_core/utils/test_file_operations.py @@ -337,6 +337,38 @@ def test__find_paths__multiple_exclude_patterns(self): result = find_paths(root, include_dirs=False, excludes=[r".*\.log", r".*\.csv"]) self.assertEqual(result, [str(root / "a.txt")]) + def test__find_paths__patterns_are_matched_relative_to_root(self): + # Patterns describe the path relative to root. Previously they were matched against + # the full absolute path, so a root-relative pattern like "sub/.*" matched nothing. + root = self.tmp_path() + self.create_dir(root, ["sub/a.txt", "other/b.txt"]) + result = find_paths(root, include_dirs=False, includes=[r"sub/.*"]) + self.assertEqual(result, [str(root / "sub" / "a.txt")]) + + def test__find_paths__absolute_patterns_no_longer_match(self): + # The flip side of relative anchoring: a pattern carrying the absolute prefix + # no longer matches, since it is compared against the relative path. + root = self.tmp_path() + self.create_dir(root, ["a.txt"]) + result = find_paths(root, include_dirs=False, includes=[f"{root}/.*"]) + self.assertEqual(result, []) + + def test__find_paths__exclude_is_relative_to_root(self): + root = self.tmp_path() + self.create_dir(root, ["sample/a.txt", "keep/b.txt"]) + result = find_paths(root, include_dirs=False, excludes=[r"sample/.*"]) + self.assertEqual(result, [str(root / "keep" / "b.txt")]) + + def test__find_paths__handles_file_root(self): + # When the root is itself a file, patterns match against its name. + root = self.tmp_path() + self.create_dir(root, ["a.txt"]) + file_root = root / "a.txt" + self.assertEqual( + find_paths(file_root, include_dirs=False, includes=[r".*\.txt"]), [str(file_root)] + ) + self.assertEqual(find_paths(file_root, include_dirs=False, includes=[r".*\.csv"]), []) + def test__move_path__handles_file(self): path = self.tmp_file() path.write_text("_" * 5) diff --git a/test/aibs_informatics_core/utils/test_filters.py b/test/aibs_informatics_core/utils/test_filters.py new file mode 100644 index 0000000..33b5eca --- /dev/null +++ b/test/aibs_informatics_core/utils/test_filters.py @@ -0,0 +1,156 @@ +import re +from pathlib import Path + +import pytest + +from aibs_informatics_core.models.aws.s3 import S3Path +from aibs_informatics_core.utils.filters import ( + compile_patterns, + filter_paths, + get_relative_path, + path_matches_filters, +) + + +@pytest.mark.parametrize( + "value, expected", + [ + pytest.param(None, None, id="none"), + pytest.param("", None, id="empty string"), + pytest.param([], None, id="empty list"), + pytest.param(r".*\.txt", [r".*\.txt"], id="single string"), + pytest.param([r"a.*", r"b.*"], [r"a.*", r"b.*"], id="list of strings"), + ], +) +def test__compile_patterns__normalizes_input(value, expected): + actual = compile_patterns(value) + if expected is None: + assert actual is None + else: + assert [p.pattern for p in actual] == expected + + +def test__compile_patterns__passes_through_compiled_patterns(): + pattern = re.compile(r".*\.txt") + assert compile_patterns(pattern) == [pattern] + assert compile_patterns([pattern, r"b.*"]) == [pattern, re.compile(r"b.*")] + + +@pytest.mark.parametrize( + "path, root, expected", + [ + pytest.param("/a/b/c.txt", None, "/a/b/c.txt", id="no root returns path as is"), + pytest.param("/a/b/c.txt", "/a", "b/c.txt", id="strips root"), + pytest.param("/a/b/c.txt", "/a/", "b/c.txt", id="strips root with trailing slash"), + pytest.param(Path("/a/b/c.txt"), Path("/a"), "b/c.txt", id="accepts path objects"), + pytest.param( + "s3://bucket/run1/s1/c.bam", + "s3://bucket/run1", + "s1/c.bam", + id="handles s3 uris without mangling scheme", + ), + pytest.param( + "s3://bucket/run1/s1/c.bam", + "s3://bucket/run1/", + "s1/c.bam", + id="handles s3 uris with trailing slash", + ), + pytest.param("/a/b/c.txt", "/a/b/c.txt", "c.txt", id="path is root uses base name"), + pytest.param("/a/b/c.txt", "/x", "/a/b/c.txt", id="path not under root is unchanged"), + ], +) +def test__get_relative_path(path, root, expected): + assert get_relative_path(path, root) == expected + + +def test__path_matches_filters__anchors_patterns_relative_to_root(): + # The pattern describes the path relative to the root, not its absolute location. + assert path_matches_filters("/data/run1/s1/a.bam", root="/data/run1", include=r"s1/.*") + assert not path_matches_filters("/data/run1/s2/a.bam", root="/data/run1", include=r"s1/.*") + # Without relative anchoring the same pattern would need the absolute prefix, which it + # no longer matches. + assert not path_matches_filters( + "/data/run1/s1/a.bam", root="/data/run1", include=r"/data/run1/s1/.*" + ) + + +def test__path_matches_filters__uses_fullmatch_not_search(): + assert path_matches_filters("a.txt", include=r".*\.txt") + # A fragment does not match -- the pattern must describe the entire path. + assert not path_matches_filters("a.txt", include=r"\.txt") + assert not path_matches_filters("sub/a.txt", include=r"a\.txt") + + +def test__path_matches_filters__exclude_beats_include(): + assert not path_matches_filters("a.txt", include=r".*\.txt", exclude=r"a\.txt") + assert path_matches_filters("b.txt", include=r".*\.txt", exclude=r"a\.txt") + + +@pytest.mark.parametrize("include", [None, "", []], ids=["none", "empty string", "empty list"]) +def test__path_matches_filters__empty_include_includes_everything(include): + assert path_matches_filters("anything/at/all.bam", include=include) + # ... but an exclude still applies. + assert not path_matches_filters("anything/at/all.bam", include=include, exclude=r".*\.bam") + + +def test__path_matches_filters__no_filters_matches_everything(): + assert path_matches_filters("/a/b/c.txt") + assert path_matches_filters("/a/b/c.txt", root="/x") + + +def test__path_matches_filters__multiple_patterns_are_ored(): + assert path_matches_filters("a.txt", include=[r".*\.txt", r".*\.csv"]) + assert path_matches_filters("a.csv", include=[r".*\.txt", r".*\.csv"]) + assert not path_matches_filters("a.log", include=[r".*\.txt", r".*\.csv"]) + assert not path_matches_filters("a.log", exclude=[r".*\.log", r".*\.tmp"]) + + +def test__filter_paths__filters_relative_to_root(): + paths = [ + "/data/run1/s1/a.bam", + "/data/run1/s1/a.bai", + "/data/run1/s2/b.bam", + ] + actual = filter_paths(paths, root="/data/run1", include=r"s1/.*") + assert actual == ["/data/run1/s1/a.bam", "/data/run1/s1/a.bai"] + + +def test__filter_paths__exclude_beats_include_and_preserves_order(): + paths = ["/r/c.txt", "/r/a.txt", "/r/b.txt", "/r/d.log"] + actual = filter_paths(paths, root="/r", include=r".*\.txt", exclude=r"b\.txt") + assert actual == ["/r/c.txt", "/r/a.txt"] + + +def test__filter_paths__no_filters_returns_all_paths(): + paths = ["/r/a.txt", "/r/b.txt"] + assert filter_paths(paths) == paths + + +def test__filter_paths__preserves_path_objects(): + # Paths are selected, never rewritten, so Path in means Path out. + paths = [Path("/r/a.txt"), Path("/r/b.log")] + actual = filter_paths(paths, root="/r", include=r".*\.txt") + assert actual == [Path("/r/a.txt")] + assert all(isinstance(p, Path) for p in actual) + # ... including on the unfiltered fast path. + assert filter_paths(paths) == paths + assert all(isinstance(p, Path) for p in filter_paths(paths)) + + +def test__filter_paths__preserves_str_subclasses(): + # S3Path subclasses str; filtering must not widen it back to a plain str, since + # downstream callers keep working with S3Path objects. + paths = [ + S3Path.build(bucket_name="bucket", key="run1/s1/a.bam"), + S3Path.build(bucket_name="bucket", key="run1/s2/b.bam"), + ] + root = S3Path.build(bucket_name="bucket", key="run1") + actual = filter_paths(paths, root=root, include=r"s1/.*") + assert actual == [S3Path.build(bucket_name="bucket", key="run1/s1/a.bam")] + assert all(isinstance(p, S3Path) for p in actual) + + +def test__filter_paths__empty_include_includes_everything(): + paths = ["/r/a.txt", "/r/b.log"] + assert filter_paths(paths, root="/r", include=[]) == paths + assert filter_paths(paths, root="/r", include=[], exclude=r".*\.log") == ["/r/a.txt"] diff --git a/test/aibs_informatics_core/utils/tools/test_strtools.py b/test/aibs_informatics_core/utils/tools/test_strtools.py index a80a0a9..2a1fc4e 100644 --- a/test/aibs_informatics_core/utils/tools/test_strtools.py +++ b/test/aibs_informatics_core/utils/tools/test_strtools.py @@ -1,4 +1,7 @@ +import pytest + from aibs_informatics_core.utils.tools.strtools import ( + condense_str, is_prefixed, is_suffixed, lowercase, @@ -40,3 +43,59 @@ def test__removesuffix__works(): assert removesuffix("v1", "v") == "v1" assert removesuffix("v1", "v1") == "" assert removesuffix("1v1", "v1") == "1" + + +def test__condense_str__returns_value_unchanged_when_it_fits(): + # Must be a no-op for values already in budget. Otherwise adopting this helper + # anywhere would silently rename every existing resource. + assert condense_str("short-name", max_length=24) == "short-name" + assert condense_str("a" * 24, max_length=24) == "a" * 24 + + +def test__condense_str__condenses_to_exactly_max_length(): + assert len(condense_str("a" * 100, max_length=24)) == 24 + + +def test__condense_str__keeps_readable_prefix_and_hex_suffix(): + result = condense_str("scratch-volume-with-a-very-long-name", max_length=24) + assert result.startswith("scratch-volume") + digest = result.rpartition("-")[2] + assert len(digest) == 8 + assert all(c in "0123456789abcdef" for c in digest) + + +def test__condense_str__is_deterministic(): + # Names that changed between runs would churn downstream resources (e.g. register + # a new AWS Batch job definition revision every time). + value = "x" * 80 + assert condense_str(value, max_length=24) == condense_str(value, max_length=24) + + +def test__condense_str__distinguishes_values_sharing_a_long_prefix(): + # The hash covers the whole original value, not the discarded tail, so values that + # truncate identically still differ. + shared = "shared-prefix-" * 5 + a = condense_str(shared + "alpha", max_length=24) + b = condense_str(shared + "beta", max_length=24) + assert a != b + assert a[:15] == b[:15] + + +def test__condense_str__honors_custom_delimiter_and_hash_length(): + result = condense_str("y" * 60, max_length=20, delimiter="_", hash_length=4) + assert len(result) == 20 + assert result[-5] == "_" + assert len(result.rpartition("_")[2]) == 4 + + +@pytest.mark.parametrize("hash_length", [0, -1]) +def test__condense_str__rejects_non_positive_hash_length(hash_length): + with pytest.raises(ValueError, match="hash_length must be positive"): + condense_str("z" * 40, max_length=24, hash_length=hash_length) + + +def test__condense_str__rejects_max_length_with_no_room_for_a_prefix(): + # 8 hash chars + 1 delimiter = 9; max_length 9 leaves zero prefix. Silently + # truncating to a bare hash would invite collisions, so this is an error. + with pytest.raises(ValueError, match="leaves no room for a prefix"): + condense_str("q" * 40, max_length=9)