Skip to content

Replace the HuBMAP C2M2 dataloader with one built on the files search API — Closes #127 - #128

Draft
conradbzura wants to merge 37 commits into
masterfrom
127-hubmap-files-api-dataloader
Draft

conradbzura wants to merge 37 commits into
masterfrom
127-hubmap-files-api-dataloader

Conversation

@conradbzura

@conradbzura conradbzura commented Nov 20, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Replace HuBMAP's C2M2 zip ingest with a loader that builds CFDB documents directly from the portal's file-grain search index, POST https://search.api.hubmapconsortium.org/v3/files/search, following the rest_api precedent ENCODE set. HuBMAP becomes a rest_api DCC: cfdb sync hubmap makes no zip download, no TSV load and no Rust materializer run, and the two HuBMAP enrichment stages, the DOI-URL matching heuristic and the non-public pruning pass are deleted.

Dataset-level context the files index lacks (donor demographics, pipeline, assay metadata, genome assembly) is prefetched once from the dataset index (/v3/portal/search, ~11.8k Dataset and Support entities) into an in-memory map keyed by dataset_uuid, before the cutover lock is taken. Organ codes map to UBERON through a checked-in table rather than a per-sync request. Each file document is therefore emitted fully populated in a single insert pass, through an _ingest_rows generalized from ENCODE's rather than forked.

Scope is set two ways. A configurable filename-suffix allowlist, HUBMAP_FILE_EXTENSIONS, is applied server-side together with a data_access_level: public filter; its default covers the genomics and tabular formats and the image formats, admitting .tif only as .ome.tif so the ~9.7M acquisition tiles stay out. And only files from datasets marked processed are loaded: raw acquisitions stay with the portal. Against the live index on 2026-11-23 that is 62,646 files, 10,655 of them OME-TIFF images (4,670 viewer-ready pyramids). access_url is the file's direct assets URL, so /data streams HuBMAP files straight from assets.hubmapconsortium.org and now maps an upstream refusal to its real status before the response starts.

The load refuses rather than degrades whenever it cannot tell a complete answer from a partial one: an empty or short files walk, an empty or short dataset walk, or a deadline too close to finish the walk all raise and leave the previous slice served. A sync-lock heartbeat at each DCC boundary gives HuBMAP, which runs last, a full hour of lock life rather than whatever 4DN and ENCODE left of it.

Two costs remain, shared with ENCODE's in-lock design and tracked in #129: the file stream holds the global cutover lock while it runs, and a failure after the first committed batch still leaves a partial slice. Only a staged load swapped in under a short lock would remove both.

Closes #127

Proposed changes

HuBMAP files search API loader (services/hubmap.py)

  • fetch_file_metadata(extensions, *, deadline=None) streams the files index with search_after pagination in pages of 1000, filtered server-side to the allowlist and to public files. A compound allowlist entry such as .ome.tif is matched as its last segment plus a case-insensitive rel_path suffix, because the index records only a file's last suffix. The first page asks for an exact total (track_total_hits), and a walk that ends with fewer documents raises.
  • fetch_dataset_metadata_bulk(*, deadline=None) is keyed by dataset uuid (it was doi_url), so it joins against the dataset_uuid every file document carries. It walks both Dataset and Support entities, since HuBMAP files its image pyramids as Support entities with the same fields. It collects donor metadata from both donor and donors[], and is held to the same exact-total check.
  • Every search page goes through _search_page, which retries up to three times with backoff on a transport error, a timeout, a 429/5xx, or a 200 that is partial (failed shards, timed_out, or no hits envelope), since Elasticsearch answers 200 with whatever the healthy shards returned. All fetches share one deadline, HUBMAP_SYNC_TIMEOUT_SECONDS (default 1800).
  • build_donor_lookup merges donors across datasets into one uuid-keyed map.
  • transform_file_to_cfdb(src, *, dataset_metadata, donor_lookup, organ_map=None, stats=None) maps one index document to one CFDB document:
    • file_uuid becomes local_id, with accession_id explicitly null (Populate accession_id for HuBMAP collections #102); rel_path supplies the basename filename, with the full path on extra.hubmap.rel_path.
    • Files from a dataset that is not processed are skipped and counted, and so are files whose dataset is absent from the dataset map, which cannot be confirmed processed.
    • size_in_bytes is stored as an integer, closing the string-typed gap of the C2M2 TSV path, with real md5 and sha256. A missing size or checksum is counted per field. The index's 32-bit ceiling, 2,147,483,647, is stored as null and counted separately, since it is a clamp rather than a size.
    • access_url is https://assets.hubmapconsortium.org/{dataset_uuid}/{rel_path}, percent-encoded.
    • file_format is derived from the inner extension with any compression suffix stripped, trying the last two segments first so .ome.tif maps to OME-TIFF, and compression_format uses ENCODE's absent-when-undetermined derivation.
    • One collection per file, built from its parent dataset, with subjects from the deduplicated donors[] and anatomy from organs[] through the organ table. Unknown organ codes and join misses are counted, never fabricated.
    • is_data_product is parsed from the index's "True"/"False" strings, and left absent when missing or unrecognized.
  • file_extensions_from_env() normalizes case and leading dots and collapses repeats; set-but-empty ingests nothing and warns, matching ENCODE_ANNOTATION_TYPES. The default adds .ome.tif, .tiff, .qptiff, .svs, .ndpi, .scn, .czi, .vsi, .ets, .png and .jpg to the genomics and tabular formats. .bcf is excluded because every .bcf in the index is a CODEX acquisition sidecar, not binary VCF.
  • dcc_registry.py: HuBMAP becomes type: "rest_api" with id_namespace https://hubmapconsortium.org, mirroring ENCODE's portal-URL convention.

Shared ingest helpers (services/ingest_common.py)

  • Move timeout_from_env, the compression-suffix tables and derive_compression_format out of encode.py into a DCC-neutral module both loaders import, so a refactor of one loader cannot silently change the other. ENCODE's tests for them move to tests/test_ingest_common.py.

HuBMAP organ table (services/ontology_mappings.py)

  • Add HUBMAP_ORGAN_TO_UBERON, a 47-code snapshot of the UBKG organs endpoint with UBERON labels from OLS4. A per-sync UBKG fetch would have stripped anatomy from a whole sync whenever it failed, and UBKG's display terms are not UBERON labels.
  • Where UBKG's term is wrong, the table corrects it: the lateral organs UBKG gives only FMA ids map to their side-neutral UBERON parent, MB maps to manubrium of sternum (UBKG gives a teleost term), and PR to prostate gland (UBKG gives the whole male reproductive system).
  • Add EDAM mappings for mtx, salmon sf, and the HDF5 containers h5mu, h5 and snap. Mint cfdb:arrow and cfdb:parquet, since EDAM has neither term.
  • Add the image formats: TIFF (format:3591), OME-TIFF (format:3727) and jpeg. The vendor slide formats (QPTIFF, SVS, NDPI, SCN, CZI, VSI, ETS) have no EDAM term and are minted as cfdb: tokens rather than aliased onto TIFF.

Sync pipeline (services/sync.py, services/locks.py)

  • Add sync_hubmap. It resolves the allowlist, computes the deadline, and prefetches the dataset map outside the cutover lock, refusing an empty map. It then refuses to start the file stream unless the remaining deadline covers the walk. Under the HuBMAP cutover lock it clears the raw C2M2 collections, upserts the DCC record and streams, transforms and inserts in one pass. In finally it ensures the materialized files indexes, since no materializer run creates them for this DCC. It logs per-extension counts, files skipped as unprocessed (info) or unjoinable (warning), capped sizes, donor join misses, unmapped organs and missing integrity fields.
  • Each document is transformed and validated against FileMetadataModel inside one guard, so a malformed or wrongly-typed document is skipped and counted instead of aborting the stream or breaking every API page that holds it.
  • Refactor _ingest_encode_rows into _ingest_rows(..., stale_filter, tally=None, clear_on_empty=True). With clear_on_empty=False, which HuBMAP passes, a stream that drains cleanly with no rows raises instead of clearing the slice.
  • Clamp the deadline to end five minutes before the sync lock would turn stale, and heartbeat the sync lock as each DCC starts (heartbeat_sync_lock, scoped to the holding task). Staleness is judged from the heartbeat, falling back to started_at for older locks.
  • Delete _enrich_hubmap_collections_and_subjects, _prune_non_public_hubmap_raw_records, _enrich_hubmap_files, and the HuBMAP branches of _sync_c2m2_zip.

Direct streaming (api/routers/data.py, api/routers/cache_stream.py)

  • Route every non-drs:// access_url through _stream_direct_url (the renamed ENCODE path), which validates the URL against the outbound allowlist up front.
  • stream_upstream_url now pulls the first upstream chunk before building the response, so a DRS 404, 403, timeout or other upstream error becomes a 404, 403, 504 or 502 rather than a 200 cut off mid-body. This applies to every caller, including the /index sidecar path.

Model, GraphQL and dump

  • Add EnrichedHubmapCollection.dataset_status, exposed and filterable through GraphQL; schema.graphql is regenerated.
  • Add a dataset_status column to collection_extra_hubmap and bump the dump's schema_version from 2 to 3.

Docs

  • Rewrite HUBMAP-SUPPLEMENT.md around the new loader: source endpoints and retries, refusals, entity construction, the processed-only rule, the allowlist and its image formats, the field and organ mapping, the deadline, floor and heartbeat, the costs tracked in Load REST-API DCCs into a staging area and swap under a short cutover lock #129, and the re-sync a rollback past this loader needs.
  • Update the README's minted-format list, BigInt, compression_format, accession_id, materialize-target and dump notes, the /index status table (504; upstream 403/404), and the rollback note; correct ENCODE-SUPPLEMENT.md's consumer count for the format mapping.

Test cases

# Test Suite Given When Then Coverage Target
1 test_hubmap.py HUBMAP_FILE_EXTENSIONS unset The allowlist is resolved The default allowlist is returned, without .bcf or plain .tif, with .ome.tif and the slide formats Default allowlist
2 test_hubmap.py Mixed-case, dotless, repeated or empty entries The allowlist is resolved Entries are normalized and deduplicated, and empty warns Allowlist parsing
3 test_hubmap.py Any list of alphanumeric entries (property) The allowlist is resolved Every entry has the index's dot-prefixed lower-case shape Index-shaped output
4 test_hubmap.py Workflow descriptions naming assembly aliases The assembly is extracted Canonical names are returned Assembly canonicalization
5 test_hubmap.py Filenames with and without compression suffixes, image filenames, and any stem (property) The format is derived The inner extension maps, unchanged by a compression wrapper; .ome.tif maps to OME-TIFF and vendor formats to minted tokens Format derivation
6 test_hubmap.py A complete index document It is transformed Identity, checksums, integer size, status, format and assets URL are set, and the model validates File-level mapping
7 test_hubmap.py A rel_path with spaces, and any path (property) The assets URL is built Segments are percent-encoded and round-trip to the path URL construction
8 test_hubmap.py Dataset and donor metadata, or a processed dataset with no other context It is transformed The collection and subjects carry the joined context, or degrade without it, with donor misses counted In-memory join
9 test_hubmap.py Mapped, unmapped, duplicated and lateral organ codes It is transformed Anatomy carries UBERON ids and labels from the table, and unmapped codes are counted Organ mapping
10 test_hubmap.py A document missing an address field, or with a non-numeric size It is transformed It is skipped and counted, or its size is null Unaddressable and size coercion
11 test_hubmap.py Documents missing a size or md5 They are transformed Each missing field is counted Integrity counters
12 test_hubmap.py Repeated donors, and any donors list (property) It is transformed One subject per distinct non-blank donor in order Donor dedupe
13 test_hubmap.py is_data_product as strings, bools, unknown values or absent It is transformed The flag is the matching bool or is omitted Flag parsing
14 test_hubmap.py Paged search results and an allowlist The files stream is drained Pages follow search_after, filtered to the allowlist and public files, requesting is_data_product Files pagination and filter
15 test_hubmap.py HTTP and network errors, transient failures, partial 200s, a 4xx The files stream is drained Transient pages are retried, persistent failures raise, a 4xx raises at once Retry policy
16 test_hubmap.py A first page reporting more documents than the walk delivers The files or dataset walk runs It raises naming the shortfall Short-walk refusal
17 test_hubmap.py A deadline already passed Either fetch runs It raises a timeout Deadline
18 test_hubmap.py Dataset hits with and without uuids, donors and sort values The dataset index is drained Entries are keyed by uuid with every listed donor, and the walk stops on a sortless page Dataset map
19 test_hubmap.py Datasets naming overlapping donors The donor lookup is built Donors are merged into one uuid-keyed map Donor lookup
20 test_hubmap.py The static HuBMAP configuration The DCC record is built It carries the submission, registry id, labels and namespace DCC record
21 test_sync.py One index document with full context sync_hubmap runs The inserted document is fully populated and the DCC record upserted Single-pass load
22 test_sync.py Existing HuBMAP and ENCODE documents sync_hubmap runs Only the HuBMAP slice is replaced Slice isolation
23 test_sync.py A stream that dies early, yields nothing, or an empty dataset map or allowlist sync_hubmap runs The previous HuBMAP slice is still served Refusals keep the slice
24 test_sync.py A successful load or a failing stream sync_hubmap finishes The materialized files indexes are ensured Index creation
25 test_sync.py A dataset fetch that records the cutover lock state sync_hubmap runs The prefetch ran outside the lock Prefetch placement
26 test_sync.py A malformed document, or one that fails model validation sync_hubmap runs Only the well-formed document is stored Per-document guard
27 test_sync.py A sync lock last alive 40 minutes ago, or heartbeated just now sync_hubmap runs The deadline is clamped to the lock, or is the full budget Deadline clamp
28 test_sync.py A sync lock leaving less than the floor sync_hubmap runs It raises before opening the stream and the slice is untouched Deadline floor
29 test_sync.py A sync whose lock heartbeat is rewound The sync runs The loader sees a refreshed heartbeat DCC-boundary heartbeat
30 test_locks.py Locks with and without heartbeats, active, released or held by another task The lock helpers run Staleness follows the heartbeat, and only the holder's active lock is refreshed Heartbeat semantics
31 test_locks.py A lock whose heartbeat is past the threshold A second sync acquires It takes the lock over with a fresh start and heartbeat Stale takeover
32 test_data.py A public HuBMAP document with an assets URL /data streams it, raw or not The bytes come from the assets URL directly Direct streaming
33 test_data.py An upstream answering 403, 404, 5xx or timing out /data streams it The mapped status is raised before any response Upstream status
34 test_data.py A direct URL outside the allowlist /data streams it It answers 502 up front Outbound allowlist
35 test_index.py A 4DN sidecar whose upstream refuses or times out /index streams it The mapped status is raised before any response Sidecar upstream status
36 test_ingest_common.py Timeout env values and compression suffixes, including property cases The helpers run Values parse or fail loudly, and suffixes map to the verified EDAM terms Shared helpers
37 test_ontology_mappings.py The organ table It is inspected Every entry is UBERON, lateral FMA-only organs map to their parent, MB and PR are corrected Organ table
38 test_dump.py A HuBMAP document built by the transform, carrying dataset_status It is dumped It loads and collection_extra_hubmap.dataset_status holds the value Dump column
39 test_hubmap.py An allowlist with a plain extension and .ome.tif The files stream issues its first request .ome.tif is matched as .tif plus a case-insensitive rel_path suffix Compound suffixes
40 test_hubmap.py The dataset walk It issues its first request It matches entity type Dataset or Support Support entities
41 test_hubmap.py A file from a raw dataset, one with no processing state, or one absent from the map It is transformed It is skipped and counted under its reason Processed-only rule
42 test_hubmap.py A document whose size is 2,147,483,647 It is transformed The size is null and counted as capped, not missing Size ceiling
43 test_sync.py Files from a processed, a raw, and an unknown dataset sync_hubmap runs Only the processed file is stored; the raw skip is logged and the unknown one warned Processed-only load

HuBMAP publishes its processed outputs in formats the EDAM table had no
entry for, so their file_format came out null. BCF, Matrix Market and
salmon quant.sf have EDAM terms; h5mu, h5 and SnapATAC .snap are HDF5
containers. EDAM has no Arrow or Parquet term, so those mint cfdb:
tokens rather than aliasing a columnar binary onto a text or HDF5 term.
The files search index carries each file's parent dataset status
(Published, QA, ...). It is a property of the dataset, so it belongs on
the collection's HuBMAP enrichment alongside pipeline and processing,
filterable through EnrichedHubmapCollectionInput.
The batching, deferred stale-clear, cancellation and finally-flush
semantics in the ENCODE ingest are subtle enough that a second REST API
DCC forking them would be how the two copies drift. The function now
takes the submission whose slice it owns and an optional per-document
tally callback, so the ENCODE-specific compression and annotation-type
distributions move into the ENCODE caller. Progress and log lines name
the submission instead of hard-coding ENCODE.
HuBMAP's quarterly C2M2 zip disagrees with what its portal actually
serves, and most of the datasets worth having are unreachable through
it. The loader now builds documents straight from the portal's
file-grain Elasticsearch index (/v3/files/search), following the
rest_api precedent ENCODE set: no zip download, no TSV load, and no
materializer run.

Dataset-level context the files index lacks -- donor demographics,
pipeline, assay metadata, genome assembly -- is prefetched once from
the dataset index into memory and joined per file, and organ codes map
to UBERON through one UBKG request. Documents therefore land fully
populated in a single insert pass, so the two HuBMAP enrichment stages,
the DOI-URL matching heuristic and the non-public pruning pass are all
deleted. The index holds only public files, which is what retired the
pruning.

Files carry real md5, sha256 and an int64 size_in_bytes, access_url
points at the assets endpoint, and is_data_product is parsed from the
index's "True"/"False" strings. Donors are deduplicated because the
index repeats one donor per contributing tissue block. A configurable
extension allowlist (HUBMAP_FILE_EXTENSIONS) is applied server-side,
since 98% of the 9.9M indexed files are .tif microscopy tiles the API
cannot serve meaningfully.

The id_namespace moves to https://hubmapconsortium.org, mirroring
ENCODE's portal-URL convention. Every sync clears and rebuilds the
HuBMAP slice, so the change costs no continuity.
The collection enrichment gained dataset_status, but the dump's
collection_extra_hubmap table had no column for it, so every dump
dropped it silently. Adding the column changes the schema's shape, so
schema_version moves to 3.
HUBMAP-SUPPLEMENT.md described the C2M2 enrichment stages, the
DOI-URL matching, and the pruning pass, all of which are gone. It now
documents the source endpoints, entity construction, the extension
allowlist, and the per-entity field mapping.

The README and the dump loader no longer say that HuBMAP stores
size_in_bytes as a string or takes compression_format from a C2M2
datapackage. Both now come from the files index, an int64 and a
filename-suffix derivation respectively, as for ENCODE.
Pins the behaviors the live index forced: a donor repeated once per
tissue block becomes one subject (including a property over arbitrary
repetition), and is_data_product parses the index's "True"/"False"
strings while an absent or unrecognized value stays unknown rather
than becoming false. Also covers the fetch paths no test reached: a
client error propagating from both search walks, a sortless page
ending pagination, uuid-less dataset hits being skipped, and a UBKG
error status degrading to an empty organ map.
@conradbzura conradbzura self-assigned this Nov 20, 2026
Every function under test in services/hubmap.py is module-level, and
the Python test guide requires such functions to be tested by
module-level test functions rather than inside Test-prefixed classes
naming no real class. The ENCODE precedent, tests/test_encode.py,
already follows that layout. Pure restructure: no test body changes.
The files-index loader stores HuBMAP access_url as an https assets URL
rather than a drs:// URI, but /data bypassed DRS only for ENCODE by
name, so every HuBMAP file that streams rather than serving a cached
artifact -- passthrough formats, formats with no processor, raw=true,
and everything when the workflow subsystem is off -- was parsed as a
DRS URI and answered 400, while its readiness probe reported ready.

Dispatch on the URL scheme instead, as resolve_download_url already
does for the workers: anything that is not drs:// streams directly,
and only drs:// resolves through a broker. The direct path checks the
DB-sourced URL against the outbound allowlist before the response
starts, so a disallowed URL is a clean 502 rather than a stream that
fails after its headers were sent. The HuBMAP test fixtures move to
the document shape the loader actually writes, which is what hid this.
Probing the live HuBMAP and UBKG APIs showed several upstream fields
do not hold what their names promise, and the fetchers trusted them:

- UBKG's organ_uberon carries FMA ids for the lateral organs (knee,
  mammary gland, tonsil), which landed as anatomy ids where the data
  model promises UBERON. Accept only UBERON ids, falling back to the
  entry's side-neutral category term, and leave a code with neither
  unmapped. Name anatomy by the UBKG term rather than the per-file
  label, which drifts between files for one code.
- The organ map's documented degrade-not-abort contract caught only
  ClientError, while aiohttp raises a bare TimeoutError on an exceeded
  total; a timeout, an undecodable body, or a non-list body now
  degrades to no anatomy terms with a warning.
- Every .bcf in the index is a CODEX raw-acquisition sidecar, not
  binary VCF, so the default allowlist no longer ingests them.
- One transient error among ~54 sequential pages failed the sync after
  the old slice was cleared, and a 200 with failed shards, an upstream
  timeout, or no hits envelope was walked past or read as the end of
  the stream. Each page is now retried with backoff and partial pages
  are refused. The file stream takes an optional deadline so the sync
  can bound its time under the cutover lock.
- The file query now filters on data_access_level public, turning the
  all-public assumption that retired the pruning pass into an
  invariant of the load.

The property test gains its required settings and patches the
environment through mocker instead of writing os.environ directly.
The HuBMAP sync took the global cutover lock before prefetching ~10k
datasets and the UBKG organ map, though neither touches the database,
so every API request for any DCC waited out that network time and
failed at the 60s cutover timeout. The prefetch now runs before the
lock, and the in-lock file stream carries one deadline from
HUBMAP_SYNC_TIMEOUT_SECONDS (default 1800) so the lock cannot outlive
the sync lock's one-hour stale threshold and admit a second, clearing
sync -- the bound ENCODE's metadata budget already applies.

An empty HUBMAP_FILE_EXTENSIONS drained an empty stream, which the
shared ingest treats as an authoritative empty result, deleting the
whole HuBMAP slice. It is now a no-op that leaves the slice in place,
the outcome an empty ENCODE_ANNOTATION_TYPES has for ENCODE.

Index creation moves into a finally, so a stream that fails mid-load
still leaves its partial slice indexed, as ENCODE's does.
The dump's HuBMAP fixture still models the retired C2M2 shape, and
passes only because the loader accepts both. Feeding it the loader's
own output pins the shape the PR introduces: integer sizes, the file
and collection extensions, and the collection-level anatomy and
subject junctions HuBMAP uses in place of biosamples.
The supplement described the default allowlist as a genomics tail when
most of it is imaging-derived tables and NIfTI masks, claimed every
assets URL resolves without authentication, said processed datasets
retain no BAMs, and promised ENCODE parity for an empty allowlist that
the loader did not honor. It now records what the default admits and
why .bcf is excluded, the retry and partial-page handling, the UBKG
UBERON fallback, and the prefetch-outside-the-lock flow.

The README's materialize-dcc example used DCC=hubmap, which now deletes
the HuBMAP corpus since no raw tables remain to rebuild from; it uses
4dn and says which DCCs are never materialized. It also lists the
minted arrow and parquet tokens, and notes that v_file_biosample is
biosample-grained so HuBMAP rows there carry no anatomy or subject.
Comments in matrix.py, the router helpers, and the file model still
described HuBMAP sizes as strings, a pruning pass, and DRS-only access
URLs.
Routing HuBMAP's https access URLs through the direct-stream path
exposed a defect it shares with ENCODE and the 4DN sidecar: the
response was built with status 200/206 before upstream was contacted,
and Starlette sends the status line before iterating the body, so an
upstream 403, 404 or 5xx reached the client as a truncated 200 rather
than the 403/404/502 the /data contract documents.

stream_upstream_url now pulls the first chunk before building the
response, which opens the request, follows redirects and reads the
status, and maps upstream refusal, absence, failure and timeout to
403, 404, 502 and 504. HEAD stays a metadata answer. The HuBMAP /data
tests now mock at the drs boundary rather than the internal streaming
helper, seed the files collection the loader writes, and pin each
upstream status.
The HuBMAP loader imported the timeout parser -- a private name -- and
the compression-suffix tables and derivation from services/encode.py,
so a refactor of ENCODE internals could silently change HuBMAP. They
are DCC-neutral, so they move to services/ingest_common.py, the
timeout parser as the public timeout_from_env, and both loaders import
them from there. Their tests move with them, and timeout_from_env,
newly public, gains direct tests of its default, parse, and refusal
paths.
A snapshot of UBKG's organs endpoint, keyed by the organ code the HuBMAP
files index carries, mapping each code to its UBERON id and its UBERON
label (from OLS4). The lateral knee, mammary gland and tonsil codes,
for which UBKG's organ_uberon holds FMA ids, map to the side-neutral
UBERON parent UBKG names under category. Naming by the UBERON label
rather than UBKG's display term gives an anatomy id the same name in
HuBMAP as in ENCODE and 4DN.
The sync tests drive the module's private per-DCC loaders directly,
against the guide's rule on private references, because the only
public entry point schedules the run as a detached task and returns
before doing any work. The exception was a convention nobody had
written down; the module docstring now records it and why, so a new
loader's tests follow it knowingly.
Several ways a HuBMAP sync could replace a good slice with a worse one
and report success:

- A files walk that drained cleanly with no documents -- what a mapping
  change on the index, or an allowlist matching nothing, returns -- was
  treated as authoritative and deleted the whole submission. The shared
  ingest gains a clear_on_empty switch, HuBMAP turns it off, and an
  empty drain now raises instead. The first page also asks for an exact
  total, and a walk ending short of it raises.
- An empty dataset map loaded every file without its dataset context;
  it is now refused before the cutover lock. Join misses are counted
  and logged, and donors listed only under a pooled dataset's plural
  donors field now join.
- One malformed upstream document aborted the stream after the stale
  clear; it is now skipped and counted.
- The UBKG organ fetch, on any failure, left the whole slice without
  anatomy, and named terms with UBKG display strings. Organs now map
  through the checked-in UBERON table, so there is no fetch to fail and
  ids carry UBERON labels.
- The budget was counted from HuBMAP's own start, but the sync lock's
  staleness counts from the start of the whole run and HuBMAP runs
  last, so a late HuBMAP sync could outlive the lock. The deadline is
  now clamped to what remains of it and covers the dataset prefetch.
- The bcf -> BCF mapping existed only to mislabel HuBMAP's CODEX .bcf
  sidecars if an operator opted them in; it is dropped.

Wide-domain helpers gain the property tests the guide requires: format
derivation ignores any compression wrapper, and every access_url
decodes back to its dataset and rel_path.
The supplement now covers the organ table and why it replaced the UBKG
fetch, the empty-walk, short-walk and empty-dataset-map refusals, the
deadline clamped to the sync lock, join-miss counting, the pooled
donors join, and the read outage and partial-slice window the in-lock
design still carries (tracked in #129). It corrects the retry count,
says how /data reports an asset that fails upstream, and warns that
the assets host throttles and can block a client by IP.

The README's materialize-files row now warns that it deletes every
ENCODE and HuBMAP document, as the adjacent materialize-dcc row does,
and ENCODE-SUPPLEMENT no longer claims ENCODE is the only consumer of
the format table.
The loader's tests reached it through a private name under a recorded
exception to the test guide, and grouped tests of a module-level
function in a class. Making sync_hubmap public removes the need for the
exception for the new loader, and module-level test functions match
the guide's placement rule.
The backoff fixture patched the sleep attribute of the shared asyncio
module, stubbing it for every coroutine running during a test. The
loader's pacing constants are now public, so the fixture zeroes those
instead. Two docstrings still described the removed organ prefetch and
the UBKG mapping; they now name the organ map.
The sync lock's staleness counted from the start of the whole run, so
the DCC that ran last inherited what the earlier ones left of the hour,
and the HuBMAP deadline clamp could leave it no time at all. The sync
now records a heartbeat as each DCC starts, staleness is judged from
it (falling back to the start time for older locks), and the clamp
counts from the heartbeat. The heartbeat is scoped to the task holding
the lock, so a run that was taken over cannot keep its successor alive.
The HuBMAP slice is cleared at the stream's first committed batch, so
a deadline that expires mid-walk left a truncated slice. Before taking
the cutover lock, the sync now checks how much of its deadline remains
and refuses, keeping the existing slice, unless it covers the walk.
The API builds the model for every document on a page, so one stored
document of the wrong shape, such as a donor reporting two races where
one string is expected, failed every page holding it. The transform
guard now validates against FileMetadataModel too, skipping and
counting a document that fails.
Files the index lists without a size, md5 or sha256 were stored with a
null field and nothing recorded the shortfall. The transform now counts
each missing field and the sync logs the counts.
The files walk was held to the exact total its first page reported,
but the dataset walk was not, so a walk that ended early returned a
partial map and documents loaded without their dataset context. The
dataset walk now asks for the same exact total and raises when it
delivers fewer datasets.
UBKG maps the manubrium to UBERON:2001553, a teleost term, and the
prostate to UBERON:0000079, the whole male reproductive system. The
table now holds the human organs, manubrium of sternum and prostate
gland, and a test pins both.
Opening the upstream stream before the response is built applies to
the 4DN sidecar path of /index as well as /data, but only /data had a
test for it.
Correct the claim that the deferred clear survives a clamped deadline,
describe the heartbeat and the floor that replace it, and state the
real bound on how long the file stream can hold the cutover lock. Add
the model validation, missing-field counters and dataset completeness
check, the corrected organ terms, the integer width of size_in_bytes,
the statuses /index can now return, and the re-sync a rollback past
this loader needs.
The files index reports 2147483647 for 263 public files it could not
size in 32 bits; a sampled qptiff carrying it is really 3287888901
bytes. Stored as a size, /data would refuse every Range request past
2 GiB of such a file. The transform now nulls it, counts it apart from
sizes that are missing outright, and the sync logs the count.
A file's dataset_uuid can name a Support entity, which is how HuBMAP
files its image pyramids (1,585 entities, every one processed). The
dataset walk asked for entity_type Dataset only, so those files joined
to nothing and loaded without donors, pipeline or processing state.
Support entities carry the same fields, so the walk now takes both.
TIFF and OME-TIFF have EDAM terms. The vendor whole-slide formats
(QPTIFF, SVS, NDPI, SCN, CZI, VSI, ETS) have none and get minted cfdb:
tokens rather than an alias onto TIFF, since a client choosing a reader
needs the vendor layout. The HuBMAP derivation tries a filename's last
two segments first, so a .ome.tif resolves to OME-TIFF.
The files index records only a file's last suffix, so OME-TIFF images
and 9.7M plain .tif acquisition tiles share file_extension .tif. An
allowlist entry with more than one dot is now matched server-side as
its last segment plus a case-insensitive rel_path suffix, so .ome.tif
can be admitted without the tiles.
cfdb loads file metadata, not bytes, and /data streams an image as-is,
so an image is as useful a record as a table. The default allowlist now
takes .ome.tif, .tiff, the slide-scanner formats, .png and .jpg; plain
.tif stays out.
Raw datasets hold the acquisitions the portal serves; processed ones
hold pipeline outputs and the viewer-ready image pyramids. The files
index carries no processing field, so the transform checks the joined
dataset and skips files from one that is not processed, counted and
logged at info. A file whose dataset is absent from the dataset map
cannot be confirmed processed and is skipped too, under its own warning;
it used to load without dataset context.

Against the live index this keeps 62,646 of 117,438 allowlisted files,
and drops all 2,723 Cell DIVE .nii.gz masks, whose assets URLs 404.
Records the compound-suffix allowlist and its new default, the Support
entity walk, the processed-only rule with its live counts, and the size
ceiling. Corrects the claim that the assets host blocks clients by IP:
the 403s behind it were its refusal of curl's default user agent.

This branch has not been deployed

No deployments
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.

Replace the HuBMAP C2M2 dataloader with one built on the files search API

1 participant