Skip to content

OCSDV-452 (PR-A): data sync include/exclude filter models + shared filter helper - #54

Merged
rpmcginty merged 5 commits into
mainfrom
feature/OCSDV-452-data-sync-filter-models
Aug 14, 2026
Merged

rpmcginty merged 5 commits into
mainfrom
feature/OCSDV-452-data-sync-filter-models

Conversation

@rpmcginty

@rpmcginty rpmcginty commented Aug 7, 2026 •

Copy link
Copy Markdown
Collaborator

Jira: OCSDV-452 — PR-A of 5, release R1.

This is the aibs-informatics-core half of data sync include/exclude filtering. It adds the models and the one shared filter helper that the aws-utils (PR-C) and aws-lambda (PR-D) changes will route through. No version bump — core releases once, after PR-B (OCSDV-453) lands.

What's here

1. DataSyncFilterConfig (models/data_sync.py)

include / exclude as str | list[str] | None, with include_patterns / exclude_patterns @cached_property accessors compiling to re.Pattern. This copies the convention already used by ListDataPathsRequest in aibs_informatics_aws_lambda/handlers/data_sync/model.py, so the two stay consistent — the difference is that the compile step is now the shared compile_patterns helper rather than a private static method.

2. DataSyncTask.filter_config / .filter_root

Filters describe what to move, so they hang off the task rather than the config.

filter_root is internal plumbing — set by the prepare handler, never by users, and documented as such on the field. It exists because the distributed 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 a pattern written against run1/ would silently stop matching without an explicit anchor.

Note for PR-D: filter_root is typed str | None per the refinement decision, and Pydantic will not coerce a Path into it — the prepare handler needs to pass str(...).

3. DataSyncConfig.delete: bool = True

Currently hardcoded True at three sites in data_sync/operations.py; this exposes it. The field carries a prominent warning: filters narrow what the sync considers "the source", so with delete=True any file already at the destination that the filters exclude is treated as unexpected and deleted. Callers who filter are expected to pass delete=False.

There is deliberately no validator blocking filter_config + delete=True — mirroring a filtered subset is a legitimate use, and delete is the gate. Per the ticket's Known gaps section.

4. DataSyncRequest.config / .task

Both properties enumerate fields by hand, so new fields are silently dropped unless added. The new fields are added, and two tests (test__DataSyncRequest__config_carries_every_config_field, ..._task_carries_every_task_field) now iterate model_fields so a future dropped field fails CI instead of going unnoticed.

5. utils/filters.py — the one shared helper

New module, deliberately separate from file_operations.py: S3 code paths in aws-utils will import it, and file_operations pulls in fcntl/tarfile/archive machinery they don't need.

The contract, in one place:

  • patterns are regexes, not globs
  • matched with re.fullmatch — the pattern must describe the whole path
  • matched against the path relative to a supplied root
  • exclude wins over include
  • absent/empty include includes everything

Public surface: compile_patterns, get_relative_path, path_matches_filters (per-path predicate, for in-loop S3 listing), filter_paths (batch, compiles once).

filter_paths is type preserving. It selects from the paths it is given without rewriting them, and is typed with a bound TypeVar:

AnyPath = TypeVar("AnyPath", bound=str | Path)

def filter_paths(paths: Iterable[AnyPath], ...) -> list[AnyPath]: ...

So list[Path] -> list[Path], list[str] -> list[str], list[S3Path] -> list[S3Path], and callers holding Path objects no longer have to re-wrap every element. The TypeVar is bound rather than constrained on purpose: S3Path subclasses str (via ValidatedStr), so a constrained TypeVar — or a pair of str/Path @overloads — would widen list[S3Path] back to list[str], which is exactly the type the aws-utils sync code wants to keep hold of. Verified against mypy rather than assumed.

get_relative_path is string-prefix based rather than pathlib based on purpose — Path("s3://bucket/key") collapses the // and mangles the scheme. Two edge cases worth review: when the path is the root (single-file source) it relativizes to the base name so patterns still have something to match, and when the path is not under the root at all it is returned unchanged.

6. find_paths routed through the helper

Behavior change: find_paths previously matched patterns against the full absolute path. It now matches against the path relative to root. Concretely, excludes=[r"sample/.*"] used to do nothing under a local root while working under S3; now it behaves the same in both places. This is design decision #1 in the ticket, unifying three inconsistent implementations.

On the ~13 existing find_paths tests

The ticket flagged these as needing deliberate updating. In the end, none of their assertions changed — all 53 tests in test_file_operations.py pass untouched.

The reason: every existing filter test uses patterns already prefixed with .* (.*\.txt, .*\.log, .*d2.*, .*b\.txt). Under fullmatch, a leading .* absorbs whichever prefix is present, so those patterns match identically against /tmp/xyz/a.txt and a.txt. The tests were written prefix-agnostically and are blind to the change.

That also means the existing suite did not pin the new behavior, so rather than editing assertions I added four tests that do:

Test Pins
test__find_paths__patterns_are_matched_relative_to_root includes=["sub/.*"] now matches; previously matched nothing
test__find_paths__absolute_patterns_no_longer_match a pattern carrying the absolute prefix no longer matches — the removed behavior
test__find_paths__exclude_is_relative_to_root the sample/.* case named in the ticket
test__find_paths__handles_file_root root-is-a-file relativizes to the base name

The only pre-existing assertions that changed anywhere are two to_dict() expectations in test_data_sync.py (test__BatchDataSyncRequest__to_dict, test__PrepareBatchDataSyncResponse__to_dict), which gained "delete": True because the new field serializes.

Downstream callers to be aware of in PR-C: s3.py:727 passes user include/exclude into find_paths and is the call site this change is meant to fix. s3.py:414, 765, and 1311 call find_paths with no patterns and hit the unchanged early-return path.

BatchDataSyncRequest._handle_single_flattened_request

Verified (scope item 7). It calls DataSyncRequest.is_valid(data), which round-trips through Pydantic:

  • a flattened request with a nested filter_config dict validates and is wrapped correctly — test__BatchDataSyncRequest__from_dict__flattened_request_with_filter_config
  • a genuine batch-shaped dict is still not valid as a DataSyncRequest (source_path/destination_path are required), so the flattening branch does not misfire

One hazard checked explicitly: cached_property values live in the instance __dict__, so I confirmed that touching include_patterns does not leak into to_dict() or break equality — pinned by test__DataSyncFilterConfig__cached_properties_do_not_leak_into_serialization.

Tests

New test/aibs_informatics_core/utils/test_filters.py (28 tests) covers relative anchoring, fullmatch vs. fragment matching, exclude-beats-include, empty/absent include, multi-pattern OR-ing, compiled-pattern passthrough, S3 URI handling, path-is-root / path-outside-root, and element-type preservation for both Path and S3Path.

test_data_sync.py adds model round-trips to_dict() -> from_dict() with and without filter_config, including through BatchDataSyncRequest and PrepareBatchDataSyncResponse — the seam the SFN Map state crosses.

make format && make lint && make test all clean: ruff clean, mypy clean over 65 source files, 1092 tests passing.

Out of scope

models/demand_execution/** (Resolvable, JobParam, serializer, hash) is untouched — that is PR-B in this same repo. No version bump, no release.

🤖 Generated with Claude Code


End-to-end verification (dev)

This PR contributes the DataSyncFilterConfig model, the filter_root / filter_config fields on DataSyncTask, DataSyncConfig.delete, and the shared fullmatch filter helper to the behavior verified below.

Four DemandExecutions were run against the deployed dev-de environment (account 051791135335, us-west-2) using a shared 12-object / 541,610-byte S3 fixture. All four Step Functions executions reached SUCCEEDED, and in every case the set of objects that landed in S3 matches the declared include/exclude filters exactly — no missing matches and no leaked non-matches.

Because a single demand execution exercises the whole chain — the data-sync request/filter model in aibs-informatics-core, the S3 transfer and filtering implementation in aibs-informatics-aws-utils, and the Batch/EFS execution wiring in aibs-informatics-aws-lambda — this same evidence block is attached to every PR in the set rather than split across them.

Related PRs

These five PRs are one change set and are intended to merge in release order (R1 first, then R2, then R3), since each release depends on the one before it.

PR Repository / number Release Link
PR-A aibs-informatics-core#54 R1 (core) #54
PR-B aibs-informatics-core#55 R1 (core) #55
PR-C aibs-informatics-aws-utils#47 R2 (aws-utils) AllenInstitute/aibs-informatics-aws-utils#47
PR-D aibs-informatics-aws-lambda#40 R3 (aws-lambda) AllenInstitute/aibs-informatics-aws-lambda#40
PR-E aibs-informatics-aws-lambda#41 R3 (aws-lambda) AllenInstitute/aibs-informatics-aws-lambda#41

Fixture

s3://dev-de-core-us-west-2-051791135335/test_data/ocsdv-452-filters/input/ (the fixture now lives in the environment's own bucket, having been moved off an orphaned bucket that no stack owns, so inputs and outputs share one bucket) — 12 objects, 541,610 bytes total (aws s3 ls --recursive --summarize reports Total Objects: 12 / Total Size: 541610):

Key Bytes
README.md 130
metadata.json 214
sampleA/aligned.bam 262,140
sampleA/aligned.bam.bai 4,064
sampleA/qc_summary.txt 463
sampleA/reads_R1.fastq 1,983
sampleA/reads_R2.fastq 1,983
sampleB/aligned.bam 262,140
sampleB/aligned.bam.bai 4,064
sampleB/qc_summary.txt 463
sampleB/reads_R1.fastq 1,983
sampleB/reads_R2.fastq 1,983

Each case runs the same container command: list ${INPUT_DATA}, cp -R ${INPUT_DATA}/. ${OUTPUT_DATA}/, list ${OUTPUT_DATA}. The container itself does no filtering, so any difference between the fixture and the uploaded set is attributable to the data-sync filters.

Results

Counts are objects. "In" is the fixture, "localized" is what survived the input filter and was present under ${INPUT_DATA} in the container, "uploaded" is what was observed in S3 under the case prefix.

Case Input filter Output filter In → localized → uploaded Uploaded bytes Result
tc1-input-exclude-bam exclude: [".*\\.bam", ".*\\.bam\\.bai"] none 12 → 8 → 8 9,202 PASS
tc2-input-include-fastq include: [".*\\.fastq"] none 12 → 4 → 4 7,932 PASS
tc3-output-exclude-fastq none exclude: [".*\\.fastq"] 12 → 12 → 8 533,678 PASS
tc4-both-ends-filtered include: ["sampleA/.*"] include: [".*\\.txt"] 12 → 5 → 1 463 PASS

Across the four cases: 21 objects, 551,275 bytes written under s3://dev-de-core-us-west-2-051791135335/test_results/ocsdv-452-filters/.

Two independent confirmations worth noting:

  • Byte arithmetic closes. tc1: 9,202 uploaded + 532,408 excluded (2 × (262,140 + 4,064)) = 541,610 = the fixture total. tc3: 541,610 − 533,678 = 7,932 = 4 × 1,983, exactly the four .fastq files and nothing else. Uploaded file sizes are byte-identical to their sources, so nothing was truncated in transit.
  • tc3 isolates the filter to the upload step. The Batch container log for tc3 (jobId 7f83fd65-6e9e-4817-a48d-e6e796b1cedf) prints all 12 files under --- localized input (post input-filter) --- and all 12 again under --- staged for upload (pre output-filter) ---, yet only 8 objects reached S3. That rules out the output filter being misapplied at localization time, which an object count alone could not.

Note on attribution for tc1 and tc2: because the container copies ${INPUT_DATA} wholesale into ${OUTPUT_DATA}, the final S3 state for an input-side filter is indistinguishable from an equivalent output-side filter. For those two cases the input-side attribution rests on the payload (filters declared on input_data, output_data bare) plus the container's find output, not on the S3 listing alone. tc3 and tc4 are unambiguous.

Directory structure is preserved end to end in all cases — the sampleA/ and sampleB/ prefixes survive the round trip, so patterns are matched against the same relative path that is used to construct the destination key.

tc1-input-exclude-bam — input-side exclude, 8 objects uploaded (9,202 bytes)

Uploaded (relative to s3://dev-de-core-us-west-2-051791135335/test_results/ocsdv-452-filters/tc1-input-exclude-bam/; aws s3 ls --recursive --summarize reports Total Objects: 8 / Total Size: 9202):

README.md
metadata.json
sampleA/qc_summary.txt
sampleA/reads_R1.fastq
sampleA/reads_R2.fastq
sampleB/qc_summary.txt
sampleB/reads_R1.fastq
sampleB/reads_R2.fastq

Correctly not uploaded — these four match one of the two input-side exclude patterns (.*\.bam, .*\.bam\.bai), so they were never localized and therefore never staged:

Key Excluded by
sampleA/aligned.bam .*\.bam
sampleA/aligned.bam.bai .*\.bam\.bai
sampleB/aligned.bam .*\.bam
sampleB/aligned.bam.bai .*\.bam\.bai

Every excluded object matches a declared pattern, and every object matching a declared pattern is excluded. Step Functions execution d247218f-34e6-47cc-ad4b-a175180b2e45 on arn:aws:states:us-west-2:051791135335:stateMachine:dev-de-demand-execution, SUCCEEDED, 2026-08-12 14:46:07 → 14:51:02 (-07:00); object timestamps (14:50:37) fall inside that window.

{
  "execution_type": "ocsdv452",
  "execution_id": "ocsdv452-tc1-input-exclude-bam",
  "execution_image": "public.ecr.aws/ubuntu/ubuntu:22.04",
  "execution_parameters": {
    "command": [
      "set",
      "-eu",
      "&&",
      "echo",
      "'=== tc1-input-exclude-bam ==='",
      "&&",
      "echo",
      "'--- localized input (post input-filter) ---'",
      "&&",
      "find",
      "${INPUT_DATA}",
      "-type",
      "f",
      "|",
      "sort",
      "&&",
      "mkdir",
      "-p",
      "${OUTPUT_DATA}",
      "&&",
      "cp",
      "-R",
      "${INPUT_DATA}/.",
      "${OUTPUT_DATA}/",
      "&&",
      "echo",
      "'--- staged for upload (pre output-filter) ---'",
      "&&",
      "find",
      "${OUTPUT_DATA}",
      "-type",
      "f",
      "|",
      "sort"
    ],
    "params": {
      "input_data": {
        "remote": "s3://dev-de-core-us-west-2-051791135335/test_data/ocsdv-452-filters/input/",
        "local": "input_data",
        "exclude": [
          ".*\\.bam",
          ".*\\.bam\\.bai"
        ]
      },
      "output_data": {
        "local": "output_data",
        "remote": "s3://dev-de-core-us-west-2-051791135335/test_results/ocsdv-452-filters/tc1-input-exclude-bam/"
      }
    },
    "inputs": [
      "input_data"
    ],
    "outputs": [
      "output_data"
    ],
    "output_s3_prefix": "s3://dev-de-core-us-west-2-051791135335/test_results/ocsdv-452-filters/tc1-input-exclude-bam/"
  },
  "execution_platform": {
    "aws_batch": {
      "job_queue_name": "dev-de-demand-on-demand-job-queue"
    }
  },
  "resource_requirements": {
    "vcpus": 1,
    "memory": 2048
  }
}
tc2-input-include-fastq — input-side include, 4 objects uploaded (7,932 bytes)

Uploaded (Total Objects: 4 / Total Size: 7932; 4 × 1,983 = 7,932, matching source sizes exactly):

sampleA/reads_R1.fastq
sampleA/reads_R2.fastq
sampleB/reads_R1.fastq
sampleB/reads_R2.fastq

Correctly not uploaded — the input side declares a single include pattern .*\.fastq and no exclude, so any key that does not match is not localized. None of these eight keys end in .fastq:

README.md
metadata.json
sampleA/aligned.bam
sampleA/aligned.bam.bai
sampleA/qc_summary.txt
sampleB/aligned.bam
sampleB/aligned.bam.bai
sampleB/qc_summary.txt

All four fixture keys that do match .*\.fastq are present, so membership is correct in both directions. Step Functions execution arn:aws:states:us-west-2:051791135335:execution:dev-de-demand-execution:ocsdv452-tc2-input-include-fastq, SUCCEEDED, 2026-08-12 15:37:27 → 15:42:09 (-07:00).

{
  "execution_type": "ocsdv452",
  "execution_id": "ocsdv452-tc2-input-include-fastq",
  "execution_image": "public.ecr.aws/ubuntu/ubuntu:22.04",
  "execution_parameters": {
    "command": [
      "set",
      "-eu",
      "&&",
      "echo",
      "'=== tc2-input-include-fastq ==='",
      "&&",
      "echo",
      "'--- localized input (post input-filter) ---'",
      "&&",
      "find",
      "${INPUT_DATA}",
      "-type",
      "f",
      "|",
      "sort",
      "&&",
      "mkdir",
      "-p",
      "${OUTPUT_DATA}",
      "&&",
      "cp",
      "-R",
      "${INPUT_DATA}/.",
      "${OUTPUT_DATA}/",
      "&&",
      "echo",
      "'--- staged for upload (pre output-filter) ---'",
      "&&",
      "find",
      "${OUTPUT_DATA}",
      "-type",
      "f",
      "|",
      "sort"
    ],
    "params": {
      "input_data": {
        "remote": "s3://dev-de-core-us-west-2-051791135335/test_data/ocsdv-452-filters/input/",
        "local": "input_data",
        "include": [
          ".*\\.fastq"
        ]
      },
      "output_data": {
        "local": "output_data",
        "remote": "s3://dev-de-core-us-west-2-051791135335/test_results/ocsdv-452-filters/tc2-input-include-fastq/"
      }
    },
    "inputs": [
      "input_data"
    ],
    "outputs": [
      "output_data"
    ],
    "output_s3_prefix": "s3://dev-de-core-us-west-2-051791135335/test_results/ocsdv-452-filters/tc2-input-include-fastq/"
  },
  "execution_platform": {
    "aws_batch": {
      "job_queue_name": "dev-de-demand-on-demand-job-queue"
    }
  },
  "resource_requirements": {
    "vcpus": 1,
    "memory": 2048
  }
}
tc3-output-exclude-fastq — output-side exclude, 8 objects uploaded (533,678 bytes)

Uploaded (Total Objects: 8 / Total Size: 533678):

README.md
metadata.json
sampleA/aligned.bam
sampleA/aligned.bam.bai
sampleA/qc_summary.txt
sampleB/aligned.bam
sampleB/aligned.bam.bai
sampleB/qc_summary.txt

Correctly not uploaded — the input side is unfiltered, so all 12 objects were localized and all 12 were staged under ${OUTPUT_DATA}. These four were dropped at upload because they match the output-side exclude .*\.fastq:

sampleA/reads_R1.fastq
sampleA/reads_R2.fastq
sampleB/reads_R1.fastq
sampleB/reads_R2.fastq

This is the case that distinguishes output-side filtering from input-side filtering by observation rather than by declaration: the container log lists all 12 files at both checkpoints, yet only 8 objects reached S3. Step Functions execution ocsdv452-tc3-output-exclude-fastq, SUCCEEDED, 2026-08-12 15:38:21 → 15:41:58 (-07:00); Batch job 7f83fd65-6e9e-4817-a48d-e6e796b1cedf on dev-de-demand-on-demand-job-queue, SUCCEEDED.

{
  "execution_type": "ocsdv452",
  "execution_id": "ocsdv452-tc3-output-exclude-fastq",
  "execution_image": "public.ecr.aws/ubuntu/ubuntu:22.04",
  "execution_parameters": {
    "command": [
      "set",
      "-eu",
      "&&",
      "echo",
      "'=== tc3-output-exclude-fastq ==='",
      "&&",
      "echo",
      "'--- localized input (post input-filter) ---'",
      "&&",
      "find",
      "${INPUT_DATA}",
      "-type",
      "f",
      "|",
      "sort",
      "&&",
      "mkdir",
      "-p",
      "${OUTPUT_DATA}",
      "&&",
      "cp",
      "-R",
      "${INPUT_DATA}/.",
      "${OUTPUT_DATA}/",
      "&&",
      "echo",
      "'--- staged for upload (pre output-filter) ---'",
      "&&",
      "find",
      "${OUTPUT_DATA}",
      "-type",
      "f",
      "|",
      "sort"
    ],
    "params": {
      "input_data": {
        "remote": "s3://dev-de-core-us-west-2-051791135335/test_data/ocsdv-452-filters/input/",
        "local": "input_data"
      },
      "output_data": {
        "local": "output_data",
        "remote": "s3://dev-de-core-us-west-2-051791135335/test_results/ocsdv-452-filters/tc3-output-exclude-fastq/",
        "exclude": [
          ".*\\.fastq"
        ]
      }
    },
    "inputs": [
      "input_data"
    ],
    "outputs": [
      "output_data"
    ],
    "output_s3_prefix": "s3://dev-de-core-us-west-2-051791135335/test_results/ocsdv-452-filters/tc3-output-exclude-fastq/"
  },
  "execution_platform": {
    "aws_batch": {
      "job_queue_name": "dev-de-demand-on-demand-job-queue"
    }
  },
  "resource_requirements": {
    "vcpus": 1,
    "memory": 2048
  }
}
tc4-both-ends-filtered — include on both ends, 1 object uploaded (463 bytes)

Uploaded (verbatim from aws s3 ls ... --recursive):

2026-08-12 15:41:52        463 test_results/ocsdv-452-filters/tc4-both-ends-filtered/sampleA/qc_summary.txt

Correctly not uploaded — two stages, in order:

  1. Input include sampleA/.* admits only the 5 objects under sampleA/. Dropped at localization (7 objects): README.md and metadata.json (top level, no sampleA/ prefix), and all 5 sampleB/* objects.
  2. Output include .*\.txt admits only qc_summary.txt of the 5 that were staged. Dropped at upload (4 objects): sampleA/aligned.bam, sampleA/aligned.bam.bai, sampleA/reads_R1.fastq, sampleA/reads_R2.fastq.

Each of the 11 absent files is absent for a reason one of the two filters calls for, and the single present file is the only one both filters admit. The sampleA/ path component survives into the destination key, confirming the include pattern is matched against the same relative path that is preserved on upload. Step Functions execution arn:aws:states:us-west-2:051791135335:execution:dev-de-demand-execution:ocsdv452-tc4-both-ends-filtered, SUCCEEDED, 2026-08-12 15:38:39 → 15:42:23 (-07:00); the object's LastModified falls inside that window.

{
  "execution_type": "ocsdv452",
  "execution_id": "ocsdv452-tc4-both-ends-filtered",
  "execution_image": "public.ecr.aws/ubuntu/ubuntu:22.04",
  "execution_parameters": {
    "command": [
      "set",
      "-eu",
      "&&",
      "echo",
      "'=== tc4-both-ends-filtered ==='",
      "&&",
      "echo",
      "'--- localized input (post input-filter) ---'",
      "&&",
      "find",
      "${INPUT_DATA}",
      "-type",
      "f",
      "|",
      "sort",
      "&&",
      "mkdir",
      "-p",
      "${OUTPUT_DATA}",
      "&&",
      "cp",
      "-R",
      "${INPUT_DATA}/.",
      "${OUTPUT_DATA}/",
      "&&",
      "echo",
      "'--- staged for upload (pre output-filter) ---'",
      "&&",
      "find",
      "${OUTPUT_DATA}",
      "-type",
      "f",
      "|",
      "sort"
    ],
    "params": {
      "input_data": {
        "remote": "s3://dev-de-core-us-west-2-051791135335/test_data/ocsdv-452-filters/input/",
        "local": "input_data",
        "include": [
          "sampleA/.*"
        ]
      },
      "output_data": {
        "local": "output_data",
        "remote": "s3://dev-de-core-us-west-2-051791135335/test_results/ocsdv-452-filters/tc4-both-ends-filtered/",
        "include": [
          ".*\\.txt"
        ]
      }
    },
    "inputs": [
      "input_data"
    ],
    "outputs": [
      "output_data"
    ],
    "output_s3_prefix": "s3://dev-de-core-us-west-2-051791135335/test_results/ocsdv-452-filters/tc4-both-ends-filtered/"
  },
  "execution_platform": {
    "aws_batch": {
      "job_queue_name": "dev-de-demand-on-demand-job-queue"
    }
  },
  "resource_requirements": {
    "vcpus": 1,
    "memory": 2048
  }
}

Note on the first attempt

The first attempt at these four runs failed before the container started, with an efs-utils error reporting File name too long. The cause was the generated ECS volume name: it made the mount helper's CA database path exceed OpenSSL's 256-byte BSIZE guard by 4 characters. It was worked around for the run above by shortening execution_type to ocsdv452. PR-E addresses it properly by condensing the generated volume name from 50 characters to 16, which puts the path back under the limit without relying on short caller-supplied names.

Scope

This is a dev-environment functional check of four small cases against a 12-object fixture. It demonstrates that the filter semantics behave as declared on both the input and output sides of a real demand execution; it is not a performance or scale test, and it does not cover large transfers, multipart uploads, or concurrent executions. Verification was read-only (s3 ls, s3api list-objects-v2, sts get-caller-identity, stepfunctions list/describe-execution, batch list/describe-jobs, logs get-log-events).

Addendum: container logs confirm the input filter runs on the download, not just the upload

The S3 result alone cannot fully separate input-side from output-side filtering for tc1 and tc2, because the container copies its input directory wholesale into the output directory — an unfiltered download plus an equivalent output-side exclude would produce the same uploaded set. tc3 and tc4 disambiguate by construction (tc3 uploads the .bam files that tc1 drops, from the same fixture), but it is worth closing directly.

The container prints its localized input before copying. From /aws/batch/job, stream
dev-de-ocsdv452-43c8f938.../bc357a293a09432681668be032cb1cb3 (tc1-input-exclude-bam):

=== tc1-input-exclude-bam ===
--- localized input (post input-filter) ---
.../input_data/README.md
.../input_data/metadata.json
.../input_data/sampleA/qc_summary.txt
.../input_data/sampleA/reads_R1.fastq
.../input_data/sampleA/reads_R2.fastq
.../input_data/sampleB/qc_summary.txt
.../input_data/sampleB/reads_R1.fastq
.../input_data/sampleB/reads_R2.fastq

Eight files, not twelve. The four .bam/.bam.bai objects never reached the container's EFS
working directory — the filter was applied during the download, so the 524 KB of alignment data
was never transferred. That is the behavior the feature exists to provide, and it is what
distinguishes filtering from post-hoc pruning.

Only this one stream was still retained in CloudWatch when the logs were pulled, so this direct
confirmation covers tc1; the other three cases rest on the S3 results and their Step Functions
executions above.

…lter helper

Adds the core-side half of data sync include/exclude filtering (PR-A).

- New `DataSyncFilterConfig(include, exclude)` with `include_patterns` /
  `exclude_patterns` cached-property accessors, following the existing
  `ListDataPathsRequest` convention in aibs-informatics-aws-lambda.
- `DataSyncTask` gains `filter_config` (what to move) and `filter_root`
  (internal plumbing set by the prepare handler so patterns stay anchored
  across the prepare -> batch split).
- `DataSyncConfig` gains `delete: bool = True`, documenting that filters
  combined with `delete=True` remove non-matching files already present at
  the destination. Deliberately unguarded; `delete` is the gate.
- `DataSyncRequest.config` / `.task` enumerate fields by hand, so the new
  fields are added there explicitly, with tests that fail if a future field
  is dropped.
- New `utils/filters.py` holds the single filter contract: regex patterns
  matched with `fullmatch` against the path relative to a supplied root,
  exclude beats include, empty include includes everything.
- `find_paths` now routes through that helper. Behavior change: it
  previously matched the full absolute path.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Copilot AI lite review requested due to automatic review settings August 7, 2026 21:21
@codecov

codecov Bot commented Aug 7, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.46835% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 97.09%. Comparing base (09b7e3d) to head (e8b26a9).

Files with missing lines Patch % Lines
src/aibs_informatics_core/utils/filters.py 95.65% 1 Missing and 1 partial ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main      #54      +/-   ##
==========================================
- Coverage   97.10%   97.09%   -0.01%     
==========================================
  Files          57       58       +1     
  Lines        3347     3412      +65     
  Branches      382      391       +9     
==========================================
+ Hits         3250     3313      +63     
- Misses         53       54       +1     
- Partials       44       45       +1     
Files with missing lines Coverage Δ
src/aibs_informatics_core/models/data_sync.py 100.00% <100.00%> (ø)
src/aibs_informatics_core/utils/file_operations.py 97.16% <100.00%> (-0.16%) ⬇️
src/aibs_informatics_core/utils/tools/strtools.py 100.00% <100.00%> (ø)
src/aibs_informatics_core/utils/filters.py 95.65% <95.65%> (ø)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copilot AI 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.

Pull request overview

Adds a shared include/exclude filtering contract and wires it into core data-sync models and local path discovery so filtering semantics are consistent across local/S3/EFS listings.

Changes:

  • Introduces utils/filters.py with shared helpers for compiling patterns, relativizing paths, and applying include/exclude rules using re.fullmatch.
  • Adds DataSyncFilterConfig, DataSyncTask.filter_config / filter_root, and DataSyncConfig.delete to models/data_sync.py, plus stronger tests to ensure DataSyncRequest.config / .task carry all fields.
  • Routes find_paths through the shared helper and adds tests that pin the new “match relative to root” behavior.

Reviewed changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
src/aibs_informatics_core/utils/filters.py New shared filtering helpers establishing a single include/exclude contract.
src/aibs_informatics_core/utils/file_operations.py Updates find_paths to apply filters via the shared helper (relative-to-root + fullmatch).
src/aibs_informatics_core/models/data_sync.py Adds filter models/fields and exposes delete on config; updates DataSyncRequest.config / .task.
test/aibs_informatics_core/utils/test_filters.py New unit tests covering shared filtering semantics and edge cases.
test/aibs_informatics_core/utils/test_file_operations.py Adds tests pinning find_paths relative-filter behavior and file-root handling.
test/aibs_informatics_core/models/test_data_sync.py Adds/updates serialization and field-carrying tests for new data sync filter/delete fields.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +83 to +86

include: str | list[str] | None = None
exclude: str | list[str] | None = None

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

ok I will remove the cached_property

Comment on lines +109 to +113
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. Defaults to the source path when unset.
"""
filter_paths selected paths but always returned list[str], forcing callers
holding Path objects to re-wrap every element. It now selects without
rewriting and is typed with a bound TypeVar, so the element type survives:
list[Path] -> list[Path], list[str] -> list[str].

The TypeVar is bound rather than constrained deliberately. S3Path subclasses
str (via ValidatedStr), so a constrained TypeVar -- or a pair of str/Path
overloads -- would widen list[S3Path] back to list[str], which is exactly the
type the aws-utils sync code wants to keep hold of.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Copilot AI review requested due to automatic review settings August 7, 2026 21:47

Copilot AI 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.

Pull request overview

Copilot reviewed 6 out of 6 changed files in this pull request and generated no new comments.

Suppressed comments (3)

test/aibs_informatics_core/utils/test_filters.py:36

  • re.Pattern objects generally don't compare equal unless they're the same object, so this assertion is likely to fail by comparing against a newly-compiled pattern. It’s safer to assert identity for the pass-through pattern and compare .pattern for the compiled string input.
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.*")]

src/aibs_informatics_core/models/data_sync.py:112

  • The docstring says filter_root "Defaults to the source path when unset", but the field default is None and there’s no validator or property implementing that default. This can mislead readers; either implement the defaulting behavior or adjust the doc to reflect that callers must treat None as "use source_path".
            original root here. Defaults to the source path when unset.

src/aibs_informatics_core/utils/file_operations.py:372

  • The includes/excludes args are typed as Sequence[Pattern | str], but the docstring still documents them as Sequence[str]. Updating the doc avoids confusion and makes it clear compiled regexes are supported.
        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.

@rpmcginty

Copy link
Copy Markdown
Collaborator Author

LOC breakdown

Although GitHub reports 654 additions and 23 deletions, most of the change is tests, documentation, comments, and typing rather than new source-code logic.

Area Files Additions Deletions Total churn
Production source 3 292 23 315
Tests 3 362 0 362
Total 6 654 23 677
  • 55.4% of additions are tests: 362 of 654 lines.
  • Production source accounts for 44.6% of additions.
  • Tests account for 53.5% of total line churn.

Changes by file

File Additions Deletions Purpose
src/aibs_informatics_core/models/data_sync.py 99 4 Models, fields, request wiring, and API documentation
src/aibs_informatics_core/utils/file_operations.py 8 19 Replaces inline filtering with the shared helper
src/aibs_informatics_core/utils/filters.py 185 0 Shared filtering implementation, contract documentation, and typing
test/aibs_informatics_core/models/test_data_sync.py 174 0 Model serialization, propagation, and regression tests
test/aibs_informatics_core/utils/test_file_operations.py 32 0 find_paths integration tests
test/aibs_informatics_core/utils/test_filters.py 156 0 Shared filtering helper unit tests

Estimated source-code logic change

Manual classification puts the actual new executable production logic at approximately 55–60 lines:

  • About 44 lines implement the shared filtering behavior.
  • About 12–15 lines add model fields, compiled-pattern properties, and request propagation.
  • One line delegates the existing find_paths implementation to the shared helper.
  • The remaining production additions are primarily docstrings, comments, blank lines, imports, exports, type declarations, and function signatures.

The deletions primarily remove the old inline filtering implementation, replacing it with the shared helper.

Bottom line: this is a well-tested, heavily documented change with roughly 55–60 lines of new runtime behavior, despite the headline +654 / -23 LOC.

@schristinelin schristinelin left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

lgtm no concerns from me

Generated AWS resource names sometimes have to fit a downstream length limit,
and plain truncation risks collisions. condense_str keeps as much readable
prefix as fits and appends a hash of the FULL original value, so two values
sharing a long prefix still condense differently.

Two properties callers depend on:
  * a value that already fits is returned unchanged, so adopting this helper
    renames nothing that was previously in budget
  * the result is deterministic, so names do not churn between runs

Raises rather than silently truncating when the budget cannot fit the hash
suffix plus a prefix character; a bare-hash fallback would quietly invite the
collisions this exists to prevent.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Copilot AI review requested due to automatic review settings August 12, 2026 22:12

Copilot AI 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.

Pull request overview

Copilot reviewed 8 out of 8 changed files in this pull request and generated no new comments.

Suppressed comments (3)

test/aibs_informatics_core/utils/test_filters.py:36

  • The compile_patterns passthrough test compares lists of compiled re.Pattern objects directly. Pattern objects don't have stable value-based equality, so this assertion can fail even when the patterns are correct. Compare identity for the passthrough element and compare .pattern strings for compiled results instead.
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.*")]

src/aibs_informatics_core/models/data_sync.py:113

  • DataSyncTask.filter_root is documented as "Defaults to the source path when unset", but the field default is None and there’s no validator or property here that applies that default. Either implement that defaulting behavior or adjust the docstring so it doesn’t promise a behavior the model doesn’t provide.
            re-lists from its own root, so patterns written against ``run1/``
            would silently stop matching. Sub-requests therefore carry the
            original root here. Defaults to the source path when unset.
    """

src/aibs_informatics_core/utils/file_operations.py:375

  • The find_paths docstring says it returns "absolute paths" under root, but find_all_paths() returns whatever os.walk() yields. If root is relative, the returned paths will also be relative. Update the docstring to avoid claiming the paths are absolute.
    Returns:
        list of paths matching criteria (as absolute paths under ``root``)

Review feedback on PR #54.

DataSyncFilterConfig.include_patterns/exclude_patterns were cached_property on a
mutable pydantic model, so reassigning include/exclude left the compiled patterns
stale -- the config would serialize one set of patterns while filtering by
another. Reproduced both by direct assignment and via model_copy(update=...).

Converted to plain properties rather than freezing the model. Freezing blocks
assignment but does NOT close the model_copy path, because pydantic copies the
instance __dict__ with the populated cache along with the fields; it also
synthesizes a __hash__ that raises on the list-valued fields. Recompiling is
cheap since re.compile keeps its own module-level cache. Two tests pin this, and
both fail if cached_property is restored.

Docstrings:
  * DataSyncTask.filter_root claimed it "Defaults to the source path when unset",
    but the model applies no fallback -- the consumer does. Reworded to say None
    means "not set", and to record why resolving it here would be wrong: it would
    materialize source_path into the serialized task, which to_dict() currently
    omits while the field is None.
  * find_paths said it returns "absolute paths under root". It returns paths
    prefixed with root as given, so a relative root yields relative paths
    (verified). That line was added by this PR. While there, corrected the
    includes/excludes parameter types, documented as Sequence[str] but actually
    Sequence[Pattern | str] -- pre-existing drift in the same docstring.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Copilot AI review requested due to automatic review settings August 14, 2026 02:14

Copilot AI 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.

Pull request overview

Copilot reviewed 8 out of 8 changed files in this pull request and generated no new comments.

Suppressed comments (2)

src/aibs_informatics_core/models/data_sync.py:98

  • PR description states include_patterns / exclude_patterns are @cached_property, but the implementation here is plain @property (which is consistent with the in-code comment about avoiding staleness on mutation). Please update the PR description (or any associated docs) so it matches the actual behavior, to avoid downstream consumers assuming caching semantics.
    # 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)

src/aibs_informatics_core/utils/tools/strtools.py:29

  • This PR introduces the new public helper condense_str (exported via __all__) and adds tests for it, but the PR description’s change list does not mention it. If this is intentional cross-PR plumbing (e.g., for downstream AWS name length limits), please call it out explicitly in the PR description; otherwise consider deferring it to the PR where it’s used to keep scope focused.
__all__ = [
    "camelcase",
    "condense_str",
    "is_prefixed",
    "is_suffixed",
    "lowercase",
    "pascalcase",
    "removeprefix",
    "removesuffix",
    "snakecase",
    "spinalcase",
    "uppercase",
]

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:

Review feedback (schristinelin on #55): the "do these filters filter anything"
check is written in more than one place, and differently -- `bool(x) or bool(y)`
in one, `not x and not y` in another. Logically equivalent today, which is how
drift starts.

from_patterns() is now the one definition, returning None when nothing is
actually filtered so that empty reads as absent. That distinction is
load-bearing: sanitize_serialized_params branches on filter presence and feeds
an execution hash, so an empty-but-present config must not read as filtered.

Also adds a parity test that fails if DataSyncFilterConfig gains a field.
ResolvableBase and ResolvableJobParam mirror include/exclude as their own flat
fields rather than nesting this model -- deliberately, to keep the demand
execution models independent of the data sync schema -- so a new field here
would be silently absent there and a value-comparing test would stay green.
The test's docstring carries the migration note, including that a bare field
swap to a nested config would silently drop filters from flat payloads, since
PydanticBaseModel sets extra="ignore".

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Copilot AI review requested due to automatic review settings August 14, 2026 03:38

Copilot AI 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.

Pull request overview

Copilot reviewed 8 out of 8 changed files in this pull request and generated no new comments.

Suppressed comments (1)

src/aibs_informatics_core/utils/filters.py:94

  • get_relative_path only treats path as equal to root when the strings match exactly. If path includes a trailing slash (common for S3 “directory marker” keys or caller-provided roots) and root does not (or vice versa), the function will return an empty relative path via the prefix-strip branch instead of the intended basename. That makes fullmatch-based filters behave unexpectedly for that edge case.
    str_root = str(root).rstrip("/")
    if not str_root:
        return str_path.lstrip("/")
    if str_path == str_root:
        return basename(str_path)

@rpmcginty
rpmcginty merged commit 770ed14 into main Aug 14, 2026
9 checks passed
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.

4 participants