Repository navigation
Pile up alignments on first use when the loader is given BAMs — Closes #28 - #29
Open
conradbzura wants to merge 11 commits into
Open
conradbzura wants to merge 11 commits into
conradbzura wants to merge 11 commits into
Conversation
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
changed the base branch from
23-refuse-unhonoured-loader-inputs
to
main
November 23, 2026 17:50
_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
conradbzura
force-pushed
the
28-managed-pileup
branch
from
November 23, 2026 18:49
77e1322 to
66d40e7
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Training from alignments took two steps: run
pileup_alignmentsonce per channel, keep the track directories it writes, and pass their paths tobuild_training_loader. This PR lets a channel be given as the alignments themselves.build_training_loaderpiles 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.signals=[["s.+.track.parquet", "s.-.track.parquet"]], after apileup_alignmentscall the caller ran and keptsignals=[Alignments(["a.bam", "b.bam"])], piled up intodefault_cache_dir("tracks")on the first call and found there afterwardsAn 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 ofquadrat.loaderandquadrat.cache. It targetsmainso CI runs, the workflow running only on pull requests intomain, 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_dirby kind,hash_referenceandfile_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, asAggregatecannot.pathsis one BAM or SAM path or a list or tuple of them, read throughitem_listand held as a tuple ofstr, and several are pooled into one channel aspileup_alignmentspools 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 strandedAlignmentsinside a larger group is refused withValueErrorbefore anything is piled up, because the mirror would reverse the whole group.resolve_alignmentstakes every specification at once, the signals' and the controls'(tracks, group_sizes)asnormalize_signal_groupsanswers them, and replaces eachAlignmentsby 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_tracksanswerstrack_dir/<key>:alignments_keyhashes the installed package version andMANIFEST_VERSION; each alignment's absolute path andfile_stamp(size and modification time), in order; each BAI'sfile_stamp, or its absence; every field of the aggregate; and the reference throughhash_reference, its path and its.fai.hash_referenceandfile_stampare moved down intoquadrat.cacheand shared withwindow_cache_keyand its track hashing, so each thing is fingerprinted one way. Alignments are keyed by a stat, not by content, for the reasonwindow_cache_keygives for tracks: hashing tens of gigabytes per call would cost much of the pileup the key exists to skip.stage_directorysibling, whichcommit_directoryswaps 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 failrequire_complete, is piled up again.track_dir. On a miss, an exclusiveflockontrack_dir/<key>.lockis 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 honoursflock.default_cache_dirstates 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_loadergainstrack_dir:track_dircache_dirNoneFalsedefault_cache_dir("tracks"), persistedNoneFalseAnything else,
Falseincluded, is refused withTypeError. A namedcache_dirdoes not move the tracks. The loader resolves the default, andmanaged_track_dir_factory(track_dir, scratch_dir)takes only a directory, orNonefor scratch, and yields a factory that makes the scratch directory on first call.default_cache_dirtakes a kind,"windows"(the default, unchanged) or"tracks", each a directory under the one root, and states that nothing reclaims either.make_scratch_diris the scratch creationWindowSignalCache.from_arraysdid inline,QUADRAT_SCRATCH_DIRincluded, so both callers make scratch directories in the same place. A scratch directory is made only if anAlignmentsis 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_windowsrefuses 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, asdefault_cache_dirstates.The index path (
quadrat.alignments)_has_bam_indexbecomesbam_index_path, which answers the BAI's path orNoneso the key can stat it.warn_unindexed_splitreads it as the bool it read before. Both htslib spellings still count and a CSI still does not.Decisions for the owner
window_cache_key's choice for tracks. A rewrite that restores the size and the nanosecond modification time would be missed.window_cache_keydoes withCACHE_VERSION, and costs a pileup per channel per upgrade.flock. POSIX only. CI runs on Linux, andquadrat.loaderalready imports torch. Ranks on several hosts sharing NFS get whatever theirflockgives; the docstring says so.cache_dirdoes not move the tracks.cache_dirnames the window directory itself, so a sibling of it would be a guess about the caller's layout. Tracks followQUADRAT_CACHE_DIRortrack_dir.cache_dir=False, each rank piles up its own copy into its own scratch directory, because nothing is shared. Thetrack_dirdocs point multi-rank jobs at a directory they share.Test cases
TestAlignmentsstrorpathlib.Path; a list ofstr,bytesandPathAlignmentsis builtpathsis a tuple ofstr, in orderTestAlignmentsNone, aset; an empty list or tuple; adictaggregateAlignmentsis builtTypeError,ValueError,TypeErrorTestAlignmentsAlignmentsis builtpathsis the same paths asstr, in orderTestAlignmentsstrand asPath, and under another aggregate; asstrand asbytes(Hypothesis)__eq__and__hash__TestAlignmentsAlignmentsTypeErrornaming ittest_managedalignments_keytest_managedalignments_keytest_managedalignments_keytest_managedalignments_keytest_managedalignments_keyFileNotFoundError;TypeErrortest_managedmanaged_tracksand a directpileup_alignmentstest_managedmanaged_tracksagaintest_managedmanaged_tracksagaintest_managedmanaged_tracksagaintest_managedmanaged_tracksagaintest_managedmanaged_tracksValueError"none of the 2 contigs", nothing but the lock lefttest_managedtest_managedAlignments, and(None, None); then up to three drawn specifications of plain names (Hypothesis)resolve_alignmentswith a directory that must not be calledtest_managedAlignmentsalone, a group of a track and an unstranded one; a second specification of the unstranded oneresolve_alignments[1, 2, 2], tracks in place; the second its one tracktest_managedAlignmentsto pile up in the first specification, and a stranded one grouped with a track, or with another, in the secondresolve_alignmentswith a factory that must not be calledValueError, nothing piled up for eithertest_managedNone; a block never askedmanaged_track_dir_factoryQUADRAT_SCRATCH_DIR, removed on exit; nothing madetest_managedFalse,True, a number, a listmanaged_track_dir_factoryis enteredTypeErrortest_loaderAlignments, as a stranded signal and an unstranded control(2,)test_loaderAlignments, then over another jitter margintest_loadercache_dir=Falseand a namedscratch_dir, withQUADRAT_SCRATCH_DIRand the platform temporary directory each watchedtest_loadercache_dir=Falseand a missingscratch_dirFileNotFoundErrorscratch_dirreaches the pileuptest_loadercache_dirdefault_cache_dir("tracks"), nothing beside the named directorycache_dirdoes not move the trackstest_loaderAlignments,verboseofftest_loadertrack_dirwithcache_dir=Falsetest_loadertrack_dir=FalseandTrueTypeError, nothing under the cache roottest_loaderAlignmentsValueError, nothing under the cache roottest_loaderAlignmentssignal, and a control group of a track and a strandedAlignmentsValueError, nothing under the cache roottest_cachedefault_cache_dir("windows"),("tracks"),("bigwigs")ValueErrornaming both kindstest_cachehash_referencetest_cachefile_stamp5:<mtime_ns>, then6:…;FileNotFoundErrortest_cacheQUADRAT_SCRATCH_DIRsetmake_scratch_dirtest_alignmentsx.bam.baiorx.bai; both; nothing or only a CSIbam_index_pathx.bam.bai;NoneReview
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/.Real defects the review caught:
track_dir=Falsewith a persisted cache wrote a window entry nothing could ever hit.Alignmentsinside a group made the mirror swap the wrong channels, and a bad control group was refused only after the signals were piled up.$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 asbackup/28-pre-restructure).