Skip to content

Pile up alignments on first use when the loader is given BAMs — Closes #28 - #29

Open
conradbzura wants to merge 11 commits into
mainfrom
28-managed-pileup
Open

conradbzura wants to merge 11 commits into
mainfrom
28-managed-pileup

Conversation

@conradbzura

@conradbzura conradbzura commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Training from alignments took two steps: run pileup_alignments once per channel, keep the track directories it writes, and pass their paths to build_training_loader. This PR lets a channel be given as the alignments themselves. build_training_loader piles each one up into a managed entry on first sight, reuses that entry on every later call, and then reads it exactly as it reads a track today.

Before After
signals=[["s.+.track.parquet", "s.-.track.parquet"]], after a pileup_alignments call the caller ran and kept signals=[Alignments(["a.bam", "b.bam"])], piled up into default_cache_dir("tracks") on the first call and found there afterwards
Track directories named, stored and versioned by the caller Entries keyed by what decides their contents, staged and committed atomically, and locked so the ranks of one job pile an entry up once

An entry is keyed by the alignments, their aggregate and the reference, and not by the windows, so changing the window geometry, the exclusions, the filters or the loci regroups the tracks it finds and piles nothing up again. That is what keeps pre-piled tracks cheap to iterate over, and this keeps it.

Stacked on #26. This branch is cut from 23-refuse-unhonoured-loader-inputs, because #26 rewrites much of quadrat.loader and quadrat.cache. It targets main so CI runs, the workflow running only on pull requests into main, so until #26 merges the diff also shows #26's seven commits. This PR's own are the last four: bam_index_path, default_cache_dir by kind, hash_reference and file_stamp, and the managed pileup. Merge #26 first.

Closes #28

Proposed changes

A channel given as alignments (quadrat.managed)

Alignments(paths, aggregate=Aggregate()) is a frozen value that cannot be subclassed, as Aggregate cannot. paths is one BAM or SAM path or a list or tuple of them, read through item_list and held as a tuple of str, and several are pooled into one channel as pileup_alignments pools them. An unstranded aggregate makes one channel. A stranded one makes two, + then -, and is a group of its own, so a mirrored draw swaps the pair as it swaps a stranded pair of tracks. A stranded Alignments inside a larger group is refused with ValueError before anything is piled up, because the mirror would reverse the whole group.

resolve_alignments takes every specification at once, the signals' and the controls' (tracks, group_sizes) as normalize_signal_groups answers them, and replaces each Alignments by its tracks while growing its group, so the nesting rules stay in one place. It checks every group of every specification before it piles anything up, so a refused control group piles up no signal.

The managed entry (quadrat.managed)

managed_tracks answers track_dir/<key>:

  • Key. alignments_key hashes the installed package version and MANIFEST_VERSION; each alignment's absolute path and file_stamp (size and modification time), in order; each BAI's file_stamp, or its absence; every field of the aggregate; and the reference through hash_reference, its path and its .fai. hash_reference and file_stamp are moved down into quadrat.cache and shared with window_cache_key and its track hashing, so each thing is fingerprinted one way. Alignments are keyed by a stat, not by content, for the reason window_cache_key gives for tracks: hashing tens of gigabytes per call would cost much of the pileup the key exists to skip.
  • Atomicity. The pileup writes into a stage_directory sibling, which commit_directory swaps in and records last, the protocol a window entry already uses. An entry is never complete before every track is written. One whose record is gone, or whose tracks fail require_complete, is piled up again.
  • Concurrency. A complete entry is answered without a lock, so reading one needs no write access to track_dir. On a miss, an exclusive flock on track_dir/<key>.lock is taken, the entry is looked for again, and the lock is held until after the commit, so a second caller waits and then finds the entry complete. This serialises processes on one host, and on a filesystem that honours flock.
  • Reclamation. default_cache_dir states that nothing reclaims either kind. It also says that one track entry is kept per alignment specification whatever the window sets, that an upgrade piles every specification up again and leaves the old entries, and that deleting a track entry strands every window entry built from it, because a window entry keys its tracks by their files.

Where entries go (quadrat.managed, quadrat.cache, quadrat.loader)

build_training_loader gains track_dir:

track_dir cache_dir Entries go to
None anything but False default_cache_dir("tracks"), persisted
None False a scratch directory of this process's, removed before the loader returns
a path anything that path, persisted

Anything else, False included, is refused with TypeError. A named cache_dir does not move the tracks. The loader resolves the default, and managed_track_dir_factory(track_dir, scratch_dir) takes only a directory, or None for scratch, and yields a factory that makes the scratch directory on first call.

default_cache_dir takes a kind, "windows" (the default, unchanged) or "tracks", each a directory under the one root, and states that nothing reclaims either. make_scratch_dir is the scratch creation WindowSignalCache.from_arrays did inline, QUADRAT_SCRATCH_DIR included, so both callers make scratch directories in the same place. A scratch directory is made only if an Alignments is to be piled up, and it is removed however the build exits.

The pileup runs after every refusal the loader makes before reading anything, and before the window key is taken, since that key hashes the tracks. The loader's last three value refusals (no peak kept, no negative kept, and what load_windows refuses by value) therefore come after a pileup, and its docstring says so. A window-cache hit therefore needs the managed tracks to exist. They persist by default, so it finds them. If they have been deleted, it piles them up again and misses, because the new files carry new modification times; the old window entry is stranded, as default_cache_dir states.

The index path (quadrat.alignments)

_has_bam_index becomes bam_index_path, which answers the BAI's path or None so the key can stat it. warn_unindexed_split reads it as the bool it read before. Both htslib spellings still count and a CSI still does not.

Decisions for the owner

  • Stat, not content, for alignments. This follows window_cache_key's choice for tracks. A rewrite that restores the size and the nanosecond modification time would be missed.
  • The package version is in the key. An upgrade piles every entry up again. That over-specifies, as window_cache_key does with CACHE_VERSION, and costs a pileup per channel per upgrade.
  • flock. POSIX only. CI runs on Linux, and quadrat.loader already imports torch. Ranks on several hosts sharing NFS get whatever their flock gives; the docstring says so.
  • A named cache_dir does not move the tracks. cache_dir names the window directory itself, so a sibling of it would be a guess about the caller's layout. Tracks follow QUADRAT_CACHE_DIR or track_dir.
  • Scratch is per process. With cache_dir=False, each rank piles up its own copy into its own scratch directory, because nothing is shared. The track_dir docs point multi-rank jobs at a directory they share.
  • Pile up before the window key. Keying the window entry by the alignments rather than by their tracks would let a window hit skip the managed tracks entirely, but it would add a second way to key a channel. This PR keeps one.

Test cases

# Test Suite Given When Then Coverage Target
1 TestAlignments One path as str or pathlib.Path; a list of str, bytes and Path An Alignments is built paths is a tuple of str, in order Path normalisation
2 TestAlignments A number, a list holding None, a set; an empty list or tuple; a dict aggregate An Alignments is built TypeError, ValueError, TypeError Refusals
2a TestAlignments Any list or tuple of paths in any of the three spellings (Hypothesis) An Alignments is built paths is the same paths as str, in order Normalisation property
3 TestAlignments Any paths as str and as Path, and under another aggregate; as str and as bytes (Hypothesis) Compared; hashed Equal, the third differing; equal hashes __eq__ and __hash__
4 TestAlignments A class deriving from Alignments It is defined TypeError naming it No subclass past the validation
5 test_managed One specification keyed twice alignments_key Equal keys Stability
6 test_managed Another aggregate, another alignment, both alignments in either order alignments_key Five distinct keys Key inputs
7 test_managed An alignment rewritten with one more byte; its index removed; its index rewritten; the same alignment at another path with the same stamp; another reference; another package version alignments_key The key changes each time Every input in the key
7a test_managed Any two different aggregates (Hypothesis) alignments_key Different keys Every aggregate field in the key
8 test_managed A missing alignment; a reference that is not a path alignments_key FileNotFoundError; TypeError Key refusals
9 test_managed Both alignments, stranded and unstranded managed_tracks and a direct pileup_alignments Same track count, each complete, equal rows Entry contents
10 test_managed An entry piled up once managed_tracks again Same paths, same directory inode Reuse
10a test_managed An entry piled up, its lock removed, its directory made read-only managed_tracks again Same paths, no lock made Reading needs no write access
11 test_managed An entry stripped of its record managed_tracks again Piled up again, record back, tracks complete Incomplete entry is a miss
11a test_managed An entry whose record stands but one track's record is gone managed_tracks again A fresh commit (new inode), every track complete An incomplete track is a miss
12 test_managed A reference the alignment shares no contig with managed_tracks ValueError "none of the 2 contigs", nothing but the lock left Failed pileup commits nothing
13 test_managed The entry's lock held, two spawned processes asking for it The lock is released Both answer the same paths and the same entry inode; fails with the lock removed One pileup under concurrency
14 test_managed A specification with no Alignments, and (None, None); then up to three drawn specifications of plain names (Hypothesis) resolve_alignments with a directory that must not be called Answered unchanged, in order Identity, no directory without a pileup
15 test_managed A track, a stranded Alignments alone, a group of a track and an unstranded one; a second specification of the unstranded one resolve_alignments Groups [1, 2, 2], tracks in place; the second its one track Expansion
15a test_managed An Alignments to pile up in the first specification, and a stranded one grouped with a track, or with another, in the second resolve_alignments with a factory that must not be called ValueError, nothing piled up for either Every group checked first
16 test_managed A named directory; None; a block never asked managed_track_dir_factory Named kept; scratch under QUADRAT_SCRATCH_DIR, removed on exit; nothing made Directory resolution
17 test_managed False, True, a number, a list managed_track_dir_factory is entered TypeError Refusal
18 test_loader Two alignments piled up directly vs given as Alignments, as a stranded signal and an unstranded control One epoch drawn from both loaders Equal batch for batch, signal grouped (2,) End-to-end equivalence
19 test_loader A loader built from an Alignments, then over another jitter margin The second build One track entry, same inode; two window entries Reuse across window sets
20 test_loader cache_dir=False and a named scratch_dir, with QUADRAT_SCRATCH_DIR and the platform temporary directory each watched Built and drawn The named directory written to and empty again, the other two untouched, nothing under the cache root Nothing persisted, the named scratch used
20a test_loader cache_dir=False and a missing scratch_dir Built FileNotFoundError scratch_dir reaches the pileup
20b test_loader A named cache_dir Built One entry in default_cache_dir("tracks"), nothing beside the named directory A named cache_dir does not move the tracks
20c test_loader An Alignments, verbose off Built cold Nothing printed A quiet pileup
21 test_loader A named track_dir with cache_dir=False Built One committed entry there, default directory absent Named directory honoured
22 test_loader track_dir=False and True Built TypeError, nothing under the cache root Refused before piling up
22a test_loader One group of a track and a stranded Alignments Built ValueError, nothing under the cache root Grouping refusal reaches the loader
22b test_loader A stranded Alignments signal, and a control group of a track and a stranded Alignments Built ValueError, nothing under the cache root A refused control group piles up no signal
23 test_cache A cache root in the environment, and the XDG and home fallbacks for both kinds; an unknown kind default_cache_dir("windows"), ("tracks"), ("bigwigs") Sibling directories; ValueError naming both kinds Kinds
23a test_cache A reference hashed twice, then with other bases of the same layout; then a longer contig hash_reference Indexed; equal digests; then a different one Reference fingerprint
23b test_cache A five-byte file, then six; a missing file file_stamp 5:<mtime_ns>, then 6:…; FileNotFoundError Stat fingerprint
24 test_cache A named root; none, with QUADRAT_SCRATCH_DIR set make_scratch_dir An empty, prefixed directory under the named root, or the variable's Scratch creation
25 test_alignments x.bam.bai or x.bai; both; nothing or only a CSI bam_index_path That path; x.bam.bai; None Index lookup

Review

The sdlc MCP server was down for the whole PR (CONNECTION_CLOSED), so the four rounds were run by hand from .sdlc/guides/, with three reviewers per role, and consolidated in the usual format under .sdlc/reviews/issue-#28/.

Round Roles Found Outcome
1 api, python, perf (9 reviewers) 6 blocking, 5 advisory All blocking fixed. A5 (locus check before the pileup) taken as no change
1.2 api, python, perf (9) reopened B2; 1 blocking, 3 advisory All fixed
2 docs, qa (6) 10 blocking, 12 advisory All fixed
2.2 docs, qa (6) reopened Q2 and A11; 8 blocking, 5 advisory All fixed

Real defects the review caught:

  • track_dir=False with a persisted cache wrote a window entry nothing could ever hit.
  • A stranded Alignments inside a group made the mirror swap the wrong channels, and a bad control group was refused only after the signals were piled up.
  • Taking the lock on hits made a read-only shared directory unreadable.
  • Several tests passed against broken mutants: the concurrency test without the lock, the aggregate property with fields dropped, and the scratch test with tracks leaked to $TMPDIR.

The decisions are ledgered in .sdlc/deferred-findings.md. The history is restructured into the four commits above. Each passes lint and the full suite on its own, and the final tree is byte-identical to the reviewed head (77e1322, kept as backup/28-pre-restructure).

The integer rule, any numbers.Integral but a bool, was written inline
in require_index and again in the Jitter, Exclusion and Aggregate field
checks. It now lives once in quadrat._engine, the lowest layer, so
require_index, those fields, and the sampler and loader arguments that
follow all refuse the same values in the same words.

A plain int is answered before the ABC test, which costs several times
the call on the per-draw epoch path; bool is a subclass and fails it.

as_jitter and validate_signal_groups keep their own checks, whose
messages name what require_integer cannot: the Jitter alternative, and
the whole group specification.
PeakNegativeMixSampler(True, True) built a sampler over one peak and
one negative, set_epoch(True) set epoch 1, RechunkedLoader read True as
a batch of one, and in_window=True built one-base windows, because each
normalised through int() or not at all, which admits a bool and
truncates a float.

Every integer argument of both samplers and their validate_arguments,
RechunkedLoader, auto_fetch_size and build_training_loader, and the
window widths load_windows and LocusDataset take, now goes through
require_integer and raises TypeError naming the argument.
build_training_loader makes these refusals before anything is read; a
float fetch_size is now a TypeError where it was a ValueError. Both
validate_arguments answer the values they normalised, and
auto_fetch_size still takes the prefetch_factor of None a loader
without workers holds.

require_index now always takes the row count; the one caller that used
it as a bare integer check, the dataset's epoch, calls require_integer.
LocusDataset bounded a draw by its two window frames and never by the
cache it reads, so a cache over more windows answered another window's
signal for every draw, and one over fewer failed only at the first read
past its end. WindowSignalCache now answers n_windows from the counts
array_meta recorded, or counts its arrays where it has none, and the
dataset refuses a missing signal cache, and a signal or control cache
whose count is not the frames' rows combined, as it already refuses a
sampler of the wrong size. The caches and widths are read-only
attributes, so nothing checked at construction can be bypassed by
assigning another.

A cache over other windows of the same count still passes; no count
can tell it apart.
load_windows raised FileNotFoundError for a missing reference, while
SequenceStore, and so extract_sequences and extract_loci, raised
pyfaidx's FastaNotFoundError, and chrom_lengths fell through to a scan
that failed in the engine's words. Both types are OSError, but a
caller handling one missed the other.

The refusal now lives in reference.require_reference, which
chrom_lengths and SequenceStore call before opening the file, so every
entry point, the pileups included, raises FileNotFoundError in the same
words. A path running through a file counts as missing; one that
cannot be examined raises OSError, and a reference that exists but
cannot be opened still raises pyfaidx's error. chrom_lengths is where
the published docs state this, and every other reader points there.
A bigWig or any other file given as a track passed require_complete,
track_frame, track_contigs and TrackStore, and failed later in polars'
words, naming no file. The port had dropped upstream's suffix test on
purpose, since a single-file table need carry no suffix. track_signal,
the one verifier of a track, now reads the four bytes every Parquet
file begins with and refuses a file without them with a ValueError
naming the path and saying what a track is; track_frame and
track_contigs consult it for a single file as for a directory. A
directory neither named as a track nor holding any Parquet is refused
in the same words, rather than told to pile up again.

Each entry point's refusal of a missing track is unchanged.
extract_loci(signals=[]) answered zero-channel signal tensors, and its
default target_idx of 0 then named no track without raising. An empty
signals or controls list is now refused with a ValueError saying to
pass None to read none; zero channels mean nothing to either.
Exclusion(Exclusion(...)) was refused with a message saying to list
both, but Exclusion([Exclusion(...), "b.bed"]) passed construction and
failed later when the regions were read. An Exclusion anywhere in a
list or tuple of regions now gets the top-level refusal.
@conradbzura
conradbzura changed the base branch from 23-refuse-unhonoured-loader-inputs to main November 23, 2026 17:50
@conradbzura conradbzura reopened this Nov 23, 2026
_has_bam_index answered a bool, and a key over an alignment needs the
index's path to stat it. bam_index_path answers that path, or None,
with the same two htslib spellings counted and a CSI still not, the
.bam.bai spelling first where both exist. warn_unindexed_split reads
it as the bool it read before.
…ctories in one place

default_cache_dir takes a kind, "windows" or "tracks", each a directory
of its own under the one root QUADRAT_CACHE_DIR or the XDG convention
decides, and states that nothing reclaims either. make_scratch_dir is
the scratch-directory creation WindowSignalCache.from_arrays did
inline, QUADRAT_SCRATCH_DIR included, so a second caller makes its
scratch directory where the first does.
window_cache_key indexed and hashed the reference inline, and
_hash_track stamped each Parquet file inline. hash_reference and
file_stamp hold the two, with the reference's contract and the reasons
for it moving to hash_reference, so a second key folds the same inputs
the same way. The bytes folded in are unchanged, so every existing
window entry keeps its key.
build_training_loader accepts a quadrat.managed.Alignments, one or more
BAM or SAM paths and an Aggregate, wherever it accepts a track, in
signals and in controls. Each is piled up with pileup_alignments into an
entry under track_dir, keyed by alignments_key, or found there from an
earlier call, and is then read as the tracks it piled up into. A
stranded aggregate makes two channels and is a group of its own; one
inside a larger group is refused before anything is piled up, for
signals and controls alike, since a mirror would reverse the whole
group. Alignments cannot be subclassed.

The key holds the package version, MANIFEST_VERSION, each alignment's
absolute path and file_stamp, each index's file_stamp or its absence,
every field of the aggregate, and the reference through hash_reference.
An entry is staged and committed as a window entry is, so it is never
complete before every track is written. A complete entry is answered
without a lock; on a miss an flock on a sibling lock file serialises
callers, so ranks of one job sharing a directory pile it up once. The
entry is keyed by the alignments and not the windows, so changing the
geometry, the exclusions, the filters or the loci regroups the tracks
and piles nothing up again.

track_dir is a directory, or None for default_cache_dir("tracks"), or
for a scratch directory removed before the loader returns where
cache_dir is False. False is refused: scratch tracks under a persisted
window cache would key a window entry nothing could hit again.

The Aggregate test strategy moves to tests/__init__.py, shared by the
aggregate and managed tests.

Closes #28
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.

Pile up alignments on first use when the loader is given BAMs

1 participant