From 88db0293192237c256ae8e8fef7a2acac1e42de8 Mon Sep 17 00:00:00 2001 From: Conrad Date: Fri, 20 Nov 2026 16:13:31 -0500 Subject: [PATCH 01/37] feat: Map BCF, MTX, salmon sf, HDF5 variants, Arrow and Parquet 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. --- src/cfdb/services/ontology_mappings.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/cfdb/services/ontology_mappings.py b/src/cfdb/services/ontology_mappings.py index adebb0c..b02b800 100644 --- a/src/cfdb/services/ontology_mappings.py +++ b/src/cfdb/services/ontology_mappings.py @@ -38,6 +38,7 @@ "bed broadpeak": {"id": "format:3614", "name": "BroadPeak"}, # Variant formats "vcf": {"id": "format:3016", "name": "VCF"}, + "bcf": {"id": "format:3020", "name": "BCF"}, # Annotation formats "gtf": {"id": "format:2306", "name": "GTF"}, "gff": {"id": "format:1975", "name": "GFF"}, @@ -85,6 +86,17 @@ "csfasta": {"id": "format:1929", "name": "FASTA"}, # color-space FASTA (SOLiD) "csqual": {"id": "format:2330", "name": "Plain text"}, # color-space quality scores "h5ad": {"id": "format:3590", "name": "HDF5"}, # AnnData HDF5 format + "h5mu": {"id": "format:3590", "name": "HDF5"}, # MuData HDF5 format + "h5": {"id": "format:3590", "name": "HDF5"}, + "snap": {"id": "format:3590", "name": "HDF5"}, # SnapATAC cell matrix, HDF5-based + "mtx": {"id": "format:3916", "name": "MTX"}, # Matrix Market exchange + "sf": {"id": "format:3475", "name": "TSV"}, # salmon quant.sf, tab-separated + # EDAM has neither an Arrow nor a Parquet term (OLS4 returns nothing for + # either), and aliasing columnar binaries onto a text or HDF5 term would + # misdescribe them to every consumer that trusts the id, so the tokens + # are minted — same reasoning as "bedpe" above. + "arrow": {"id": f"{MINTED_FORMAT_PREFIX}arrow", "name": "Arrow"}, + "parquet": {"id": f"{MINTED_FORMAT_PREFIX}parquet", "name": "Parquet"}, } # ENCODE output_type to EDAM data CV terms From 8c25e2ed610720dd8b496379b86a0f168ba1a8cb Mon Sep 17 00:00:00 2001 From: Conrad Date: Fri, 20 Nov 2026 16:13:31 -0500 Subject: [PATCH 02/37] feat: Add dataset_status to the HuBMAP collection enrichment 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. --- schema.graphql | 2 ++ src/cfdb/api/gql/inputs.py | 1 + src/cfdb/models.py | 1 + 3 files changed, 4 insertions(+) diff --git a/schema.graphql b/schema.graphql index 7497264..13302b8 100644 --- a/schema.graphql +++ b/schema.graphql @@ -351,6 +351,7 @@ input EnrichedHubmapCollectionInput { groupName: [String!] = null analyteClass: [String!] = null visualization: [Boolean!] = null + datasetStatus: [String!] = null } type EnrichedHubmapCollectionType { @@ -360,6 +361,7 @@ type EnrichedHubmapCollectionType { visualization: Boolean vitessceHints: [String!] metadata: JSON + datasetStatus: String } input EnrichedHubmapFileInput { diff --git a/src/cfdb/api/gql/inputs.py b/src/cfdb/api/gql/inputs.py index fb9871a..27ae722 100644 --- a/src/cfdb/api/gql/inputs.py +++ b/src/cfdb/api/gql/inputs.py @@ -150,6 +150,7 @@ class EnrichedHubmapCollectionInput: group_name: list[str] | None = None analyte_class: list[str] | None = None visualization: list[bool] | None = None + dataset_status: list[str] | None = None @strawberry.input diff --git a/src/cfdb/models.py b/src/cfdb/models.py index bb7d09d..56b8465 100644 --- a/src/cfdb/models.py +++ b/src/cfdb/models.py @@ -215,6 +215,7 @@ class EnrichedHubmapCollection(BaseModel): visualization: Optional[bool] = None vitessce_hints: Optional[List[str]] = None metadata: Optional[dict] = None + dataset_status: Optional[str] = None class EnrichedHubmapSubject(BaseModel): From 8bd0b5768f63398b8f9935ae787c2d9d8e0131f0 Mon Sep 17 00:00:00 2001 From: Conrad Date: Fri, 20 Nov 2026 16:13:47 -0500 Subject: [PATCH 03/37] refactor: Generalize the ENCODE row ingest for any REST API DCC 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. --- src/cfdb/services/sync.py | 97 +++++++++++++++++++++++++-------------- tests/test_sync.py | 2 +- 2 files changed, 63 insertions(+), 36 deletions(-) diff --git a/src/cfdb/services/sync.py b/src/cfdb/services/sync.py index 0f506e2..0bbac5c 100644 --- a/src/cfdb/services/sync.py +++ b/src/cfdb/services/sync.py @@ -1057,21 +1057,23 @@ async def _enrich_hubmap_files(dataset_metadata: dict[str, dict]) -> None: ) -async def _ingest_encode_rows( +async def _ingest_rows( task: SyncTask, + submission: str, label: str, rows, transform, - compression_counts: Counter[str | None], - annotation_type_counts: Counter[str], counts_by_phase: dict[str, int], stale_filter: dict, + tally=None, ) -> None: - """Transform and batch-insert one ENCODE metadata stream. + """Transform and batch-insert one upstream metadata stream. - Shared by the experiment and annotation phases so both use the same - batching, the same skip-on-None handling, and contribute to the same - corpus-wide tallies. + Shared by the ENCODE phases and the HuBMAP loader so every REST-API + ingest uses the same batching, the same skip-on-None handling, and the + same deferred stale-clearing -- the detach-before-await, cancellation, + and finally-flush semantics below are subtle enough that forking them + per DCC would be how they diverge. The row count is reported by mutating ``counts_by_phase`` rather than by returning, and a partial batch left buffered by a dead stream is flushed @@ -1081,9 +1083,10 @@ async def _ingest_encode_rows( does. Reporting by return meant a failed phase contributed nothing to the caller's total even though its completed batches were already committed, so the sync under-reported the corpus by up to everything - that phase had loaded, while the tallies below (mutated per row, not per - batch) over-reported it by the discarded partial batch. Three numbers in - one log block that disagreed with each other and with the database. + that phase had loaded, while the caller's tallies (mutated per row, not + per batch) over-reported it by the discarded partial batch. Three + numbers in one log block that disagreed with each other and with the + database. The *clean-path* flush is deliberately not in that ``finally``. A ``finally`` runs whether or not an exception is in flight, so suppressing @@ -1094,15 +1097,24 @@ async def _ingest_encode_rows( Args: task: Sync task whose ``progress`` is updated per batch. - label: Names this stream in progress and log lines. - rows: Async iterable of TSV row dicts. + submission: DCC whose slice of ``files`` this stream loads. Scopes + the stale clear and names the stream in progress and log lines. + label: Names this stream alongside ``submission``, so with several + streams per sync a progress or timeout message identifies which + one it came from. + rows: Async iterable of upstream row/document dicts. transform: Row -> document callable; None means skip the row. - compression_counts: Mutated with each document's compression term. - annotation_type_counts: Mutated with each document's annotation type. counts_by_phase: Mutated with this phase's committed row count, on the failure path as well as the success path. - stale_filter: Selects the slice of ``files`` this phase owns, deleted - once replacement rows are in hand. See ``clear_stale_once``. + stale_filter: Selects the slice of ``files`` this phase owns within + the submission, deleted once replacement rows are in hand. An + empty dict means the whole submission. See ``clear_stale_once``. + tally: Optional callable invoked with each transformed document + before it is buffered, so a caller can maintain corpus-wide + distributions without this function knowing their shape. Like + the row count, it runs per row rather than per batch, so a + mid-flight death leaves it ahead of the database by the + discarded partial batch. """ batch: list[dict] = [] count = 0 @@ -1112,7 +1124,7 @@ async def clear_stale_once() -> None: """Delete the slice this phase owns, once, before its first write. Deferred to the first batch rather than run before the stream opens. - The known ENCODE failures -- a 504 while the portal assembles the + The known upstream failures -- a 504 while a portal assembles the response, an exhausted download budget -- strike before any row arrives, and clearing up front would delete the slice and then have nothing to put back, serving an empty one until the next successful @@ -1125,10 +1137,13 @@ async def clear_stale_once() -> None: return stale_cleared = True deleted = await api.db.files.delete_many( - {"submission": "encode", **stale_filter} + {"submission": submission, **stale_filter} ) logger.info( - "ENCODE %s: cleared %d stale files", label, deleted.deleted_count + "%s %s: cleared %d stale files", + submission.upper(), + label, + deleted.deleted_count, ) async def commit(pending: list[dict]) -> None: @@ -1147,20 +1162,16 @@ async def commit(pending: list[dict]) -> None: # The stream owns an aiohttp session inside its own ``async with``, # released only when the generator is finalized -- left to the # garbage collector that is neither prompt nor guaranteed in a - # long-lived API process, and the annotation fan-out turned one - # stream per sync into N+1. + # long-lived API process, and the ENCODE annotation fan-out turned + # one stream per sync into N+1. async with aclosing(rows): async for row in rows: doc = transform(row) if doc is None: continue - compression_counts[doc.get("compression_format")] += 1 - annotation_type = ( - doc.get("extra", {}).get("encode", {}).get("annotation_type") - ) - if annotation_type: - annotation_type_counts[annotation_type] += 1 + if tally is not None: + tally(doc) batch.append(doc) count += 1 @@ -1175,12 +1186,16 @@ async def commit(pending: list[dict]) -> None: if len(batch) >= BATCH_SIZE: pending, batch = batch, [] await commit(pending) - task.progress = f"Inserted {count} ENCODE {label} files..." + task.progress = ( + f"{submission.upper()} {label}: inserted " + f"{count} files..." + ) logger.info(task.progress) # The stream drained without error, so its result is authoritative - # even when it is empty: clear here too, or a type ENCODE stopped - # publishing would keep serving last sync's rows indefinitely. + # even when it is empty: clear here too, or a type the upstream + # stopped publishing would keep serving last sync's rows + # indefinitely. await clear_stale_once() # The clean-path flush: inside the ``try``, so a sink failure with no @@ -1209,12 +1224,15 @@ async def commit(pending: list[dict]) -> None: except Exception: # Never let the flush replace the exception that caused it. logger.exception( - "ENCODE %s: failed to commit the final %d-row batch", + "%s %s: failed to commit the final %d-row batch", + submission.upper(), label, len(batch), ) counts_by_phase[label] = count - logger.info(f"ENCODE {label} ingest complete: {count} files") + logger.info( + f"{submission.upper()} {label} ingest complete: {count} files" + ) async def _sync_encode(task: SyncTask) -> None: @@ -1344,17 +1362,26 @@ async def _sync_encode(task: SyncTask) -> None: ) ) + def tally(doc: dict) -> None: + """Maintain the ENCODE-specific corpus-wide distributions.""" + compression_counts[doc.get("compression_format")] += 1 + annotation_type = ( + doc.get("extra", {}).get("encode", {}).get("annotation_type") + ) + if annotation_type: + annotation_type_counts[annotation_type] += 1 + for label, open_stream, transform, stale_filter in phases: try: - await _ingest_encode_rows( + await _ingest_rows( task, + "encode", label, open_stream(), transform, - compression_counts, - annotation_type_counts, counts_by_phase, stale_filter, + tally=tally, ) except Exception as exc: # Deliberately broad: the point is that no failure mode of diff --git a/tests/test_sync.py b/tests/test_sync.py index 3f1c4c8..409197d 100644 --- a/tests/test_sync.py +++ b/tests/test_sync.py @@ -1580,7 +1580,7 @@ async def test__sync_encode_should_insert_one_batch_per_batch_size_rows( mocker.patch.object( encode_module, "fetch_encode_metadata", lambda deadline=None: _async_iter(rows) ) - # Spied, not asserted on by argument: _ingest_encode_rows clears the + # Spied, not asserted on by argument: _ingest_rows clears the # same list it hands to insert_many, so a recorded call reads back # empty. spy = mocker.spy(mock_db.files, "insert_many") From ffef63faec150239404ee8942c4c31e9001e133a Mon Sep 17 00:00:00 2001 From: Conrad Date: Fri, 20 Nov 2026 16:14:12 -0500 Subject: [PATCH 04/37] feat: Build HuBMAP documents from the files search API 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. --- src/cfdb/dcc_registry.py | 5 +- src/cfdb/services/hubmap.py | 793 ++++++++++++++++++++++++++----- src/cfdb/services/sync.py | 574 ++++++---------------- tests/test_hubmap.py | 925 ++++++++++++++++++++++++++++++++++++ tests/test_sync.py | 445 +++++++++-------- 5 files changed, 1966 insertions(+), 776 deletions(-) create mode 100644 tests/test_hubmap.py diff --git a/src/cfdb/dcc_registry.py b/src/cfdb/dcc_registry.py index 8e3aa2f..1ec2e07 100644 --- a/src/cfdb/dcc_registry.py +++ b/src/cfdb/dcc_registry.py @@ -12,10 +12,9 @@ "hubmap": { "name": "HuBMAP", "display_name": "Human BioMolecular Atlas Program", - "type": "c2m2_zip", - "s3_base": "https://cfde-drc.s3.amazonaws.com/HuBMAP/C2M2/", - "latest_url": "https://cfde-drc.s3.amazonaws.com/HuBMAP/C2M2/2025-09-15/HuBMAP_C2M2_Fall_2025.zip", + "type": "rest_api", "api_base": "https://search.api.hubmapconsortium.org/v3", + "id_namespace": "https://hubmapconsortium.org", }, "encode": { "name": "ENCODE", diff --git a/src/cfdb/services/hubmap.py b/src/cfdb/services/hubmap.py index e1aa78e..14ab8de 100644 --- a/src/cfdb/services/hubmap.py +++ b/src/cfdb/services/hubmap.py @@ -1,101 +1,204 @@ -"""HuBMAP Search API integration for dataset metadata enrichment. +"""HuBMAP files search API client and CFDB transformation service. -Fetches dataset, donor, and file metadata from the HuBMAP Search API -(Elasticsearch-backed) to enrich C2M2-materialized documents. Three -enrichment targets run during sync: collections and subjects -(pre-materialization) and files (post-materialization). +Builds CFDB file documents directly from HuBMAP's file-grain search index, +following the precedent ENCODE set in :mod:`cfdb.services.encode`. One index +document is one file; every document in the index is public, so no pruning +pass exists. Dataset-level context the files index does not carry — donor +demographics, pipeline, genome assembly — is prefetched once from the +dataset-level index into an in-memory map keyed by ``dataset_uuid`` and +joined during transformation, so documents land fully populated in a single +insert pass with no post-load enrichment. API URLs -------- -Bulk dataset search (search_after pagination): - https://search.api.hubmapconsortium.org/v3/portal/search - -Entity Matching ---------------- -Collection persistent_id matches doi_url -Subject local_id contains donor uuid -File matched via collection doi_url → dataset, then filename +File search (search_after pagination, one document per file): + https://search.api.hubmapconsortium.org/v3/files/search -Field Mapping (HuBMAP Search API → CFDB) ------------------------------------------- +Dataset search (search_after pagination, one document per dataset): + https://search.api.hubmapconsortium.org/v3/portal/search -File (post-materialization) -~~~~~~~~~~~~~~~~~~~~~~~~~~~ -data_access_level → data_access_level -ingest_metadata.workflow_description → genome_assembly (regex-derived) +Organ code -> UBERON (one request per sync): + https://ontology.api.hubmapconsortium.org/organs?application_context=HUBMAP + +Field Mapping (HuBMAP files search API -> CFDB) +----------------------------------------------- + +File +~~~~ +file_uuid -> local_id (HuBMAP issues no file + accessions; accession_id stays null) +rel_path (basename) -> filename +size -> size_in_bytes (stored as int64) +md5_checksum -> md5 +sha256_checksum -> sha256 +filename (compression suffix stripped) -> file_format (EDAM-mapped) +filename -> compression_format (suffix-derived, + shared with the ENCODE derivation) +assets URL (dataset_uuid + rel_path) -> access_url +data_access_level -> data_access_level +dataset_status -> status +dataset workflow_description -> genome_assembly (regex-derived, + joined from the dataset index) Enriched File ~~~~~~~~~~~~~ -files[].rel_path → extra.hubmap.rel_path -files[].is_data_product → extra.hubmap.is_data_product - -Collection (pre-materialization) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -dataset_type → collections[].experiment_type -analyte_class → collections[].analyte_class - -Enriched Collection -~~~~~~~~~~~~~~~~~~~ -pipeline → collections[].extra.hubmap.pipeline -processing → collections[].extra.hubmap.processing -group_name → collections[].extra.hubmap.group_name -visualization → collections[].extra.hubmap.visualization -vitessce-hints → collections[].extra.hubmap.vitessce_hints -metadata → collections[].extra.hubmap.metadata - -Enriched Subject (pre-materialization, from donor.mapped_metadata) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -sex → subjects[].extra.hubmap.sex -race → subjects[].extra.hubmap.race -age_value → subjects[].extra.hubmap.age_value -age_unit → subjects[].extra.hubmap.age_unit -height_value → subjects[].extra.hubmap.height_value -height_unit → subjects[].extra.hubmap.height_unit -weight_value → subjects[].extra.hubmap.weight_value -weight_unit → subjects[].extra.hubmap.weight_unit -body_mass_index_value → subjects[].extra.hubmap.body_mass_index_value -body_mass_index_unit → subjects[].extra.hubmap.body_mass_index_unit -cause_of_death → subjects[].extra.hubmap.cause_of_death -death_event → subjects[].extra.hubmap.death_event -mechanism_of_injury → subjects[].extra.hubmap.mechanism_of_injury -medical_history → subjects[].extra.hubmap.medical_history -social_history → subjects[].extra.hubmap.social_history +rel_path -> extra.hubmap.rel_path +is_data_product ("True"/"False" string) -> extra.hubmap.is_data_product +dataset workflow_description -> extra.hubmap.genome_assembly + +Collection (one per file, from its parent dataset) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +dataset_uuid -> collections[].local_id +dataset_hubmap_id -> collections[].name +portal dataset URL -> collections[].persistent_id +dataset_type -> collections[].experiment_type +analyte_class -> collections[].analyte_class +organs[] (code -> UBERON via UBKG) -> collections[].anatomy + +Enriched Collection (dataset index join) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +pipeline -> collections[].extra.hubmap.pipeline +processing -> collections[].extra.hubmap.processing +group_name -> collections[].extra.hubmap.group_name +visualization -> collections[].extra.hubmap.visualization +vitessce-hints -> collections[].extra.hubmap.vitessce_hints +metadata -> collections[].extra.hubmap.metadata +dataset_status -> collections[].extra.hubmap.dataset_status + +Subject +~~~~~~~ +donors[].uuid -> collections[].subjects[].local_id +(HuBMAP is human-only) -> collections[].subjects[].taxonomy + +Enriched Subject (dataset index join, from donor.mapped_metadata) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +sex -> subjects[].extra.hubmap.sex +race -> subjects[].extra.hubmap.race +age_value -> subjects[].extra.hubmap.age_value +age_unit -> subjects[].extra.hubmap.age_unit +height_value -> subjects[].extra.hubmap.height_value +height_unit -> subjects[].extra.hubmap.height_unit +weight_value -> subjects[].extra.hubmap.weight_value +weight_unit -> subjects[].extra.hubmap.weight_unit +body_mass_index_value -> subjects[].extra.hubmap.body_mass_index_value +body_mass_index_unit -> subjects[].extra.hubmap.body_mass_index_unit +cause_of_death -> subjects[].extra.hubmap.cause_of_death +death_event -> subjects[].extra.hubmap.death_event +mechanism_of_injury -> subjects[].extra.hubmap.mechanism_of_injury +medical_history -> subjects[].extra.hubmap.medical_history +social_history -> subjects[].extra.hubmap.social_history + +DCC +~~~ +Static / config-derived: dcc.id, dcc.dcc_name, + dcc.dcc_abbreviation, + dcc.dcc_description, + dcc.contact_email, dcc.contact_name, + dcc.dcc_url, dcc.project_id_namespace, + dcc.project_local_id """ import asyncio import logging +import os import re -from typing import Optional +from collections import Counter +from typing import AsyncGenerator, Optional +from urllib.parse import quote import aiohttp from cfdb.dcc_registry import get_dcc_config +from cfdb.services.encode import ( + COMPRESSION_SUFFIX_TO_EDAM, + UNMAPPABLE_COMPRESSION_SUFFIXES, + derive_compression_format, +) +from cfdb.services.ontology_mappings import get_file_format, get_taxonomy logger = logging.getLogger(__name__) # Rate limit: max 10 requests/second → 100ms between requests _REQUEST_INTERVAL = 0.1 -# Fields to request from the HuBMAP Search API for enrichment -_BULK_SOURCE_FIELDS = [ - "doi_url", - "dataset_type", - "pipeline", - "processing", - "group_name", - "analyte_class", - "visualization", - "vitessce-hints", - "metadata", - "data_access_level", - "files", - "donor.mapped_metadata", - "donor.uuid", - "ingest_metadata.workflow_description", -] +ASSETS_BASE_URL = "https://assets.hubmapconsortium.org" +PORTAL_DATASET_URL = "https://portal.hubmapconsortium.org/browse/dataset/{uuid}" +UBKG_ORGANS_URL = ( + "https://ontology.api.hubmapconsortium.org/organs?application_context=HUBMAP" +) + +#: Environment variable overriding which file extensions are ingested, and +#: the allowlist applied when it is unset. An allowlist rather than a filter +#: retrofitted later: the files index holds 9.9M documents and 98% of them +#: are ``.tif`` microscopy tiles the API cannot serve meaningfully, so +#: ingesting the extension space wholesale would grow the corpus ~11x with +#: dead weight. The default is the genomics + tabular tail of the live +#: distribution, ~53k files. +_FILE_EXTENSIONS_ENV = "HUBMAP_FILE_EXTENSIONS" +_FILE_EXTENSIONS_DEFAULT: tuple[str, ...] = ( + ".h5ad", + ".h5mu", + ".h5", + ".hdf5", + ".bcf", + ".gz", + ".mtx", + ".arrow", + ".parquet", + ".bed", + ".narrowpeak", + ".bam", + ".sf", + ".snap", + ".csv", + ".tsv", +) + + +def file_extensions_from_env() -> tuple[str, ...]: + """Resolve the file-extension allowlist to ingest. + + Reads a comma-separated ``HUBMAP_FILE_EXTENSIONS``, stripping each entry, + lower-casing it, prefixing a missing leading dot, and dropping blanks — + so ``h5ad, .BCF`` and ``.h5ad,.bcf`` configure the same thing, and what + is sent to the search API matches the index's dot-prefixed + ``file_extension`` values exactly. An unset variable yields the default + allowlist; a variable set to an empty (or all-blank) value yields an + empty tuple, which ingests nothing — the same explicit-empty semantics + as ``ENCODE_ANNOTATION_TYPES``, and warned about for the same reason: + empty values arrive by accident routinely, and a silently empty corpus + shows up only as an absence. + + Repeats are collapsed, first occurrence winning, so a duplicated token + cannot widen the server-side ``terms`` filter or reorder the logged + allowlist. + """ + raw = os.getenv(_FILE_EXTENSIONS_ENV) + if raw is None: + return _FILE_EXTENSIONS_DEFAULT + + entries = (entry.strip().lower() for entry in raw.split(",")) + normalized = ( + entry if entry.startswith(".") else f".{entry}" + for entry in entries + if entry + ) + allowlist = tuple(dict.fromkeys(normalized)) + + if not allowlist: + logger.warning( + "%s is set but empty: no HuBMAP files will be ingested. Unset " + "it entirely to restore the default allowlist (%s).", + _FILE_EXTENSIONS_ENV, + ", ".join(_FILE_EXTENSIONS_DEFAULT), + ) + return allowlist -_GENOME_ASSEMBLY_RE = re.compile(r"\b(GRCh38|hg38|GRCh37|hg19|GRCm39|mm10)\b", re.IGNORECASE) + +_GENOME_ASSEMBLY_RE = re.compile( + r"\b(GRCh38|hg38|GRCh37|hg19|GRCm39|mm10)\b", re.IGNORECASE +) # Normalize variant names to canonical assembly identifiers _ASSEMBLY_ALIASES = { @@ -117,19 +220,81 @@ def extract_genome_assembly(workflow_description: str) -> Optional[str]: return None +# Compression suffixes stripped before mapping a filename's extension to a +# file format: the named EDAM-expressible wrappers plus the ones no EDAM term +# covers. Longest first so ``.gzip`` is never half-stripped as ``.gz``'s +# shorter cousin. ``.zip`` is excluded deliberately — a ZIP holds many +# members with many formats, so the name under it describes an archive +# member, not the file. +_STRIPPABLE_COMPRESSION_SUFFIXES: tuple[str, ...] = tuple( + sorted( + ( + suffix + for suffix in ( + *COMPRESSION_SUFFIX_TO_EDAM, + *UNMAPPABLE_COMPRESSION_SUFFIXES, + ) + if suffix != ".zip" + ), + key=len, + reverse=True, + ) +) + + +def derive_file_format(filename: str) -> Optional[dict]: + """Map a filename to an EDAM file-format term. + + The files index's ``file_extension`` names the outermost suffix, which + for a ``.fastq.gz`` is the compression wrapper rather than the format — + so the derivation strips one known compression suffix from the filename + first, then maps whatever extension remains through the shared + EDAM table. ``None`` when no extension remains or none maps. + """ + base = filename.lower().rsplit("/", 1)[-1] + for suffix in _STRIPPABLE_COMPRESSION_SUFFIXES: + if base.endswith(suffix): + base = base[: -len(suffix)] + break + if "." not in base: + return None + return get_file_format(base.rsplit(".", 1)[-1]) + + +# Fields to request from the dataset-level index. Only what the files index +# cannot supply: per-dataset processing context, donor demographics, and the +# free-text workflow description the genome assembly is extracted from. +_DATASET_SOURCE_FIELDS = [ + "uuid", + "pipeline", + "processing", + "group_name", + "visualization", + "vitessce-hints", + "metadata", + "donor.mapped_metadata", + "donor.uuid", + "ingest_metadata.workflow_description", +] + + async def fetch_dataset_metadata_bulk() -> dict[str, dict]: """ - Fetch all published HuBMAP dataset metadata from the Search API. + Fetch all HuBMAP dataset metadata from the dataset-level search index. - Uses Elasticsearch ``search_after`` pagination to iterate all published - datasets in batches of 1000. Returns a dict keyed by ``doi_url`` so - callers can match to C2M2 collection ``persistent_id``. + Uses Elasticsearch ``search_after`` pagination to iterate all datasets in + batches of 1000. Returns a dict keyed by dataset ``uuid`` so the file + transformation can join on the ``dataset_uuid`` every files-index + document carries. + + An HTTP or network error raises rather than returning the partial map: + the loader clears the HuBMAP slice before reloading, so a silently + partial dataset map would mean silently under-enriched documents. Returns: - {doi_url: {dataset_type, pipeline, processing, group_name, - analyte_class, visualization, vitessce_hints, metadata, - data_access_level, files, donor_metadata, - genome_assembly}} + {dataset_uuid: {pipeline, processing, group_name, visualization, + vitessce_hints, metadata, donor_uuid, donor_metadata, + genome_assembly}} """ config = get_dcc_config("hubmap") api_base = config["api_base"] @@ -142,16 +307,9 @@ async def fetch_dataset_metadata_bulk() -> dict[str, dict]: async with aiohttp.ClientSession() as session: while True: query: dict = { - "query": { - "bool": { - "must": [ - {"term": {"entity_type.keyword": "Dataset"}}, - {"exists": {"field": "doi_url"}}, - ] - } - }, + "query": {"term": {"entity_type.keyword": "Dataset"}}, "size": page_size, - "_source": _BULK_SOURCE_FIELDS, + "_source": _DATASET_SOURCE_FIELDS, "sort": [{"_id": "asc"}], } @@ -166,16 +324,16 @@ async def fetch_dataset_metadata_bulk() -> dict[str, dict]: timeout=aiohttp.ClientTimeout(total=60), ) as response: if response.status != 200: - logger.error( - f"HuBMAP Search API error: HTTP {response.status}" + raise RuntimeError( + f"HuBMAP dataset search API error: " + f"HTTP {response.status}" ) - break data = await response.json() except aiohttp.ClientError as e: - logger.error(f"HuBMAP Search API network error: {e}") - break + logger.error(f"HuBMAP dataset search API network error: {e}") + raise await asyncio.sleep(_REQUEST_INTERVAL) @@ -185,22 +343,13 @@ async def fetch_dataset_metadata_bulk() -> dict[str, dict]: for hit in hits: src = hit.get("_source", {}) - doi_url = src.get("doi_url") - if not doi_url: + uuid = src.get("uuid") + if not uuid: continue entry: dict = {} - # Dataset-level fields - for key in ( - "dataset_type", - "pipeline", - "processing", - "group_name", - "analyte_class", - "visualization", - "data_access_level", - ): + for key in ("pipeline", "processing", "group_name", "visualization"): val = src.get(key) if val is not None: entry[key] = val @@ -214,11 +363,6 @@ async def fetch_dataset_metadata_bulk() -> dict[str, dict]: if metadata: entry["metadata"] = metadata - # File listings - files = src.get("files") - if files: - entry["files"] = files - # Donor demographics donor = src.get("donor") or {} donor_metadata = donor.get("mapped_metadata") @@ -236,8 +380,7 @@ async def fetch_dataset_metadata_bulk() -> dict[str, dict]: if assembly: entry["genome_assembly"] = assembly - if entry: - results[doi_url] = entry + results[uuid] = entry # Prepare next page search_after = hits[-1].get("sort") @@ -246,8 +389,428 @@ async def fetch_dataset_metadata_bulk() -> dict[str, dict]: if len(results) % 5000 < page_size: logger.info( - f"HuBMAP bulk fetch: {len(results)} datasets fetched so far" + f"HuBMAP dataset fetch: {len(results)} datasets fetched so far" ) - logger.info(f"HuBMAP bulk fetch: {len(results)} total datasets fetched") + logger.info(f"HuBMAP dataset fetch: {len(results)} total datasets fetched") return results + + +# Fields to request from the files index — the whole per-file surface the +# transformation maps. +_FILE_SOURCE_FIELDS = [ + "file_uuid", + "rel_path", + "file_extension", + "size", + "md5_checksum", + "sha256_checksum", + "data_access_level", + "is_data_product", + "dataset_uuid", + "dataset_hubmap_id", + "dataset_type", + "dataset_status", + "analyte_class", + "donors", + "organs", +] + + +async def fetch_file_metadata( + extensions: tuple[str, ...], +) -> AsyncGenerator[dict, None]: + """ + Stream file documents from the HuBMAP files search index. + + Uses ``search_after`` pagination on ``file_uuid.keyword`` in batches of + 1000. When ``extensions`` is non-empty, the allowlist is applied + server-side as a ``terms`` filter on ``file_extension.keyword``, so the + excluded 9.7M microscopy tiles never cross the wire. An empty allowlist + yields nothing — the explicit-empty configuration documented on + :func:`file_extensions_from_env`. + + Errors raise rather than ending the stream early, for the same reason + :func:`fetch_dataset_metadata_bulk` raises: a partial stream behind a + clear-before-reload would silently shrink the corpus. + + Yields: + The ``_source`` dict of each matching file document. + """ + if not extensions: + return + + config = get_dcc_config("hubmap") + api_base = config["api_base"] + search_url = f"{api_base}/files/search" + + page_size = 1000 + search_after: Optional[list] = None + total = 0 + + async with aiohttp.ClientSession() as session: + while True: + query: dict = { + "query": {"terms": {"file_extension.keyword": list(extensions)}}, + "size": page_size, + "_source": _FILE_SOURCE_FIELDS, + "sort": [{"file_uuid.keyword": "asc"}], + } + + if search_after is not None: + query["search_after"] = search_after + + try: + async with session.post( + search_url, + json=query, + headers={"Content-Type": "application/json"}, + timeout=aiohttp.ClientTimeout(total=60), + ) as response: + if response.status != 200: + raise RuntimeError( + f"HuBMAP files search API error: " + f"HTTP {response.status}" + ) + + data = await response.json() + + except aiohttp.ClientError as e: + logger.error(f"HuBMAP files search API network error: {e}") + raise + + await asyncio.sleep(_REQUEST_INTERVAL) + + hits = data.get("hits", {}).get("hits", []) + if not hits: + break + + for hit in hits: + yield hit.get("_source", {}) + total += 1 + + if total % 10000 < page_size: + logger.info(f"HuBMAP file fetch: {total} files fetched so far") + + # Prepare next page + search_after = hits[-1].get("sort") + if not search_after: + break + + logger.info(f"HuBMAP file fetch: {total} total files fetched") + + +async def fetch_organ_map() -> dict[str, dict]: + """ + Fetch the HuBMAP organ-code → UBERON mapping from the UBKG ontology API. + + One small request per sync. Returns ``{rui_code: {"id": uberon_id, + "name": term}}`` for every organ carrying both a code and a UBERON id. + Failure degrades rather than aborts — anatomy is enrichment, not + identity, so a UBKG outage costs the anatomy terms of one sync, not the + corpus — and returns an empty map with a warning. + """ + try: + async with aiohttp.ClientSession() as session: + async with session.get( + UBKG_ORGANS_URL, + timeout=aiohttp.ClientTimeout(total=60), + ) as response: + if response.status != 200: + logger.warning( + f"UBKG organs API error: HTTP {response.status}; " + "HuBMAP collections will carry no anatomy terms " + "this sync" + ) + return {} + organs = await response.json() + except aiohttp.ClientError as e: + logger.warning( + f"UBKG organs API network error: {e}; HuBMAP collections will " + "carry no anatomy terms this sync" + ) + return {} + + organ_map: dict[str, dict] = {} + for organ in organs: + code = organ.get("rui_code") + uberon = organ.get("organ_uberon") + if code and uberon: + organ_map[code] = {"id": uberon, "name": organ.get("term") or code} + + logger.info(f"UBKG organs: {len(organ_map)} organ codes mapped to UBERON") + return organ_map + + +# Scalar demographics HuBMAP returns as single-element lists; unwrapped to +# the scalar on the way in. +_DONOR_SCALAR_FIELDS = ( + "age_value", + "age_unit", + "sex", + "race", + "body_mass_index_value", + "body_mass_index_unit", + "cause_of_death", + "death_event", + "mechanism_of_injury", + "height_value", + "height_unit", + "weight_value", + "weight_unit", +) + +# Genuinely multi-valued demographics, kept as lists. +_DONOR_LIST_FIELDS = ("medical_history", "social_history") + + +def _donor_extra(donor_metadata: dict) -> dict: + """Shape one donor's ``mapped_metadata`` into ``subjects[].extra.hubmap``.""" + extra: dict = {} + for key in _DONOR_SCALAR_FIELDS: + val = donor_metadata.get(key) + if val is None: + continue + if isinstance(val, list) and len(val) == 1: + val = val[0] + extra[key] = val + + for key in _DONOR_LIST_FIELDS: + val = donor_metadata.get(key) + if isinstance(val, list) and val: + extra[key] = val + + return extra + + +def _parse_flag(value: object) -> Optional[bool]: + """Parse one of the files index's stringly-typed booleans. + + The index serializes ``is_data_product`` as the strings ``"True"`` and + ``"False"``, so a plain truthiness test would read ``"False"`` as true. + Anything that is neither spelling yields ``None`` -- an unrecognized + value is unknown, and reporting it as ``False`` would fabricate a fact. + """ + if isinstance(value, bool): + return value + if isinstance(value, str): + return {"true": True, "false": False}.get(value.strip().lower()) + return None + + +def _dcc_fields() -> dict: + """The static HuBMAP DCC fields, shared by the inline file-document copy + and the ``dcc`` collection record.""" + config = get_dcc_config("hubmap") + id_namespace = config["id_namespace"] + + return { + "id": "cfde_registry_dcc:hubmap", + "dcc_name": "HuBMAP", + "dcc_abbreviation": "HuBMAP", + "dcc_description": ( + "The Human BioMolecular Atlas Program (HuBMAP) is an NIH Common " + "Fund initiative developing an open, global atlas of the human " + "body at the cellular level." + ), + "contact_email": "help@hubmapconsortium.org", + "contact_name": "HuBMAP Help Desk", + "dcc_url": "https://hubmapconsortium.org", + "project_id_namespace": id_namespace, + "project_local_id": "HuBMAP", + } + + +def build_hubmap_dcc_record() -> dict: + """ + Build DCC collection record for HuBMAP. + + Returns: + DCC document for insertion into dcc collection + """ + return {"submission": "hubmap", **_dcc_fields()} + + +def transform_file_to_cfdb( + src: dict, + *, + dataset_metadata: dict[str, dict], + donor_lookup: dict[str, dict], + organ_map: dict[str, dict], + stats: Counter | None = None, +) -> Optional[dict]: + """ + Transform one files-index document into a CFDB file document. + + Args: + src: The ``_source`` dict of a files-index document, as yielded by + :func:`fetch_file_metadata`. + dataset_metadata: Dataset-level context keyed by dataset uuid, from + :func:`fetch_dataset_metadata_bulk`. A missing dataset degrades + the document (no demographics, pipeline, or assembly) rather + than dropping it. + donor_lookup: Donor demographics keyed by donor uuid, built from + ``dataset_metadata`` by the caller. + organ_map: Organ-code → UBERON mapping from :func:`fetch_organ_map`. + An unmapped code skips that anatomy term rather than fabricating + an id. + stats: Optional counter the transform reports into — per-extension + document tallies, skip reasons, and unmapped organ codes — so + the sync can log one distribution instead of a line per file. + + Returns: + CFDB-compatible dict for insertion into the files collection, or + None for a document missing the fields that make it addressable + (``file_uuid``, ``rel_path``, ``dataset_uuid``). + """ + config = get_dcc_config("hubmap") + id_namespace = config["id_namespace"] + + file_uuid = src.get("file_uuid") + rel_path = src.get("rel_path") + dataset_uuid = src.get("dataset_uuid") + if not file_uuid or not rel_path or not dataset_uuid: + if stats is not None: + stats["skipped:incomplete"] += 1 + logger.warning( + "Skipping HuBMAP file document missing file_uuid, rel_path, or " + f"dataset_uuid (file_uuid={file_uuid!r})" + ) + return None + + filename = rel_path.rsplit("/", 1)[-1] + + try: + size_in_bytes = int(src["size"]) + except (KeyError, TypeError, ValueError): + size_in_bytes = None + + dataset_meta = dataset_metadata.get(dataset_uuid) or {} + + doc: dict = { + "submission": "hubmap", + "id_namespace": id_namespace, + "local_id": file_uuid, + # HuBMAP issues no file accessions (#102); explicit so the field is + # queryably null rather than merely absent. + "accession_id": None, + "filename": filename, + "size_in_bytes": size_in_bytes, + "md5": src.get("md5_checksum") or None, + "sha256": src.get("sha256_checksum") or None, + "access_url": ( + f"{ASSETS_BASE_URL}/{dataset_uuid}/{quote(rel_path, safe='/')}" + ), + "status": src.get("dataset_status"), + "data_access_level": src.get("data_access_level"), + } + + file_format = derive_file_format(filename) + if file_format: + doc["file_format"] = file_format + + # Same absent-when-undetermined contract as the ENCODE derivation; see + # derive_compression_format. + compression_format = derive_compression_format(filename) + if compression_format is not None: + doc["compression_format"] = compression_format + + extra_hubmap: dict = {"rel_path": rel_path} + + is_data_product = _parse_flag(src.get("is_data_product")) + if is_data_product is not None: + extra_hubmap["is_data_product"] = is_data_product + + genome_assembly = dataset_meta.get("genome_assembly") + if genome_assembly: + doc["genome_assembly"] = genome_assembly + extra_hubmap["genome_assembly"] = genome_assembly + + doc["extra"] = {"hubmap": extra_hubmap} + + # --- Subjects, from the file's donors joined to dataset demographics --- + taxonomy = get_taxonomy("Homo sapiens") + subjects = [] + # The index repeats a donor once per contributing tissue block -- one + # live file lists the same uuid 26 times -- so dedupe, as for organs. + seen_donors: set[str] = set() + for donor in src.get("donors") or []: + donor_uuid = (donor or {}).get("uuid") + if not donor_uuid or donor_uuid in seen_donors: + continue + seen_donors.add(donor_uuid) + subject: dict = { + "id_namespace": id_namespace, + "local_id": donor_uuid, + "project_id_namespace": id_namespace, + "project_local_id": "HuBMAP", + } + if taxonomy: + subject["taxonomy"] = taxonomy + donor_metadata = donor_lookup.get(donor_uuid) + if donor_metadata: + donor_extra = _donor_extra(donor_metadata) + if donor_extra: + subject["extra"] = {"hubmap": donor_extra} + subjects.append(subject) + + # --- Anatomy, from the file's organs through the UBKG mapping --- + anatomy = [] + seen_codes: set[str] = set() + for organ in src.get("organs") or []: + code = (organ or {}).get("code") + if not code or code in seen_codes: + continue + seen_codes.add(code) + term = organ_map.get(code) + if not term: + if stats is not None: + stats[f"unmapped_organ:{code}"] += 1 + continue + anatomy.append({"id": term["id"], "name": organ.get("label") or term["name"]}) + + # --- Collection, one per file: its parent dataset --- + collection: dict = { + "id_namespace": id_namespace, + "local_id": dataset_uuid, + "name": src.get("dataset_hubmap_id") or dataset_uuid, + "persistent_id": PORTAL_DATASET_URL.format(uuid=dataset_uuid), + "biosamples": [], + "subjects": subjects, + } + if anatomy: + collection["anatomy"] = anatomy + + dataset_type = src.get("dataset_type") + if dataset_type: + collection["experiment_type"] = dataset_type + analyte_class = src.get("analyte_class") + if analyte_class: + collection["analyte_class"] = analyte_class + + collection_extra: dict = {} + for key in ( + "pipeline", + "processing", + "group_name", + "visualization", + "vitessce_hints", + "metadata", + ): + val = dataset_meta.get(key) + if val is not None: + collection_extra[key] = val + dataset_status = src.get("dataset_status") + if dataset_status: + collection_extra["dataset_status"] = dataset_status + if collection_extra: + collection["extra"] = {"hubmap": collection_extra} + + doc["collections"] = [collection] + + doc["dcc"] = _dcc_fields() + + if stats is not None: + stats[f"extension:{src.get('file_extension')}"] += 1 + + return doc diff --git a/src/cfdb/services/sync.py b/src/cfdb/services/sync.py index 0bbac5c..d538ccc 100644 --- a/src/cfdb/services/sync.py +++ b/src/cfdb/services/sync.py @@ -153,6 +153,8 @@ async def _sync_dccs(task: SyncTask) -> None: # Branch on DCC type if dcc_type == "rest_api" and dcc == "encode": await _sync_encode(task) + elif dcc_type == "rest_api" and dcc == "hubmap": + await _sync_hubmap(task) else: await _sync_c2m2_zip(task, data_path, downloads_path) except Exception as exc: @@ -289,16 +291,6 @@ async def _sync_c2m2_zip( logger.info(task.progress) await _stamp_4dn_file_accessions() await _enrich_4dn_collections() - elif dcc == "hubmap": - task.current_step = "enriching_collections" - task.progress = "Enriching HuBMAP collections and subjects from Search API..." - logger.info(task.progress) - dataset_metadata = await _enrich_hubmap_collections_and_subjects() - - task.current_step = "pruning" - task.progress = "Pruning non-public HuBMAP files..." - logger.info(task.progress) - await _prune_non_public_hubmap_raw_records(dataset_metadata) # Step 7: Materialize files collection for this DCC task.current_step = "materializing" @@ -313,11 +305,6 @@ async def _sync_c2m2_zip( task.progress = "Enriching 4DN files from portal API..." logger.info(task.progress) await _enrich_4dn_api_metadata() - elif dcc == "hubmap": - task.current_step = "enriching" - task.progress = "Enriching HuBMAP files from Search API..." - logger.info(task.progress) - await _enrich_hubmap_files(dataset_metadata) async def _set_accession_ids(collection, stamps: list, label: str) -> int: @@ -640,423 +627,6 @@ async def _enrich_4dn_collections() -> None: ) -async def _enrich_hubmap_collections_and_subjects() -> dict[str, dict]: - """Enrich HuBMAP collections and subjects with metadata from the Search API. - - Performs a single bulk fetch of all HuBMAP datasets, then: - 1. Stores dataset-level metadata on collection.extra.hubmap - 2. Stores donor demographics on subject.extra.hubmap - """ - from pymongo import UpdateOne - - from cfdb.services.hubmap import fetch_dataset_metadata_bulk - - if api.db is None: - raise RuntimeError("Database not initialized") - - # Single bulk fetch for all datasets - dataset_metadata = await fetch_dataset_metadata_bulk() - logger.info(f"HuBMAP enrichment: {len(dataset_metadata)} dataset entries fetched") - - # --- Collection enrichment --- - collection_ops = [] - cursor = api.db.collection.find( - {"submission": "hubmap"}, - {"_id": 1, "persistent_id": 1}, - ) - async for doc in cursor: - persistent_id = doc.get("persistent_id", "") - meta = dataset_metadata.get(persistent_id) - if not meta: - continue - - update_set: dict = {} - - # Promoted to Collection top-level - dataset_type = meta.get("dataset_type") - if dataset_type is not None: - update_set["experiment_type"] = dataset_type - analyte_class = meta.get("analyte_class") - if analyte_class is not None: - update_set["analyte_class"] = analyte_class - - # HuBMAP-specific fields stay nested on extra.hubmap - hubmap_extra: dict = {} - for key in ( - "pipeline", - "processing", - "group_name", - "visualization", - "vitessce_hints", - "metadata", - ): - val = meta.get(key) - if val is not None: - hubmap_extra[key] = val - - if hubmap_extra: - update_set["extra.hubmap"] = hubmap_extra - - if update_set: - collection_ops.append( - UpdateOne({"_id": doc["_id"]}, {"$set": update_set}) - ) - - if collection_ops: - total_modified = 0 - for i in range(0, len(collection_ops), BATCH_SIZE): - batch = collection_ops[i : i + BATCH_SIZE] - result = await api.db.collection.bulk_write(batch, ordered=False) - total_modified += result.modified_count - logger.info(f"HuBMAP collection enrichment: updated {total_modified} collections") - else: - logger.warning("HuBMAP collection enrichment: no updates to apply") - - # --- Subject enrichment --- - # Build donor_uuid -> donor_metadata lookup from the bulk fetch - donor_lookup: dict[str, dict] = {} - for meta in dataset_metadata.values(): - donor_uuid = meta.get("donor_uuid") - donor_metadata = meta.get("donor_metadata") - if donor_uuid and donor_metadata: - donor_lookup[donor_uuid] = donor_metadata - - if not donor_lookup: - logger.info("HuBMAP subject enrichment: no donor metadata available") - return dataset_metadata - - # Match subjects by local_id containing the donor UUID (HuBMAP C2M2 uses - # donor UUID as part of the subject local_id) - subject_ops = [] - cursor = api.db.subject.find( - {"submission": "hubmap"}, - {"_id": 1, "local_id": 1}, - ) - async for doc in cursor: - local_id = doc.get("local_id", "") - # Try to match donor UUID in the subject local_id - matched_donor = None - for donor_uuid, donor_meta in donor_lookup.items(): - if donor_uuid in local_id: - matched_donor = donor_meta - break - - if not matched_donor: - continue - - extra: dict = {} - for key in ( - "age_value", - "age_unit", - "body_mass_index_value", - "body_mass_index_unit", - "cause_of_death", - "death_event", - "mechanism_of_injury", - "height_value", - "height_unit", - "weight_value", - "weight_unit", - ): - val = matched_donor.get(key) - if val is not None: - # HuBMAP returns single-element lists for some fields - if isinstance(val, list) and len(val) == 1: - val = val[0] - extra[key] = val - - # String list fields - for key in ("sex", "race"): - val = matched_donor.get(key) - if val is not None: - if isinstance(val, list) and len(val) == 1: - val = val[0] - extra[key] = val - - for key in ("medical_history", "social_history"): - val = matched_donor.get(key) - if isinstance(val, list) and val: - extra[key] = val - - if extra: - subject_ops.append( - UpdateOne({"_id": doc["_id"]}, {"$set": {"extra.hubmap": extra}}) - ) - - if subject_ops: - total_modified = 0 - for i in range(0, len(subject_ops), BATCH_SIZE): - batch = subject_ops[i : i + BATCH_SIZE] - result = await api.db.subject.bulk_write(batch, ordered=False) - total_modified += result.modified_count - logger.info(f"HuBMAP subject enrichment: updated {total_modified} subjects") - else: - logger.warning("HuBMAP subject enrichment: no updates to apply") - - return dataset_metadata - - -async def _prune_non_public_hubmap_raw_records( - dataset_metadata: dict[str, dict], -) -> None: - """Remove non-public HuBMAP records from raw C2M2 tables before materialization. - - Deletes ``file_in_collection`` links and orphaned ``file`` rows for any - dataset whose ``data_access_level`` is not ``"public"``. Datasets with a - missing access level are treated as non-public (conservative default). - """ - if api.db is None: - raise RuntimeError("Database not initialized") - - # 1. Identify non-public DOIs - non_public_dois = [ - doi - for doi, meta in dataset_metadata.items() - if meta.get("data_access_level") != "public" - ] - - if not non_public_dois: - logger.info("HuBMAP pruning: all datasets are public, nothing to prune") - return - - logger.info( - f"HuBMAP pruning: {len(non_public_dois)} non-public datasets identified" - ) - - # 2. Find matching raw collection records - collection_keys: list[dict] = [] - cursor = api.db.collection.find( - { - "submission": "hubmap", - "persistent_id": {"$in": non_public_dois}, - }, - {"id_namespace": 1, "local_id": 1}, - ) - async for doc in cursor: - collection_keys.append( - { - "id_namespace": doc["id_namespace"], - "local_id": doc["local_id"], - } - ) - - if not collection_keys: - logger.info("HuBMAP pruning: no raw collection records match non-public DOIs") - return - - # 3. Collect potentially-orphaned file keys from file_in_collection - or_filter = [ - { - "collection_id_namespace": ck["id_namespace"], - "collection_local_id": ck["local_id"], - } - for ck in collection_keys - ] - - candidate_file_keys: set[tuple[str, str]] = set() - cursor = api.db.file_in_collection.find( - {"$or": or_filter}, - {"file_id_namespace": 1, "file_local_id": 1}, - ) - async for doc in cursor: - candidate_file_keys.add( - (doc["file_id_namespace"], doc["file_local_id"]) - ) - - # 4. Delete non-public file_in_collection links - fic_result = await api.db.file_in_collection.delete_many({"$or": or_filter}) - logger.info( - f"HuBMAP pruning: deleted {fic_result.deleted_count} file_in_collection links" - ) - - # 4b. Delete files matched to a non-public dataset via the persistent_id - # (DOI) fallback join. HuBMAP's C2M2 export never populates - # file_in_collection (confirmed empty on every sync), so the - # materializer falls back to matching file.persistent_id against - # collection.persistent_id (see materialize/src/main.rs, "Fallback: - # look up collection by persistent_id"). Step 4 above is blind to that - # join, so without this a file whose own persistent_id names a - # non-public dataset survives pruning and gets the blanket - # data_access_level=public stamp below regardless of its true access - # level -- confirmed to leak files registered under dbGaP - # controlled-access studies. - doi_result = await api.db.file.delete_many( - {"submission": "hubmap", "persistent_id": {"$in": non_public_dois}} - ) - logger.info( - f"HuBMAP pruning: deleted {doi_result.deleted_count} file records via " - "persistent_id (DOI) fallback match" - ) - - # 5. Find which candidate files still have links (shared with a public collection) - if candidate_file_keys: - still_linked: set[tuple[str, str]] = set() - file_or_filter = [ - {"file_id_namespace": ns, "file_local_id": lid} - for ns, lid in candidate_file_keys - ] - cursor = api.db.file_in_collection.find( - {"$or": file_or_filter}, - {"file_id_namespace": 1, "file_local_id": 1}, - ) - async for doc in cursor: - still_linked.add( - (doc["file_id_namespace"], doc["file_local_id"]) - ) - - orphaned = candidate_file_keys - still_linked - - # 6. Delete truly orphaned files - if orphaned: - orphan_filter = [ - {"id_namespace": ns, "local_id": lid} - for ns, lid in orphaned - ] - file_result = await api.db.file.delete_many({"$or": orphan_filter}) - logger.info( - f"HuBMAP pruning: deleted {file_result.deleted_count} orphaned file records" - ) - else: - logger.info("HuBMAP pruning: no orphaned file records to delete") - else: - logger.info("HuBMAP pruning: no file_in_collection links found for non-public collections") - - -async def _enrich_hubmap_files(dataset_metadata: dict[str, dict]) -> None: - """Enrich materialized HuBMAP files with metadata from the Search API. - - Stores ``genome_assembly``, ``is_data_product``, and ``rel_path`` on - ``extra``, then stamps all HuBMAP files as ``data_access_level = "public"`` - (non-public records were already pruned before materialization). - """ - from pymongo import UpdateOne - - if api.db is None: - raise RuntimeError("Database not initialized") - - # Build DOI -> file-level lookup - doi_file_info: dict[str, dict] = {} - for doi_url, meta in dataset_metadata.items(): - info: dict = {} - - genome_assembly = meta.get("genome_assembly") - if genome_assembly: - info["genome_assembly"] = genome_assembly - - # Build filename -> file metadata lookup from files array - files_list = meta.get("files", []) - file_lookup: dict[str, dict] = {} - for f in files_list: - rel_path = f.get("rel_path") - if rel_path: - entry = {"rel_path": rel_path} - is_data_product = f.get("is_data_product") - if is_data_product is not None: - entry["is_data_product"] = is_data_product - # Use the basename as key for matching with C2M2 filename - basename = rel_path.rsplit("/", 1)[-1] if "/" in rel_path else rel_path - file_lookup[basename] = entry - if file_lookup: - info["file_lookup"] = file_lookup - - if info: - doi_file_info[doi_url] = info - - if not doi_file_info: - logger.warning("HuBMAP file enrichment: no dataset metadata available") - # Still stamp all HuBMAP files as public - await api.db.files.update_many( - {"submission": "hubmap"}, - {"$set": {"data_access_level": "public"}}, - ) - return - - # Get DOI URLs for all HuBMAP collections (to map files to datasets) - collection_doi_map: dict[str, str] = {} # (id_namespace, local_id) key -> doi_url - cursor = api.db.collection.find( - {"submission": "hubmap"}, - {"_id": 1, "id_namespace": 1, "local_id": 1, "persistent_id": 1}, - ) - async for doc in cursor: - persistent_id = doc.get("persistent_id", "") - if persistent_id in doi_file_info: - key = f"{doc.get('id_namespace', '')}|{doc.get('local_id', '')}" - collection_doi_map[key] = persistent_id - - logger.info( - f"HuBMAP file enrichment: {len(collection_doi_map)} collections matched to datasets" - ) - - # Iterate materialized files and build updates - operations = [] - cursor = api.db.files.find( - {"submission": "hubmap"}, - {"_id": 1, "filename": 1, "collections": 1}, - ) - async for doc in cursor: - # Find matching dataset via collection DOI - collections = doc.get("collections", []) - matched_info = None - for coll in collections: - if isinstance(coll, dict): - key = f"{coll.get('id_namespace', '')}|{coll.get('local_id', '')}" - else: - continue - doi_url = collection_doi_map.get(key) - if doi_url: - matched_info = doi_file_info.get(doi_url) - if matched_info: - break - - if not matched_info: - continue - - update: dict = {} - - # Promoted field - genome_assembly = matched_info.get("genome_assembly") - if genome_assembly: - update["genome_assembly"] = genome_assembly - - # Try to match by filename to get per-file metadata - filename = doc.get("filename", "") - file_lookup = matched_info.get("file_lookup", {}) - if filename and filename in file_lookup: - file_meta = file_lookup[filename] - rel_path = file_meta.get("rel_path") - if rel_path: - update["extra.hubmap.rel_path"] = rel_path - is_data_product = file_meta.get("is_data_product") - if is_data_product is not None: - update["extra.hubmap.is_data_product"] = is_data_product - - if update: - operations.append(UpdateOne({"_id": doc["_id"]}, {"$set": update})) - - if not operations: - logger.warning("HuBMAP file enrichment: no updates to apply") - # Still stamp all HuBMAP files as public - await api.db.files.update_many( - {"submission": "hubmap"}, - {"$set": {"data_access_level": "public"}}, - ) - return - - total_modified = 0 - for i in range(0, len(operations), BATCH_SIZE): - batch = operations[i : i + BATCH_SIZE] - result = await api.db.files.bulk_write(batch, ordered=False) - total_modified += result.modified_count - - logger.info(f"HuBMAP file enrichment: updated {total_modified} files") - - # All surviving HuBMAP files are public (non-public pruned before materialization) - await api.db.files.update_many( - {"submission": "hubmap"}, - {"$set": {"data_access_level": "public"}}, - ) - - async def _ingest_rows( task: SyncTask, submission: str, @@ -1444,6 +1014,146 @@ def tally(doc: dict) -> None: ) from failures[0][1] +async def _sync_hubmap(task: SyncTask) -> None: + """ + Sync HuBMAP data from the files search API. + + Like ENCODE, HuBMAP documents are pre-materialized directly into the + files collection -- no C2M2 zip download, no TSV load, and no Rust + materializer run. Dataset-level context (donor demographics, pipeline, + genome assembly) and the organ-to-UBERON map are prefetched before the + file stream opens, so every document is emitted fully populated in one + insert pass and no post-load enrichment or pruning stages exist. The + index itself holds only public files, which is what retired the pruning + pass. + + A single stream loads the whole submission, so there is no per-phase + isolation: any failure propagates and is recorded as this DCC's failure + by ``_sync_dccs``, while ``_ingest_rows``'s deferred clear ensures a + fetch that dies before delivering rows leaves the previous corpus being + served rather than empty. + """ + from cfdb.services.hubmap import ( + build_hubmap_dcc_record, + fetch_dataset_metadata_bulk, + fetch_file_metadata, + fetch_organ_map, + file_extensions_from_env, + transform_file_to_cfdb, + ) + + if api.db is None: + raise RuntimeError("Database not initialized") + + counts_by_phase: dict[str, int] = {} + # One counter for everything the transform wants observed -- the + # per-extension document distribution, skip reasons, and unmapped organ + # codes -- logged as distributions below rather than a line per file. + stats: Counter[str] = Counter() + + async with locks.CutoverLock("hubmap"): + # Step 1: Clear existing raw HuBMAP data. ``files`` is deliberately + # not cleared here: ``_ingest_rows`` clears that slice once + # replacement rows are in hand, so a fetch that fails before + # delivering any leaves the previous corpus being served rather + # than empty. The raw C2M2 collections (file, collection, subject, + # ...) are cleared outright -- nothing reloads them anymore. + task.current_step = "clearing" + task.progress = "Clearing existing HuBMAP data..." + logger.info(task.progress) + await _clear_dcc_data_async("hubmap", skip_collections={"files"}) + + # Step 2: Upsert DCC record + task.current_step = "dcc_record" + task.progress = "Creating HuBMAP DCC record..." + logger.info(task.progress) + await api.db.dcc.update_one( + {"submission": "hubmap"}, + {"$set": build_hubmap_dcc_record()}, + upsert=True, + ) + + # Step 3: Prefetch the dataset-level context the files index does + # not carry, plus the organ-to-UBERON map. ~10k datasets held in + # memory -- small against the file stream they enrich, and what + # makes the single-pass join possible. + task.current_step = "fetching" + task.progress = "Fetching HuBMAP dataset metadata..." + logger.info(task.progress) + + dataset_metadata = await fetch_dataset_metadata_bulk() + donor_lookup = { + meta["donor_uuid"]: meta["donor_metadata"] + for meta in dataset_metadata.values() + if meta.get("donor_uuid") and meta.get("donor_metadata") + } + organ_map = await fetch_organ_map() + + extensions = file_extensions_from_env() + logger.info( + "HuBMAP file ingest: extension allowlist %s", list(extensions) + ) + + # Step 4: Stream, transform, and insert in one pass. + task.current_step = "loading" + task.progress = "Loading HuBMAP files from the files search API..." + logger.info(task.progress) + + def transform(src: dict) -> Optional[dict]: + return transform_file_to_cfdb( + src, + dataset_metadata=dataset_metadata, + donor_lookup=donor_lookup, + organ_map=organ_map, + stats=stats, + ) + + await _ingest_rows( + task, + "hubmap", + "files index", + fetch_file_metadata(extensions), + transform, + counts_by_phase, + # One stream owns the whole submission, so its slice is the + # whole submission. + stale_filter={}, + ) + + # HuBMAP writes straight into the materialized collection and never runs + # the materializer, which is the only other creator of files indexes -- + # same reasoning as the ENCODE path above. + await ensure_indexes(api.db, materialized_files_index_specs()) + + count = counts_by_phase.get("files index", 0) + task.progress = f"HuBMAP sync complete: {count} files" + logger.info(task.progress) + logger.info( + "HuBMAP extension distribution: %s", + { + key.removeprefix("extension:"): n + for key, n in stats.most_common() + if key.startswith("extension:") + }, + ) + skipped = stats.get("skipped:incomplete", 0) + if skipped: + logger.warning( + f"HuBMAP ingest: skipped {skipped} documents missing file_uuid, " + "rel_path, or dataset_uuid" + ) + unmapped = { + key.removeprefix("unmapped_organ:"): n + for key, n in stats.items() + if key.startswith("unmapped_organ:") + } + if unmapped: + logger.warning( + f"HuBMAP ingest: organ codes with no UBERON mapping {unmapped}; " + "those anatomy terms were omitted" + ) + + async def _materialize_files(submission: str) -> None: """Run the Rust materializer for a specific DCC submission.""" materialize_bin = shutil.which(MATERIALIZE_BIN) diff --git a/tests/test_hubmap.py b/tests/test_hubmap.py new file mode 100644 index 0000000..d75fa17 --- /dev/null +++ b/tests/test_hubmap.py @@ -0,0 +1,925 @@ +"""Tests for the HuBMAP files search API fetches and transform.""" + +from __future__ import annotations + +import aiohttp +import pytest +from hypothesis import given +from hypothesis import strategies as st + +from cfdb.models import FileMetadataModel +from cfdb.services import hubmap as hubmap_module +from cfdb.services.hubmap import ( + build_hubmap_dcc_record, + derive_file_format, + extract_genome_assembly, + fetch_dataset_metadata_bulk, + fetch_file_metadata, + fetch_organ_map, + file_extensions_from_env, + transform_file_to_cfdb, +) + +#: The variable bounding which file extensions are ingested. Named here +#: rather than imported so the tests pin the operator-facing contract: +#: renaming it in the module should fail these tests, not silently follow +#: along. +EXTENSIONS_ENV = "HUBMAP_FILE_EXTENSIONS" + + +def _file_doc(**overrides) -> dict: + """Return a minimal but realistic files-index ``_source`` document.""" + doc = { + "file_uuid": "abc123", + "rel_path": "processed/secondary_analysis.h5ad", + "file_extension": ".h5ad", + "size": 5529765, + "md5_checksum": "0b05f823fd4b3cc86204366c6f71eae9", + "sha256_checksum": ( + "f51518c924f3bab02847b19594afced3bc908c9d8be7f58fe36941a5c966ce72" + ), + "data_access_level": "public", + "dataset_uuid": "ds-uuid-1", + "dataset_hubmap_id": "HBM339.XXWC.842", + "dataset_type": "RNAseq", + "dataset_status": "Published", + "analyte_class": "RNA", + "donors": [{"entity_type": "Donor", "uuid": "donor-1"}], + "organs": [{"code": "TH", "label": "Thymus", "uuid": "org-1"}], + } + doc.update(overrides) + return doc + + +def _transform(src: dict, **overrides) -> dict | None: + """Run the transform with empty join inputs unless a test supplies them.""" + kwargs = { + "dataset_metadata": {}, + "donor_lookup": {}, + "organ_map": {}, + } + kwargs.update(overrides) + return transform_file_to_cfdb(src, **kwargs) + + +class _FakeJsonResponse: + """Async-context-manager stand-in for a JSON aiohttp response.""" + + def __init__(self, status: int, payload): + self.status = status + self._payload = payload + + async def __aenter__(self): + return self + + async def __aexit__(self, *exc): + return False + + async def json(self): + return self._payload + + +class _SearchSession: + """Fake aiohttp session serving one Elasticsearch page per ``post``. + + Records every request body so pagination (``search_after``) and the + server-side extension filter are both observable. Once the configured + pages run out, an empty page is served, which is how the real index + ends a ``search_after`` walk. + """ + + def __init__(self, pages=None, status=200, error=None): + self._pages = list(pages or []) + self._status = status + self._error = error + self.post_bodies: list[dict] = [] + self.post_urls: list[str] = [] + + async def __aenter__(self): + return self + + async def __aexit__(self, *exc): + return False + + def post(self, url, json=None, **kwargs): + self.post_urls.append(url) + self.post_bodies.append(json) + if self._error is not None: + raise self._error + if self._pages: + payload = self._pages.pop(0) + else: + payload = {"hits": {"hits": []}} + return _FakeJsonResponse(self._status, payload) + + +class _OrganSession: + """Fake aiohttp session for the single UBKG organs ``get``.""" + + def __init__(self, payload=None, status=200, error=None): + self._payload = payload or [] + self._status = status + self._error = error + + async def __aenter__(self): + return self + + async def __aexit__(self, *exc): + return False + + def get(self, url, **kwargs): + if self._error is not None: + raise self._error + return _FakeJsonResponse(self._status, self._payload) + + +def _page(*sources: dict, sort_key: str = "file_uuid") -> dict: + """Wrap ``_source`` dicts in the Elasticsearch page envelope.""" + return { + "hits": { + "hits": [ + {"_source": src, "sort": [src.get(sort_key, "x")]} + for src in sources + ] + } + } + + +class TestFileExtensionsFromEnv: + def test_file_extensions_from_env_should_return_default_when_unset( + self, monkeypatch + ): + """Test the default allowlist applies when the variable is unset. + + Given: + No HUBMAP_FILE_EXTENSIONS in the environment. + When: + file_extensions_from_env resolves the allowlist. + Then: + It should return the non-empty default, dot-prefixed throughout. + """ + # Arrange + monkeypatch.delenv(EXTENSIONS_ENV, raising=False) + + # Act + allowlist = file_extensions_from_env() + + # Assert + assert allowlist + assert ".h5ad" in allowlist + assert all(ext.startswith(".") for ext in allowlist) + + def test_file_extensions_from_env_should_normalize_case_and_missing_dots( + self, monkeypatch + ): + """Test entries normalize to what the index's field values look like. + + The server-side terms filter matches ``file_extension`` exactly, so + an entry that keeps its case or lacks its dot silently matches + nothing. + + Given: + A mixed-case, mixed-dot, whitespace-padded override. + When: + file_extensions_from_env resolves the allowlist. + Then: + Every entry should come out lower-cased with a leading dot, in + the configured order. + """ + # Arrange + monkeypatch.setenv(EXTENSIONS_ENV, " h5ad, .BCF ,Gz") + + # Act + allowlist = file_extensions_from_env() + + # Assert + assert allowlist == (".h5ad", ".bcf", ".gz") + + def test_file_extensions_from_env_should_return_empty_and_warn_when_set_empty( + self, monkeypatch, caplog + ): + """Test an explicitly empty value disables ingest loudly. + + Given: + HUBMAP_FILE_EXTENSIONS set to a blank string. + When: + file_extensions_from_env resolves the allowlist. + Then: + It should return an empty tuple and log a warning naming the + variable. + """ + # Arrange + monkeypatch.setenv(EXTENSIONS_ENV, " ") + + # Act + with caplog.at_level("WARNING"): + allowlist = file_extensions_from_env() + + # Assert + assert allowlist == () + assert any(EXTENSIONS_ENV in record.message for record in caplog.records) + + def test_file_extensions_from_env_should_collapse_repeats_keeping_order( + self, monkeypatch + ): + """Test a duplicated token cannot widen or reorder the filter. + + Given: + An override repeating one extension in two spellings. + When: + file_extensions_from_env resolves the allowlist. + Then: + The first occurrence should win and order should be preserved. + """ + # Arrange + monkeypatch.setenv(EXTENSIONS_ENV, ".h5ad,bcf,.H5AD,.bcf") + + # Act + allowlist = file_extensions_from_env() + + # Assert + assert allowlist == (".h5ad", ".bcf") + + @given( + entries=st.lists( + st.text( + alphabet=st.characters( + whitelist_categories=("Ll", "Lu", "Nd") + ), + min_size=1, + max_size=8, + ), + min_size=1, + max_size=8, + ) + ) + def test_file_extensions_from_env_should_emit_index_shaped_entries( + self, entries + ): + """Test every resolved entry matches the index's value shape. + + Given: + Any comma-joined list of alphanumeric tokens. + When: + file_extensions_from_env resolves the allowlist. + Then: + Every entry should be lower-cased, dot-prefixed, and unique. + """ + import os + + # Arrange + os.environ[EXTENSIONS_ENV] = ",".join(entries) + try: + # Act + allowlist = file_extensions_from_env() + finally: + del os.environ[EXTENSIONS_ENV] + + # Assert + assert all(ext.startswith(".") and ext == ext.lower() for ext in allowlist) + assert len(set(allowlist)) == len(allowlist) + + +class TestExtractGenomeAssembly: + @pytest.mark.parametrize( + ("text", "expected"), + [ + ("aligned against hg38 reference", "GRCh38"), + ("aligned against GRCh38", "GRCh38"), + ("built on hg19", "GRCh37"), + ("mouse mm10 pipeline", "GRCm38"), + ("GRCm39 assembly", "GRCm39"), + ("no assembly named here", None), + ], + ) + def test_extract_genome_assembly_should_normalize_to_canonical_names( + self, text, expected + ): + """Test assembly mentions resolve to their canonical identifiers. + + Given: + A workflow description naming an assembly in one of the + recognized spellings, or none at all. + When: + extract_genome_assembly scans it. + Then: + It should return the canonical assembly name, or None when no + pattern matches. + """ + # Act & assert + assert extract_genome_assembly(text) == expected + + +class TestDeriveFileFormat: + @pytest.mark.parametrize( + ("filename", "expected_name"), + [ + ("secondary_analysis.h5ad", "HDF5"), + ("reads.fastq.gz", "FASTQ"), + ("variants.bcf", "BCF"), + ("matrix.mtx", "MTX"), + ("expr.csv", "CSV"), + ], + ) + def test_derive_file_format_should_map_the_inner_extension( + self, filename, expected_name + ): + """Test the format comes from the extension under any compression. + + The index's file_extension names the outermost suffix, which for a + .fastq.gz is the wrapper rather than the format. + + Given: + A filename, compressed or not. + When: + derive_file_format maps it. + Then: + It should name the format of the bytes under the compression. + """ + # Act + result = derive_file_format(filename) + + # Assert + assert result is not None + assert result["name"] == expected_name + + def test_derive_file_format_should_return_none_when_nothing_maps(self): + """Test an unknown or absent extension maps to no format. + + Given: + A filename with an unmapped extension and one with none. + When: + derive_file_format maps each. + Then: + It should return None for both rather than guessing. + """ + # Act & assert + assert derive_file_format("notes.unknownext") is None + assert derive_file_format("README") is None + + +class TestTransformFileToCfdb: + def test_transform_file_to_cfdb_should_map_the_file_level_fields(self): + """Test the per-file surface of the index lands on the document. + + Given: + A complete files-index document with no dataset join inputs. + When: + transform_file_to_cfdb runs. + Then: + It should carry the identity, checksum, size, status, format, + and assets access_url fields the index provides. + """ + # Act + doc = _transform(_file_doc()) + + # Assert + assert doc["submission"] == "hubmap" + assert doc["local_id"] == "abc123" + assert doc["accession_id"] is None + assert doc["filename"] == "secondary_analysis.h5ad" + assert doc["extra"]["hubmap"]["rel_path"] == ( + "processed/secondary_analysis.h5ad" + ) + assert doc["size_in_bytes"] == 5529765 + assert isinstance(doc["size_in_bytes"], int) + assert doc["md5"] == "0b05f823fd4b3cc86204366c6f71eae9" + assert doc["sha256"].startswith("f51518c924f3") + assert doc["access_url"] == ( + "https://assets.hubmapconsortium.org/ds-uuid-1/" + "processed/secondary_analysis.h5ad" + ) + assert doc["status"] == "Published" + assert doc["data_access_level"] == "public" + assert doc["file_format"]["name"] == "HDF5" + + def test_transform_file_to_cfdb_should_produce_a_valid_model(self): + """Test the emitted document validates against the file model. + + Given: + A complete files-index document with full join inputs. + When: + transform_file_to_cfdb runs and the result is validated. + Then: + FileMetadataModel should accept it without error. + """ + # Arrange + dataset_metadata = { + "ds-uuid-1": { + "pipeline": "Salmon", + "genome_assembly": "GRCh38", + "donor_uuid": "donor-1", + "donor_metadata": {"sex": ["Female"]}, + } + } + + # Act + doc = _transform( + _file_doc(), + dataset_metadata=dataset_metadata, + donor_lookup={"donor-1": {"sex": ["Female"], "age_value": [67.0]}}, + organ_map={"TH": {"id": "UBERON:0002370", "name": "Thymus"}}, + ) + + # Assert + model = FileMetadataModel(**doc) + assert model.local_id == "abc123" + assert model.collections[0].extra.hubmap.dataset_status == "Published" + + def test_transform_file_to_cfdb_should_percent_encode_the_access_url(self): + """Test a rel_path with URL-hostile characters still forms a URL. + + Given: + A rel_path containing spaces. + When: + transform_file_to_cfdb builds the assets URL. + Then: + Path segments should be percent-encoded with the separators + kept. + """ + # Act + doc = _transform(_file_doc(rel_path="a dir/file name.h5ad")) + + # Assert + assert doc["access_url"] == ( + "https://assets.hubmapconsortium.org/ds-uuid-1/" + "a%20dir/file%20name.h5ad" + ) + + def test_transform_file_to_cfdb_should_join_dataset_and_donor_metadata(self): + """Test the in-memory join lands demographics and dataset context. + + Given: + Dataset metadata and donor demographics keyed for the file's + dataset and donor. + When: + transform_file_to_cfdb runs. + Then: + The collection should carry the dataset context and the subject + the unwrapped demographics. + """ + # Arrange + dataset_metadata = { + "ds-uuid-1": { + "pipeline": "Salmon", + "processing": "processed", + "group_name": "Stanford TMC", + "visualization": True, + "vitessce_hints": ["rna"], + "metadata": {"library_layout": "paired-end"}, + "genome_assembly": "GRCh38", + } + } + donor_lookup = { + "donor-1": { + "sex": ["Female"], + "age_value": [67.0], + "medical_history": ["Diabetes", "Hypertension"], + } + } + + # Act + doc = _transform( + _file_doc(), + dataset_metadata=dataset_metadata, + donor_lookup=donor_lookup, + ) + + # Assert + assert doc["genome_assembly"] == "GRCh38" + assert doc["extra"]["hubmap"]["genome_assembly"] == "GRCh38" + collection = doc["collections"][0] + assert collection["local_id"] == "ds-uuid-1" + assert collection["name"] == "HBM339.XXWC.842" + assert collection["persistent_id"] == ( + "https://portal.hubmapconsortium.org/browse/dataset/ds-uuid-1" + ) + assert collection["experiment_type"] == "RNAseq" + assert collection["analyte_class"] == "RNA" + assert collection["extra"]["hubmap"] == { + "pipeline": "Salmon", + "processing": "processed", + "group_name": "Stanford TMC", + "visualization": True, + "vitessce_hints": ["rna"], + "metadata": {"library_layout": "paired-end"}, + "dataset_status": "Published", + } + subject = collection["subjects"][0] + assert subject["local_id"] == "donor-1" + assert subject["taxonomy"]["id"] == "NCBI:txid9606" + assert subject["extra"]["hubmap"]["sex"] == "Female" + assert subject["extra"]["hubmap"]["age_value"] == 67.0 + assert subject["extra"]["hubmap"]["medical_history"] == [ + "Diabetes", + "Hypertension", + ] + + def test_transform_file_to_cfdb_should_degrade_when_dataset_unknown(self): + """Test a file whose dataset is missing from the map still loads. + + The dataset map is prefetched from a different index, so a dataset + the files index knows and the dataset index does not must degrade + the document rather than drop it. + + Given: + Empty join inputs. + When: + transform_file_to_cfdb runs. + Then: + The document should carry the file fields, no genome_assembly, + a subject without demographics, and a collection without the + dataset-index extras. + """ + # Act + doc = _transform(_file_doc()) + + # Assert + assert "genome_assembly" not in doc + collection = doc["collections"][0] + assert collection["extra"]["hubmap"] == {"dataset_status": "Published"} + assert "extra" not in collection["subjects"][0] + + def test_transform_file_to_cfdb_should_map_organs_through_the_organ_map( + self, + ): + """Test anatomy terms come from the UBKG mapping, never fabricated. + + Given: + One mappable organ code, one unmapped, and one duplicated, with + a stats counter attached. + When: + transform_file_to_cfdb runs. + Then: + The collection should carry exactly one UBERON term named by + the document's label, and the unmapped code should be counted. + """ + from collections import Counter + + # Arrange + organs = [ + {"code": "TH", "label": "Thymus"}, + {"code": "TH", "label": "Thymus"}, + {"code": "ZZ", "label": "Mystery"}, + ] + stats: Counter[str] = Counter() + + # Act + doc = transform_file_to_cfdb( + _file_doc(organs=organs), + dataset_metadata={}, + donor_lookup={}, + organ_map={"TH": {"id": "UBERON:0002370", "name": "Thymus"}}, + stats=stats, + ) + + # Assert + assert doc["collections"][0]["anatomy"] == [ + {"id": "UBERON:0002370", "name": "Thymus"} + ] + assert stats["unmapped_organ:ZZ"] == 1 + + @pytest.mark.parametrize( + "missing", ["file_uuid", "rel_path", "dataset_uuid"] + ) + def test_transform_file_to_cfdb_should_return_none_when_unaddressable( + self, missing + ): + """Test a document missing an identity field is skipped. + + Given: + A files-index document missing one of the fields that make it + addressable. + When: + transform_file_to_cfdb runs with a stats counter. + Then: + It should return None and count the skip. + """ + from collections import Counter + + # Arrange + stats: Counter[str] = Counter() + + # Act + doc = transform_file_to_cfdb( + _file_doc(**{missing: None}), + dataset_metadata={}, + donor_lookup={}, + organ_map={}, + stats=stats, + ) + + # Assert + assert doc is None + assert stats["skipped:incomplete"] == 1 + + def test_transform_file_to_cfdb_should_null_an_unparseable_size(self): + """Test a size the index mistypes degrades to null, not a string. + + Given: + A document whose size is not a number. + When: + transform_file_to_cfdb runs. + Then: + size_in_bytes should be None. + """ + # Act + doc = _transform(_file_doc(size="not-a-number")) + + # Assert + assert doc["size_in_bytes"] is None + + def test_transform_file_to_cfdb_should_count_extensions_into_stats(self): + """Test the transform reports what it emitted for the sync's log. + + Given: + A document and a stats counter. + When: + transform_file_to_cfdb runs. + Then: + The counter should tally the document under its extension. + """ + from collections import Counter + + # Arrange + stats: Counter[str] = Counter() + + # Act + transform_file_to_cfdb( + _file_doc(), + dataset_metadata={}, + donor_lookup={}, + organ_map={}, + stats=stats, + ) + + # Assert + assert stats["extension:.h5ad"] == 1 + + +class TestFetchFileMetadata: + @pytest.mark.asyncio + async def test_fetch_file_metadata_should_paginate_with_search_after( + self, mocker + ): + """Test the walk carries each page's sort key into the next request. + + Given: + Two pages of file documents. + When: + fetch_file_metadata drains the stream. + Then: + It should yield every document and send the second request with + the first page's last sort value as search_after. + """ + # Arrange + session = _SearchSession( + pages=[ + _page(_file_doc(file_uuid="aaa"), _file_doc(file_uuid="bbb")), + _page(_file_doc(file_uuid="ccc")), + ] + ) + mocker.patch.object( + hubmap_module.aiohttp, "ClientSession", return_value=session + ) + + # Act + docs = [doc async for doc in fetch_file_metadata((".h5ad",))] + + # Assert + assert [doc["file_uuid"] for doc in docs] == ["aaa", "bbb", "ccc"] + assert "search_after" not in session.post_bodies[0] + assert session.post_bodies[1]["search_after"] == ["bbb"] + + @pytest.mark.asyncio + async def test_fetch_file_metadata_should_filter_extensions_server_side( + self, mocker + ): + """Test the allowlist becomes a terms filter in the request body. + + Excluding 9.7M microscopy tiles client-side would stream them all; + the filter has to ride the query. + + Given: + A two-extension allowlist. + When: + fetch_file_metadata issues its first request. + Then: + The body should carry a terms filter on file_extension.keyword + with exactly those values. + """ + # Arrange + session = _SearchSession() + mocker.patch.object( + hubmap_module.aiohttp, "ClientSession", return_value=session + ) + + # Act + [doc async for doc in fetch_file_metadata((".h5ad", ".bcf"))] + + # Assert + assert session.post_bodies[0]["query"] == { + "terms": {"file_extension.keyword": [".h5ad", ".bcf"]} + } + + @pytest.mark.asyncio + async def test_fetch_file_metadata_should_yield_nothing_when_allowlist_empty( + self, mocker + ): + """Test the explicit-empty configuration never opens a request. + + Given: + An empty allowlist. + When: + fetch_file_metadata is drained. + Then: + It should yield nothing and make no network request. + """ + # Arrange + session_factory = mocker.patch.object( + hubmap_module.aiohttp, "ClientSession" + ) + + # Act + docs = [doc async for doc in fetch_file_metadata(())] + + # Assert + assert docs == [] + session_factory.assert_not_called() + + @pytest.mark.asyncio + async def test_fetch_file_metadata_should_raise_on_http_error(self, mocker): + """Test an upstream error fails the stream instead of truncating it. + + The loader clears before reloading, so a stream that quietly ended + early would silently shrink the corpus. + + Given: + A files search endpoint answering HTTP 503. + When: + fetch_file_metadata is drained. + Then: + It should raise rather than end the stream. + """ + # Arrange + session = _SearchSession(status=503) + mocker.patch.object( + hubmap_module.aiohttp, "ClientSession", return_value=session + ) + + # Act & assert + with pytest.raises(RuntimeError, match="HTTP 503"): + [doc async for doc in fetch_file_metadata((".h5ad",))] + + +class TestFetchDatasetMetadataBulk: + @pytest.mark.asyncio + async def test_fetch_dataset_metadata_bulk_should_key_results_by_uuid( + self, mocker + ): + """Test the map joins against what the files index actually carries. + + The files index names a parent dataset only by dataset_uuid, so a + map keyed any other way (the retired doi_url keying) cannot be + joined against it. + + Given: + One dataset document with donor metadata and a workflow + description naming hg38. + When: + fetch_dataset_metadata_bulk drains the index. + Then: + The entry should sit under the dataset uuid with the donor + fields and the canonicalized assembly. + """ + # Arrange + src = { + "uuid": "ds-uuid-1", + "pipeline": "Salmon", + "donor": {"uuid": "donor-1", "mapped_metadata": {"sex": ["F"]}}, + "ingest_metadata": {"workflow_description": "aligned to hg38"}, + } + session = _SearchSession(pages=[_page(src, sort_key="uuid")]) + mocker.patch.object( + hubmap_module.aiohttp, "ClientSession", return_value=session + ) + + # Act + results = await fetch_dataset_metadata_bulk() + + # Assert + assert set(results) == {"ds-uuid-1"} + entry = results["ds-uuid-1"] + assert entry["pipeline"] == "Salmon" + assert entry["donor_uuid"] == "donor-1" + assert entry["donor_metadata"] == {"sex": ["F"]} + assert entry["genome_assembly"] == "GRCh38" + + @pytest.mark.asyncio + async def test_fetch_dataset_metadata_bulk_should_raise_on_http_error( + self, mocker + ): + """Test a partial dataset map is refused rather than returned. + + A silently partial map would mean silently under-enriched + documents behind a clear-before-reload. + + Given: + A dataset search endpoint answering HTTP 502. + When: + fetch_dataset_metadata_bulk runs. + Then: + It should raise rather than return what it fetched so far. + """ + # Arrange + session = _SearchSession(status=502) + mocker.patch.object( + hubmap_module.aiohttp, "ClientSession", return_value=session + ) + + # Act & assert + with pytest.raises(RuntimeError, match="HTTP 502"): + await fetch_dataset_metadata_bulk() + + +class TestFetchOrganMap: + @pytest.mark.asyncio + async def test_fetch_organ_map_should_key_uberon_terms_by_rui_code( + self, mocker + ): + """Test the UBKG payload becomes a code-keyed UBERON lookup. + + Given: + A UBKG organs payload with one complete entry and one missing + its UBERON id. + When: + fetch_organ_map runs. + Then: + Only the complete entry should be mapped. + """ + # Arrange + payload = [ + {"rui_code": "TH", "term": "Thymus", "organ_uberon": "UBERON:0002370"}, + {"rui_code": "XX", "term": "No Uberon", "organ_uberon": None}, + ] + session = _OrganSession(payload=payload) + mocker.patch.object( + hubmap_module.aiohttp, "ClientSession", return_value=session + ) + + # Act + organ_map = await fetch_organ_map() + + # Assert + assert organ_map == {"TH": {"id": "UBERON:0002370", "name": "Thymus"}} + + @pytest.mark.asyncio + async def test_fetch_organ_map_should_return_empty_and_warn_on_failure( + self, mocker, caplog + ): + """Test a UBKG outage degrades anatomy instead of failing the sync. + + Given: + A UBKG endpoint that raises a client error. + When: + fetch_organ_map runs. + Then: + It should return an empty map and log a warning. + """ + # Arrange + session = _OrganSession(error=aiohttp.ClientError("down")) + mocker.patch.object( + hubmap_module.aiohttp, "ClientSession", return_value=session + ) + + # Act + with caplog.at_level("WARNING"): + organ_map = await fetch_organ_map() + + # Assert + assert organ_map == {} + assert any("UBKG" in record.message for record in caplog.records) + + +class TestBuildHubmapDccRecord: + def test_build_hubmap_dcc_record_should_carry_the_static_dcc_fields(self): + """Test the DCC record names HuBMAP under its registry id. + + Given: + The static HuBMAP configuration. + When: + build_hubmap_dcc_record runs. + Then: + The record should carry the submission, registry id, labels, + and project namespace fields the dcc collection expects. + """ + # Act + record = build_hubmap_dcc_record() + + # Assert + assert record["submission"] == "hubmap" + assert record["id"] == "cfde_registry_dcc:hubmap" + assert record["dcc_abbreviation"] == "HuBMAP" + assert record["dcc_url"] == "https://hubmapconsortium.org" + assert record["project_id_namespace"] == "https://hubmapconsortium.org" + assert record["project_local_id"] == "HuBMAP" diff --git a/tests/test_sync.py b/tests/test_sync.py index 409197d..1668eb4 100644 --- a/tests/test_sync.py +++ b/tests/test_sync.py @@ -12,21 +12,20 @@ from cfdb import api from cfdb.services import encode as encode_module from cfdb.services import fourdn as fourdn_module +from cfdb.services import hubmap as hubmap_module from cfdb.services import sync as sync_module from cfdb.services.sync import ( SyncTask, _enrich_4dn_api_metadata, _enrich_4dn_collections, - _enrich_hubmap_collections_and_subjects, - _enrich_hubmap_files, _load_dataset_async, - _prune_non_public_hubmap_raw_records, _set_accession_ids, _stamp_4dn_file_accessions, _sync_dccs, _sync_encode, + _sync_hubmap, ) -from cfdb.indexes import data_index_specs +from cfdb.indexes import data_index_specs, materialized_files_index_specs from tests.conftest import FakeDB @@ -215,6 +214,9 @@ async def test__sync_dccs_should_sync_the_remaining_dccs_when_one_fails( zip_sync = mocker.patch.object( sync_module, "_sync_c2m2_zip", mocker.AsyncMock() ) + hubmap_sync = mocker.patch.object( + sync_module, "_sync_hubmap", mocker.AsyncMock() + ) mocker.patch.object(sync_module, "ensure_indexes", mocker.AsyncMock()) mocker.patch.object( sync_module, "_log_accession_coverage", mocker.AsyncMock() @@ -225,7 +227,8 @@ async def test__sync_dccs_should_sync_the_remaining_dccs_when_one_fails( with pytest.raises(RuntimeError, match="encode"): await _sync_dccs(task) - assert zip_sync.await_count == 2 + assert zip_sync.await_count == 1 + hubmap_sync.assert_awaited_once() @pytest.mark.asyncio async def test__sync_dccs_should_ensure_data_indexes_when_a_dcc_failed( @@ -252,7 +255,7 @@ async def test__sync_dccs_should_ensure_data_indexes_when_a_dcc_failed( "_sync_encode", mocker.AsyncMock(side_effect=RuntimeError("encode died")), ) - mocker.patch.object(sync_module, "_sync_c2m2_zip", mocker.AsyncMock()) + mocker.patch.object(sync_module, "_sync_hubmap", mocker.AsyncMock()) ensure_mock = mocker.patch.object( sync_module, "ensure_indexes", mocker.AsyncMock() ) @@ -289,7 +292,7 @@ async def test__sync_dccs_should_not_report_a_failed_dcc_as_synced( "_sync_encode", mocker.AsyncMock(side_effect=RuntimeError("encode died")), ) - mocker.patch.object(sync_module, "_sync_c2m2_zip", mocker.AsyncMock()) + mocker.patch.object(sync_module, "_sync_hubmap", mocker.AsyncMock()) mocker.patch.object(sync_module, "ensure_indexes", mocker.AsyncMock()) coverage = mocker.patch.object( sync_module, "_log_accession_coverage", mocker.AsyncMock() @@ -325,7 +328,7 @@ async def test__sync_dccs_should_chain_the_first_dcc_failure_as_the_cause( sync_module, "_sync_encode", mocker.AsyncMock(side_effect=first) ) mocker.patch.object( - sync_module, "_sync_c2m2_zip", mocker.AsyncMock(side_effect=second) + sync_module, "_sync_hubmap", mocker.AsyncMock(side_effect=second) ) mocker.patch.object(sync_module, "ensure_indexes", mocker.AsyncMock()) mocker.patch.object( @@ -365,8 +368,8 @@ async def test__sync_dccs_should_propagate_a_cancellation( "_sync_encode", mocker.AsyncMock(side_effect=asyncio.CancelledError()), ) - zip_sync = mocker.patch.object( - sync_module, "_sync_c2m2_zip", mocker.AsyncMock() + hubmap_sync = mocker.patch.object( + sync_module, "_sync_hubmap", mocker.AsyncMock() ) mocker.patch.object(sync_module, "ensure_indexes", mocker.AsyncMock()) task = SyncTask(id="t1", dcc_names=["encode", "hubmap"]) @@ -375,258 +378,248 @@ async def test__sync_dccs_should_propagate_a_cancellation( with pytest.raises(asyncio.CancelledError): await _sync_dccs(task) - zip_sync.assert_not_awaited() + hubmap_sync.assert_not_awaited() # --------------------------------------------------------------------------- -# _prune_non_public_hubmap_raw_records +# _sync_hubmap # --------------------------------------------------------------------------- -class TestPruneNonPublicHubmapRawRecords: - @pytest.mark.asyncio - async def test_mixed_public_and_non_public(self, mock_db): - """ - GIVEN a dataset_metadata dict with one public and one non-public dataset, - and raw collection/file_in_collection/file records for both - WHEN _prune_non_public_hubmap_raw_records is called - THEN only the non-public records are deleted - """ - dataset_metadata = { - "https://doi.org/public": {"data_access_level": "public"}, - "https://doi.org/consortium": {"data_access_level": "consortium"}, - } - - mock_db.collection.docs = [ - {"submission": "hubmap", "persistent_id": "https://doi.org/public", "id_namespace": "ns", "local_id": "pub-coll"}, - {"submission": "hubmap", "persistent_id": "https://doi.org/consortium", "id_namespace": "ns", "local_id": "con-coll"}, - ] - mock_db.file_in_collection.docs = [ - {"collection_id_namespace": "ns", "collection_local_id": "pub-coll", "file_id_namespace": "ns", "file_local_id": "file-pub"}, - {"collection_id_namespace": "ns", "collection_local_id": "con-coll", "file_id_namespace": "ns", "file_local_id": "file-con"}, - ] - mock_db.file.docs = [ - {"id_namespace": "ns", "local_id": "file-pub"}, - {"id_namespace": "ns", "local_id": "file-con"}, - ] - - await _prune_non_public_hubmap_raw_records(dataset_metadata) - - # Public file_in_collection link survives - assert len(mock_db.file_in_collection.docs) == 1 - assert mock_db.file_in_collection.docs[0]["collection_local_id"] == "pub-coll" +def _hubmap_file_doc(**overrides) -> dict: + """Return a minimal but realistic HuBMAP files-index _source document.""" + doc = { + "file_uuid": "abc123", + "rel_path": "processed/expr matrix/secondary_analysis.h5ad", + "file_extension": ".h5ad", + "size": 5529765, + "md5_checksum": "0b05f823fd4b3cc86204366c6f71eae9", + "sha256_checksum": ( + "f51518c924f3bab02847b19594afced3bc908c9d8be7f58fe36941a5c966ce72" + ), + "data_access_level": "public", + "dataset_uuid": "ds-uuid-1", + "dataset_hubmap_id": "HBM339.XXWC.842", + "dataset_type": "RNAseq", + "dataset_status": "Published", + "analyte_class": "RNA", + "donors": [{"entity_type": "Donor", "uuid": "donor-1"}], + "organs": [{"code": "TH", "label": "Thymus", "uuid": "org-1"}], + } + doc.update(overrides) + return doc + + +def _patch_hubmap_fetches( + mocker, + file_docs, + dataset_metadata=None, + organ_map=None, +): + """Point the three network boundaries of _sync_hubmap at fixed data.""" + mocker.patch.object( + hubmap_module, + "fetch_dataset_metadata_bulk", + mocker.AsyncMock(return_value=dataset_metadata or {}), + ) + mocker.patch.object( + hubmap_module, + "fetch_organ_map", + mocker.AsyncMock(return_value=organ_map or {}), + ) + mocker.patch.object( + hubmap_module, + "fetch_file_metadata", + lambda extensions: file_docs, + ) - # Orphaned non-public file is deleted; public file survives - assert len(mock_db.file.docs) == 1 - assert mock_db.file.docs[0]["local_id"] == "file-pub" +class TestSyncHubmap: @pytest.mark.asyncio - async def test_all_public(self, mock_db): - """ - GIVEN all datasets are public - WHEN _prune_non_public_hubmap_raw_records is called - THEN no records are deleted - """ - dataset_metadata = { - "https://doi.org/a": {"data_access_level": "public"}, - "https://doi.org/b": {"data_access_level": "public"}, - } - - mock_db.file_in_collection.docs = [ - {"collection_id_namespace": "ns", "collection_local_id": "c1", "file_id_namespace": "ns", "file_local_id": "f1"}, - ] - mock_db.file.docs = [ - {"id_namespace": "ns", "local_id": "f1"}, - ] - - await _prune_non_public_hubmap_raw_records(dataset_metadata) + async def test__sync_hubmap_should_insert_fully_populated_documents( + self, mock_db, mocker + ): + """Test the single-pass load joins everything into one document. - assert len(mock_db.file_in_collection.docs) == 1 - assert len(mock_db.file.docs) == 1 + HuBMAP writes the files collection directly with no post-load + enrichment, so this pipeline is the only writer of dataset context, + donor demographics, and anatomy for that DCC. - @pytest.mark.asyncio - async def test_all_non_public(self, mock_db): - """ - GIVEN all datasets are non-public - WHEN _prune_non_public_hubmap_raw_records is called - THEN all matching records are deleted + Given: + One files-index document whose dataset carries pipeline context, + donor demographics, and a mappable organ code. + When: + _sync_hubmap runs the fetch-transform-insert pipeline. + Then: + The inserted document should carry the file fields, the joined + dataset and donor metadata, the UBERON anatomy term, and the + DCC record should be upserted. """ + # Arrange dataset_metadata = { - "https://doi.org/a": {"data_access_level": "consortium"}, - "https://doi.org/b": {"data_access_level": "protected"}, + "ds-uuid-1": { + "pipeline": "Salmon", + "processing": "processed", + "genome_assembly": "GRCh38", + "donor_uuid": "donor-1", + "donor_metadata": { + "sex": ["Female"], + "age_value": [67.0], + "medical_history": ["Diabetes"], + }, + } } + organ_map = {"TH": {"id": "UBERON:0002370", "name": "Thymus"}} + _patch_hubmap_fetches( + mocker, + _async_iter([_hubmap_file_doc()]), + dataset_metadata=dataset_metadata, + organ_map=organ_map, + ) - mock_db.collection.docs = [ - {"submission": "hubmap", "persistent_id": "https://doi.org/a", "id_namespace": "ns", "local_id": "c1"}, - {"submission": "hubmap", "persistent_id": "https://doi.org/b", "id_namespace": "ns", "local_id": "c2"}, - ] - mock_db.file_in_collection.docs = [ - {"collection_id_namespace": "ns", "collection_local_id": "c1", "file_id_namespace": "ns", "file_local_id": "f1"}, - {"collection_id_namespace": "ns", "collection_local_id": "c2", "file_id_namespace": "ns", "file_local_id": "f2"}, - ] - mock_db.file.docs = [ - {"id_namespace": "ns", "local_id": "f1"}, - {"id_namespace": "ns", "local_id": "f2"}, - ] - - await _prune_non_public_hubmap_raw_records(dataset_metadata) - - assert len(mock_db.file_in_collection.docs) == 0 - assert len(mock_db.file.docs) == 0 - - @pytest.mark.asyncio - async def test_file_linked_to_both_public_and_non_public(self, mock_db): - """ - GIVEN a file is linked to both a public and a non-public collection - WHEN _prune_non_public_hubmap_raw_records is called - THEN the non-public link is removed but the file is preserved - """ - dataset_metadata = { - "https://doi.org/public": {"data_access_level": "public"}, - "https://doi.org/consortium": {"data_access_level": "consortium"}, - } + # Act + await _sync_hubmap(SyncTask(id="t1", dcc_names=["hubmap"])) - mock_db.collection.docs = [ - {"submission": "hubmap", "persistent_id": "https://doi.org/public", "id_namespace": "ns", "local_id": "pub-coll"}, - {"submission": "hubmap", "persistent_id": "https://doi.org/consortium", "id_namespace": "ns", "local_id": "con-coll"}, - ] - # shared-file belongs to both collections - mock_db.file_in_collection.docs = [ - {"collection_id_namespace": "ns", "collection_local_id": "pub-coll", "file_id_namespace": "ns", "file_local_id": "shared-file"}, - {"collection_id_namespace": "ns", "collection_local_id": "con-coll", "file_id_namespace": "ns", "file_local_id": "shared-file"}, - ] - mock_db.file.docs = [ - {"id_namespace": "ns", "local_id": "shared-file"}, + # Assert + doc = next(d for d in mock_db.files.docs if d["submission"] == "hubmap") + assert doc["local_id"] == "abc123" + assert doc["accession_id"] is None + assert doc["filename"] == "secondary_analysis.h5ad" + assert doc["size_in_bytes"] == 5529765 + assert isinstance(doc["size_in_bytes"], int) + assert doc["md5"] == "0b05f823fd4b3cc86204366c6f71eae9" + assert doc["sha256"].startswith("f51518c924f3") + assert doc["access_url"] == ( + "https://assets.hubmapconsortium.org/ds-uuid-1/" + "processed/expr%20matrix/secondary_analysis.h5ad" + ) + assert doc["status"] == "Published" + assert doc["data_access_level"] == "public" + assert doc["genome_assembly"] == "GRCh38" + assert doc["file_format"]["name"] == "HDF5" + assert doc["extra"]["hubmap"]["rel_path"] == ( + "processed/expr matrix/secondary_analysis.h5ad" + ) + collection = doc["collections"][0] + assert collection["local_id"] == "ds-uuid-1" + assert collection["name"] == "HBM339.XXWC.842" + assert collection["experiment_type"] == "RNAseq" + assert collection["analyte_class"] == "RNA" + assert collection["anatomy"] == [ + {"id": "UBERON:0002370", "name": "Thymus"} ] - - await _prune_non_public_hubmap_raw_records(dataset_metadata) - - # Non-public link deleted, public link survives - assert len(mock_db.file_in_collection.docs) == 1 - assert mock_db.file_in_collection.docs[0]["collection_local_id"] == "pub-coll" - - # File is preserved because it still has a public link - assert len(mock_db.file.docs) == 1 + assert collection["extra"]["hubmap"]["pipeline"] == "Salmon" + assert collection["extra"]["hubmap"]["dataset_status"] == "Published" + subject = collection["subjects"][0] + assert subject["local_id"] == "donor-1" + assert subject["extra"]["hubmap"]["sex"] == "Female" + assert subject["extra"]["hubmap"]["age_value"] == 67.0 + assert subject["extra"]["hubmap"]["medical_history"] == ["Diabetes"] + dcc_doc = next( + d for d in mock_db.dcc.docs if d["submission"] == "hubmap" + ) + assert dcc_doc["dcc_abbreviation"] == "HuBMAP" @pytest.mark.asyncio - async def test_missing_access_level_treated_as_non_public(self, mock_db): - """ - GIVEN a dataset with no data_access_level key - WHEN _prune_non_public_hubmap_raw_records is called - THEN it is treated as non-public and its records are pruned - """ - dataset_metadata = { - "https://doi.org/unknown": {"dataset_type": "RNAseq"}, - } - - mock_db.collection.docs = [ - {"submission": "hubmap", "persistent_id": "https://doi.org/unknown", "id_namespace": "ns", "local_id": "c1"}, - ] - mock_db.file_in_collection.docs = [ - {"collection_id_namespace": "ns", "collection_local_id": "c1", "file_id_namespace": "ns", "file_local_id": "f1"}, - ] - mock_db.file.docs = [ - {"id_namespace": "ns", "local_id": "f1"}, - ] - - await _prune_non_public_hubmap_raw_records(dataset_metadata) - - assert len(mock_db.file_in_collection.docs) == 0 - assert len(mock_db.file.docs) == 0 + async def test__sync_hubmap_should_replace_only_the_hubmap_slice( + self, mock_db, mocker + ): + """Test the stale clear is scoped to the submission being reloaded. - @pytest.mark.asyncio - async def test_file_matched_via_persistent_id_fallback(self, mock_db): - """ - GIVEN a non-public dataset whose files carry the dataset DOI as their - own persistent_id, with no file_in_collection entry at all -- - the shape HuBMAP's C2M2 export actually produces, since it - never populates file_in_collection and the materializer falls - back to matching file.persistent_id against - collection.persistent_id (materialize/src/main.rs) - WHEN _prune_non_public_hubmap_raw_records is called - THEN the file is deleted via the persistent_id fallback match, even - though the file_in_collection-based path finds nothing + Given: + A files collection holding a stale HuBMAP document and a 4DN + document, and a stream delivering one replacement file. + When: + _sync_hubmap runs. + Then: + The stale HuBMAP document should be gone, the replacement + present, and the 4DN document untouched. """ - dataset_metadata = { - "https://doi.org/protected": {"data_access_level": "protected"}, - } - - mock_db.collection.docs = [ - {"submission": "hubmap", "persistent_id": "https://doi.org/protected", "id_namespace": "ns", "local_id": "prot-coll"}, - ] - # No file_in_collection entries at all -- HuBMAP never populates this table. - mock_db.file.docs = [ - {"submission": "hubmap", "id_namespace": "ns", "local_id": "f1", "persistent_id": "https://doi.org/protected"}, - ] - - await _prune_non_public_hubmap_raw_records(dataset_metadata) + # Arrange + mock_db.files.docs.extend( + [ + {"submission": "hubmap", "local_id": "stale-1"}, + {"submission": "4dn", "local_id": "keep-1"}, + ] + ) + _patch_hubmap_fetches(mocker, _async_iter([_hubmap_file_doc()])) - assert len(mock_db.file.docs) == 0 + # Act + await _sync_hubmap(SyncTask(id="t1", dcc_names=["hubmap"])) + # Assert + ids = {(d["submission"], d["local_id"]) for d in mock_db.files.docs} + assert ("hubmap", "stale-1") not in ids + assert ("hubmap", "abc123") in ids + assert ("4dn", "keep-1") in ids -# --------------------------------------------------------------------------- -# _enrich_hubmap_collections_and_subjects -# --------------------------------------------------------------------------- + @pytest.mark.asyncio + async def test__sync_hubmap_should_keep_previous_corpus_when_fetch_dies_early( + self, mock_db, mocker + ): + """Test a fetch that fails before delivering rows clears nothing. + The deferred stale clear exists for exactly this shape: an upstream + failure before the first row would otherwise empty the slice with + nothing to put back. -class TestEnrichHubmapCollectionsAndSubjects: - @pytest.mark.asyncio - async def test_returns_dataset_metadata(self, mock_db, mocker): - """ - GIVEN a mocked fetch_dataset_metadata_bulk returning sample data - WHEN _enrich_hubmap_collections_and_subjects is called - THEN it returns the dataset_metadata dict + Given: + A files collection holding a HuBMAP document and a file stream + that raises before yielding anything. + When: + _sync_hubmap runs. + Then: + The error should propagate and the previous HuBMAP document + should still be served. """ - sample = { - "https://doi.org/10.35079/HBM123": { - "data_access_level": "public", - "dataset_type": "RNAseq", - } - } - mocker.patch( - "cfdb.services.hubmap.fetch_dataset_metadata_bulk", - return_value=sample, + # Arrange + mock_db.files.docs.append( + {"submission": "hubmap", "local_id": "previous-1"} + ) + _patch_hubmap_fetches( + mocker, _async_raise(RuntimeError("files index down")) ) - # Need at least an empty collection cursor to iterate - mock_db.collection.docs = [] - mock_db.subject.docs = [] - - result = await _enrich_hubmap_collections_and_subjects() - - assert result is sample + # Act & assert + with pytest.raises(RuntimeError, match="files index down"): + await _sync_hubmap(SyncTask(id="t1", dcc_names=["hubmap"])) + assert mock_db.files.docs == [ + {"submission": "hubmap", "local_id": "previous-1"} + ] -# --------------------------------------------------------------------------- -# _enrich_hubmap_files -# --------------------------------------------------------------------------- + @pytest.mark.asyncio + async def test__sync_hubmap_should_ensure_materialized_files_indexes( + self, mock_db, mocker + ): + """Test the load ends by ensuring the files collection indexes. + HuBMAP writes straight into the materialized collection and never + runs the materializer, the only other creator of files indexes, so + skipping this leaves accession and submission lookups scanning. -class TestEnrichHubmapFiles: - @pytest.mark.asyncio - async def test_sets_public_access_level_on_all_hubmap_files(self, mock_db): - """ - GIVEN materialized HuBMAP files in the files collection - WHEN _enrich_hubmap_files is called - THEN all HuBMAP files get data_access_level set to "public" + Given: + A sync whose stream delivers one file document. + When: + _sync_hubmap runs. + Then: + It should ensure the materialized files index specs once. """ - mock_db.files.docs = [ - {"_id": "1", "submission": "hubmap", "filename": "a.bam", "collections": []}, - {"_id": "2", "submission": "hubmap", "filename": "b.bam", "collections": []}, - {"_id": "3", "submission": "4dn", "filename": "c.bam", "collections": []}, - ] - mock_db.collection.docs = [] - - await _enrich_hubmap_files({}) + # Arrange + _patch_hubmap_fetches(mocker, _async_iter([_hubmap_file_doc()])) + ensure_mock = mocker.patch.object( + sync_module, "ensure_indexes", mocker.AsyncMock() + ) - # HuBMAP files stamped as public - for doc in mock_db.files.docs: - if doc["submission"] == "hubmap": - assert doc["data_access_level"] == "public" + # Act + await _sync_hubmap(SyncTask(id="t1", dcc_names=["hubmap"])) - # Non-HuBMAP files untouched - non_hubmap = [d for d in mock_db.files.docs if d["submission"] == "4dn"] - assert "data_access_level" not in non_hubmap[0] + # Assert + ensure_mock.assert_awaited_once() + specs = ensure_mock.await_args.args[1] + assert [spec.name for spec in specs] == [ + spec.name for spec in materialized_files_index_specs() + ] # --------------------------------------------------------------------------- From c17d8f777adeb17a958cc26794ec3dca37af5e8d Mon Sep 17 00:00:00 2001 From: Conrad Date: Fri, 20 Nov 2026 16:14:24 -0500 Subject: [PATCH 05/37] feat: Carry HuBMAP dataset_status in the DuckDB dump 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. --- src/cfdb/dump/loader.py | 1 + src/cfdb/dump/schema.sql | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/cfdb/dump/loader.py b/src/cfdb/dump/loader.py index cf24528..7bc0f9f 100644 --- a/src/cfdb/dump/loader.py +++ b/src/cfdb/dump/loader.py @@ -801,6 +801,7 @@ def _register_collection_extras(self, collection: Collection) -> None: if hubmap.metadata is None else json.dumps(hubmap.metadata, sort_keys=True) ), + "dataset_status": hubmap.dataset_status, } if self._any_value(row, key_cols): self._register("collection_extra_hubmap", row) diff --git a/src/cfdb/dump/schema.sql b/src/cfdb/dump/schema.sql index 1b6074a..88c6d20 100644 --- a/src/cfdb/dump/schema.sql +++ b/src/cfdb/dump/schema.sql @@ -1,6 +1,6 @@ -- cfdb DuckDB dump schema (issue #123). -- --- schema_version: 2 +-- schema_version: 3 -- -- The schema of record for the flattened relational dump of the -- materialized ``files`` collection. The design rules, the per-consortium @@ -390,6 +390,7 @@ CREATE TABLE collection_extra_hubmap ( visualization BOOLEAN, vitessce_hints VARCHAR[], metadata JSON, -- open-ended assay-specific dict; no fixed columns + dataset_status VARCHAR, PRIMARY KEY (id_namespace, local_id), FOREIGN KEY (id_namespace, local_id) REFERENCES collection (id_namespace, local_id) From 8e44fb476f9acb7c709d3e8d7824236656d04221 Mon Sep 17 00:00:00 2001 From: Conrad Date: Fri, 20 Nov 2026 16:14:30 -0500 Subject: [PATCH 06/37] docs: Document the HuBMAP files search API dataloader 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. --- HUBMAP-SUPPLEMENT.md | 184 +++++++++++++++++++++------------------- README.md | 11 +-- src/cfdb/dump/loader.py | 10 +-- 3 files changed, 106 insertions(+), 99 deletions(-) diff --git a/HUBMAP-SUPPLEMENT.md b/HUBMAP-SUPPLEMENT.md index f311dd8..6bbd5f5 100644 --- a/HUBMAP-SUPPLEMENT.md +++ b/HUBMAP-SUPPLEMENT.md @@ -1,84 +1,104 @@ -# HuBMAP API Enrichment +# HuBMAP Files Search API Dataloader -Field mapping from HuBMAP Search API to the CFDB data model. Enrichment runs during sync as a single bulk Elasticsearch query against `POST /v3/portal/search`, paginated with `search_after` in batches of 1000. +Field mapping from HuBMAP's file-grain search index to the CFDB data model. HuBMAP is a `rest_api` DCC: `cfdb sync hubmap` builds documents directly from the live index — no C2M2 zip download, no TSV load, no Rust materializer run, and no post-load enrichment or pruning stages. The index itself holds only public files, which is what retired the pruning pass the C2M2 path needed. -## Entity Matching +## Source Endpoints -| CFDB Entity | Match Key (CFDB) | Match Key (HuBMAP) | -|-------------|------------------|---------------------| -| Collection | `collection.persistent_id` | `doi_url` | -| Subject | `subject.local_id` contains UUID | `donor.uuid` | -| File | `file.filename` (basename) | `files[].rel_path` (basename) | +| Endpoint | Role | Pagination | +|----------|------|------------| +| `POST https://search.api.hubmapconsortium.org/v3/files/search` | One Elasticsearch document per file; the primary stream | `search_after` on `file_uuid.keyword`, batches of 1000 | +| `POST https://search.api.hubmapconsortium.org/v3/portal/search` | One document per dataset; prefetched once into an in-memory map keyed by `uuid` | `search_after` on `_id`, batches of 1000 | +| `GET https://ontology.api.hubmapconsortium.org/organs?application_context=HUBMAP` | Organ `rui_code` → UBERON id | One request per sync | -Collections are the primary join point. One HuBMAP dataset = one C2M2 collection = many files. Subject matching uses the donor UUID embedded in the C2M2 subject `local_id`. File matching joins through the parent collection's DOI, then matches individual files by filename. +The files index is ~9.9M documents, 98% of them `.tif` microscopy tiles, so the loader applies a configurable extension allowlist **server-side** (a `terms` filter on `file_extension.keyword`) and the excluded files never cross the wire. -## Collection Enrichment +## Entity Construction -Stored on `collection.extra.hubmap` (`EnrichedHubmapCollection`). Runs pre-materialization. +There is no entity matching. The C2M2 path had to join its TSVs to the Search API through heuristics — collection `persistent_id` against `doi_url`, donor uuid substring-matched inside subject `local_id`, files matched by filename basename within a dataset — and each heuristic was a place for records to fall through. The files index names its parent dataset and donors directly, so every entity is constructed, not matched: -| CFDB Field | HuBMAP Source Path | Type | Example | -|------------|-------------------|------|---------| -| `dataset_type` | `dataset_type` | string | `"RNAseq"`, `"ATACseq [SnapATAC]"` | -| `pipeline` | `pipeline` | string | `"Salmon"`, `"SnapATAC"` | -| `processing` | `processing` | string | `"raw"`, `"processed"` | -| `group_name` | `group_name` | string | `"Stanford TMC"` | -| `analyte_class` | `analyte_class` | string | `"RNA"`, `"DNA"` | -| `visualization` | `visualization` | bool | `true` | -| `vitessce_hints` | `vitessce-hints` | string[] | `["rna", "is_sc"]` | -| `metadata` | `metadata` | dict | Full assay-specific metadata (~130 keys, varies by assay type) | +| CFDB Entity | Built from | +|-------------|-----------| +| File | The files-index document itself; `local_id` is `file_uuid` | +| Collection | The file's parent dataset: `local_id` is `dataset_uuid`, one collection per file | +| Subject | The file's `donors[]`: `local_id` is the donor uuid | +| Anatomy | The file's `organs[]`, with UBERON ids from the UBKG organ map | -### Assay-Specific Metadata Keys +Dataset-level context the files index does not carry — donor demographics, pipeline, assay metadata, genome assembly — is prefetched from the dataset index (~10k documents) into memory and joined by `dataset_uuid` during transformation, so documents land fully populated in a single insert pass. A dataset missing from that map degrades its files (no demographics, pipeline, or assembly) rather than dropping them. -The `metadata` dict is stored verbatim. Common keys for sequencing assays: +The `id_namespace` is `https://hubmapconsortium.org` (configured in `dcc_registry.py`), mirroring the ENCODE convention of using the portal URL rather than the C2M2 tag-URI. Every sync clears and rebuilds the HuBMAP slice, so the namespace change has no continuity cost. -| Key | Example | -|-----|---------| -| `acquisition_instrument_model` | `"NovaSeq6000"` | -| `acquisition_instrument_vendor` | `"Illumina"` | -| `sequencing_read_format` | `"150/8/8/150"` | -| `library_layout` | `"paired-end"` | -| `rnaseq_assay_method` | `"NEBNext Ultra II RNA Lib Prep Kit"` | -| `library_average_fragment_size` | `350` | -| `sequencing_read_percent_q30` | `94.27` | +## Extension Allowlist -## Subject Enrichment +`HUBMAP_FILE_EXTENSIONS` — comma-separated, case-insensitive, leading dot optional (`h5ad, .BCF` and `.h5ad,.bcf` configure the same thing). Unset applies the default below; set-but-empty ingests nothing and logs a warning, matching the `ENCODE_ANNOTATION_TYPES` semantics. -Stored on `subject.extra.hubmap` (`EnrichedHubmapSubject`). Runs pre-materialization. +Default: `.h5ad`, `.h5mu`, `.h5`, `.hdf5`, `.bcf`, `.gz`, `.mtx`, `.arrow`, `.parquet`, `.bed`, `.narrowpeak`, `.bam`, `.sf`, `.snap`, `.csv`, `.tsv` — the genomics and tabular tail of the live distribution, ~53k files against the 9.7M `.tif` tiles the default excludes. -Source path is `donor.mapped_metadata.`. HuBMAP returns some fields as single-element lists (e.g., `["Female"]`); these are unwrapped to scalar values during enrichment. +## File Mapping -| CFDB Field | HuBMAP Source Key | Type | Example | -|------------|------------------|------|---------| -| `age_value` | `age_value` | float | `67.0` | -| `age_unit` | `age_unit` | string | `"years"` | -| `sex` | `sex` | string | `"Female"` | -| `race` | `race` | string | `"White"` | -| `body_mass_index_value` | `body_mass_index_value` | float | `28.5` | -| `body_mass_index_unit` | `body_mass_index_unit` | string | `"kg/m2"` | -| `cause_of_death` | `cause_of_death` | string | `"Anoxia"` | -| `death_event` | `death_event` | string | `"Cardiac death"` | -| `mechanism_of_injury` | `mechanism_of_injury` | string | `"Blunt injury"` | -| `medical_history` | `medical_history` | string[] | `["Diabetes", "Hypertension"]` | -| `social_history` | `social_history` | string[] | `["Smoking"]` | -| `height_value` | `height_value` | float | `170.0` | -| `height_unit` | `height_unit` | string | `"cm"` | -| `weight_value` | `weight_value` | float | `80.0` | -| `weight_unit` | `weight_unit` | string | `"kg"` | +| CFDB Field | Source | Notes | +|------------|--------|-------| +| `local_id` | `file_uuid` | HuBMAP issues no file accessions; `accession_id` is explicitly null ([#102](https://github.com/abdenlab/cfdb/issues/102)) | +| `filename` | `rel_path` basename | Full path kept on `extra.hubmap.rel_path` | +| `size_in_bytes` | `size` | Stored as int64 — the C2M2 TSV path stored it as a string, which left size filters inert | +| `md5` / `sha256` | `md5_checksum` / `sha256_checksum` | Real per-file checksums; the C2M2 TSVs lacked or mistyped both | +| `file_format` | filename, compression suffix stripped | EDAM-mapped from the inner extension, so `x.fastq.gz` maps to FASTQ rather than nothing | +| `compression_format` | filename suffix | Same derivation and absent-when-undetermined contract as ENCODE | +| `access_url` | `https://assets.hubmapconsortium.org/{dataset_uuid}/{rel_path}` | Path segments percent-encoded; resolves without authentication for these (all-public) files | +| `status` | `dataset_status` | e.g. `"Published"` | +| `data_access_level` | `data_access_level` | `"public"` on every document in this index | +| `genome_assembly` | dataset `ingest_metadata.workflow_description` | Regex-extracted and canonicalized; mirrored on `extra.hubmap.genome_assembly`. See below. | +| `extra.hubmap.is_data_product` | `is_data_product` | The index serializes it as the strings `"True"`/`"False"`; parsed to a bool, and left absent when missing or unrecognized rather than defaulted to `false` | -## File Enrichment +## Collection Mapping -Runs post-materialization against the `files` collection. `data_access_level` is stored at the top level of the file document; other fields go on `file.extra`. +One collection per file: its parent dataset. -| CFDB Field | HuBMAP Source Path | Type | Notes | -|------------|-------------------|------|-------| -| `data_access_level` | `data_access_level` | string | Top-level field. `"public"` or `"protected"`. Inherited from parent dataset — one value per dataset applies to all its files. | -| `extra.hubmap.genome_assembly` | `ingest_metadata.workflow_description` | string | Regex-extracted. Normalized: `hg38` -> `GRCh38`, `hg19` -> `GRCh37`, `mm10` -> `GRCm38`. Inherited from parent dataset. | -| `extra.hubmap.is_data_product` | `files[].is_data_product` | bool | Per-file, matched by filename basename. | -| `extra.hubmap.rel_path` | `files[].rel_path` | string | Per-file. Enables constructing the assets URL: `https://assets.hubmapconsortium.org/{dataset_uuid}/{rel_path}` | +| CFDB Field | Source | +|------------|--------| +| `local_id` | `dataset_uuid` | +| `name` | `dataset_hubmap_id` (e.g. `HBM339.XXWC.842`) | +| `persistent_id` | `https://portal.hubmapconsortium.org/browse/dataset/{dataset_uuid}` | +| `experiment_type` | `dataset_type` | +| `analyte_class` | `analyte_class` | +| `anatomy[]` | `organs[]` — UBERON id from the UBKG organ map by `code`, name from the document's `label` | -### Genome Assembly Extraction +An organ code the UBKG map does not know is skipped and counted rather than given a fabricated id; the sync logs the unmapped codes. A UBKG outage degrades the same way — collections carry no anatomy that sync, with a warning — because anatomy is enrichment, not identity. -The HuBMAP Search API has no structured `genome_assembly` field. Assembly is extracted by regex from the `ingest_metadata.workflow_description` free-text field, which mentions the reference genome in ~851 datasets. Recognized patterns and their canonical forms: +### `extra.hubmap` (`EnrichedHubmapCollection`), joined from the dataset index + +| CFDB Field | Source | Type | +|------------|--------|------| +| `pipeline` | `pipeline` | string | +| `processing` | `processing` | string | +| `group_name` | `group_name` | string | +| `visualization` | `visualization` | bool | +| `vitessce_hints` | `vitessce-hints` | string[] | +| `metadata` | `metadata` | dict — full assay-specific metadata, stored verbatim | +| `dataset_status` | files-index `dataset_status` | string | + +## Subject Mapping + +One subject per entry in the file's `donors[]`, with `local_id` the donor uuid and `taxonomy` fixed to Homo sapiens (HuBMAP is human-only). Demographics come from the dataset index's `donor.mapped_metadata`, joined by donor uuid; HuBMAP returns most fields as single-element lists, which are unwrapped to scalars. + +Stored on `subjects[].extra.hubmap` (`EnrichedHubmapSubject`): + +| CFDB Field | Type | Example | +|------------|------|---------| +| `sex` | string | `"Female"` | +| `race` | string | `"White"` | +| `age_value` / `age_unit` | float / string | `67.0`, `"years"` | +| `height_value` / `height_unit` | float / string | `170.0`, `"cm"` | +| `weight_value` / `weight_unit` | float / string | `80.0`, `"kg"` | +| `body_mass_index_value` / `body_mass_index_unit` | float / string | `28.5`, `"kg/m2"` | +| `cause_of_death` | string | `"Anoxia"` | +| `death_event` | string | `"Cardiac death"` | +| `mechanism_of_injury` | string | `"Blunt injury"` | +| `medical_history` | string[] | `["Diabetes", "Hypertension"]` | +| `social_history` | string[] | `["Smoking"]` | + +## Genome Assembly Extraction + +The Search API has no structured `genome_assembly` field; assembly is extracted by regex from the dataset's free-text `ingest_metadata.workflow_description`. Recognized patterns and their canonical forms: | Pattern | Canonical | |---------|-----------| @@ -93,35 +113,21 @@ HuBMAP is human-only, so the vast majority resolve to `GRCh38`. If no pattern ma | Field | Status | Notes | |-------|--------|-------| -| Index files (`.bai`, `.tbi`, `.crai`) | Not available | Raw sequencing data is protected; processed datasets don't retain BAMs. No `/index/hubmap/{id}` route. | -| Per-file sequencing metrics | Not available | `files[]` has `rel_path`, `size`, `type`, `edam_term` but no per-file QC or sequencing metrics. | -| Structured genome assembly | Not available | Only in prose `workflow_description`. See extraction logic above. | +| `accession_id` | Not issued | HuBMAP has no file accessions; files are keyed by uuid ([#102](https://github.com/abdenlab/cfdb/issues/102)) | +| `creation_time` | Not mapped | The index carries only `last_modified_at`, which is a modification time, not a creation time; mapping it would misstate what the field means | +| Index files (`.bai`, `.tbi`, `.crai`) | Not available | Raw sequencing data is protected upstream; processed datasets don't retain BAMs | +| Per-file sequencing metrics | Not available | The files index carries checksums and size but no per-file QC | +| Biosamples | Not built | The files index names organs and donors but no sample-level entities; anatomy lands on the collection | -## Sync Hooks - -All enrichment uses a single bulk fetch from the Search API. No per-entity API calls. - -| Hook | Phase | Function | -|------|-------|----------| -| Collection + Subject enrichment | Pre-materialization | `_enrich_hubmap_collections_and_subjects()` | -| File enrichment | Post-materialization | `_enrich_hubmap_files()` | - -### Data Flow +## Data Flow ```text -fetch_dataset_metadata_bulk() # Single bulk Elasticsearch query - │ # Returns dict keyed by doi_url +fetch_dataset_metadata_bulk() # dataset index -> {dataset_uuid: context} +fetch_organ_map() # UBKG -> {rui_code: UBERON term} │ - ├─> _enrich_hubmap_collections_and_subjects() [pre-materialization] - │ ├─ Match collection.persistent_id == doi_url - │ │ └─ Write EnrichedHubmapCollection -> collection.extra.hubmap - │ └─ Match subject.local_id contains donor.uuid - │ └─ Write EnrichedHubmapSubject -> subject.extra.hubmap - │ - ├─> _materialize_files() [Rust materializer] - │ - └─> _enrich_hubmap_files() [post-materialization] - ├─ Join files -> collections -> doi_url - ├─ Set data_access_level (top-level) - └─ Set genome_assembly, is_data_product, rel_path (on extra.hubmap) + └─> fetch_file_metadata(allowlist) # files index, filtered server-side + └─ transform_file_to_cfdb(...) # one fully-populated document per file + └─ insert into files # single pass, deferred stale clear ``` + +The whole pipeline is `_sync_hubmap` in `services/sync.py`, sharing `_ingest_rows` with the ENCODE path: the stale HuBMAP slice is cleared only once replacement rows are in hand, so an upstream failure before the first row leaves the previous corpus being served rather than empty. diff --git a/README.md b/README.md index 1405bfc..0f3a0a9 100644 --- a/README.md +++ b/README.md @@ -381,7 +381,7 @@ The published contract is `schema.graphql` at the repo root — a generated arti | `BigInt` | JSON number | `sizeInBytes`, on both `FileMetadataType` and `FileMetadataInput` | | `JSON` | Any JSON value | `distinctValues.values`, `collections[].extra.hubmap.metadata` | -`BigInt` is a signed 64-bit integer. The GraphQL specification fixes `Int` at 32 bits, so a file larger than 2,147,483,647 bytes (~2.1 GB) could not be represented at all: the field resolved to `null` and contributed a `Int cannot represent non 32-bit signed integer value` entry to the response's `errors` array, degrading a whole page of results to a partial one. That affects every ENCODE `.hic` file (6–51 GB) and the larger 4DN mcools, so it is the common case for contact maps rather than an edge case. The input filter carries the same scalar — a 32-bit filter would leave exactly the files the widened output field exposes unfilterable. Note that size filtering is exact-match, not a range, and that `size_in_bytes` is stored as a BSON int64 only for ENCODE: 4DN and HuBMAP load it as a string through the C2M2 TSV path, so a numeric equality predicate does not match their documents. That is an ingest-layer gap independent of the scalar's width — the filter was equally inert at `Int` — and normalising it is tracked separately. +`BigInt` is a signed 64-bit integer. The GraphQL specification fixes `Int` at 32 bits, so a file larger than 2,147,483,647 bytes (~2.1 GB) could not be represented at all: the field resolved to `null` and contributed a `Int cannot represent non 32-bit signed integer value` entry to the response's `errors` array, degrading a whole page of results to a partial one. That affects every ENCODE `.hic` file (6–51 GB) and the larger 4DN mcools, so it is the common case for contact maps rather than an edge case. The input filter carries the same scalar — a 32-bit filter would leave exactly the files the widened output field exposes unfilterable. Note that size filtering is exact-match, not a range, and that `size_in_bytes` is stored as a BSON int64 for ENCODE and HuBMAP but not 4DN, which loads it as a string through the C2M2 TSV path — so a numeric equality predicate does not match 4DN documents. That is an ingest-layer gap independent of the scalar's width — the filter was equally inert at `Int` — and normalising it is tracked separately. `BigInt` stays a JSON **number** on the wire rather than a string, so `sizeInBytes` remains directly usable in client-side arithmetic and comparisons with no parsing step. The usual objection to that choice — values above `Number.MAX_SAFE_INTEGER` (2^53-1) lose precision in JavaScript — does not bind here: 2^53 bytes is ~9 PB, far above any file this API serves. That is a property of *which* fields are routed through the scalar rather than something the scalar enforces, so staying under 2^53 is an admission criterion for any future `BigInt` field. What the scalar does enforce is the signed 64-bit range — exactly where BSON itself stops — plus a rejection of non-integers, including `true`/`false`, on both input and output. @@ -519,11 +519,11 @@ The central entity representing a stable digital asset. | `data_access_level` | string? | Access level: public, consortium, or protected | | `extra` | EnrichedFile? | DCC-specific file metadata (see EnrichedFile) | -**A note on `compression_format`, because it is easy to over-read.** The field reports compression that is *extrinsic* to `file_format` — a wrapper the source reveals and `file_format` does not. It is not a statement about whether the bytes are compressed. A BAM, bigWig or bigBed carries `""` despite being internally compressed, because its `file_format` already names that container. Conversely 4DN and HuBMAP take the value straight from their upstream C2M2 datapackage, which in practice leaves it blank on every file — including gzipped ones — so `""` from those DCCs means "upstream recorded nothing", not "uncompressed". Never treat `""` as a licence to skip inspecting the bytes. +**A note on `compression_format`, because it is easy to over-read.** The field reports compression that is *extrinsic* to `file_format` — a wrapper the source reveals and `file_format` does not. It is not a statement about whether the bytes are compressed. A BAM, bigWig or bigBed carries `""` despite being internally compressed, because its `file_format` already names that container. Conversely 4DN takes the value straight from its upstream C2M2 datapackage, which in practice leaves it blank on every file — including gzipped ones — so `""` from 4DN means "upstream recorded nothing", not "uncompressed". Never treat `""` as a licence to skip inspecting the bytes. -ENCODE derives the value from the download URL's filename suffix, because the ENCODE metadata TSV has no compression column. Two consequences are worth knowing. The field is **absent** (rendered as null) rather than `""` when nothing could be determined — no filename in the URL, or a compression suffix no EDAM term expresses (`.bz2`, `.xz`, `.zst`, `.zip`, `.starch`) — so treat null as "sniff the bytes", never as "uncompressed". And `format:3989` means "gzip-family stream": ENCODE names both plain gzip and BGZF `.gz` (it publishes no `.bgz` at all, and roughly a quarter of its `.gz` files are BGZF), so the value cannot distinguish them. Anything deciding on `gunzip | bgzip` must read the BGZF header — which is what `cfdb.workflows.processors.tabix` does, deliberately, and that byte-level check remains the decision of record. +ENCODE and HuBMAP derive the value from the filename suffix — the ENCODE metadata TSV has no compression column, and the HuBMAP files index has none either. Two consequences are worth knowing. The field is **absent** (rendered as null) rather than `""` when nothing could be determined — no filename in the URL, or a compression suffix no EDAM term expresses (`.bz2`, `.xz`, `.zst`, `.zip`, `.starch`) — so treat null as "sniff the bytes", never as "uncompressed". And `format:3989` means "gzip-family stream": ENCODE names both plain gzip and BGZF `.gz` (it publishes no `.bgz` at all, and roughly a quarter of its `.gz` files are BGZF), so the value cannot distinguish them. Anything deciding on `gunzip | bgzip` must read the BGZF header — which is what `cfdb.workflows.processors.tabix` does, deliberately, and that byte-level check remains the decision of record. -**A note on `accession_id`, because a null does not mean what it looks like.** The field exists so one input works across DCCs: 4DN puts an opaque UUID in `local_id` and carries its accession only inside the `persistent_id` URL, while ENCODE stores the accession *as* `local_id`. It is stored case-folded and filter values are folded identically, so `accessionId: ["4dnfimcjxzkh"]` and `["4DNFIMCJXZKH"]` match the same file. Three different situations all render as a null field and a `totalCount` of 0, and the API cannot distinguish them for you: the accession genuinely does not exist; the DCC issues none (all of HuBMAP, which matches files by filename within a dataset — tracked in [#102](https://github.com/abdenlab/cfdb/issues/102)); or that DCC has not been synced since the field was added. **A deployment must re-sync each DCC before `accessionId` returns anything.** Each sync logs its coverage (`4DN accession coverage: 53697/53697 files carry accession_id`), which is the only place that distinction is visible. +**A note on `accession_id`, because a null does not mean what it looks like.** The field exists so one input works across DCCs: 4DN puts an opaque UUID in `local_id` and carries its accession only inside the `persistent_id` URL, while ENCODE stores the accession *as* `local_id`. It is stored case-folded and filter values are folded identically, so `accessionId: ["4dnfimcjxzkh"]` and `["4DNFIMCJXZKH"]` match the same file. Three different situations all render as a null field and a `totalCount` of 0, and the API cannot distinguish them for you: the accession genuinely does not exist; the DCC issues none (all of HuBMAP, whose files are keyed by uuid — tracked in [#102](https://github.com/abdenlab/cfdb/issues/102)); or that DCC has not been synced since the field was added. **A deployment must re-sync each DCC before `accessionId` returns anything.** Each sync logs its coverage (`4DN accession coverage: 53697/53697 files carry accession_id`), which is the only place that distinction is visible. #### Dcc @@ -720,6 +720,7 @@ Additional protocol fields: `crosslinking_method`, `crosslinking_temperature`, ` | `visualization` | bool? | Whether visualization is available | | `vitessce_hints` | string[]? | Vitessce visualization hints | | `metadata` | dict? | Full assay-specific metadata | +| `dataset_status` | string? | Dataset status (e.g., "Published") | #### EnrichedBiosample @@ -1288,4 +1289,4 @@ cfdb dump duckdb cfdb.duckdb -s 4dn -s encode --to-parquet ./parquet Enrichment with no common slot today — ENCODE's `annotation_type`, `organism`, `software_used`, `encyclopedia_version`, `life_stage`, `age`, `age_units` among it — stays in the extension tables under its upstream name, and promoting such a field later is a schema change the `schema_version` header records. -**Loader policies.** Entity rows repeated across documents are first-write-wins, and every divergent later copy is counted and sampled into `dump_conflict` — divergence is reported, never silently resolved. Junction rows take the union over all copies instead, so a relationship present in only one copy is never dropped. A `(id_namespace, local_id)` key appearing under two submissions aborts the dump: the natural keys are only globally unique because id_namespaces are DCC-scoped, and the loader asserts that rather than trusting it (duplicate file keys abort likewise). String-typed numbers from the C2M2 TSV path (`size_in_bytes` on 4DN/HuBMAP) and unparseable timestamps coerce to NULL with a counter, a document failing model validation is skipped with a counter, and every counter plus per-table row counts land in `dump_stat`, next to `dump_info` (schema version, generation time, cfdb version/commit, source database, submissions, file count) — so a dump is self-describing about which code produced it and where the source disagreed with itself. Counters measure occurrences, not entities: a divergent or uncoercible value on an entity embedded by many documents counts once per embedding document, so a large count can be one bad shared entity rather than many. Foreign keys are declared and enforced, so a dump that violates referential integrity fails at write time rather than surprising a reader. An aborted or interrupted run deletes its partial output, and the backstop if one ever survives is `dump_info`: the row is written last, so a database without one is a partial dump. +**Loader policies.** Entity rows repeated across documents are first-write-wins, and every divergent later copy is counted and sampled into `dump_conflict` — divergence is reported, never silently resolved. Junction rows take the union over all copies instead, so a relationship present in only one copy is never dropped. A `(id_namespace, local_id)` key appearing under two submissions aborts the dump: the natural keys are only globally unique because id_namespaces are DCC-scoped, and the loader asserts that rather than trusting it (duplicate file keys abort likewise). String-typed numbers from the C2M2 TSV path (`size_in_bytes` on 4DN) and unparseable timestamps coerce to NULL with a counter, a document failing model validation is skipped with a counter, and every counter plus per-table row counts land in `dump_stat`, next to `dump_info` (schema version, generation time, cfdb version/commit, source database, submissions, file count) — so a dump is self-describing about which code produced it and where the source disagreed with itself. Counters measure occurrences, not entities: a divergent or uncoercible value on an entity embedded by many documents counts once per embedding document, so a large count can be one bad shared entity rather than many. Foreign keys are declared and enforced, so a dump that violates referential integrity fails at write time rather than surprising a reader. An aborted or interrupted run deletes its partial output, and the backstop if one ever survives is `dump_info`: the row is written last, so a database without one is a partial dump. diff --git a/src/cfdb/dump/loader.py b/src/cfdb/dump/loader.py index 7bc0f9f..2a9b263 100644 --- a/src/cfdb/dump/loader.py +++ b/src/cfdb/dump/loader.py @@ -353,11 +353,11 @@ def _coerce_timestamp( def _precoerce_int(self, container: Any, key: str, counter: str) -> None: """Coerce a known string-typed numeric field on the raw document. - 4DN and HuBMAP load ``size_in_bytes`` (and 4DN its sidecar - ``file_size``) as strings through the C2M2 TSV path. Left alone, - a non-numeric value would fail the whole document's model - validation; coerced here, the failure costs one NULL and one - counted coercion instead of the document. + 4DN loads ``size_in_bytes`` (and its sidecar ``file_size``) as + strings through the C2M2 TSV path. Left alone, a non-numeric value + would fail the whole document's model validation; coerced here, the + failure costs one NULL and one counted coercion instead of the + document. """ if not isinstance(container, dict): return From b72c948687e909fbe3f582bc06dcfa2995694e73 Mon Sep 17 00:00:00 2001 From: Conrad Date: Fri, 20 Nov 2026 16:23:05 -0500 Subject: [PATCH 07/37] test: Cover HuBMAP donor dedupe, flag parsing, and fetch edges 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. --- tests/test_hubmap.py | 333 ++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 332 insertions(+), 1 deletion(-) diff --git a/tests/test_hubmap.py b/tests/test_hubmap.py index d75fa17..06bd315 100644 --- a/tests/test_hubmap.py +++ b/tests/test_hubmap.py @@ -4,7 +4,7 @@ import aiohttp import pytest -from hypothesis import given +from hypothesis import given, settings from hypothesis import strategies as st from cfdb.models import FileMetadataModel @@ -656,6 +656,141 @@ def test_transform_file_to_cfdb_should_count_extensions_into_stats(self): # Assert assert stats["extension:.h5ad"] == 1 + def test_transform_file_to_cfdb_should_dedupe_repeated_donors(self): + """Test a donor the index repeats becomes one subject. + + The live index lists a donor once per contributing tissue block -- + one file names the same uuid 26 times -- so emitting a subject per + entry would stack identical subjects on one collection. + + Given: + A document whose donors list repeats one uuid around a second. + When: + transform_file_to_cfdb runs. + Then: + The collection should carry one subject per distinct donor, in + first-occurrence order. + """ + # Arrange + donors = [ + {"entity_type": "Donor", "uuid": "donor-1"}, + {"entity_type": "Donor", "uuid": "donor-1"}, + {"entity_type": "Donor", "uuid": "donor-2"}, + {"entity_type": "Donor", "uuid": "donor-1"}, + ] + + # Act + doc = _transform(_file_doc(donors=donors)) + + # Assert + subjects = doc["collections"][0]["subjects"] + assert [s["local_id"] for s in subjects] == ["donor-1", "donor-2"] + + @given( + uuids=st.lists( + st.one_of(st.sampled_from(["d1", "d2", "d3"]), st.none(), st.just("")), + max_size=12, + ) + ) + @settings(max_examples=50) + def test_transform_file_to_cfdb_should_emit_each_donor_once(self, uuids): + """Test subjects are the distinct donors, whatever the repetition. + + Given: + Any donors list drawn from a small uuid pool, with repeats and + blank or missing uuids mixed in. + When: + transform_file_to_cfdb runs. + Then: + Subject local_ids should equal the distinct non-blank uuids in + first-occurrence order. + """ + # Arrange + donors = [{"entity_type": "Donor", "uuid": uuid} for uuid in uuids] + expected = list(dict.fromkeys(uuid for uuid in uuids if uuid)) + + # Act + doc = _transform(_file_doc(donors=donors)) + + # Assert + subjects = doc["collections"][0]["subjects"] + assert [s["local_id"] for s in subjects] == expected + + @pytest.mark.parametrize( + ("raw", "expected"), + [ + ("True", True), + ("False", False), + (" false ", False), + (True, True), + (False, False), + ], + ) + def test_transform_file_to_cfdb_should_parse_is_data_product_flags( + self, raw, expected + ): + """Test the index's stringly-typed flag lands as a real bool. + + The index serializes is_data_product as "True"/"False", so a + truthiness test would read "False" as true. + + Given: + A document whose is_data_product is one of the recognized + spellings. + When: + transform_file_to_cfdb runs. + Then: + extra.hubmap.is_data_product should be the matching bool. + """ + # Act + doc = _transform(_file_doc(is_data_product=raw)) + + # Assert + assert doc["extra"]["hubmap"]["is_data_product"] is expected + + @pytest.mark.parametrize("raw", [None, "yes", "", 1]) + def test_transform_file_to_cfdb_should_omit_is_data_product_when_unrecognized( + self, raw + ): + """Test an unrecognized flag reads as unknown, not as false. + + Given: + A document whose is_data_product is missing or neither + recognized spelling. + When: + transform_file_to_cfdb runs. + Then: + extra.hubmap should carry no is_data_product key at all. + """ + # Act + doc = _transform(_file_doc(is_data_product=raw)) + + # Assert + assert "is_data_product" not in doc["extra"]["hubmap"] + + def test_transform_file_to_cfdb_should_omit_is_data_product_when_absent(self): + """Test a document without the flag stays unknown. + + A third of the live allowlisted files carry no is_data_product, and + defaulting them to false would fabricate a fact. + + Given: + A document with no is_data_product key. + When: + transform_file_to_cfdb runs. + Then: + extra.hubmap should carry no is_data_product key. + """ + # Arrange + src = _file_doc() + src.pop("is_data_product", None) + + # Act + doc = _transform(src) + + # Assert + assert "is_data_product" not in doc["extra"]["hubmap"] + class TestFetchFileMetadata: @pytest.mark.asyncio @@ -771,6 +906,88 @@ async def test_fetch_file_metadata_should_raise_on_http_error(self, mocker): with pytest.raises(RuntimeError, match="HTTP 503"): [doc async for doc in fetch_file_metadata((".h5ad",))] + @pytest.mark.asyncio + async def test_fetch_file_metadata_should_request_is_data_product( + self, mocker + ): + """Test the requested source fields include the data-product flag. + + A field missing from _source never crosses the wire, so the + transform would see every file as flagless. + + Given: + An allowlist. + When: + fetch_file_metadata issues its first request. + Then: + The body's _source should name is_data_product. + """ + # Arrange + session = _SearchSession() + mocker.patch.object( + hubmap_module.aiohttp, "ClientSession", return_value=session + ) + + # Act + [doc async for doc in fetch_file_metadata((".h5ad",))] + + # Assert + assert "is_data_product" in session.post_bodies[0]["_source"] + + @pytest.mark.asyncio + async def test_fetch_file_metadata_should_raise_on_network_error( + self, mocker + ): + """Test a dropped connection fails the stream instead of ending it. + + Given: + A files search endpoint whose request raises a client error. + When: + fetch_file_metadata is drained. + Then: + The client error should propagate. + """ + # Arrange + session = _SearchSession(error=aiohttp.ClientError("reset")) + mocker.patch.object( + hubmap_module.aiohttp, "ClientSession", return_value=session + ) + + # Act & assert + with pytest.raises(aiohttp.ClientError, match="reset"): + [doc async for doc in fetch_file_metadata((".h5ad",))] + + @pytest.mark.asyncio + async def test_fetch_file_metadata_should_stop_when_a_page_has_no_sort( + self, mocker + ): + """Test a page without a sort cursor ends the walk. + + Without a cursor there is nothing to resume from; re-sending the + query would re-serve the same page forever. + + Given: + A page whose last hit carries no sort value. + When: + fetch_file_metadata is drained. + Then: + It should yield that page and issue no second request. + """ + # Arrange + session = _SearchSession( + pages=[{"hits": {"hits": [{"_source": _file_doc()}]}}] + ) + mocker.patch.object( + hubmap_module.aiohttp, "ClientSession", return_value=session + ) + + # Act + docs = [doc async for doc in fetch_file_metadata((".h5ad",))] + + # Assert + assert len(docs) == 1 + assert len(session.post_bodies) == 1 + class TestFetchDatasetMetadataBulk: @pytest.mark.asyncio @@ -841,6 +1058,93 @@ async def test_fetch_dataset_metadata_bulk_should_raise_on_http_error( with pytest.raises(RuntimeError, match="HTTP 502"): await fetch_dataset_metadata_bulk() + @pytest.mark.asyncio + async def test_fetch_dataset_metadata_bulk_should_skip_hits_without_uuid( + self, mocker + ): + """Test unkeyable datasets are dropped and the rest keep their context. + + Given: + One dataset hit with no uuid and one carrying vitessce-hints + and assay metadata. + When: + fetch_dataset_metadata_bulk drains the index. + Then: + Only the keyed dataset should be returned, with vitessce-hints + under vitessce_hints and the metadata dict intact. + """ + # Arrange + keyed = { + "uuid": "ds-uuid-1", + "vitessce-hints": ["is_sc", "rna"], + "metadata": {"assay_category": "sequence"}, + } + session = _SearchSession( + pages=[_page({"pipeline": "Salmon"}, keyed, sort_key="uuid")] + ) + mocker.patch.object( + hubmap_module.aiohttp, "ClientSession", return_value=session + ) + + # Act + results = await fetch_dataset_metadata_bulk() + + # Assert + assert set(results) == {"ds-uuid-1"} + assert results["ds-uuid-1"]["vitessce_hints"] == ["is_sc", "rna"] + assert results["ds-uuid-1"]["metadata"] == {"assay_category": "sequence"} + + @pytest.mark.asyncio + async def test_fetch_dataset_metadata_bulk_should_raise_on_network_error( + self, mocker + ): + """Test a dropped connection refuses the partial map. + + Given: + A dataset search endpoint whose request raises a client error. + When: + fetch_dataset_metadata_bulk runs. + Then: + The client error should propagate. + """ + # Arrange + session = _SearchSession(error=aiohttp.ClientError("reset")) + mocker.patch.object( + hubmap_module.aiohttp, "ClientSession", return_value=session + ) + + # Act & assert + with pytest.raises(aiohttp.ClientError, match="reset"): + await fetch_dataset_metadata_bulk() + + @pytest.mark.asyncio + async def test_fetch_dataset_metadata_bulk_should_stop_when_a_page_has_no_sort( + self, mocker + ): + """Test a page without a sort cursor ends the walk. + + Given: + A page whose last hit carries no sort value. + When: + fetch_dataset_metadata_bulk runs. + Then: + It should return that page's dataset after a single request. + """ + # Arrange + session = _SearchSession( + pages=[{"hits": {"hits": [{"_source": {"uuid": "ds-uuid-1"}}]}}] + ) + mocker.patch.object( + hubmap_module.aiohttp, "ClientSession", return_value=session + ) + + # Act + results = await fetch_dataset_metadata_bulk() + + # Assert + assert set(results) == {"ds-uuid-1"} + assert len(session.post_bodies) == 1 + class TestFetchOrganMap: @pytest.mark.asyncio @@ -900,6 +1204,33 @@ async def test_fetch_organ_map_should_return_empty_and_warn_on_failure( assert organ_map == {} assert any("UBKG" in record.message for record in caplog.records) + @pytest.mark.asyncio + async def test_fetch_organ_map_should_return_empty_and_warn_on_http_error( + self, mocker, caplog + ): + """Test a UBKG error status degrades anatomy like an outage does. + + Given: + A UBKG endpoint answering HTTP 500. + When: + fetch_organ_map runs. + Then: + It should return an empty map and log a warning naming UBKG. + """ + # Arrange + session = _OrganSession(status=500) + mocker.patch.object( + hubmap_module.aiohttp, "ClientSession", return_value=session + ) + + # Act + with caplog.at_level("WARNING"): + organ_map = await fetch_organ_map() + + # Assert + assert organ_map == {} + assert any("HTTP 500" in record.message for record in caplog.records) + class TestBuildHubmapDccRecord: def test_build_hubmap_dcc_record_should_carry_the_static_dcc_fields(self): From 338e4c59066b4c2b7190ab20ba1b0e1f681b2a0c Mon Sep 17 00:00:00 2001 From: Conrad Date: Fri, 20 Nov 2026 16:23:05 -0500 Subject: [PATCH 08/37] test: Cover the HuBMAP dataset_status column in the DuckDB dump --- tests/test_dump.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/tests/test_dump.py b/tests/test_dump.py index 9daad2b..117c5fc 100644 --- a/tests/test_dump.py +++ b/tests/test_dump.py @@ -1256,6 +1256,31 @@ def test_dump_files_should_roundtrip_json_and_list_columns(): assert hints == ["is_sc", "rna"] +def test_dump_files_should_carry_the_hubmap_dataset_status(): + """Test the collection enrichment's dataset status reaches the dump. + + Given: + A HuBMAP document whose collection enrichment carries a + dataset_status. + When: + The document is dumped. + Then: + collection_extra_hubmap.dataset_status should hold that value. + """ + # Arrange + doc = make_hubmap_doc() + doc["collections"][0]["extra"]["hubmap"]["dataset_status"] = "Published" + + # Act + con, _ = run_dump([doc]) + + # Assert + (status,) = con.execute( + "SELECT dataset_status FROM collection_extra_hubmap" + ).fetchone() + assert status == "Published" + + def test_dump_files_should_order_extra_files_by_source_position(): """Test sidecar child-table ordinal ordering. From 1350665aae63dd463e93ee9521ea0c99f7c67df8 Mon Sep 17 00:00:00 2001 From: Conrad Date: Fri, 20 Nov 2026 17:03:57 -0500 Subject: [PATCH 09/37] test: Flatten HuBMAP tests to module-level functions 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. --- tests/test_hubmap.py | 2059 +++++++++++++++++++++--------------------- 1 file changed, 1040 insertions(+), 1019 deletions(-) diff --git a/tests/test_hubmap.py b/tests/test_hubmap.py index 06bd315..af890fb 100644 --- a/tests/test_hubmap.py +++ b/tests/test_hubmap.py @@ -145,1112 +145,1133 @@ def _page(*sources: dict, sort_key: str = "file_uuid") -> dict: } -class TestFileExtensionsFromEnv: - def test_file_extensions_from_env_should_return_default_when_unset( - self, monkeypatch - ): - """Test the default allowlist applies when the variable is unset. - - Given: - No HUBMAP_FILE_EXTENSIONS in the environment. - When: - file_extensions_from_env resolves the allowlist. - Then: - It should return the non-empty default, dot-prefixed throughout. - """ - # Arrange - monkeypatch.delenv(EXTENSIONS_ENV, raising=False) +def test_file_extensions_from_env_should_return_default_when_unset( + monkeypatch +): + """Test the default allowlist applies when the variable is unset. + + Given: + No HUBMAP_FILE_EXTENSIONS in the environment. + When: + file_extensions_from_env resolves the allowlist. + Then: + It should return the non-empty default, dot-prefixed throughout. + """ + # Arrange + monkeypatch.delenv(EXTENSIONS_ENV, raising=False) + + # Act + allowlist = file_extensions_from_env() + + # Assert + assert allowlist + assert ".h5ad" in allowlist + assert all(ext.startswith(".") for ext in allowlist) + + +def test_file_extensions_from_env_should_normalize_case_and_missing_dots( + monkeypatch +): + """Test entries normalize to what the index's field values look like. + + The server-side terms filter matches ``file_extension`` exactly, so + an entry that keeps its case or lacks its dot silently matches + nothing. + + Given: + A mixed-case, mixed-dot, whitespace-padded override. + When: + file_extensions_from_env resolves the allowlist. + Then: + Every entry should come out lower-cased with a leading dot, in + the configured order. + """ + # Arrange + monkeypatch.setenv(EXTENSIONS_ENV, " h5ad, .BCF ,Gz") - # Act - allowlist = file_extensions_from_env() + # Act + allowlist = file_extensions_from_env() - # Assert - assert allowlist - assert ".h5ad" in allowlist - assert all(ext.startswith(".") for ext in allowlist) + # Assert + assert allowlist == (".h5ad", ".bcf", ".gz") - def test_file_extensions_from_env_should_normalize_case_and_missing_dots( - self, monkeypatch - ): - """Test entries normalize to what the index's field values look like. - - The server-side terms filter matches ``file_extension`` exactly, so - an entry that keeps its case or lacks its dot silently matches - nothing. - - Given: - A mixed-case, mixed-dot, whitespace-padded override. - When: - file_extensions_from_env resolves the allowlist. - Then: - Every entry should come out lower-cased with a leading dot, in - the configured order. - """ - # Arrange - monkeypatch.setenv(EXTENSIONS_ENV, " h5ad, .BCF ,Gz") - # Act +def test_file_extensions_from_env_should_return_empty_and_warn_when_set_empty( + monkeypatch, caplog +): + """Test an explicitly empty value disables ingest loudly. + + Given: + HUBMAP_FILE_EXTENSIONS set to a blank string. + When: + file_extensions_from_env resolves the allowlist. + Then: + It should return an empty tuple and log a warning naming the + variable. + """ + # Arrange + monkeypatch.setenv(EXTENSIONS_ENV, " ") + + # Act + with caplog.at_level("WARNING"): allowlist = file_extensions_from_env() - # Assert - assert allowlist == (".h5ad", ".bcf", ".gz") + # Assert + assert allowlist == () + assert any(EXTENSIONS_ENV in record.message for record in caplog.records) - def test_file_extensions_from_env_should_return_empty_and_warn_when_set_empty( - self, monkeypatch, caplog - ): - """Test an explicitly empty value disables ingest loudly. - - Given: - HUBMAP_FILE_EXTENSIONS set to a blank string. - When: - file_extensions_from_env resolves the allowlist. - Then: - It should return an empty tuple and log a warning naming the - variable. - """ - # Arrange - monkeypatch.setenv(EXTENSIONS_ENV, " ") - # Act - with caplog.at_level("WARNING"): - allowlist = file_extensions_from_env() +def test_file_extensions_from_env_should_collapse_repeats_keeping_order( + monkeypatch +): + """Test a duplicated token cannot widen or reorder the filter. - # Assert - assert allowlist == () - assert any(EXTENSIONS_ENV in record.message for record in caplog.records) + Given: + An override repeating one extension in two spellings. + When: + file_extensions_from_env resolves the allowlist. + Then: + The first occurrence should win and order should be preserved. + """ + # Arrange + monkeypatch.setenv(EXTENSIONS_ENV, ".h5ad,bcf,.H5AD,.bcf") - def test_file_extensions_from_env_should_collapse_repeats_keeping_order( - self, monkeypatch - ): - """Test a duplicated token cannot widen or reorder the filter. - - Given: - An override repeating one extension in two spellings. - When: - file_extensions_from_env resolves the allowlist. - Then: - The first occurrence should win and order should be preserved. - """ - # Arrange - monkeypatch.setenv(EXTENSIONS_ENV, ".h5ad,bcf,.H5AD,.bcf") + # Act + allowlist = file_extensions_from_env() - # Act - allowlist = file_extensions_from_env() + # Assert + assert allowlist == (".h5ad", ".bcf") - # Assert - assert allowlist == (".h5ad", ".bcf") - - @given( - entries=st.lists( - st.text( - alphabet=st.characters( - whitelist_categories=("Ll", "Lu", "Nd") - ), - min_size=1, - max_size=8, + +@given( + entries=st.lists( + st.text( + alphabet=st.characters( + whitelist_categories=("Ll", "Lu", "Nd") ), min_size=1, max_size=8, - ) + ), + min_size=1, + max_size=8, ) - def test_file_extensions_from_env_should_emit_index_shaped_entries( - self, entries - ): - """Test every resolved entry matches the index's value shape. - - Given: - Any comma-joined list of alphanumeric tokens. - When: - file_extensions_from_env resolves the allowlist. - Then: - Every entry should be lower-cased, dot-prefixed, and unique. - """ - import os - - # Arrange - os.environ[EXTENSIONS_ENV] = ",".join(entries) - try: - # Act - allowlist = file_extensions_from_env() - finally: - del os.environ[EXTENSIONS_ENV] - - # Assert - assert all(ext.startswith(".") and ext == ext.lower() for ext in allowlist) - assert len(set(allowlist)) == len(allowlist) - - -class TestExtractGenomeAssembly: - @pytest.mark.parametrize( - ("text", "expected"), - [ - ("aligned against hg38 reference", "GRCh38"), - ("aligned against GRCh38", "GRCh38"), - ("built on hg19", "GRCh37"), - ("mouse mm10 pipeline", "GRCm38"), - ("GRCm39 assembly", "GRCm39"), - ("no assembly named here", None), - ], +) +def test_file_extensions_from_env_should_emit_index_shaped_entries( + entries +): + """Test every resolved entry matches the index's value shape. + + Given: + Any comma-joined list of alphanumeric tokens. + When: + file_extensions_from_env resolves the allowlist. + Then: + Every entry should be lower-cased, dot-prefixed, and unique. + """ + import os + + # Arrange + os.environ[EXTENSIONS_ENV] = ",".join(entries) + try: + # Act + allowlist = file_extensions_from_env() + finally: + del os.environ[EXTENSIONS_ENV] + + # Assert + assert all(ext.startswith(".") and ext == ext.lower() for ext in allowlist) + assert len(set(allowlist)) == len(allowlist) + + +@pytest.mark.parametrize( + ("text", "expected"), + [ + ("aligned against hg38 reference", "GRCh38"), + ("aligned against GRCh38", "GRCh38"), + ("built on hg19", "GRCh37"), + ("mouse mm10 pipeline", "GRCm38"), + ("GRCm39 assembly", "GRCm39"), + ("no assembly named here", None), + ], +) +def test_extract_genome_assembly_should_normalize_to_canonical_names( + text, expected +): + """Test assembly mentions resolve to their canonical identifiers. + + Given: + A workflow description naming an assembly in one of the + recognized spellings, or none at all. + When: + extract_genome_assembly scans it. + Then: + It should return the canonical assembly name, or None when no + pattern matches. + """ + # Act & assert + assert extract_genome_assembly(text) == expected + + +@pytest.mark.parametrize( + ("filename", "expected_name"), + [ + ("secondary_analysis.h5ad", "HDF5"), + ("reads.fastq.gz", "FASTQ"), + ("variants.bcf", "BCF"), + ("matrix.mtx", "MTX"), + ("expr.csv", "CSV"), + ], +) +def test_derive_file_format_should_map_the_inner_extension( + filename, expected_name +): + """Test the format comes from the extension under any compression. + + The index's file_extension names the outermost suffix, which for a + .fastq.gz is the wrapper rather than the format. + + Given: + A filename, compressed or not. + When: + derive_file_format maps it. + Then: + It should name the format of the bytes under the compression. + """ + # Act + result = derive_file_format(filename) + + # Assert + assert result is not None + assert result["name"] == expected_name + + +def test_derive_file_format_should_return_none_when_nothing_maps(): + """Test an unknown or absent extension maps to no format. + + Given: + A filename with an unmapped extension and one with none. + When: + derive_file_format maps each. + Then: + It should return None for both rather than guessing. + """ + # Act & assert + assert derive_file_format("notes.unknownext") is None + assert derive_file_format("README") is None + + +def test_transform_file_to_cfdb_should_map_the_file_level_fields(): + """Test the per-file surface of the index lands on the document. + + Given: + A complete files-index document with no dataset join inputs. + When: + transform_file_to_cfdb runs. + Then: + It should carry the identity, checksum, size, status, format, + and assets access_url fields the index provides. + """ + # Act + doc = _transform(_file_doc()) + + # Assert + assert doc["submission"] == "hubmap" + assert doc["local_id"] == "abc123" + assert doc["accession_id"] is None + assert doc["filename"] == "secondary_analysis.h5ad" + assert doc["extra"]["hubmap"]["rel_path"] == ( + "processed/secondary_analysis.h5ad" ) - def test_extract_genome_assembly_should_normalize_to_canonical_names( - self, text, expected - ): - """Test assembly mentions resolve to their canonical identifiers. - - Given: - A workflow description naming an assembly in one of the - recognized spellings, or none at all. - When: - extract_genome_assembly scans it. - Then: - It should return the canonical assembly name, or None when no - pattern matches. - """ - # Act & assert - assert extract_genome_assembly(text) == expected - - -class TestDeriveFileFormat: - @pytest.mark.parametrize( - ("filename", "expected_name"), - [ - ("secondary_analysis.h5ad", "HDF5"), - ("reads.fastq.gz", "FASTQ"), - ("variants.bcf", "BCF"), - ("matrix.mtx", "MTX"), - ("expr.csv", "CSV"), - ], + assert doc["size_in_bytes"] == 5529765 + assert isinstance(doc["size_in_bytes"], int) + assert doc["md5"] == "0b05f823fd4b3cc86204366c6f71eae9" + assert doc["sha256"].startswith("f51518c924f3") + assert doc["access_url"] == ( + "https://assets.hubmapconsortium.org/ds-uuid-1/" + "processed/secondary_analysis.h5ad" ) - def test_derive_file_format_should_map_the_inner_extension( - self, filename, expected_name - ): - """Test the format comes from the extension under any compression. - - The index's file_extension names the outermost suffix, which for a - .fastq.gz is the wrapper rather than the format. - - Given: - A filename, compressed or not. - When: - derive_file_format maps it. - Then: - It should name the format of the bytes under the compression. - """ - # Act - result = derive_file_format(filename) - - # Assert - assert result is not None - assert result["name"] == expected_name - - def test_derive_file_format_should_return_none_when_nothing_maps(self): - """Test an unknown or absent extension maps to no format. - - Given: - A filename with an unmapped extension and one with none. - When: - derive_file_format maps each. - Then: - It should return None for both rather than guessing. - """ - # Act & assert - assert derive_file_format("notes.unknownext") is None - assert derive_file_format("README") is None - - -class TestTransformFileToCfdb: - def test_transform_file_to_cfdb_should_map_the_file_level_fields(self): - """Test the per-file surface of the index lands on the document. - - Given: - A complete files-index document with no dataset join inputs. - When: - transform_file_to_cfdb runs. - Then: - It should carry the identity, checksum, size, status, format, - and assets access_url fields the index provides. - """ - # Act - doc = _transform(_file_doc()) - - # Assert - assert doc["submission"] == "hubmap" - assert doc["local_id"] == "abc123" - assert doc["accession_id"] is None - assert doc["filename"] == "secondary_analysis.h5ad" - assert doc["extra"]["hubmap"]["rel_path"] == ( - "processed/secondary_analysis.h5ad" - ) - assert doc["size_in_bytes"] == 5529765 - assert isinstance(doc["size_in_bytes"], int) - assert doc["md5"] == "0b05f823fd4b3cc86204366c6f71eae9" - assert doc["sha256"].startswith("f51518c924f3") - assert doc["access_url"] == ( - "https://assets.hubmapconsortium.org/ds-uuid-1/" - "processed/secondary_analysis.h5ad" - ) - assert doc["status"] == "Published" - assert doc["data_access_level"] == "public" - assert doc["file_format"]["name"] == "HDF5" - - def test_transform_file_to_cfdb_should_produce_a_valid_model(self): - """Test the emitted document validates against the file model. - - Given: - A complete files-index document with full join inputs. - When: - transform_file_to_cfdb runs and the result is validated. - Then: - FileMetadataModel should accept it without error. - """ - # Arrange - dataset_metadata = { - "ds-uuid-1": { - "pipeline": "Salmon", - "genome_assembly": "GRCh38", - "donor_uuid": "donor-1", - "donor_metadata": {"sex": ["Female"]}, - } - } + assert doc["status"] == "Published" + assert doc["data_access_level"] == "public" + assert doc["file_format"]["name"] == "HDF5" - # Act - doc = _transform( - _file_doc(), - dataset_metadata=dataset_metadata, - donor_lookup={"donor-1": {"sex": ["Female"], "age_value": [67.0]}}, - organ_map={"TH": {"id": "UBERON:0002370", "name": "Thymus"}}, - ) - - # Assert - model = FileMetadataModel(**doc) - assert model.local_id == "abc123" - assert model.collections[0].extra.hubmap.dataset_status == "Published" - - def test_transform_file_to_cfdb_should_percent_encode_the_access_url(self): - """Test a rel_path with URL-hostile characters still forms a URL. - - Given: - A rel_path containing spaces. - When: - transform_file_to_cfdb builds the assets URL. - Then: - Path segments should be percent-encoded with the separators - kept. - """ - # Act - doc = _transform(_file_doc(rel_path="a dir/file name.h5ad")) - - # Assert - assert doc["access_url"] == ( - "https://assets.hubmapconsortium.org/ds-uuid-1/" - "a%20dir/file%20name.h5ad" - ) - - def test_transform_file_to_cfdb_should_join_dataset_and_donor_metadata(self): - """Test the in-memory join lands demographics and dataset context. - - Given: - Dataset metadata and donor demographics keyed for the file's - dataset and donor. - When: - transform_file_to_cfdb runs. - Then: - The collection should carry the dataset context and the subject - the unwrapped demographics. - """ - # Arrange - dataset_metadata = { - "ds-uuid-1": { - "pipeline": "Salmon", - "processing": "processed", - "group_name": "Stanford TMC", - "visualization": True, - "vitessce_hints": ["rna"], - "metadata": {"library_layout": "paired-end"}, - "genome_assembly": "GRCh38", - } - } - donor_lookup = { - "donor-1": { - "sex": ["Female"], - "age_value": [67.0], - "medical_history": ["Diabetes", "Hypertension"], - } + +def test_transform_file_to_cfdb_should_produce_a_valid_model(): + """Test the emitted document validates against the file model. + + Given: + A complete files-index document with full join inputs. + When: + transform_file_to_cfdb runs and the result is validated. + Then: + FileMetadataModel should accept it without error. + """ + # Arrange + dataset_metadata = { + "ds-uuid-1": { + "pipeline": "Salmon", + "genome_assembly": "GRCh38", + "donor_uuid": "donor-1", + "donor_metadata": {"sex": ["Female"]}, } + } - # Act - doc = _transform( - _file_doc(), - dataset_metadata=dataset_metadata, - donor_lookup=donor_lookup, - ) - - # Assert - assert doc["genome_assembly"] == "GRCh38" - assert doc["extra"]["hubmap"]["genome_assembly"] == "GRCh38" - collection = doc["collections"][0] - assert collection["local_id"] == "ds-uuid-1" - assert collection["name"] == "HBM339.XXWC.842" - assert collection["persistent_id"] == ( - "https://portal.hubmapconsortium.org/browse/dataset/ds-uuid-1" - ) - assert collection["experiment_type"] == "RNAseq" - assert collection["analyte_class"] == "RNA" - assert collection["extra"]["hubmap"] == { + # Act + doc = _transform( + _file_doc(), + dataset_metadata=dataset_metadata, + donor_lookup={"donor-1": {"sex": ["Female"], "age_value": [67.0]}}, + organ_map={"TH": {"id": "UBERON:0002370", "name": "Thymus"}}, + ) + + # Assert + model = FileMetadataModel(**doc) + assert model.local_id == "abc123" + assert model.collections[0].extra.hubmap.dataset_status == "Published" + + +def test_transform_file_to_cfdb_should_percent_encode_the_access_url(): + """Test a rel_path with URL-hostile characters still forms a URL. + + Given: + A rel_path containing spaces. + When: + transform_file_to_cfdb builds the assets URL. + Then: + Path segments should be percent-encoded with the separators + kept. + """ + # Act + doc = _transform(_file_doc(rel_path="a dir/file name.h5ad")) + + # Assert + assert doc["access_url"] == ( + "https://assets.hubmapconsortium.org/ds-uuid-1/" + "a%20dir/file%20name.h5ad" + ) + + +def test_transform_file_to_cfdb_should_join_dataset_and_donor_metadata(): + """Test the in-memory join lands demographics and dataset context. + + Given: + Dataset metadata and donor demographics keyed for the file's + dataset and donor. + When: + transform_file_to_cfdb runs. + Then: + The collection should carry the dataset context and the subject + the unwrapped demographics. + """ + # Arrange + dataset_metadata = { + "ds-uuid-1": { "pipeline": "Salmon", "processing": "processed", "group_name": "Stanford TMC", "visualization": True, "vitessce_hints": ["rna"], "metadata": {"library_layout": "paired-end"}, - "dataset_status": "Published", + "genome_assembly": "GRCh38", } - subject = collection["subjects"][0] - assert subject["local_id"] == "donor-1" - assert subject["taxonomy"]["id"] == "NCBI:txid9606" - assert subject["extra"]["hubmap"]["sex"] == "Female" - assert subject["extra"]["hubmap"]["age_value"] == 67.0 - assert subject["extra"]["hubmap"]["medical_history"] == [ - "Diabetes", - "Hypertension", - ] + } + donor_lookup = { + "donor-1": { + "sex": ["Female"], + "age_value": [67.0], + "medical_history": ["Diabetes", "Hypertension"], + } + } - def test_transform_file_to_cfdb_should_degrade_when_dataset_unknown(self): - """Test a file whose dataset is missing from the map still loads. - - The dataset map is prefetched from a different index, so a dataset - the files index knows and the dataset index does not must degrade - the document rather than drop it. - - Given: - Empty join inputs. - When: - transform_file_to_cfdb runs. - Then: - The document should carry the file fields, no genome_assembly, - a subject without demographics, and a collection without the - dataset-index extras. - """ - # Act - doc = _transform(_file_doc()) + # Act + doc = _transform( + _file_doc(), + dataset_metadata=dataset_metadata, + donor_lookup=donor_lookup, + ) + + # Assert + assert doc["genome_assembly"] == "GRCh38" + assert doc["extra"]["hubmap"]["genome_assembly"] == "GRCh38" + collection = doc["collections"][0] + assert collection["local_id"] == "ds-uuid-1" + assert collection["name"] == "HBM339.XXWC.842" + assert collection["persistent_id"] == ( + "https://portal.hubmapconsortium.org/browse/dataset/ds-uuid-1" + ) + assert collection["experiment_type"] == "RNAseq" + assert collection["analyte_class"] == "RNA" + assert collection["extra"]["hubmap"] == { + "pipeline": "Salmon", + "processing": "processed", + "group_name": "Stanford TMC", + "visualization": True, + "vitessce_hints": ["rna"], + "metadata": {"library_layout": "paired-end"}, + "dataset_status": "Published", + } + subject = collection["subjects"][0] + assert subject["local_id"] == "donor-1" + assert subject["taxonomy"]["id"] == "NCBI:txid9606" + assert subject["extra"]["hubmap"]["sex"] == "Female" + assert subject["extra"]["hubmap"]["age_value"] == 67.0 + assert subject["extra"]["hubmap"]["medical_history"] == [ + "Diabetes", + "Hypertension", + ] + + +def test_transform_file_to_cfdb_should_degrade_when_dataset_unknown(): + """Test a file whose dataset is missing from the map still loads. + + The dataset map is prefetched from a different index, so a dataset + the files index knows and the dataset index does not must degrade + the document rather than drop it. + + Given: + Empty join inputs. + When: + transform_file_to_cfdb runs. + Then: + The document should carry the file fields, no genome_assembly, + a subject without demographics, and a collection without the + dataset-index extras. + """ + # Act + doc = _transform(_file_doc()) + + # Assert + assert "genome_assembly" not in doc + collection = doc["collections"][0] + assert collection["extra"]["hubmap"] == {"dataset_status": "Published"} + assert "extra" not in collection["subjects"][0] - # Assert - assert "genome_assembly" not in doc - collection = doc["collections"][0] - assert collection["extra"]["hubmap"] == {"dataset_status": "Published"} - assert "extra" not in collection["subjects"][0] - def test_transform_file_to_cfdb_should_map_organs_through_the_organ_map( - self, +def test_transform_file_to_cfdb_should_map_organs_through_the_organ_map( ): - """Test anatomy terms come from the UBKG mapping, never fabricated. - - Given: - One mappable organ code, one unmapped, and one duplicated, with - a stats counter attached. - When: - transform_file_to_cfdb runs. - Then: - The collection should carry exactly one UBERON term named by - the document's label, and the unmapped code should be counted. - """ - from collections import Counter - - # Arrange - organs = [ - {"code": "TH", "label": "Thymus"}, - {"code": "TH", "label": "Thymus"}, - {"code": "ZZ", "label": "Mystery"}, - ] - stats: Counter[str] = Counter() + """Test anatomy terms come from the UBKG mapping, never fabricated. + + Given: + One mappable organ code, one unmapped, and one duplicated, with + a stats counter attached. + When: + transform_file_to_cfdb runs. + Then: + The collection should carry exactly one UBERON term named by + the document's label, and the unmapped code should be counted. + """ + from collections import Counter + + # Arrange + organs = [ + {"code": "TH", "label": "Thymus"}, + {"code": "TH", "label": "Thymus"}, + {"code": "ZZ", "label": "Mystery"}, + ] + stats: Counter[str] = Counter() + + # Act + doc = transform_file_to_cfdb( + _file_doc(organs=organs), + dataset_metadata={}, + donor_lookup={}, + organ_map={"TH": {"id": "UBERON:0002370", "name": "Thymus"}}, + stats=stats, + ) + + # Assert + assert doc["collections"][0]["anatomy"] == [ + {"id": "UBERON:0002370", "name": "Thymus"} + ] + assert stats["unmapped_organ:ZZ"] == 1 - # Act - doc = transform_file_to_cfdb( - _file_doc(organs=organs), - dataset_metadata={}, - donor_lookup={}, - organ_map={"TH": {"id": "UBERON:0002370", "name": "Thymus"}}, - stats=stats, - ) - - # Assert - assert doc["collections"][0]["anatomy"] == [ - {"id": "UBERON:0002370", "name": "Thymus"} - ] - assert stats["unmapped_organ:ZZ"] == 1 - @pytest.mark.parametrize( - "missing", ["file_uuid", "rel_path", "dataset_uuid"] +@pytest.mark.parametrize( + "missing", ["file_uuid", "rel_path", "dataset_uuid"] +) +def test_transform_file_to_cfdb_should_return_none_when_unaddressable( + missing +): + """Test a document missing an identity field is skipped. + + Given: + A files-index document missing one of the fields that make it + addressable. + When: + transform_file_to_cfdb runs with a stats counter. + Then: + It should return None and count the skip. + """ + from collections import Counter + + # Arrange + stats: Counter[str] = Counter() + + # Act + doc = transform_file_to_cfdb( + _file_doc(**{missing: None}), + dataset_metadata={}, + donor_lookup={}, + organ_map={}, + stats=stats, ) - def test_transform_file_to_cfdb_should_return_none_when_unaddressable( - self, missing - ): - """Test a document missing an identity field is skipped. - Given: - A files-index document missing one of the fields that make it - addressable. - When: - transform_file_to_cfdb runs with a stats counter. - Then: - It should return None and count the skip. - """ - from collections import Counter + # Assert + assert doc is None + assert stats["skipped:incomplete"] == 1 - # Arrange - stats: Counter[str] = Counter() - # Act - doc = transform_file_to_cfdb( - _file_doc(**{missing: None}), - dataset_metadata={}, - donor_lookup={}, - organ_map={}, - stats=stats, - ) - - # Assert - assert doc is None - assert stats["skipped:incomplete"] == 1 - - def test_transform_file_to_cfdb_should_null_an_unparseable_size(self): - """Test a size the index mistypes degrades to null, not a string. - - Given: - A document whose size is not a number. - When: - transform_file_to_cfdb runs. - Then: - size_in_bytes should be None. - """ - # Act - doc = _transform(_file_doc(size="not-a-number")) +def test_transform_file_to_cfdb_should_null_an_unparseable_size(): + """Test a size the index mistypes degrades to null, not a string. - # Assert - assert doc["size_in_bytes"] is None + Given: + A document whose size is not a number. + When: + transform_file_to_cfdb runs. + Then: + size_in_bytes should be None. + """ + # Act + doc = _transform(_file_doc(size="not-a-number")) - def test_transform_file_to_cfdb_should_count_extensions_into_stats(self): - """Test the transform reports what it emitted for the sync's log. + # Assert + assert doc["size_in_bytes"] is None - Given: - A document and a stats counter. - When: - transform_file_to_cfdb runs. - Then: - The counter should tally the document under its extension. - """ - from collections import Counter - # Arrange - stats: Counter[str] = Counter() +def test_transform_file_to_cfdb_should_count_extensions_into_stats(): + """Test the transform reports what it emitted for the sync's log. - # Act - transform_file_to_cfdb( - _file_doc(), - dataset_metadata={}, - donor_lookup={}, - organ_map={}, - stats=stats, - ) - - # Assert - assert stats["extension:.h5ad"] == 1 - - def test_transform_file_to_cfdb_should_dedupe_repeated_donors(self): - """Test a donor the index repeats becomes one subject. - - The live index lists a donor once per contributing tissue block -- - one file names the same uuid 26 times -- so emitting a subject per - entry would stack identical subjects on one collection. - - Given: - A document whose donors list repeats one uuid around a second. - When: - transform_file_to_cfdb runs. - Then: - The collection should carry one subject per distinct donor, in - first-occurrence order. - """ - # Arrange - donors = [ - {"entity_type": "Donor", "uuid": "donor-1"}, - {"entity_type": "Donor", "uuid": "donor-1"}, - {"entity_type": "Donor", "uuid": "donor-2"}, - {"entity_type": "Donor", "uuid": "donor-1"}, - ] + Given: + A document and a stats counter. + When: + transform_file_to_cfdb runs. + Then: + The counter should tally the document under its extension. + """ + from collections import Counter + + # Arrange + stats: Counter[str] = Counter() + + # Act + transform_file_to_cfdb( + _file_doc(), + dataset_metadata={}, + donor_lookup={}, + organ_map={}, + stats=stats, + ) - # Act - doc = _transform(_file_doc(donors=donors)) + # Assert + assert stats["extension:.h5ad"] == 1 + + +def test_transform_file_to_cfdb_should_dedupe_repeated_donors(): + """Test a donor the index repeats becomes one subject. - # Assert - subjects = doc["collections"][0]["subjects"] - assert [s["local_id"] for s in subjects] == ["donor-1", "donor-2"] + The live index lists a donor once per contributing tissue block -- + one file names the same uuid 26 times -- so emitting a subject per + entry would stack identical subjects on one collection. - @given( - uuids=st.lists( - st.one_of(st.sampled_from(["d1", "d2", "d3"]), st.none(), st.just("")), - max_size=12, - ) + Given: + A document whose donors list repeats one uuid around a second. + When: + transform_file_to_cfdb runs. + Then: + The collection should carry one subject per distinct donor, in + first-occurrence order. + """ + # Arrange + donors = [ + {"entity_type": "Donor", "uuid": "donor-1"}, + {"entity_type": "Donor", "uuid": "donor-1"}, + {"entity_type": "Donor", "uuid": "donor-2"}, + {"entity_type": "Donor", "uuid": "donor-1"}, + ] + + # Act + doc = _transform(_file_doc(donors=donors)) + + # Assert + subjects = doc["collections"][0]["subjects"] + assert [s["local_id"] for s in subjects] == ["donor-1", "donor-2"] + + +@given( + uuids=st.lists( + st.one_of(st.sampled_from(["d1", "d2", "d3"]), st.none(), st.just("")), + max_size=12, ) - @settings(max_examples=50) - def test_transform_file_to_cfdb_should_emit_each_donor_once(self, uuids): - """Test subjects are the distinct donors, whatever the repetition. - - Given: - Any donors list drawn from a small uuid pool, with repeats and - blank or missing uuids mixed in. - When: - transform_file_to_cfdb runs. - Then: - Subject local_ids should equal the distinct non-blank uuids in - first-occurrence order. - """ - # Arrange - donors = [{"entity_type": "Donor", "uuid": uuid} for uuid in uuids] - expected = list(dict.fromkeys(uuid for uuid in uuids if uuid)) +) +@settings(max_examples=50) +def test_transform_file_to_cfdb_should_emit_each_donor_once(uuids): + """Test subjects are the distinct donors, whatever the repetition. + + Given: + Any donors list drawn from a small uuid pool, with repeats and + blank or missing uuids mixed in. + When: + transform_file_to_cfdb runs. + Then: + Subject local_ids should equal the distinct non-blank uuids in + first-occurrence order. + """ + # Arrange + donors = [{"entity_type": "Donor", "uuid": uuid} for uuid in uuids] + expected = list(dict.fromkeys(uuid for uuid in uuids if uuid)) + + # Act + doc = _transform(_file_doc(donors=donors)) + + # Assert + subjects = doc["collections"][0]["subjects"] + assert [s["local_id"] for s in subjects] == expected + + +@pytest.mark.parametrize( + ("raw", "expected"), + [ + ("True", True), + ("False", False), + (" false ", False), + (True, True), + (False, False), + ], +) +def test_transform_file_to_cfdb_should_parse_is_data_product_flags( + raw, expected +): + """Test the index's stringly-typed flag lands as a real bool. + + The index serializes is_data_product as "True"/"False", so a + truthiness test would read "False" as true. + + Given: + A document whose is_data_product is one of the recognized + spellings. + When: + transform_file_to_cfdb runs. + Then: + extra.hubmap.is_data_product should be the matching bool. + """ + # Act + doc = _transform(_file_doc(is_data_product=raw)) + + # Assert + assert doc["extra"]["hubmap"]["is_data_product"] is expected + + +@pytest.mark.parametrize("raw", [None, "yes", "", 1]) +def test_transform_file_to_cfdb_should_omit_is_data_product_when_unrecognized( + raw +): + """Test an unrecognized flag reads as unknown, not as false. + + Given: + A document whose is_data_product is missing or neither + recognized spelling. + When: + transform_file_to_cfdb runs. + Then: + extra.hubmap should carry no is_data_product key at all. + """ + # Act + doc = _transform(_file_doc(is_data_product=raw)) - # Act - doc = _transform(_file_doc(donors=donors)) - - # Assert - subjects = doc["collections"][0]["subjects"] - assert [s["local_id"] for s in subjects] == expected - - @pytest.mark.parametrize( - ("raw", "expected"), - [ - ("True", True), - ("False", False), - (" false ", False), - (True, True), - (False, False), - ], + # Assert + assert "is_data_product" not in doc["extra"]["hubmap"] + + +def test_transform_file_to_cfdb_should_omit_is_data_product_when_absent(): + """Test a document without the flag stays unknown. + + A third of the live allowlisted files carry no is_data_product, and + defaulting them to false would fabricate a fact. + + Given: + A document with no is_data_product key. + When: + transform_file_to_cfdb runs. + Then: + extra.hubmap should carry no is_data_product key. + """ + # Arrange + src = _file_doc() + src.pop("is_data_product", None) + + # Act + doc = _transform(src) + + # Assert + assert "is_data_product" not in doc["extra"]["hubmap"] + + +@pytest.mark.asyncio +async def test_fetch_file_metadata_should_paginate_with_search_after( + mocker +): + """Test the walk carries each page's sort key into the next request. + + Given: + Two pages of file documents. + When: + fetch_file_metadata drains the stream. + Then: + It should yield every document and send the second request with + the first page's last sort value as search_after. + """ + # Arrange + session = _SearchSession( + pages=[ + _page(_file_doc(file_uuid="aaa"), _file_doc(file_uuid="bbb")), + _page(_file_doc(file_uuid="ccc")), + ] + ) + mocker.patch.object( + hubmap_module.aiohttp, "ClientSession", return_value=session ) - def test_transform_file_to_cfdb_should_parse_is_data_product_flags( - self, raw, expected - ): - """Test the index's stringly-typed flag lands as a real bool. - - The index serializes is_data_product as "True"/"False", so a - truthiness test would read "False" as true. - - Given: - A document whose is_data_product is one of the recognized - spellings. - When: - transform_file_to_cfdb runs. - Then: - extra.hubmap.is_data_product should be the matching bool. - """ - # Act - doc = _transform(_file_doc(is_data_product=raw)) - # Assert - assert doc["extra"]["hubmap"]["is_data_product"] is expected + # Act + docs = [doc async for doc in fetch_file_metadata((".h5ad",))] - @pytest.mark.parametrize("raw", [None, "yes", "", 1]) - def test_transform_file_to_cfdb_should_omit_is_data_product_when_unrecognized( - self, raw - ): - """Test an unrecognized flag reads as unknown, not as false. - - Given: - A document whose is_data_product is missing or neither - recognized spelling. - When: - transform_file_to_cfdb runs. - Then: - extra.hubmap should carry no is_data_product key at all. - """ - # Act - doc = _transform(_file_doc(is_data_product=raw)) + # Assert + assert [doc["file_uuid"] for doc in docs] == ["aaa", "bbb", "ccc"] + assert "search_after" not in session.post_bodies[0] + assert session.post_bodies[1]["search_after"] == ["bbb"] - # Assert - assert "is_data_product" not in doc["extra"]["hubmap"] - def test_transform_file_to_cfdb_should_omit_is_data_product_when_absent(self): - """Test a document without the flag stays unknown. +@pytest.mark.asyncio +async def test_fetch_file_metadata_should_filter_extensions_server_side( + mocker +): + """Test the allowlist becomes a terms filter in the request body. - A third of the live allowlisted files carry no is_data_product, and - defaulting them to false would fabricate a fact. + Excluding 9.7M microscopy tiles client-side would stream them all; + the filter has to ride the query. - Given: - A document with no is_data_product key. - When: - transform_file_to_cfdb runs. - Then: - extra.hubmap should carry no is_data_product key. - """ - # Arrange - src = _file_doc() - src.pop("is_data_product", None) + Given: + A two-extension allowlist. + When: + fetch_file_metadata issues its first request. + Then: + The body should carry a terms filter on file_extension.keyword + with exactly those values. + """ + # Arrange + session = _SearchSession() + mocker.patch.object( + hubmap_module.aiohttp, "ClientSession", return_value=session + ) - # Act - doc = _transform(src) + # Act + [doc async for doc in fetch_file_metadata((".h5ad", ".bcf"))] - # Assert - assert "is_data_product" not in doc["extra"]["hubmap"] + # Assert + assert session.post_bodies[0]["query"] == { + "terms": {"file_extension.keyword": [".h5ad", ".bcf"]} + } -class TestFetchFileMetadata: - @pytest.mark.asyncio - async def test_fetch_file_metadata_should_paginate_with_search_after( - self, mocker - ): - """Test the walk carries each page's sort key into the next request. - - Given: - Two pages of file documents. - When: - fetch_file_metadata drains the stream. - Then: - It should yield every document and send the second request with - the first page's last sort value as search_after. - """ - # Arrange - session = _SearchSession( - pages=[ - _page(_file_doc(file_uuid="aaa"), _file_doc(file_uuid="bbb")), - _page(_file_doc(file_uuid="ccc")), - ] - ) - mocker.patch.object( - hubmap_module.aiohttp, "ClientSession", return_value=session - ) +@pytest.mark.asyncio +async def test_fetch_file_metadata_should_yield_nothing_when_allowlist_empty( + mocker +): + """Test the explicit-empty configuration never opens a request. - # Act - docs = [doc async for doc in fetch_file_metadata((".h5ad",))] + Given: + An empty allowlist. + When: + fetch_file_metadata is drained. + Then: + It should yield nothing and make no network request. + """ + # Arrange + session_factory = mocker.patch.object( + hubmap_module.aiohttp, "ClientSession" + ) - # Assert - assert [doc["file_uuid"] for doc in docs] == ["aaa", "bbb", "ccc"] - assert "search_after" not in session.post_bodies[0] - assert session.post_bodies[1]["search_after"] == ["bbb"] + # Act + docs = [doc async for doc in fetch_file_metadata(())] - @pytest.mark.asyncio - async def test_fetch_file_metadata_should_filter_extensions_server_side( - self, mocker - ): - """Test the allowlist becomes a terms filter in the request body. - - Excluding 9.7M microscopy tiles client-side would stream them all; - the filter has to ride the query. - - Given: - A two-extension allowlist. - When: - fetch_file_metadata issues its first request. - Then: - The body should carry a terms filter on file_extension.keyword - with exactly those values. - """ - # Arrange - session = _SearchSession() - mocker.patch.object( - hubmap_module.aiohttp, "ClientSession", return_value=session - ) + # Assert + assert docs == [] + session_factory.assert_not_called() - # Act - [doc async for doc in fetch_file_metadata((".h5ad", ".bcf"))] - # Assert - assert session.post_bodies[0]["query"] == { - "terms": {"file_extension.keyword": [".h5ad", ".bcf"]} - } +@pytest.mark.asyncio +async def test_fetch_file_metadata_should_raise_on_http_error(mocker): + """Test an upstream error fails the stream instead of truncating it. - @pytest.mark.asyncio - async def test_fetch_file_metadata_should_yield_nothing_when_allowlist_empty( - self, mocker - ): - """Test the explicit-empty configuration never opens a request. - - Given: - An empty allowlist. - When: - fetch_file_metadata is drained. - Then: - It should yield nothing and make no network request. - """ - # Arrange - session_factory = mocker.patch.object( - hubmap_module.aiohttp, "ClientSession" - ) + The loader clears before reloading, so a stream that quietly ended + early would silently shrink the corpus. - # Act - docs = [doc async for doc in fetch_file_metadata(())] - - # Assert - assert docs == [] - session_factory.assert_not_called() - - @pytest.mark.asyncio - async def test_fetch_file_metadata_should_raise_on_http_error(self, mocker): - """Test an upstream error fails the stream instead of truncating it. - - The loader clears before reloading, so a stream that quietly ended - early would silently shrink the corpus. - - Given: - A files search endpoint answering HTTP 503. - When: - fetch_file_metadata is drained. - Then: - It should raise rather than end the stream. - """ - # Arrange - session = _SearchSession(status=503) - mocker.patch.object( - hubmap_module.aiohttp, "ClientSession", return_value=session - ) - - # Act & assert - with pytest.raises(RuntimeError, match="HTTP 503"): - [doc async for doc in fetch_file_metadata((".h5ad",))] - - @pytest.mark.asyncio - async def test_fetch_file_metadata_should_request_is_data_product( - self, mocker - ): - """Test the requested source fields include the data-product flag. - - A field missing from _source never crosses the wire, so the - transform would see every file as flagless. - - Given: - An allowlist. - When: - fetch_file_metadata issues its first request. - Then: - The body's _source should name is_data_product. - """ - # Arrange - session = _SearchSession() - mocker.patch.object( - hubmap_module.aiohttp, "ClientSession", return_value=session - ) + Given: + A files search endpoint answering HTTP 503. + When: + fetch_file_metadata is drained. + Then: + It should raise rather than end the stream. + """ + # Arrange + session = _SearchSession(status=503) + mocker.patch.object( + hubmap_module.aiohttp, "ClientSession", return_value=session + ) - # Act + # Act & assert + with pytest.raises(RuntimeError, match="HTTP 503"): [doc async for doc in fetch_file_metadata((".h5ad",))] - # Assert - assert "is_data_product" in session.post_bodies[0]["_source"] - @pytest.mark.asyncio - async def test_fetch_file_metadata_should_raise_on_network_error( - self, mocker - ): - """Test a dropped connection fails the stream instead of ending it. - - Given: - A files search endpoint whose request raises a client error. - When: - fetch_file_metadata is drained. - Then: - The client error should propagate. - """ - # Arrange - session = _SearchSession(error=aiohttp.ClientError("reset")) - mocker.patch.object( - hubmap_module.aiohttp, "ClientSession", return_value=session - ) - - # Act & assert - with pytest.raises(aiohttp.ClientError, match="reset"): - [doc async for doc in fetch_file_metadata((".h5ad",))] - - @pytest.mark.asyncio - async def test_fetch_file_metadata_should_stop_when_a_page_has_no_sort( - self, mocker - ): - """Test a page without a sort cursor ends the walk. - - Without a cursor there is nothing to resume from; re-sending the - query would re-serve the same page forever. - - Given: - A page whose last hit carries no sort value. - When: - fetch_file_metadata is drained. - Then: - It should yield that page and issue no second request. - """ - # Arrange - session = _SearchSession( - pages=[{"hits": {"hits": [{"_source": _file_doc()}]}}] - ) - mocker.patch.object( - hubmap_module.aiohttp, "ClientSession", return_value=session - ) +@pytest.mark.asyncio +async def test_fetch_file_metadata_should_request_is_data_product( + mocker +): + """Test the requested source fields include the data-product flag. - # Act - docs = [doc async for doc in fetch_file_metadata((".h5ad",))] + A field missing from _source never crosses the wire, so the + transform would see every file as flagless. - # Assert - assert len(docs) == 1 - assert len(session.post_bodies) == 1 + Given: + An allowlist. + When: + fetch_file_metadata issues its first request. + Then: + The body's _source should name is_data_product. + """ + # Arrange + session = _SearchSession() + mocker.patch.object( + hubmap_module.aiohttp, "ClientSession", return_value=session + ) + # Act + [doc async for doc in fetch_file_metadata((".h5ad",))] -class TestFetchDatasetMetadataBulk: - @pytest.mark.asyncio - async def test_fetch_dataset_metadata_bulk_should_key_results_by_uuid( - self, mocker - ): - """Test the map joins against what the files index actually carries. - - The files index names a parent dataset only by dataset_uuid, so a - map keyed any other way (the retired doi_url keying) cannot be - joined against it. - - Given: - One dataset document with donor metadata and a workflow - description naming hg38. - When: - fetch_dataset_metadata_bulk drains the index. - Then: - The entry should sit under the dataset uuid with the donor - fields and the canonicalized assembly. - """ - # Arrange - src = { - "uuid": "ds-uuid-1", - "pipeline": "Salmon", - "donor": {"uuid": "donor-1", "mapped_metadata": {"sex": ["F"]}}, - "ingest_metadata": {"workflow_description": "aligned to hg38"}, - } - session = _SearchSession(pages=[_page(src, sort_key="uuid")]) - mocker.patch.object( - hubmap_module.aiohttp, "ClientSession", return_value=session - ) + # Assert + assert "is_data_product" in session.post_bodies[0]["_source"] - # Act - results = await fetch_dataset_metadata_bulk() - - # Assert - assert set(results) == {"ds-uuid-1"} - entry = results["ds-uuid-1"] - assert entry["pipeline"] == "Salmon" - assert entry["donor_uuid"] == "donor-1" - assert entry["donor_metadata"] == {"sex": ["F"]} - assert entry["genome_assembly"] == "GRCh38" - - @pytest.mark.asyncio - async def test_fetch_dataset_metadata_bulk_should_raise_on_http_error( - self, mocker - ): - """Test a partial dataset map is refused rather than returned. - - A silently partial map would mean silently under-enriched - documents behind a clear-before-reload. - - Given: - A dataset search endpoint answering HTTP 502. - When: - fetch_dataset_metadata_bulk runs. - Then: - It should raise rather than return what it fetched so far. - """ - # Arrange - session = _SearchSession(status=502) - mocker.patch.object( - hubmap_module.aiohttp, "ClientSession", return_value=session - ) - - # Act & assert - with pytest.raises(RuntimeError, match="HTTP 502"): - await fetch_dataset_metadata_bulk() - - @pytest.mark.asyncio - async def test_fetch_dataset_metadata_bulk_should_skip_hits_without_uuid( - self, mocker - ): - """Test unkeyable datasets are dropped and the rest keep their context. - - Given: - One dataset hit with no uuid and one carrying vitessce-hints - and assay metadata. - When: - fetch_dataset_metadata_bulk drains the index. - Then: - Only the keyed dataset should be returned, with vitessce-hints - under vitessce_hints and the metadata dict intact. - """ - # Arrange - keyed = { - "uuid": "ds-uuid-1", - "vitessce-hints": ["is_sc", "rna"], - "metadata": {"assay_category": "sequence"}, - } - session = _SearchSession( - pages=[_page({"pipeline": "Salmon"}, keyed, sort_key="uuid")] - ) - mocker.patch.object( - hubmap_module.aiohttp, "ClientSession", return_value=session - ) - # Act - results = await fetch_dataset_metadata_bulk() +@pytest.mark.asyncio +async def test_fetch_file_metadata_should_raise_on_network_error( + mocker +): + """Test a dropped connection fails the stream instead of ending it. - # Assert - assert set(results) == {"ds-uuid-1"} - assert results["ds-uuid-1"]["vitessce_hints"] == ["is_sc", "rna"] - assert results["ds-uuid-1"]["metadata"] == {"assay_category": "sequence"} + Given: + A files search endpoint whose request raises a client error. + When: + fetch_file_metadata is drained. + Then: + The client error should propagate. + """ + # Arrange + session = _SearchSession(error=aiohttp.ClientError("reset")) + mocker.patch.object( + hubmap_module.aiohttp, "ClientSession", return_value=session + ) - @pytest.mark.asyncio - async def test_fetch_dataset_metadata_bulk_should_raise_on_network_error( - self, mocker - ): - """Test a dropped connection refuses the partial map. - - Given: - A dataset search endpoint whose request raises a client error. - When: - fetch_dataset_metadata_bulk runs. - Then: - The client error should propagate. - """ - # Arrange - session = _SearchSession(error=aiohttp.ClientError("reset")) - mocker.patch.object( - hubmap_module.aiohttp, "ClientSession", return_value=session - ) - - # Act & assert - with pytest.raises(aiohttp.ClientError, match="reset"): - await fetch_dataset_metadata_bulk() - - @pytest.mark.asyncio - async def test_fetch_dataset_metadata_bulk_should_stop_when_a_page_has_no_sort( - self, mocker - ): - """Test a page without a sort cursor ends the walk. - - Given: - A page whose last hit carries no sort value. - When: - fetch_dataset_metadata_bulk runs. - Then: - It should return that page's dataset after a single request. - """ - # Arrange - session = _SearchSession( - pages=[{"hits": {"hits": [{"_source": {"uuid": "ds-uuid-1"}}]}}] - ) - mocker.patch.object( - hubmap_module.aiohttp, "ClientSession", return_value=session - ) + # Act & assert + with pytest.raises(aiohttp.ClientError, match="reset"): + [doc async for doc in fetch_file_metadata((".h5ad",))] - # Act - results = await fetch_dataset_metadata_bulk() - # Assert - assert set(results) == {"ds-uuid-1"} - assert len(session.post_bodies) == 1 +@pytest.mark.asyncio +async def test_fetch_file_metadata_should_stop_when_a_page_has_no_sort( + mocker +): + """Test a page without a sort cursor ends the walk. + Without a cursor there is nothing to resume from; re-sending the + query would re-serve the same page forever. -class TestFetchOrganMap: - @pytest.mark.asyncio - async def test_fetch_organ_map_should_key_uberon_terms_by_rui_code( - self, mocker - ): - """Test the UBKG payload becomes a code-keyed UBERON lookup. - - Given: - A UBKG organs payload with one complete entry and one missing - its UBERON id. - When: - fetch_organ_map runs. - Then: - Only the complete entry should be mapped. - """ - # Arrange - payload = [ - {"rui_code": "TH", "term": "Thymus", "organ_uberon": "UBERON:0002370"}, - {"rui_code": "XX", "term": "No Uberon", "organ_uberon": None}, - ] - session = _OrganSession(payload=payload) - mocker.patch.object( - hubmap_module.aiohttp, "ClientSession", return_value=session - ) + Given: + A page whose last hit carries no sort value. + When: + fetch_file_metadata is drained. + Then: + It should yield that page and issue no second request. + """ + # Arrange + session = _SearchSession( + pages=[{"hits": {"hits": [{"_source": _file_doc()}]}}] + ) + mocker.patch.object( + hubmap_module.aiohttp, "ClientSession", return_value=session + ) - # Act + # Act + docs = [doc async for doc in fetch_file_metadata((".h5ad",))] + + # Assert + assert len(docs) == 1 + assert len(session.post_bodies) == 1 + + +@pytest.mark.asyncio +async def test_fetch_dataset_metadata_bulk_should_key_results_by_uuid( + mocker +): + """Test the map joins against what the files index actually carries. + + The files index names a parent dataset only by dataset_uuid, so a + map keyed any other way (the retired doi_url keying) cannot be + joined against it. + + Given: + One dataset document with donor metadata and a workflow + description naming hg38. + When: + fetch_dataset_metadata_bulk drains the index. + Then: + The entry should sit under the dataset uuid with the donor + fields and the canonicalized assembly. + """ + # Arrange + src = { + "uuid": "ds-uuid-1", + "pipeline": "Salmon", + "donor": {"uuid": "donor-1", "mapped_metadata": {"sex": ["F"]}}, + "ingest_metadata": {"workflow_description": "aligned to hg38"}, + } + session = _SearchSession(pages=[_page(src, sort_key="uuid")]) + mocker.patch.object( + hubmap_module.aiohttp, "ClientSession", return_value=session + ) + + # Act + results = await fetch_dataset_metadata_bulk() + + # Assert + assert set(results) == {"ds-uuid-1"} + entry = results["ds-uuid-1"] + assert entry["pipeline"] == "Salmon" + assert entry["donor_uuid"] == "donor-1" + assert entry["donor_metadata"] == {"sex": ["F"]} + assert entry["genome_assembly"] == "GRCh38" + + +@pytest.mark.asyncio +async def test_fetch_dataset_metadata_bulk_should_raise_on_http_error( + mocker +): + """Test a partial dataset map is refused rather than returned. + + A silently partial map would mean silently under-enriched + documents behind a clear-before-reload. + + Given: + A dataset search endpoint answering HTTP 502. + When: + fetch_dataset_metadata_bulk runs. + Then: + It should raise rather than return what it fetched so far. + """ + # Arrange + session = _SearchSession(status=502) + mocker.patch.object( + hubmap_module.aiohttp, "ClientSession", return_value=session + ) + + # Act & assert + with pytest.raises(RuntimeError, match="HTTP 502"): + await fetch_dataset_metadata_bulk() + + +@pytest.mark.asyncio +async def test_fetch_dataset_metadata_bulk_should_skip_hits_without_uuid( + mocker +): + """Test unkeyable datasets are dropped and the rest keep their context. + + Given: + One dataset hit with no uuid and one carrying vitessce-hints + and assay metadata. + When: + fetch_dataset_metadata_bulk drains the index. + Then: + Only the keyed dataset should be returned, with vitessce-hints + under vitessce_hints and the metadata dict intact. + """ + # Arrange + keyed = { + "uuid": "ds-uuid-1", + "vitessce-hints": ["is_sc", "rna"], + "metadata": {"assay_category": "sequence"}, + } + session = _SearchSession( + pages=[_page({"pipeline": "Salmon"}, keyed, sort_key="uuid")] + ) + mocker.patch.object( + hubmap_module.aiohttp, "ClientSession", return_value=session + ) + + # Act + results = await fetch_dataset_metadata_bulk() + + # Assert + assert set(results) == {"ds-uuid-1"} + assert results["ds-uuid-1"]["vitessce_hints"] == ["is_sc", "rna"] + assert results["ds-uuid-1"]["metadata"] == {"assay_category": "sequence"} + + +@pytest.mark.asyncio +async def test_fetch_dataset_metadata_bulk_should_raise_on_network_error( + mocker +): + """Test a dropped connection refuses the partial map. + + Given: + A dataset search endpoint whose request raises a client error. + When: + fetch_dataset_metadata_bulk runs. + Then: + The client error should propagate. + """ + # Arrange + session = _SearchSession(error=aiohttp.ClientError("reset")) + mocker.patch.object( + hubmap_module.aiohttp, "ClientSession", return_value=session + ) + + # Act & assert + with pytest.raises(aiohttp.ClientError, match="reset"): + await fetch_dataset_metadata_bulk() + + +@pytest.mark.asyncio +async def test_fetch_dataset_metadata_bulk_should_stop_when_a_page_has_no_sort( + mocker +): + """Test a page without a sort cursor ends the walk. + + Given: + A page whose last hit carries no sort value. + When: + fetch_dataset_metadata_bulk runs. + Then: + It should return that page's dataset after a single request. + """ + # Arrange + session = _SearchSession( + pages=[{"hits": {"hits": [{"_source": {"uuid": "ds-uuid-1"}}]}}] + ) + mocker.patch.object( + hubmap_module.aiohttp, "ClientSession", return_value=session + ) + + # Act + results = await fetch_dataset_metadata_bulk() + + # Assert + assert set(results) == {"ds-uuid-1"} + assert len(session.post_bodies) == 1 + + +@pytest.mark.asyncio +async def test_fetch_organ_map_should_key_uberon_terms_by_rui_code( + mocker +): + """Test the UBKG payload becomes a code-keyed UBERON lookup. + + Given: + A UBKG organs payload with one complete entry and one missing + its UBERON id. + When: + fetch_organ_map runs. + Then: + Only the complete entry should be mapped. + """ + # Arrange + payload = [ + {"rui_code": "TH", "term": "Thymus", "organ_uberon": "UBERON:0002370"}, + {"rui_code": "XX", "term": "No Uberon", "organ_uberon": None}, + ] + session = _OrganSession(payload=payload) + mocker.patch.object( + hubmap_module.aiohttp, "ClientSession", return_value=session + ) + + # Act + organ_map = await fetch_organ_map() + + # Assert + assert organ_map == {"TH": {"id": "UBERON:0002370", "name": "Thymus"}} + + +@pytest.mark.asyncio +async def test_fetch_organ_map_should_return_empty_and_warn_on_failure( + mocker, caplog +): + """Test a UBKG outage degrades anatomy instead of failing the sync. + + Given: + A UBKG endpoint that raises a client error. + When: + fetch_organ_map runs. + Then: + It should return an empty map and log a warning. + """ + # Arrange + session = _OrganSession(error=aiohttp.ClientError("down")) + mocker.patch.object( + hubmap_module.aiohttp, "ClientSession", return_value=session + ) + + # Act + with caplog.at_level("WARNING"): organ_map = await fetch_organ_map() - # Assert - assert organ_map == {"TH": {"id": "UBERON:0002370", "name": "Thymus"}} + # Assert + assert organ_map == {} + assert any("UBKG" in record.message for record in caplog.records) - @pytest.mark.asyncio - async def test_fetch_organ_map_should_return_empty_and_warn_on_failure( - self, mocker, caplog - ): - """Test a UBKG outage degrades anatomy instead of failing the sync. - - Given: - A UBKG endpoint that raises a client error. - When: - fetch_organ_map runs. - Then: - It should return an empty map and log a warning. - """ - # Arrange - session = _OrganSession(error=aiohttp.ClientError("down")) - mocker.patch.object( - hubmap_module.aiohttp, "ClientSession", return_value=session - ) - # Act - with caplog.at_level("WARNING"): - organ_map = await fetch_organ_map() +@pytest.mark.asyncio +async def test_fetch_organ_map_should_return_empty_and_warn_on_http_error( + mocker, caplog +): + """Test a UBKG error status degrades anatomy like an outage does. - # Assert - assert organ_map == {} - assert any("UBKG" in record.message for record in caplog.records) + Given: + A UBKG endpoint answering HTTP 500. + When: + fetch_organ_map runs. + Then: + It should return an empty map and log a warning naming UBKG. + """ + # Arrange + session = _OrganSession(status=500) + mocker.patch.object( + hubmap_module.aiohttp, "ClientSession", return_value=session + ) - @pytest.mark.asyncio - async def test_fetch_organ_map_should_return_empty_and_warn_on_http_error( - self, mocker, caplog - ): - """Test a UBKG error status degrades anatomy like an outage does. - - Given: - A UBKG endpoint answering HTTP 500. - When: - fetch_organ_map runs. - Then: - It should return an empty map and log a warning naming UBKG. - """ - # Arrange - session = _OrganSession(status=500) - mocker.patch.object( - hubmap_module.aiohttp, "ClientSession", return_value=session - ) + # Act + with caplog.at_level("WARNING"): + organ_map = await fetch_organ_map() - # Act - with caplog.at_level("WARNING"): - organ_map = await fetch_organ_map() - - # Assert - assert organ_map == {} - assert any("HTTP 500" in record.message for record in caplog.records) - - -class TestBuildHubmapDccRecord: - def test_build_hubmap_dcc_record_should_carry_the_static_dcc_fields(self): - """Test the DCC record names HuBMAP under its registry id. - - Given: - The static HuBMAP configuration. - When: - build_hubmap_dcc_record runs. - Then: - The record should carry the submission, registry id, labels, - and project namespace fields the dcc collection expects. - """ - # Act - record = build_hubmap_dcc_record() - - # Assert - assert record["submission"] == "hubmap" - assert record["id"] == "cfde_registry_dcc:hubmap" - assert record["dcc_abbreviation"] == "HuBMAP" - assert record["dcc_url"] == "https://hubmapconsortium.org" - assert record["project_id_namespace"] == "https://hubmapconsortium.org" - assert record["project_local_id"] == "HuBMAP" + # Assert + assert organ_map == {} + assert any("HTTP 500" in record.message for record in caplog.records) + + +def test_build_hubmap_dcc_record_should_carry_the_static_dcc_fields(): + """Test the DCC record names HuBMAP under its registry id. + + Given: + The static HuBMAP configuration. + When: + build_hubmap_dcc_record runs. + Then: + The record should carry the submission, registry id, labels, + and project namespace fields the dcc collection expects. + """ + # Act + record = build_hubmap_dcc_record() + + # Assert + assert record["submission"] == "hubmap" + assert record["id"] == "cfde_registry_dcc:hubmap" + assert record["dcc_abbreviation"] == "HuBMAP" + assert record["dcc_url"] == "https://hubmapconsortium.org" + assert record["project_id_namespace"] == "https://hubmapconsortium.org" + assert record["project_local_id"] == "HuBMAP" From 663520d83d3cf97395faeba5010fa637f8ded721 Mon Sep 17 00:00:00 2001 From: Conrad Date: Fri, 20 Nov 2026 17:03:59 -0500 Subject: [PATCH 10/37] fix: Stream direct HTTPS access URLs without DRS resolution 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. --- src/cfdb/api/routers/data.py | 36 +++++++--- src/cfdb/workflows/urlsafe.py | 6 +- tests/test_data.py | 131 ++++++++++++++++++++++++++++++---- 3 files changed, 145 insertions(+), 28 deletions(-) diff --git a/src/cfdb/api/routers/data.py b/src/cfdb/api/routers/data.py index 1759947..bde532d 100644 --- a/src/cfdb/api/routers/data.py +++ b/src/cfdb/api/routers/data.py @@ -30,6 +30,7 @@ DRSUpstreamError, ) from cfdb.workflows.models import ArtifactKind +from cfdb.workflows.urlsafe import UnsafeOutboundURL, validate_outbound_url logger = logging.getLogger(__name__) @@ -149,9 +150,13 @@ async def stream_file( if workflow_response is not None: return workflow_response - # ENCODE files: Stream directly via HTTPS (bypass DRS) - if normalized_dcc == "encode": - return await _stream_encode_file(file_metadata, request, range) + # Direct URLs -- ENCODE downloads, HuBMAP assets -- stream as-is; + # only a drs:// URI needs a DRS broker to resolve it first. The + # split is by scheme rather than by DCC, the same one + # ``resolve_download_url`` makes for the workers, so a DCC whose + # access_url changes shape cannot fall into the wrong branch. + if not file_metadata.access_url.startswith("drs://"): + return await _stream_direct_url(file_metadata, request, range) # 6. Fetch DRS object metadata try: @@ -311,16 +316,18 @@ async def stream_file_status( ) -async def _stream_encode_file( +async def _stream_direct_url( file_metadata: _FileRef, request: Request, range_header: Optional[str] = None, ): """ - Stream ENCODE file directly via HTTPS. + Stream a file whose access URL is directly fetchable over HTTPS. - ENCODE files are publicly accessible and don't require DRS resolution. - We stream directly from the ENCODE download URL. + ENCODE download URLs and HuBMAP assets URLs need no DRS resolution. + The URL is checked against the outbound allowlist here, before the + response starts, so a disallowed DB-sourced URL is refused with a 502 + rather than failing inside a response that has already begun. Args: file_metadata: The file's access URL, filename, and size @@ -334,7 +341,16 @@ async def _stream_encode_file( filename = file_metadata.filename file_size = file_metadata.size_in_bytes - logger.info(f"Streaming ENCODE file: {filename} from {download_url}") + try: + validate_outbound_url(download_url) + except UnsafeOutboundURL as e: + logger.warning("Refusing direct file fetch: %s", e) + raise HTTPException( + status_code=status.HTTP_502_BAD_GATEWAY, + detail="Upstream URL failed allowlist validation", + ) + + logger.info(f"Streaming file directly: {filename} from {download_url}") # Determine media type from filename; default to binary. (Branches # that resolve to the default are folded away.) @@ -356,8 +372,8 @@ async def _stream_encode_file( except HTTPException: raise except Exception as e: - logger.error(f"ENCODE streaming error: {str(e)}") - raise HTTPException(status_code=502, detail="Failed to stream ENCODE file") + logger.error(f"Direct streaming error: {str(e)}") + raise HTTPException(status_code=502, detail="Failed to stream file") async def _try_serve_workflow_artifact( diff --git a/src/cfdb/workflows/urlsafe.py b/src/cfdb/workflows/urlsafe.py index daec615..b3a327d 100644 --- a/src/cfdb/workflows/urlsafe.py +++ b/src/cfdb/workflows/urlsafe.py @@ -47,9 +47,9 @@ "encode-public.s3.amazonaws.com", # HuBMAP public assets. "assets.hubmapconsortium.org", - # HuBMAP DRS broker (GA4GH DRS metadata API that every HuBMAP - # ``access_url`` resolves through before bytes flow from - # assets.hubmapconsortium.org above). + # HuBMAP DRS broker (GA4GH DRS metadata API). HuBMAP documents now + # carry assets URLs directly, so nothing current resolves through it; + # kept for documents loaded before the files-index loader. "drs.hubmapconsortium.org", ) diff --git a/tests/test_data.py b/tests/test_data.py index 869a3ed..370f85c 100644 --- a/tests/test_data.py +++ b/tests/test_data.py @@ -10,6 +10,7 @@ from wool.runtime.routine.task import do_dispatch from cfdb import api +from cfdb.api.routers import data as data_module from cfdb.api.routers.data import stream_file, stream_file_status from cfdb.services import drs, locks from cfdb.services.ontology_mappings import get_file_format @@ -33,16 +34,25 @@ def __init__(self): def _make_dcc_doc() -> dict: return { "dcc_abbreviation": "HuBMAP", - "project_id_namespace": "tag:hubmapconsortium.org,2023:", + "project_id_namespace": "https://hubmapconsortium.org", } +#: The assets URL the files-index loader writes for ``_make_file_doc``. +HUBMAP_ASSETS_URL = ( + "https://assets.hubmapconsortium.org/ds-uuid-1/" + "processed/secondary_analysis.h5ad" +) + + def _make_file_doc(*, access_level: str = "public") -> dict: + """Build a HuBMAP file document in the shape the files-index loader writes.""" return { - "id_namespace": "tag:hubmapconsortium.org,2023:", + "id_namespace": "https://hubmapconsortium.org", "local_id": "file-1", - "filename": "data.bam", - "access_url": "drs://drs.hubmapconsortium.org/abc", + "filename": "secondary_analysis.h5ad", + "size_in_bytes": 5529765, + "access_url": HUBMAP_ASSETS_URL, "data_access_level": access_level, "submission": "hubmap", } @@ -68,27 +78,118 @@ async def test_non_public_file_returns_403(self, mock_db, mocker): assert "consortium" in exc_info.value.detail @pytest.mark.asyncio - async def test_public_file_proceeds_past_access_check(self, mock_db, mocker): - """ - GIVEN a public HuBMAP file in the database - WHEN stream_file is called - THEN the access check passes (no 403) and execution continues to DRS + async def test_stream_file_should_stream_a_hubmap_assets_url_directly( + self, mock_db, mocker + ): + """Test a public HuBMAP file streams from its assets URL. + + The loader stores an https assets URL rather than a drs:// URI, so + routing HuBMAP through DRS resolution answered 400 for every file. + + Given: + A public HuBMAP h5ad document carrying an assets access_url and + no workflow subsystem. + When: + stream_file is called for it. + Then: + It should stream the assets URL directly and never consult DRS. """ + # Arrange mocker.patch.object(locks, "wait_for_cutover", return_value=None) + mocker.patch.object(api, "processor_registry", None) + mock_db.dcc.docs = [_make_dcc_doc()] + mock_db.file.docs = [_make_file_doc()] + fetch_drs = mocker.patch.object(drs, "fetch_drs_object") + stream = mocker.patch.object( + data_module, "stream_upstream_url", return_value="streamed" + ) + # Act + response = await stream_file( + "hubmap", "file-1", _make_request(), range=None + ) + + # Assert + assert response == "streamed" + assert stream.call_args.args[0] == HUBMAP_ASSETS_URL + fetch_drs.assert_not_called() + + @pytest.mark.asyncio + async def test_stream_file_should_stream_a_hubmap_assets_url_when_raw( + self, mock_db, mocker + ): + """Test a raw request for a processable HuBMAP file streams upstream. + + Given: + A public HuBMAP BED document carrying an assets access_url, a + registered processor for it, and raw=True. + When: + stream_file is called for it. + Then: + It should skip the workflow and stream the assets URL directly. + """ + # Arrange + mocker.patch.object(locks, "wait_for_cutover", return_value=None) + mocker.patch.object(api, "processor_registry", default_registry()) + bed_url = "https://assets.hubmapconsortium.org/ds-uuid-1/peaks.bed" + doc = _make_file_doc() + doc.update( + filename="peaks.bed", + access_url=bed_url, + file_format=get_file_format("bed"), + md5=FIXTURE_MD5, + ) mock_db.dcc.docs = [_make_dcc_doc()] - mock_db.file.docs = [_make_file_doc(access_level="public")] + mock_db.file.docs = [doc] + fetch_drs = mocker.patch.object(drs, "fetch_drs_object") + stream = mocker.patch.object( + data_module, "stream_upstream_url", return_value="streamed" + ) - # Let it fail at DRS resolution (proves it passed the access check) - mocker.patch.object( - drs, "fetch_drs_object", side_effect=Exception("DRS unavailable") + # Act + response = await stream_file( + "hubmap", "file-1", _make_request(), range=None, raw=True ) + # Assert + assert response == "streamed" + assert stream.call_args.args[0] == bed_url + fetch_drs.assert_not_called() + + @pytest.mark.asyncio + async def test_stream_file_should_raise_502_when_direct_url_disallowed( + self, mock_db, mocker + ): + """Test a direct URL outside the allowlist is refused up front. + + The URL comes from the database, so it is untrusted; refusing it + before the response starts gives a clean status rather than a + stream that fails after its headers were sent. + + Given: + A public HuBMAP document whose access_url names a host outside + the outbound allowlist. + When: + stream_file is called for it. + Then: + It should raise a 502 without streaming anything. + """ + # Arrange + mocker.patch.object(locks, "wait_for_cutover", return_value=None) + mocker.patch.object(api, "processor_registry", None) + doc = _make_file_doc() + doc["access_url"] = "https://attacker.example/secondary_analysis.h5ad" + mock_db.dcc.docs = [_make_dcc_doc()] + mock_db.file.docs = [doc] + stream = mocker.patch.object(data_module, "stream_upstream_url") + + # Act with pytest.raises(HTTPException) as exc_info: await stream_file("hubmap", "file-1", _make_request(), range=None) - # Should fail at DRS, not at access control - assert exc_info.value.status_code != 403 + # Assert + assert exc_info.value.status_code == 502 + stream.assert_not_called() class TestStreamFileWorkflowPath: From e4b50788fb9729d8b44c5bbad3b12dfab1050630 Mon Sep 17 00:00:00 2001 From: Conrad Date: Fri, 20 Nov 2026 17:04:24 -0500 Subject: [PATCH 11/37] fix: Harden the HuBMAP fetchers against what the live index serves 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. --- src/cfdb/services/hubmap.py | 304 +++++++++++++++++++++------ tests/test_hubmap.py | 403 ++++++++++++++++++++++++++++++++---- 2 files changed, 604 insertions(+), 103 deletions(-) diff --git a/src/cfdb/services/hubmap.py b/src/cfdb/services/hubmap.py index 14ab8de..033bd8f 100644 --- a/src/cfdb/services/hubmap.py +++ b/src/cfdb/services/hubmap.py @@ -112,6 +112,7 @@ from cfdb.services.encode import ( COMPRESSION_SUFFIX_TO_EDAM, UNMAPPABLE_COMPRESSION_SUFFIXES, + _timeout_from_env, derive_compression_format, ) from cfdb.services.ontology_mappings import get_file_format, get_taxonomy @@ -132,15 +133,17 @@ #: retrofitted later: the files index holds 9.9M documents and 98% of them #: are ``.tif`` microscopy tiles the API cannot serve meaningfully, so #: ingesting the extension space wholesale would grow the corpus ~11x with -#: dead weight. The default is the genomics + tabular tail of the live -#: distribution, ~53k files. +#: dead weight. The default is the genomics, tabular, and imaging-derived +#: table tail of the live distribution, ~52k files. _FILE_EXTENSIONS_ENV = "HUBMAP_FILE_EXTENSIONS" _FILE_EXTENSIONS_DEFAULT: tuple[str, ...] = ( ".h5ad", ".h5mu", ".h5", ".hdf5", - ".bcf", + # ".bcf" is deliberately absent: every .bcf in the index is a CODEX + # raw-acquisition sidecar (raw/Cyc1_reg1/1.bcf), not binary VCF, and + # ingesting them would label microscope files as variant calls. ".gz", ".mtx", ".arrow", @@ -164,10 +167,11 @@ def file_extensions_from_env() -> tuple[str, ...]: is sent to the search API matches the index's dot-prefixed ``file_extension`` values exactly. An unset variable yields the default allowlist; a variable set to an empty (or all-blank) value yields an - empty tuple, which ingests nothing — the same explicit-empty semantics - as ``ENCODE_ANNOTATION_TYPES``, and warned about for the same reason: - empty values arrive by accident routinely, and a silently empty corpus - shows up only as an absence. + empty tuple, on which the sync skips HuBMAP and leaves the existing + slice in place — the same outcome an empty ``ENCODE_ANNOTATION_TYPES`` + has for ENCODE's annotation phases — and which is warned about for the + same reason: empty values arrive by accident routinely, and a silently + skipped load shows up only as an absence. Repeats are collapsed, first occurrence winning, so a duplicated token cannot widen the server-side ``terms`` filter or reorder the logged @@ -187,8 +191,9 @@ def file_extensions_from_env() -> tuple[str, ...]: if not allowlist: logger.warning( - "%s is set but empty: no HuBMAP files will be ingested. Unset " - "it entirely to restore the default allowlist (%s).", + "%s is set but empty: the HuBMAP sync will be skipped and the " + "existing HuBMAP slice left in place. Unset it entirely to " + "restore the default allowlist (%s).", _FILE_EXTENSIONS_ENV, ", ".join(_FILE_EXTENSIONS_DEFAULT), ) @@ -261,6 +266,147 @@ def derive_file_format(filename: str) -> Optional[dict]: return get_file_format(base.rsplit(".", 1)[-1]) +#: Per-request timeout for one search page, in seconds. +_PAGE_TIMEOUT_SECONDS = 60 + +#: Attempts per search page before the failure is raised, and the base of +#: the linear backoff between them. A walk is ~54 sequential pages behind a +#: deferred clear, so one transient 5xx would otherwise cost the sync after +#: the old slice is gone; re-sending the same ``search_after`` page is +#: idempotent, which is what makes retrying safe. +_PAGE_ATTEMPTS = 3 +_RETRY_BACKOFF_SECONDS = 2.0 + +#: Upstream statuses worth retrying. Anything else is a request the server +#: will refuse again, so it is raised at once. +_RETRYABLE_STATUSES = frozenset({429, 500, 502, 503, 504}) + +#: Environment variable bounding the HuBMAP files stream, and its default. +#: The stream runs inside the cutover lock, which gates the whole read +#: surface, so it gets one deadline -- the reasoning ENCODE's metadata +#: budget records -- kept well under the sync lock's one-hour stale +#: threshold so a slow upstream cannot admit a second, clearing sync. +_SYNC_TIMEOUT_ENV = "HUBMAP_SYNC_TIMEOUT_SECONDS" +_SYNC_TIMEOUT_DEFAULT_SECONDS = 1800 + + +def sync_budget_seconds() -> int: + """Resolve the HuBMAP files-stream budget, in seconds. + + Read per call, like ENCODE's budget, so a malformed value fails the sync + that reads it rather than the import of this module. + """ + return _timeout_from_env(_SYNC_TIMEOUT_ENV, _SYNC_TIMEOUT_DEFAULT_SECONDS) + + +class _RetryablePageError(RuntimeError): + """A page failure that a fresh attempt at the same page may not repeat.""" + + +def _page_hits(data: object, label: str) -> list[dict]: + """Return a search response's hits, refusing a partial or malformed page. + + Elasticsearch answers 200 with whatever the healthy shards returned when + a shard fails or the query times out, and the walk would then resume + past documents it never received. A body with no hits envelope is + refused too: read as an empty page it would end the walk, which on the + first page means clearing the corpus and loading nothing. + """ + hits = data.get("hits") if isinstance(data, dict) else None + if not isinstance(hits, dict) or not isinstance(hits.get("hits"), list): + raise _RetryablePageError( + f"HuBMAP {label} search API returned a page with no hits envelope" + ) + if data.get("timed_out"): + raise _RetryablePageError( + f"HuBMAP {label} search timed out upstream; the page is partial" + ) + failed = (data.get("_shards") or {}).get("failed") or 0 + if failed: + raise _RetryablePageError( + f"HuBMAP {label} search had {failed} failed shard(s); the page " + "is partial" + ) + return hits["hits"] + + +async def _search_page( + session: aiohttp.ClientSession, + url: str, + query: dict, + label: str, + *, + deadline: float | None = None, +) -> list[dict]: + """POST one search page and return its hits, retrying transient failures. + + Transport errors, timeouts, retryable statuses, and partial or malformed + pages are retried up to ``_PAGE_ATTEMPTS`` times with linear backoff; + the last failure is raised. A non-retryable status raises at once. + + Args: + session: Open client session. + url: Search endpoint. + query: Elasticsearch request body, ``search_after`` included. + label: Names the index in log and error messages. + deadline: Event-loop clock reading by which the page must arrive. + Each attempt's timeout is clamped to what remains, and an + exhausted deadline raises ``asyncio.TimeoutError`` rather than + being retried -- aiohttp reads a non-positive total as "no + timeout", so passing a spent remainder through would turn the + budget into an unbounded request. + """ + loop = asyncio.get_running_loop() + for attempt in range(1, _PAGE_ATTEMPTS + 1): + timeout = float(_PAGE_TIMEOUT_SECONDS) + if deadline is not None: + remaining = deadline - loop.time() + if remaining <= 0: + raise asyncio.TimeoutError( + f"HuBMAP {label} fetch did not finish within the " + f"{_SYNC_TIMEOUT_ENV} budget" + ) + timeout = min(timeout, remaining) + + try: + async with session.post( + url, + json=query, + headers={"Content-Type": "application/json"}, + timeout=aiohttp.ClientTimeout(total=timeout), + ) as response: + if response.status != 200: + message = ( + f"HuBMAP {label} search API error: " + f"HTTP {response.status}" + ) + if response.status in _RETRYABLE_STATUSES: + raise _RetryablePageError(message) + raise RuntimeError(message) + try: + data = await response.json() + except ValueError as e: + raise _RetryablePageError( + f"HuBMAP {label} search API returned undecodable " + f"JSON: {e}" + ) from e + return _page_hits(data, label) + except (aiohttp.ClientError, asyncio.TimeoutError, _RetryablePageError) as e: + if attempt == _PAGE_ATTEMPTS: + logger.error( + f"HuBMAP {label} search page failed after {attempt} " + f"attempts: {e!r}" + ) + raise + logger.warning( + f"HuBMAP {label} search page failed (attempt {attempt} of " + f"{_PAGE_ATTEMPTS}): {e!r}; retrying" + ) + await asyncio.sleep(_RETRY_BACKOFF_SECONDS * attempt) + + raise AssertionError("unreachable: the last attempt returns or raises") + + # Fields to request from the dataset-level index. Only what the files index # cannot supply: per-dataset processing context, donor demographics, and the # free-text workflow description the genome assembly is extracted from. @@ -287,9 +433,10 @@ async def fetch_dataset_metadata_bulk() -> dict[str, dict]: transformation can join on the ``dataset_uuid`` every files-index document carries. - An HTTP or network error raises rather than returning the partial map: - the loader clears the HuBMAP slice before reloading, so a silently - partial dataset map would mean silently under-enriched documents. + Each page is retried on transient failure (see ``_search_page``); a + failure that outlasts the retries raises rather than returning the + partial map, since a silently partial map would mean silently + under-enriched documents. Returns: {dataset_uuid: {pipeline, processing, group_name, visualization, @@ -316,28 +463,10 @@ async def fetch_dataset_metadata_bulk() -> dict[str, dict]: if search_after is not None: query["search_after"] = search_after - try: - async with session.post( - search_url, - json=query, - headers={"Content-Type": "application/json"}, - timeout=aiohttp.ClientTimeout(total=60), - ) as response: - if response.status != 200: - raise RuntimeError( - f"HuBMAP dataset search API error: " - f"HTTP {response.status}" - ) - - data = await response.json() - - except aiohttp.ClientError as e: - logger.error(f"HuBMAP dataset search API network error: {e}") - raise + hits = await _search_page(session, search_url, query, "dataset") await asyncio.sleep(_REQUEST_INTERVAL) - hits = data.get("hits", {}).get("hits", []) if not hits: break @@ -419,6 +548,8 @@ async def fetch_dataset_metadata_bulk() -> dict[str, dict]: async def fetch_file_metadata( extensions: tuple[str, ...], + *, + deadline: float | None = None, ) -> AsyncGenerator[dict, None]: """ Stream file documents from the HuBMAP files search index. @@ -426,13 +557,26 @@ async def fetch_file_metadata( Uses ``search_after`` pagination on ``file_uuid.keyword`` in batches of 1000. When ``extensions`` is non-empty, the allowlist is applied server-side as a ``terms`` filter on ``file_extension.keyword``, so the - excluded 9.7M microscopy tiles never cross the wire. An empty allowlist - yields nothing — the explicit-empty configuration documented on + excluded 9.7M microscopy tiles never cross the wire. The query also + filters on ``data_access_level: public``: the index holds only public + files today, which is what retired the C2M2 path's pruning pass, and + the filter makes that an invariant of the load rather than an + assumption about a beta index. An empty allowlist yields nothing — the + explicit-empty configuration documented on :func:`file_extensions_from_env`. - Errors raise rather than ending the stream early, for the same reason - :func:`fetch_dataset_metadata_bulk` raises: a partial stream behind a - clear-before-reload would silently shrink the corpus. + Each page is retried on transient failure, and a partial page (failed + shards, an upstream timeout, a missing hits envelope) is refused rather + than walked past; see ``_search_page``. A failure that outlasts the + retries still raises mid-stream, and behind the loader's deferred clear + that leaves a partial slice -- loudly rather than silently, but only a + shadow-collection swap would make it atomic. + + Args: + extensions: Dot-prefixed, lower-case extension allowlist. + deadline: Event-loop clock reading by which the whole stream must + finish; each page's timeout is clamped to what remains. None + leaves only the per-page timeout. Yields: The ``_source`` dict of each matching file document. @@ -451,7 +595,14 @@ async def fetch_file_metadata( async with aiohttp.ClientSession() as session: while True: query: dict = { - "query": {"terms": {"file_extension.keyword": list(extensions)}}, + "query": { + "bool": { + "filter": [ + {"terms": {"file_extension.keyword": list(extensions)}}, + {"term": {"data_access_level.keyword": "public"}}, + ] + } + }, "size": page_size, "_source": _FILE_SOURCE_FIELDS, "sort": [{"file_uuid.keyword": "asc"}], @@ -460,28 +611,12 @@ async def fetch_file_metadata( if search_after is not None: query["search_after"] = search_after - try: - async with session.post( - search_url, - json=query, - headers={"Content-Type": "application/json"}, - timeout=aiohttp.ClientTimeout(total=60), - ) as response: - if response.status != 200: - raise RuntimeError( - f"HuBMAP files search API error: " - f"HTTP {response.status}" - ) - - data = await response.json() - - except aiohttp.ClientError as e: - logger.error(f"HuBMAP files search API network error: {e}") - raise + hits = await _search_page( + session, search_url, query, "files", deadline=deadline + ) await asyncio.sleep(_REQUEST_INTERVAL) - hits = data.get("hits", {}).get("hits", []) if not hits: break @@ -500,16 +635,41 @@ async def fetch_file_metadata( logger.info(f"HuBMAP file fetch: {total} total files fetched") +def _uberon_term(organ: dict) -> Optional[dict]: + """The UBERON term for one UBKG organ entry, or None when it has none. + + ``organ_uberon`` is not always UBERON despite its name: the lateral + organs (left/right knee, mammary gland, tonsil) carry FMA ids there, + and their side-neutral parent under ``category`` carries the UBERON + one. Falling back loses the side -- UBERON's knee is side-neutral -- + which is the honest trade: an FMA id stored where the anatomy + contract promises UBERON would not resolve for any consumer. + """ + for source in (organ, organ.get("category")): + if not isinstance(source, dict): + continue + uberon = source.get("organ_uberon") + if isinstance(uberon, str) and uberon.startswith("UBERON:"): + return {"id": uberon, "name": source.get("term") or uberon} + return None + + async def fetch_organ_map() -> dict[str, dict]: """ Fetch the HuBMAP organ-code → UBERON mapping from the UBKG ontology API. One small request per sync. Returns ``{rui_code: {"id": uberon_id, - "name": term}}`` for every organ carrying both a code and a UBERON id. - Failure degrades rather than aborts — anatomy is enrichment, not + "name": term}}`` for every organ with a UBERON term, taking the + side-neutral ``category`` term where ``organ_uberon`` is not UBERON + (see ``_uberon_term``); a code with no UBERON term at all is left out, + so the transform counts it as unmapped rather than storing a foreign + id. Failure degrades rather than aborts -- anatomy is enrichment, not identity, so a UBKG outage costs the anatomy terms of one sync, not the - corpus — and returns an empty map with a warning. + corpus -- and returns an empty map with a warning. That covers a + timeout (a bare ``TimeoutError`` in aiohttp, not a ``ClientError``) + and an undecodable or wrongly shaped body as well as transport errors. """ + degraded = "HuBMAP collections will carry no anatomy terms this sync" try: async with aiohttp.ClientSession() as session: async with session.get( @@ -519,24 +679,29 @@ async def fetch_organ_map() -> dict[str, dict]: if response.status != 200: logger.warning( f"UBKG organs API error: HTTP {response.status}; " - "HuBMAP collections will carry no anatomy terms " - "this sync" + f"{degraded}" ) return {} organs = await response.json() - except aiohttp.ClientError as e: + except (aiohttp.ClientError, asyncio.TimeoutError, ValueError) as e: + logger.warning(f"UBKG organs API failed ({e!r}); {degraded}") + return {} + + if not isinstance(organs, list): logger.warning( - f"UBKG organs API network error: {e}; HuBMAP collections will " - "carry no anatomy terms this sync" + f"UBKG organs API returned {type(organs).__name__}, not a list; " + f"{degraded}" ) return {} organ_map: dict[str, dict] = {} for organ in organs: + if not isinstance(organ, dict): + continue code = organ.get("rui_code") - uberon = organ.get("organ_uberon") - if code and uberon: - organ_map[code] = {"id": uberon, "name": organ.get("term") or code} + term = _uberon_term(organ) + if code and term: + organ_map[code] = term logger.info(f"UBKG organs: {len(organ_map)} organ codes mapped to UBERON") return organ_map @@ -767,7 +932,10 @@ def transform_file_to_cfdb( if stats is not None: stats[f"unmapped_organ:{code}"] += 1 continue - anatomy.append({"id": term["id"], "name": organ.get("label") or term["name"]}) + # The UBKG term, not the file's own label: labels drift between + # files for the same code ("Main Bronchus (Right)" vs "Bronchus + # (Right)"), which would give one id two names. + anatomy.append({"id": term["id"], "name": term["name"]}) # --- Collection, one per file: its parent dataset --- collection: dict = { diff --git a/tests/test_hubmap.py b/tests/test_hubmap.py index af890fb..3dcc159 100644 --- a/tests/test_hubmap.py +++ b/tests/test_hubmap.py @@ -2,9 +2,12 @@ from __future__ import annotations +import asyncio +import os + import aiohttp import pytest -from hypothesis import given, settings +from hypothesis import HealthCheck, given, settings from hypothesis import strategies as st from cfdb.models import FileMetadataModel @@ -76,6 +79,8 @@ async def __aexit__(self, *exc): return False async def json(self): + if isinstance(self._payload, Exception): + raise self._payload return self._payload @@ -86,12 +91,18 @@ class _SearchSession: server-side extension filter are both observable. Once the configured pages run out, an empty page is served, which is how the real index ends a ``search_after`` walk. + + ``failures`` are served first, one per request, without consuming a + page: an int is answered as that HTTP status, an exception is raised, + and a dict is answered as a 200 carrying that body. That is what lets + a test fail one attempt at a page and then serve the same page. """ - def __init__(self, pages=None, status=200, error=None): + def __init__(self, pages=None, status=200, error=None, failures=None): self._pages = list(pages or []) self._status = status self._error = error + self._failures = list(failures or []) self.post_bodies: list[dict] = [] self.post_urls: list[str] = [] @@ -104,6 +115,13 @@ async def __aexit__(self, *exc): def post(self, url, json=None, **kwargs): self.post_urls.append(url) self.post_bodies.append(json) + if self._failures: + failure = self._failures.pop(0) + if isinstance(failure, Exception): + raise failure + if isinstance(failure, int): + return _FakeJsonResponse(failure, {}) + return _FakeJsonResponse(200, failure) if self._error is not None: raise self._error if self._pages: @@ -145,6 +163,17 @@ def _page(*sources: dict, sort_key: str = "file_uuid") -> dict: } +@pytest.fixture +def no_backoff(mocker): + """Make the fetchers' retry backoff and rate-limit pauses instant. + + Returns the mock, so a test can count the pauses it took. + """ + return mocker.patch.object( + hubmap_module.asyncio, "sleep", mocker.AsyncMock() + ) + + def test_file_extensions_from_env_should_return_default_when_unset( monkeypatch ): @@ -169,6 +198,29 @@ def test_file_extensions_from_env_should_return_default_when_unset( assert all(ext.startswith(".") for ext in allowlist) +def test_file_extensions_from_env_should_exclude_bcf_by_default(monkeypatch): + """Test the default allowlist leaves out HuBMAP's .bcf files. + + Every .bcf in the index is a CODEX raw-acquisition sidecar, not binary + VCF, so ingesting them would label microscope files as variant calls. + + Given: + No HUBMAP_FILE_EXTENSIONS in the environment. + When: + file_extensions_from_env resolves the allowlist. + Then: + It should not include .bcf. + """ + # Arrange + monkeypatch.delenv(EXTENSIONS_ENV, raising=False) + + # Act + allowlist = file_extensions_from_env() + + # Assert + assert ".bcf" not in allowlist + + def test_file_extensions_from_env_should_normalize_case_and_missing_dots( monkeypatch ): @@ -256,8 +308,12 @@ def test_file_extensions_from_env_should_collapse_repeats_keeping_order( max_size=8, ) ) +@settings( + max_examples=50, + suppress_health_check=[HealthCheck.function_scoped_fixture], +) def test_file_extensions_from_env_should_emit_index_shaped_entries( - entries + entries, mocker ): """Test every resolved entry matches the index's value shape. @@ -268,15 +324,11 @@ def test_file_extensions_from_env_should_emit_index_shaped_entries( Then: Every entry should be lower-cased, dot-prefixed, and unique. """ - import os - # Arrange - os.environ[EXTENSIONS_ENV] = ",".join(entries) - try: - # Act - allowlist = file_extensions_from_env() - finally: - del os.environ[EXTENSIONS_ENV] + mocker.patch.dict(os.environ, {EXTENSIONS_ENV: ",".join(entries)}) + + # Act + allowlist = file_extensions_from_env() # Assert assert all(ext.startswith(".") and ext == ext.lower() for ext in allowlist) @@ -556,14 +608,15 @@ def test_transform_file_to_cfdb_should_map_organs_through_the_organ_map( When: transform_file_to_cfdb runs. Then: - The collection should carry exactly one UBERON term named by - the document's label, and the unmapped code should be counted. + The collection should carry exactly one UBERON term, named by + the UBKG term rather than the document's drifting label, and + the unmapped code should be counted. """ from collections import Counter # Arrange organs = [ - {"code": "TH", "label": "Thymus"}, + {"code": "TH", "label": "Thymus (Lobe)"}, {"code": "TH", "label": "Thymus"}, {"code": "ZZ", "label": "Mystery"}, ] @@ -866,9 +919,8 @@ async def test_fetch_file_metadata_should_filter_extensions_server_side( [doc async for doc in fetch_file_metadata((".h5ad", ".bcf"))] # Assert - assert session.post_bodies[0]["query"] == { - "terms": {"file_extension.keyword": [".h5ad", ".bcf"]} - } + filters = session.post_bodies[0]["query"]["bool"]["filter"] + assert {"terms": {"file_extension.keyword": [".h5ad", ".bcf"]}} in filters @pytest.mark.asyncio @@ -898,7 +950,7 @@ async def test_fetch_file_metadata_should_yield_nothing_when_allowlist_empty( @pytest.mark.asyncio -async def test_fetch_file_metadata_should_raise_on_http_error(mocker): +async def test_fetch_file_metadata_should_raise_on_http_error(mocker, no_backoff): """Test an upstream error fails the stream instead of truncating it. The loader clears before reloading, so a stream that quietly ended @@ -909,7 +961,8 @@ async def test_fetch_file_metadata_should_raise_on_http_error(mocker): When: fetch_file_metadata is drained. Then: - It should raise rather than end the stream. + It should retry the page, then raise rather than end the + stream. """ # Arrange session = _SearchSession(status=503) @@ -917,10 +970,13 @@ async def test_fetch_file_metadata_should_raise_on_http_error(mocker): hubmap_module.aiohttp, "ClientSession", return_value=session ) - # Act & assert + # Act with pytest.raises(RuntimeError, match="HTTP 503"): [doc async for doc in fetch_file_metadata((".h5ad",))] + # Assert + assert len(session.post_bodies) == 3 + @pytest.mark.asyncio async def test_fetch_file_metadata_should_request_is_data_product( @@ -952,9 +1008,7 @@ async def test_fetch_file_metadata_should_request_is_data_product( @pytest.mark.asyncio -async def test_fetch_file_metadata_should_raise_on_network_error( - mocker -): +async def test_fetch_file_metadata_should_raise_on_network_error(mocker, no_backoff): """Test a dropped connection fails the stream instead of ending it. Given: @@ -962,7 +1016,8 @@ async def test_fetch_file_metadata_should_raise_on_network_error( When: fetch_file_metadata is drained. Then: - The client error should propagate. + The client error should propagate once the page's retries + are spent. """ # Arrange session = _SearchSession(error=aiohttp.ClientError("reset")) @@ -970,10 +1025,13 @@ async def test_fetch_file_metadata_should_raise_on_network_error( hubmap_module.aiohttp, "ClientSession", return_value=session ) - # Act & assert + # Act with pytest.raises(aiohttp.ClientError, match="reset"): [doc async for doc in fetch_file_metadata((".h5ad",))] + # Assert + assert len(session.post_bodies) == 3 + @pytest.mark.asyncio async def test_fetch_file_metadata_should_stop_when_a_page_has_no_sort( @@ -1007,6 +1065,170 @@ async def test_fetch_file_metadata_should_stop_when_a_page_has_no_sort( assert len(session.post_bodies) == 1 +@pytest.mark.asyncio +async def test_fetch_file_metadata_should_filter_to_public_files(mocker): + """Test the query admits only public files. + + The retired pruning pass relied on the index holding only public + files; the filter makes that an invariant rather than an assumption. + + Given: + An allowlist. + When: + fetch_file_metadata issues its first request. + Then: + The body should filter on data_access_level public. + """ + # Arrange + session = _SearchSession() + mocker.patch.object( + hubmap_module.aiohttp, "ClientSession", return_value=session + ) + + # Act + [doc async for doc in fetch_file_metadata((".h5ad",))] + + # Assert + filters = session.post_bodies[0]["query"]["bool"]["filter"] + assert {"term": {"data_access_level.keyword": "public"}} in filters + + +@pytest.mark.asyncio +async def test_fetch_file_metadata_should_retry_a_page_that_failed_transiently( + mocker, no_backoff +): + """Test one transient failure costs a retry, not the sync. + + Given: + A files endpoint that answers HTTP 503 once and then serves a page + of two documents. + When: + fetch_file_metadata is drained. + Then: + It should yield both documents, having re-sent the identical + first-page request. + """ + # Arrange + session = _SearchSession( + pages=[_page(_file_doc(file_uuid="aaa"), _file_doc(file_uuid="bbb"))], + failures=[503], + ) + mocker.patch.object( + hubmap_module.aiohttp, "ClientSession", return_value=session + ) + + # Act + docs = [doc async for doc in fetch_file_metadata((".h5ad",))] + + # Assert + assert [doc["file_uuid"] for doc in docs] == ["aaa", "bbb"] + assert session.post_bodies[0] == session.post_bodies[1] + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("failure", "message"), + [ + ( + {"_shards": {"failed": 1}, "hits": {"hits": []}}, + "failed shard", + ), + ({"timed_out": True, "hits": {"hits": []}}, "timed out upstream"), + ({}, "no hits envelope"), + ], +) +async def test_fetch_file_metadata_should_raise_when_every_attempt_is_partial( + mocker, no_backoff, failure, message +): + """Test a partial or malformed 200 is refused rather than walked past. + + Elasticsearch answers 200 with whatever healthy shards returned, and a + body with no hits envelope would read as end-of-stream -- on the first + page, a cleared corpus with nothing loaded. + + Given: + A files endpoint whose every answer is a failed-shard, timed-out, + or envelope-less 200. + When: + fetch_file_metadata is drained. + Then: + It should raise naming the defect, after retrying the page. + """ + # Arrange + session = _SearchSession(failures=[failure] * 3) + mocker.patch.object( + hubmap_module.aiohttp, "ClientSession", return_value=session + ) + + # Act + with pytest.raises(RuntimeError, match=message): + [doc async for doc in fetch_file_metadata((".h5ad",))] + + # Assert + assert len(session.post_bodies) == 3 + + +@pytest.mark.asyncio +async def test_fetch_file_metadata_should_raise_at_once_on_a_client_error_status( + mocker, no_backoff +): + """Test a request the server refuses outright is not retried. + + Given: + A files endpoint answering HTTP 400. + When: + fetch_file_metadata is drained. + Then: + It should raise after a single request. + """ + # Arrange + session = _SearchSession(failures=[400]) + mocker.patch.object( + hubmap_module.aiohttp, "ClientSession", return_value=session + ) + + # Act + with pytest.raises(RuntimeError, match="HTTP 400"): + [doc async for doc in fetch_file_metadata((".h5ad",))] + + # Assert + assert len(session.post_bodies) == 1 + + +@pytest.mark.asyncio +async def test_fetch_file_metadata_should_raise_when_the_deadline_has_passed( + mocker, +): + """Test a spent budget is refused rather than turned into no timeout. + + aiohttp reads a non-positive total as "no timeout", so passing the + exhausted remainder through would make the request unbounded. + + Given: + A deadline already behind the event-loop clock. + When: + fetch_file_metadata is drained. + Then: + It should raise a timeout without issuing a request. + """ + # Arrange + session = _SearchSession(pages=[_page(_file_doc())]) + mocker.patch.object( + hubmap_module.aiohttp, "ClientSession", return_value=session + ) + deadline = asyncio.get_running_loop().time() - 1 + + # Act + with pytest.raises(asyncio.TimeoutError): + [ + doc + async for doc in fetch_file_metadata((".h5ad",), deadline=deadline) + ] + + # Assert + assert session.post_bodies == [] + + @pytest.mark.asyncio async def test_fetch_dataset_metadata_bulk_should_key_results_by_uuid( mocker @@ -1051,9 +1273,7 @@ async def test_fetch_dataset_metadata_bulk_should_key_results_by_uuid( @pytest.mark.asyncio -async def test_fetch_dataset_metadata_bulk_should_raise_on_http_error( - mocker -): +async def test_fetch_dataset_metadata_bulk_should_raise_on_http_error(mocker, no_backoff): """Test a partial dataset map is refused rather than returned. A silently partial map would mean silently under-enriched @@ -1064,7 +1284,8 @@ async def test_fetch_dataset_metadata_bulk_should_raise_on_http_error( When: fetch_dataset_metadata_bulk runs. Then: - It should raise rather than return what it fetched so far. + It should retry the page, then raise rather than return what + it fetched so far. """ # Arrange session = _SearchSession(status=502) @@ -1072,10 +1293,13 @@ async def test_fetch_dataset_metadata_bulk_should_raise_on_http_error( hubmap_module.aiohttp, "ClientSession", return_value=session ) - # Act & assert + # Act with pytest.raises(RuntimeError, match="HTTP 502"): await fetch_dataset_metadata_bulk() + # Assert + assert len(session.post_bodies) == 3 + @pytest.mark.asyncio async def test_fetch_dataset_metadata_bulk_should_skip_hits_without_uuid( @@ -1115,9 +1339,7 @@ async def test_fetch_dataset_metadata_bulk_should_skip_hits_without_uuid( @pytest.mark.asyncio -async def test_fetch_dataset_metadata_bulk_should_raise_on_network_error( - mocker -): +async def test_fetch_dataset_metadata_bulk_should_raise_on_network_error(mocker, no_backoff): """Test a dropped connection refuses the partial map. Given: @@ -1125,7 +1347,8 @@ async def test_fetch_dataset_metadata_bulk_should_raise_on_network_error( When: fetch_dataset_metadata_bulk runs. Then: - The client error should propagate. + The client error should propagate once the page's retries + are spent. """ # Arrange session = _SearchSession(error=aiohttp.ClientError("reset")) @@ -1133,10 +1356,13 @@ async def test_fetch_dataset_metadata_bulk_should_raise_on_network_error( hubmap_module.aiohttp, "ClientSession", return_value=session ) - # Act & assert + # Act with pytest.raises(aiohttp.ClientError, match="reset"): await fetch_dataset_metadata_bulk() + # Assert + assert len(session.post_bodies) == 3 + @pytest.mark.asyncio async def test_fetch_dataset_metadata_bulk_should_stop_when_a_page_has_no_sort( @@ -1254,6 +1480,113 @@ async def test_fetch_organ_map_should_return_empty_and_warn_on_http_error( assert any("HTTP 500" in record.message for record in caplog.records) +@pytest.mark.asyncio +async def test_fetch_organ_map_should_fall_back_to_the_category_uberon_term( + mocker, +): + """Test a lateral organ's FMA id is replaced by its UBERON parent. + + UBKG puts FMA ids in organ_uberon for the left/right knee, mammary + gland and tonsil, while their side-neutral category carries UBERON. + + Given: + A UBKG entry whose organ_uberon is FMA and whose category carries a + UBERON id. + When: + fetch_organ_map runs. + Then: + The code should map to the category's UBERON id and term. + """ + # Arrange + payload = [ + { + "rui_code": "RN", + "term": "Knee (Right)", + "organ_uberon": "FMA:24977", + "category": {"organ_uberon": "UBERON:0001465", "term": "Knee"}, + } + ] + session = _OrganSession(payload=payload) + mocker.patch.object( + hubmap_module.aiohttp, "ClientSession", return_value=session + ) + + # Act + organ_map = await fetch_organ_map() + + # Assert + assert organ_map == {"RN": {"id": "UBERON:0001465", "name": "Knee"}} + + +@pytest.mark.asyncio +async def test_fetch_organ_map_should_omit_a_code_with_no_uberon_term(mocker): + """Test a code with no UBERON term anywhere is left unmapped. + + Left out of the map, the transform counts it as an unmapped organ + rather than storing a foreign id where the contract promises UBERON. + + Given: + A UBKG entry with an FMA organ_uberon and no category. + When: + fetch_organ_map runs. + Then: + The code should be absent from the map. + """ + # Arrange + payload = [{"rui_code": "LN", "term": "Knee", "organ_uberon": "FMA:24978"}] + session = _OrganSession(payload=payload) + mocker.patch.object( + hubmap_module.aiohttp, "ClientSession", return_value=session + ) + + # Act + organ_map = await fetch_organ_map() + + # Assert + assert organ_map == {} + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("session_kwargs", "expected"), + [ + ({"error": asyncio.TimeoutError()}, "TimeoutError"), + ({"payload": ValueError("bad json")}, "bad json"), + ({"payload": {"organs": []}}, "not a list"), + ], +) +async def test_fetch_organ_map_should_return_empty_and_warn_on_a_degraded_answer( + mocker, caplog, session_kwargs, expected +): + """Test every failure shape degrades anatomy instead of failing the sync. + + aiohttp raises a bare TimeoutError on an exceeded total, not a + ClientError, and a wrongly shaped body would otherwise fail on + iteration -- both escaped the contract the docstring states. + + Given: + A UBKG request that times out, answers undecodable JSON, or + answers a JSON object instead of a list. + When: + fetch_organ_map runs. + Then: + It should return an empty map and log a warning describing it. + """ + # Arrange + session = _OrganSession(**session_kwargs) + mocker.patch.object( + hubmap_module.aiohttp, "ClientSession", return_value=session + ) + + # Act + with caplog.at_level("WARNING"): + organ_map = await fetch_organ_map() + + # Assert + assert organ_map == {} + assert any(expected in record.message for record in caplog.records) + + def test_build_hubmap_dcc_record_should_carry_the_static_dcc_fields(): """Test the DCC record names HuBMAP under its registry id. From 2ae3a12cfd0f2e5867b007d31b22f7f907095ff1 Mon Sep 17 00:00:00 2001 From: Conrad Date: Fri, 20 Nov 2026 17:04:40 -0500 Subject: [PATCH 12/37] fix: Bound the HuBMAP sync's cutover window and keep the slice on empty 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. --- src/cfdb/services/sync.py | 165 ++++++++++++++++++++--------------- tests/test_sync.py | 175 +++++++++++++++++++++++++++++++++++++- 2 files changed, 269 insertions(+), 71 deletions(-) diff --git a/src/cfdb/services/sync.py b/src/cfdb/services/sync.py index d538ccc..3156675 100644 --- a/src/cfdb/services/sync.py +++ b/src/cfdb/services/sync.py @@ -1024,14 +1024,27 @@ async def _sync_hubmap(task: SyncTask) -> None: genome assembly) and the organ-to-UBERON map are prefetched before the file stream opens, so every document is emitted fully populated in one insert pass and no post-load enrichment or pruning stages exist. The - index itself holds only public files, which is what retired the pruning - pass. + file query itself admits only public files, which is what retired the + pruning pass. + + The prefetch runs before the cutover lock is taken: it touches no + database state, and the lock gates the whole read surface, so holding + it across ~10k datasets of network fetch would fail every API request + for that long. Only the clear and the file stream run under the lock, + and the stream carries one deadline from ``sync_budget_seconds`` so the + lock cannot outlive the sync lock's stale threshold. A single stream loads the whole submission, so there is no per-phase isolation: any failure propagates and is recorded as this DCC's failure by ``_sync_dccs``, while ``_ingest_rows``'s deferred clear ensures a fetch that dies before delivering rows leaves the previous corpus being served rather than empty. + + An empty extension allowlist is a no-op that leaves the existing slice + in place -- the same outcome an empty ``ENCODE_ANNOTATION_TYPES`` has + for ENCODE's annotation phases. Draining an empty stream instead would + read as an authoritative empty result and delete the whole slice, and + empty values arrive by accident routinely. """ from cfdb.services.hubmap import ( build_hubmap_dcc_record, @@ -1039,91 +1052,103 @@ async def _sync_hubmap(task: SyncTask) -> None: fetch_file_metadata, fetch_organ_map, file_extensions_from_env, + sync_budget_seconds, transform_file_to_cfdb, ) if api.db is None: raise RuntimeError("Database not initialized") + extensions = file_extensions_from_env() + if not extensions: + task.progress = ( + "HuBMAP sync skipped: the extension allowlist is empty; the " + "existing HuBMAP slice was left in place" + ) + logger.warning(task.progress) + return + logger.info("HuBMAP file ingest: extension allowlist %s", list(extensions)) + counts_by_phase: dict[str, int] = {} # One counter for everything the transform wants observed -- the # per-extension document distribution, skip reasons, and unmapped organ # codes -- logged as distributions below rather than a line per file. stats: Counter[str] = Counter() - async with locks.CutoverLock("hubmap"): - # Step 1: Clear existing raw HuBMAP data. ``files`` is deliberately - # not cleared here: ``_ingest_rows`` clears that slice once - # replacement rows are in hand, so a fetch that fails before - # delivering any leaves the previous corpus being served rather - # than empty. The raw C2M2 collections (file, collection, subject, - # ...) are cleared outright -- nothing reloads them anymore. - task.current_step = "clearing" - task.progress = "Clearing existing HuBMAP data..." - logger.info(task.progress) - await _clear_dcc_data_async("hubmap", skip_collections={"files"}) - - # Step 2: Upsert DCC record - task.current_step = "dcc_record" - task.progress = "Creating HuBMAP DCC record..." - logger.info(task.progress) - await api.db.dcc.update_one( - {"submission": "hubmap"}, - {"$set": build_hubmap_dcc_record()}, - upsert=True, - ) - - # Step 3: Prefetch the dataset-level context the files index does - # not carry, plus the organ-to-UBERON map. ~10k datasets held in - # memory -- small against the file stream they enrich, and what - # makes the single-pass join possible. - task.current_step = "fetching" - task.progress = "Fetching HuBMAP dataset metadata..." - logger.info(task.progress) - - dataset_metadata = await fetch_dataset_metadata_bulk() - donor_lookup = { - meta["donor_uuid"]: meta["donor_metadata"] - for meta in dataset_metadata.values() - if meta.get("donor_uuid") and meta.get("donor_metadata") - } - organ_map = await fetch_organ_map() + # Step 1: Prefetch the dataset-level context the files index does not + # carry, plus the organ-to-UBERON map, outside the cutover lock. ~10k + # datasets held in memory -- small against the file stream they enrich, + # and what makes the single-pass join possible. + task.current_step = "fetching" + task.progress = "Fetching HuBMAP dataset metadata..." + logger.info(task.progress) - extensions = file_extensions_from_env() - logger.info( - "HuBMAP file ingest: extension allowlist %s", list(extensions) + dataset_metadata = await fetch_dataset_metadata_bulk() + donor_lookup = { + meta["donor_uuid"]: meta["donor_metadata"] + for meta in dataset_metadata.values() + if meta.get("donor_uuid") and meta.get("donor_metadata") + } + organ_map = await fetch_organ_map() + + def transform(src: dict) -> Optional[dict]: + return transform_file_to_cfdb( + src, + dataset_metadata=dataset_metadata, + donor_lookup=donor_lookup, + organ_map=organ_map, + stats=stats, ) - # Step 4: Stream, transform, and insert in one pass. - task.current_step = "loading" - task.progress = "Loading HuBMAP files from the files search API..." - logger.info(task.progress) - - def transform(src: dict) -> Optional[dict]: - return transform_file_to_cfdb( - src, - dataset_metadata=dataset_metadata, - donor_lookup=donor_lookup, - organ_map=organ_map, - stats=stats, + try: + async with locks.CutoverLock("hubmap"): + # Step 2: Clear existing raw HuBMAP data. ``files`` is + # deliberately not cleared here: ``_ingest_rows`` clears that + # slice once replacement rows are in hand, so a fetch that fails + # before delivering any leaves the previous corpus being served + # rather than empty. The raw C2M2 collections (file, collection, + # subject, ...) are cleared outright -- nothing reloads them + # anymore. + task.current_step = "clearing" + task.progress = "Clearing existing HuBMAP data..." + logger.info(task.progress) + await _clear_dcc_data_async("hubmap", skip_collections={"files"}) + + # Step 3: Upsert DCC record + task.current_step = "dcc_record" + task.progress = "Creating HuBMAP DCC record..." + logger.info(task.progress) + await api.db.dcc.update_one( + {"submission": "hubmap"}, + {"$set": build_hubmap_dcc_record()}, + upsert=True, ) - await _ingest_rows( - task, - "hubmap", - "files index", - fetch_file_metadata(extensions), - transform, - counts_by_phase, - # One stream owns the whole submission, so its slice is the - # whole submission. - stale_filter={}, - ) - - # HuBMAP writes straight into the materialized collection and never runs - # the materializer, which is the only other creator of files indexes -- - # same reasoning as the ENCODE path above. - await ensure_indexes(api.db, materialized_files_index_specs()) + # Step 4: Stream, transform, and insert in one pass, under one + # deadline resolved here so the lock window is bounded. + task.current_step = "loading" + task.progress = "Loading HuBMAP files from the files search API..." + logger.info(task.progress) + deadline = asyncio.get_running_loop().time() + sync_budget_seconds() + + await _ingest_rows( + task, + "hubmap", + "files index", + fetch_file_metadata(extensions, deadline=deadline), + transform, + counts_by_phase, + # One stream owns the whole submission, so its slice is the + # whole submission. + stale_filter={}, + ) + finally: + # HuBMAP writes straight into the materialized collection and never + # runs the materializer, which is the only other creator of files + # indexes -- same reasoning as the ENCODE path above, including + # running on failure: a partially loaded slice still has to be + # servable without a full collection scan. + await ensure_indexes(api.db, materialized_files_index_specs()) count = counts_by_phase.get("files index", 0) task.progress = f"HuBMAP sync complete: {count} files" diff --git a/tests/test_sync.py b/tests/test_sync.py index 1668eb4..3337475 100644 --- a/tests/test_sync.py +++ b/tests/test_sync.py @@ -13,6 +13,7 @@ from cfdb.services import encode as encode_module from cfdb.services import fourdn as fourdn_module from cfdb.services import hubmap as hubmap_module +from cfdb.services import locks from cfdb.services import sync as sync_module from cfdb.services.sync import ( SyncTask, @@ -430,7 +431,7 @@ def _patch_hubmap_fetches( mocker.patch.object( hubmap_module, "fetch_file_metadata", - lambda extensions: file_docs, + lambda extensions, **kwargs: file_docs, ) @@ -622,6 +623,178 @@ async def test__sync_hubmap_should_ensure_materialized_files_indexes( ] + @pytest.mark.asyncio + async def test__sync_hubmap_should_ensure_indexes_when_the_stream_fails( + self, mock_db, mocker + ): + """Test a failed load still leaves its slice indexed. + + A stream that dies mid-load has already committed rows; leaving + them unindexed would make every lookup against the partial slice a + full scan until the next successful sync. + + Given: + A file stream that delivers one document and then raises. + When: + _sync_hubmap runs. + Then: + The failure should propagate and the materialized files indexes + should still be ensured. + """ + # Arrange + _patch_hubmap_fetches( + mocker, + _async_iter_then_raise( + [_hubmap_file_doc()], RuntimeError("files index reset") + ), + ) + ensure_mock = mocker.patch.object( + sync_module, "ensure_indexes", mocker.AsyncMock() + ) + + # Act + with pytest.raises(RuntimeError, match="files index reset"): + await _sync_hubmap(SyncTask(id="t1", dcc_names=["hubmap"])) + + # Assert + ensure_mock.assert_awaited_once() + + @pytest.mark.asyncio + async def test__sync_hubmap_should_prefetch_outside_the_cutover_lock( + self, mock_db, mocker + ): + """Test the network prefetch does not hold the read surface hostage. + + The cutover lock blocks every API request, and the dataset and + organ prefetches touch no database state, so running them under + the lock would only lengthen the outage. + + Given: + Dataset and organ fetches that record whether the cutover lock + is active when they run. + When: + _sync_hubmap runs. + Then: + Neither fetch should observe an active cutover lock, while the + file stream that follows should. + """ + # Arrange + observed: list[bool] = [] + + async def lock_active() -> bool: + lock = await mock_db[locks.LOCKS_COLLECTION].find_one( + {"_id": locks.CUTOVER_LOCK_ID} + ) + return bool(lock and lock.get("active")) + + async def fetch_datasets(): + observed.append(await lock_active()) + return {} + + async def fetch_organs(): + observed.append(await lock_active()) + return {} + + async def stream_files(): + # The control: the stream runs under the lock, so a fake that + # never recorded the lock would fail here instead of passing + # vacuously above. + observed.append(await lock_active()) + yield _hubmap_file_doc() + + _patch_hubmap_fetches(mocker, stream_files()) + mocker.patch.object( + hubmap_module, + "fetch_dataset_metadata_bulk", + mocker.AsyncMock(side_effect=fetch_datasets), + ) + mocker.patch.object( + hubmap_module, + "fetch_organ_map", + mocker.AsyncMock(side_effect=fetch_organs), + ) + + # Act + await _sync_hubmap(SyncTask(id="t1", dcc_names=["hubmap"])) + + # Assert + assert observed == [False, False, True] + + @pytest.mark.asyncio + async def test__sync_hubmap_should_bound_the_file_stream_with_a_deadline( + self, mock_db, mocker, monkeypatch + ): + """Test the in-lock stream carries the configured budget. + + The stream runs under the cutover lock, so an unbounded one could + outlive the sync lock's stale threshold and admit a second sync. + + Given: + HUBMAP_SYNC_TIMEOUT_SECONDS set to 120 and a file stream that + records the deadline it was opened with. + When: + _sync_hubmap runs. + Then: + The stream should be opened with a deadline about 120 seconds + ahead on the event-loop clock. + """ + # Arrange + monkeypatch.setenv("HUBMAP_SYNC_TIMEOUT_SECONDS", "120") + opened: dict = {} + + def open_stream(extensions, *, deadline=None): + opened["deadline"] = deadline + return _async_iter([_hubmap_file_doc()]) + + _patch_hubmap_fetches(mocker, _async_iter([])) + mocker.patch.object(hubmap_module, "fetch_file_metadata", open_stream) + loop = asyncio.get_running_loop() + + # Act + before = loop.time() + await _sync_hubmap(SyncTask(id="t1", dcc_names=["hubmap"])) + + # Assert + assert before + 119 <= opened["deadline"] <= loop.time() + 120 + + @pytest.mark.asyncio + async def test__sync_hubmap_should_keep_the_slice_when_the_allowlist_is_empty( + self, mock_db, mocker, monkeypatch + ): + """Test an empty allowlist is a no-op, not a purge. + + An empty value arrives by accident routinely; draining an empty + stream would read as an authoritative empty result and delete the + whole HuBMAP slice. + + Given: + A files collection holding a HuBMAP document and + HUBMAP_FILE_EXTENSIONS set to an empty value. + When: + _sync_hubmap runs. + Then: + The HuBMAP document should remain and no upstream fetch should + be made. + """ + # Arrange + monkeypatch.setenv("HUBMAP_FILE_EXTENSIONS", "") + mock_db.files.docs.append( + {"submission": "hubmap", "local_id": "previous-1"} + ) + fetch_datasets = mocker.patch.object( + hubmap_module, "fetch_dataset_metadata_bulk", mocker.AsyncMock() + ) + + # Act + await _sync_hubmap(SyncTask(id="t1", dcc_names=["hubmap"])) + + # Assert + assert mock_db.files.docs == [ + {"submission": "hubmap", "local_id": "previous-1"} + ] + fetch_datasets.assert_not_awaited() + + # --------------------------------------------------------------------------- # _load_dataset_async # --------------------------------------------------------------------------- From 324e546db9ac76591034e63f57f4cad328fe802e Mon Sep 17 00:00:00 2001 From: Conrad Date: Fri, 20 Nov 2026 17:04:48 -0500 Subject: [PATCH 13/37] test: Dump a document built by the HuBMAP transform 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. --- tests/test_dump.py | 64 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) diff --git a/tests/test_dump.py b/tests/test_dump.py index 117c5fc..2af7f26 100644 --- a/tests/test_dump.py +++ b/tests/test_dump.py @@ -12,6 +12,7 @@ from hypothesis import strategies as st from cfdb.dump import SCHEMA_VERSION, DumpError, DumpReport, dump_files +from cfdb.services.hubmap import transform_file_to_cfdb #: Every table schema.sql creates, by tier. PROVENANCE_TABLES = {"dump_info", "dump_stat", "dump_conflict"} @@ -1281,6 +1282,69 @@ def test_dump_files_should_carry_the_hubmap_dataset_status(): assert status == "Published" +def test_dump_files_should_load_a_document_built_by_the_hubmap_transform(): + """Test the dump accepts the document shape the HuBMAP loader writes. + + The other HuBMAP fixtures model the retired C2M2 shape; this one is + built by the loader itself, so a change to that shape fails here + rather than only against a live corpus. + + Given: + A files-index document transformed with dataset context, donor + demographics, and a mapped organ, carrying is_data_product. + When: + The transformed document is dumped. + Then: + It should land with an integer size, its HuBMAP file and collection + extensions, the collection's anatomy and subject junctions, and no + skipped documents. + """ + # Arrange + src = { + "file_uuid": "f1", + "rel_path": "processed/secondary_analysis.h5ad", + "file_extension": ".h5ad", + "size": 5529765, + "md5_checksum": "0b05f823fd4b3cc86204366c6f71eae9", + "data_access_level": "public", + "is_data_product": "True", + "dataset_uuid": "ds1", + "dataset_hubmap_id": "HBM339.XXWC.842", + "dataset_type": "RNAseq", + "dataset_status": "Published", + "donors": [{"uuid": "donor-1"}, {"uuid": "donor-1"}], + "organs": [{"code": "TH", "label": "Thymus"}], + } + doc = transform_file_to_cfdb( + src, + dataset_metadata={"ds1": {"pipeline": "Salmon"}}, + donor_lookup={"donor-1": {"sex": ["Female"]}}, + organ_map={"TH": {"id": "UBERON:0002370", "name": "thymus"}}, + ) + + # Act + con, report = run_dump([doc]) + + # Assert + assert con.execute( + "SELECT size_in_bytes FROM file WHERE local_id = 'f1'" + ).fetchone() == (5529765,) + assert con.execute( + "SELECT rel_path, is_data_product FROM file_extra_hubmap" + ).fetchone() == ("processed/secondary_analysis.h5ad", True) + assert con.execute( + "SELECT pipeline, dataset_status FROM collection_extra_hubmap" + ).fetchone() == ("Salmon", "Published") + assert con.execute( + "SELECT anatomy FROM collection_anatomy" + ).fetchall() == [("UBERON:0002370",)] + assert con.execute( + "SELECT subject_local_id FROM subject_in_collection" + ).fetchall() == [("donor-1",)] + assert report.file_count == 1 + assert report.stats.get("documents_invalid", 0) == 0 + + def test_dump_files_should_order_extra_files_by_source_position(): """Test sidecar child-table ordinal ordering. From 025b0a1dab4529af7a1e9a215b6177f930a0f1a3 Mon Sep 17 00:00:00 2001 From: Conrad Date: Fri, 20 Nov 2026 17:04:49 -0500 Subject: [PATCH 14/37] docs: Correct HuBMAP docs and comments against the live index 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. --- HUBMAP-SUPPLEMENT.md | 38 +++++++++++++++---------- README.md | 8 +++--- src/cfdb/api/routers/_helpers.py | 15 +++++----- src/cfdb/dump/schema.sql | 6 +++- src/cfdb/models.py | 11 +++---- src/cfdb/workflows/processors/matrix.py | 6 ++-- 6 files changed, 49 insertions(+), 35 deletions(-) diff --git a/HUBMAP-SUPPLEMENT.md b/HUBMAP-SUPPLEMENT.md index 6bbd5f5..67d706a 100644 --- a/HUBMAP-SUPPLEMENT.md +++ b/HUBMAP-SUPPLEMENT.md @@ -1,6 +1,6 @@ # HuBMAP Files Search API Dataloader -Field mapping from HuBMAP's file-grain search index to the CFDB data model. HuBMAP is a `rest_api` DCC: `cfdb sync hubmap` builds documents directly from the live index — no C2M2 zip download, no TSV load, no Rust materializer run, and no post-load enrichment or pruning stages. The index itself holds only public files, which is what retired the pruning pass the C2M2 path needed. +Field mapping from HuBMAP's file-grain search index to the CFDB data model. HuBMAP is a `rest_api` DCC: `cfdb sync hubmap` builds documents directly from the live index — no C2M2 zip download, no TSV load, no Rust materializer run, and no post-load enrichment or pruning stages. The file query filters on `data_access_level: public` server-side, which is what retired the pruning pass the C2M2 path needed: the index holds only public files today, and the filter keeps that true of the load if the index ever admits others. ## Source Endpoints @@ -8,10 +8,12 @@ Field mapping from HuBMAP's file-grain search index to the CFDB data model. HuBM |----------|------|------------| | `POST https://search.api.hubmapconsortium.org/v3/files/search` | One Elasticsearch document per file; the primary stream | `search_after` on `file_uuid.keyword`, batches of 1000 | | `POST https://search.api.hubmapconsortium.org/v3/portal/search` | One document per dataset; prefetched once into an in-memory map keyed by `uuid` | `search_after` on `_id`, batches of 1000 | -| `GET https://ontology.api.hubmapconsortium.org/organs?application_context=HUBMAP` | Organ `rui_code` → UBERON id | One request per sync | +| `GET https://ontology.api.hubmapconsortium.org/organs?application_context=HUBMAP` | Organ `rui_code` → UBERON term | One request per sync | The files index is ~9.9M documents, 98% of them `.tif` microscopy tiles, so the loader applies a configurable extension allowlist **server-side** (a `terms` filter on `file_extension.keyword`) and the excluded files never cross the wire. +Every search page is retried up to three times with backoff on a transport error, a timeout, or a 429/5xx, since re-sending the same `search_after` page is idempotent. A 200 that is partial — failed shards, an upstream `timed_out`, or no hits envelope — is treated the same way rather than walked past, because Elasticsearch answers 200 with whatever the healthy shards returned and the walk would otherwise resume past documents it never received. A failure that outlasts the retries raises. + ## Entity Construction There is no entity matching. The C2M2 path had to join its TSVs to the Search API through heuristics — collection `persistent_id` against `doi_url`, donor uuid substring-matched inside subject `local_id`, files matched by filename basename within a dataset — and each heuristic was a place for records to fall through. The files index names its parent dataset and donors directly, so every entity is constructed, not matched: @@ -21,7 +23,7 @@ There is no entity matching. The C2M2 path had to join its TSVs to the Search AP | File | The files-index document itself; `local_id` is `file_uuid` | | Collection | The file's parent dataset: `local_id` is `dataset_uuid`, one collection per file | | Subject | The file's `donors[]`: `local_id` is the donor uuid | -| Anatomy | The file's `organs[]`, with UBERON ids from the UBKG organ map | +| Anatomy | The file's `organs[]`, with UBERON terms from the UBKG organ map | Dataset-level context the files index does not carry — donor demographics, pipeline, assay metadata, genome assembly — is prefetched from the dataset index (~10k documents) into memory and joined by `dataset_uuid` during transformation, so documents land fully populated in a single insert pass. A dataset missing from that map degrades its files (no demographics, pipeline, or assembly) rather than dropping them. @@ -29,9 +31,13 @@ The `id_namespace` is `https://hubmapconsortium.org` (configured in `dcc_registr ## Extension Allowlist -`HUBMAP_FILE_EXTENSIONS` — comma-separated, case-insensitive, leading dot optional (`h5ad, .BCF` and `.h5ad,.bcf` configure the same thing). Unset applies the default below; set-but-empty ingests nothing and logs a warning, matching the `ENCODE_ANNOTATION_TYPES` semantics. +`HUBMAP_FILE_EXTENSIONS` — comma-separated, case-insensitive, leading dot optional (`h5ad, .MTX` and `.h5ad,.mtx` configure the same thing). Unset applies the default below. Set-but-empty skips the HuBMAP sync entirely with a warning and leaves the existing HuBMAP slice in place, the same outcome an empty `ENCODE_ANNOTATION_TYPES` has for ENCODE's annotation phases; draining an empty stream instead would read as an authoritative empty result and delete the slice. + +Default: `.h5ad`, `.h5mu`, `.h5`, `.hdf5`, `.gz`, `.mtx`, `.arrow`, `.parquet`, `.bed`, `.narrowpeak`, `.bam`, `.sf`, `.snap`, `.csv`, `.tsv` — 51,816 files as of 2026-11-20, against the 9.7M `.tif` tiles the default excludes. It is not purely genomics, because an outer extension cannot say what a file holds: -Default: `.h5ad`, `.h5mu`, `.h5`, `.hdf5`, `.bcf`, `.gz`, `.mtx`, `.arrow`, `.parquet`, `.bed`, `.narrowpeak`, `.bam`, `.sf`, `.snap`, `.csv`, `.tsv` — the genomics and tabular tail of the live distribution, ~53k files against the 9.7M `.tif` tiles the default excludes. +- `.csv` (32,396) and `.tsv` (8,809) are mostly imaging-derived tables — roughly 27k of the `.csv` files come from Cell DIVE, CODEX, and MIBI segmentation pipelines. +- `.gz` (5,872) is mostly not genomics either: 2,723 are Cell DIVE `.nii.gz` NIfTI masks and 2,524 are salmon `aux_info/fld.gz`, which map to no `file_format`; about 500 are compressed MTX, BED, or CSV. +- `.bcf` is deliberately **not** in the default. Every `.bcf` in the index (1,851) is a CODEX raw-acquisition sidecar (`raw/Cyc1_reg1/1.bcf`), not binary VCF, and ingesting them would label microscope files as variant calls. ## File Mapping @@ -43,7 +49,7 @@ Default: `.h5ad`, `.h5mu`, `.h5`, `.hdf5`, `.bcf`, `.gz`, `.mtx`, `.arrow`, `.pa | `md5` / `sha256` | `md5_checksum` / `sha256_checksum` | Real per-file checksums; the C2M2 TSVs lacked or mistyped both | | `file_format` | filename, compression suffix stripped | EDAM-mapped from the inner extension, so `x.fastq.gz` maps to FASTQ rather than nothing | | `compression_format` | filename suffix | Same derivation and absent-when-undetermined contract as ENCODE | -| `access_url` | `https://assets.hubmapconsortium.org/{dataset_uuid}/{rel_path}` | Path segments percent-encoded; resolves without authentication for these (all-public) files | +| `access_url` | `https://assets.hubmapconsortium.org/{dataset_uuid}/{rel_path}` | Path segments percent-encoded. `/data` streams it directly, without DRS resolution. Sampled URLs resolve without authentication, but not every one does: at least one Published CODEX dataset (`HBM366.XKPX.554`) answers 403 and some root-level `*-metadata.tsv` files 404 upstream | | `status` | `dataset_status` | e.g. `"Published"` | | `data_access_level` | `data_access_level` | `"public"` on every document in this index | | `genome_assembly` | dataset `ingest_metadata.workflow_description` | Regex-extracted and canonicalized; mirrored on `extra.hubmap.genome_assembly`. See below. | @@ -60,9 +66,9 @@ One collection per file: its parent dataset. | `persistent_id` | `https://portal.hubmapconsortium.org/browse/dataset/{dataset_uuid}` | | `experiment_type` | `dataset_type` | | `analyte_class` | `analyte_class` | -| `anatomy[]` | `organs[]` — UBERON id from the UBKG organ map by `code`, name from the document's `label` | +| `anatomy[]` | `organs[]` — UBERON id and term from the UBKG organ map by `code`. The name is UBKG's term rather than the document's `label`, which drifts between files for the same code (`Main Bronchus (Right)` vs `Bronchus (Right)`) and would give one id two names | -An organ code the UBKG map does not know is skipped and counted rather than given a fabricated id; the sync logs the unmapped codes. A UBKG outage degrades the same way — collections carry no anatomy that sync, with a warning — because anatomy is enrichment, not identity. +UBKG's `organ_uberon` is not always UBERON: the lateral organs (left/right knee, mammary gland, tonsil) carry FMA ids there. For those the loader takes the side-neutral UBERON term from the entry's `category` (e.g. `RN` Knee (Right) → `UBERON:0001465` Knee), losing the side rather than storing an id that does not resolve in UBERON. An organ code with no UBERON term at all, or one the map does not know, is skipped and counted rather than given a fabricated id; the sync logs the unmapped codes. A UBKG failure — transport error, timeout, error status, or an undecodable or wrongly shaped body — degrades the same way: collections carry no anatomy that sync, with a warning, because anatomy is enrichment, not identity. ### `extra.hubmap` (`EnrichedHubmapCollection`), joined from the dataset index @@ -115,19 +121,21 @@ HuBMAP is human-only, so the vast majority resolve to `GRCh38`. If no pattern ma |-------|--------|-------| | `accession_id` | Not issued | HuBMAP has no file accessions; files are keyed by uuid ([#102](https://github.com/abdenlab/cfdb/issues/102)) | | `creation_time` | Not mapped | The index carries only `last_modified_at`, which is a modification time, not a creation time; mapping it would misstate what the field means | -| Index files (`.bai`, `.tbi`, `.crai`) | Not available | Raw sequencing data is protected upstream; processed datasets don't retain BAMs | +| Index sidecars (`.bai`, `.tbi`) | Not ingested | Not in the allowlist; `/index` builds indexes for the 92 public `.bam` files and the BED/narrowPeak files through the workflow path | | Per-file sequencing metrics | Not available | The files index carries checksums and size but no per-file QC | | Biosamples | Not built | The files index names organs and donors but no sample-level entities; anatomy lands on the collection | ## Data Flow ```text -fetch_dataset_metadata_bulk() # dataset index -> {dataset_uuid: context} -fetch_organ_map() # UBKG -> {rui_code: UBERON term} +fetch_dataset_metadata_bulk() # dataset index -> {dataset_uuid: context} (outside the cutover lock) +fetch_organ_map() # UBKG -> {rui_code: UBERON term} (outside the cutover lock) │ - └─> fetch_file_metadata(allowlist) # files index, filtered server-side - └─ transform_file_to_cfdb(...) # one fully-populated document per file - └─ insert into files # single pass, deferred stale clear + └─> [cutover lock] + fetch_file_metadata(allowlist, deadline) # files index, filtered server-side + └─ transform_file_to_cfdb(...) # one fully-populated document per file + └─ insert into files # single pass, deferred stale clear + ensure_indexes(files) # runs even when the stream fails ``` -The whole pipeline is `_sync_hubmap` in `services/sync.py`, sharing `_ingest_rows` with the ENCODE path: the stale HuBMAP slice is cleared only once replacement rows are in hand, so an upstream failure before the first row leaves the previous corpus being served rather than empty. +The whole pipeline is `_sync_hubmap` in `services/sync.py`, sharing `_ingest_rows` with the ENCODE path. The prefetch runs before the cutover lock is taken, because the lock gates the whole read surface and the prefetch touches no database state. The file stream runs under the lock with one deadline, `HUBMAP_SYNC_TIMEOUT_SECONDS` (default 1800), so the lock cannot outlive the sync lock's one-hour stale threshold. The stale HuBMAP slice is cleared only once replacement rows are in hand, so an upstream failure before the first row leaves the previous corpus being served rather than empty. A failure after that point still leaves a partial slice — loudly, with indexes ensured — and only a shadow-collection swap would make it atomic. diff --git a/README.md b/README.md index 0f3a0a9..3e34c70 100644 --- a/README.md +++ b/README.md @@ -97,7 +97,7 @@ Run `./certs/generate-certs.sh --help` for full usage information. | `make api-tiles` | Build and start the API container **with matrix tile serving enabled**, on a cache volume shared with the worker (local dev; see [Serving tiles locally](#serving-tiles-locally)) | | `make worker-tiles` | Start a containerized LAN worker pool on that same cache volume | | `make materialize-files` | Manually materialize all file metadata (usually done via sync) | -| `make materialize-dcc DCC=hubmap` | Materialize a single DCC | +| `make materialize-dcc DCC=4dn` | Materialize a single DCC. Only C2M2 DCCs (4DN) are materialized: ENCODE and HuBMAP write the `files` collection directly from their APIs and have no raw tables to rebuild from, so materializing either deletes its documents and writes none back | | `make schema` | Regenerate the checked-in `schema.graphql` from the Strawberry schema | | `make certs` | Generate TLS certificates for production | | `make mongodb-prod` | Start MongoDB with TLS/X.509 authentication | @@ -579,7 +579,7 @@ Anatomy, FileFormat, DataType, and AssayType share an identical schema: `id` (st | AssayType | OBI (Ontology for Biomedical Investigations) | | NcbiTaxonomy | NCBI Taxonomy Database | -Every `id` above resolves in its source ontology except the minted `FileFormat` tokens. EDAM has no term for a few formats cfdb ingests — `bedpe` and `bigInteract` at present — and aliasing them onto the nearest EDAM term would make each indistinguishable from the format it was aliased to, so a `cfdb:` token is minted instead. A client resolving `file_format.id` against EDAM should skip ids carrying that prefix rather than treat them as resolvable. +Every `id` above resolves in its source ontology except the minted `FileFormat` tokens. EDAM has no term for a few formats cfdb ingests — `bedpe`, `bigInteract`, `arrow` and `parquet` at present — and aliasing them onto the nearest EDAM term would make each indistinguishable from the format it was aliased to, so a `cfdb:` token is minted instead. A client resolving `file_format.id` against EDAM should skip ids carrying that prefix rather than treat them as resolvable. #### Subject @@ -1179,7 +1179,7 @@ Trigger a sync of C2M2 datapackages from DCCs. Requires API key authentication. - **Single sync at a time** - Concurrent requests return `409 Conflict` - **Background execution** - Returns immediately with `202 Accepted` while sync runs in the background -- **Materialization** - After loading each DCC's data, the Rust materializer creates the denormalized `files` collection with all joins pre-computed +- **Materialization** - After loading a C2M2 DCC's data (4DN), the Rust materializer creates the denormalized `files` collection with all joins pre-computed; ENCODE and HuBMAP build their `files` documents directly from their APIs, already denormalized - **Database cutover** - During the clear/load phase, API requests are briefly blocked to ensure data consistency **Headers:** @@ -1261,7 +1261,7 @@ cfdb dump duckdb cfdb.duckdb -s 4dn -s encode --to-parquet ./parquet - `--to-parquet` - Also `EXPORT DATABASE` every table as Parquet into this directory - `--force` - Overwrite the output file if it exists -**Schema.** The schema of record is [`src/cfdb/dump/schema.sql`](src/cfdb/dump/schema.sql) — a checked-in artifact in the same spirit as `schema.graphql`, versioned by its `schema_version` header and designed in [#123](https://github.com/abdenlab/cfdb/issues/123). The tables mirror C2M2 where C2M2 has a table (`file`, `collection`, `biosample`, `subject`, and the six junctions, all keyed by natural `(id_namespace, local_id)` composites, with `submission` as a non-key column on every entity); enrichment with a cross-consortium slot lives in promoted common columns (`genome_assembly`, `output_type`, `experiment_type`, `analyte_class`, …); the per-consortium residue lives in 1:1 `*_extra_*` extension tables, which omit verbatim-promoted fields but keep any field whose promotion is derived rather than verbatim (`replicate_info` survives because the replicate columns are regex-extracted from it). Three views carry the joins analysts would otherwise retype: `v_file` (one row per file with term names and extension columns inlined), `v_file_biosample` (the file × collection × biosample × subject fan-out grain), and `v_subject_demographics` (sex/race/age coalesced across the C2M2 columns and HuBMAP's enrichment, with a `*_source` column per value so provenance survives the coalesce). +**Schema.** The schema of record is [`src/cfdb/dump/schema.sql`](src/cfdb/dump/schema.sql) — a checked-in artifact in the same spirit as `schema.graphql`, versioned by its `schema_version` header and designed in [#123](https://github.com/abdenlab/cfdb/issues/123). The tables mirror C2M2 where C2M2 has a table (`file`, `collection`, `biosample`, `subject`, and the six junctions, all keyed by natural `(id_namespace, local_id)` composites, with `submission` as a non-key column on every entity); enrichment with a cross-consortium slot lives in promoted common columns (`genome_assembly`, `output_type`, `experiment_type`, `analyte_class`, …); the per-consortium residue lives in 1:1 `*_extra_*` extension tables, which omit verbatim-promoted fields but keep any field whose promotion is derived rather than verbatim (`replicate_info` survives because the replicate columns are regex-extracted from it). Three views carry the joins analysts would otherwise retype: `v_file` (one row per file with term names and extension columns inlined), `v_file_biosample` (the file × collection × biosample × subject fan-out grain; a collection with no biosamples — all of HuBMAP, which attaches anatomy and donors to the collection — contributes file × collection rows with NULL anatomy and subject, so read those from `collection_anatomy` and `subject_in_collection`), and `v_subject_demographics` (sex/race/age coalesced across the C2M2 columns and HuBMAP's enrichment, with a `*_source` column per value so provenance survives the coalesce). **Common-column mapping.** Each promoted column and the upstream field that fills it, per consortium. A column populated by one consortium today is still a common column, not a 4DN or ENCODE column: it names a slot any consortium could fill, which is what makes the next DCC's ingest a mapping exercise rather than a schema change. diff --git a/src/cfdb/api/routers/_helpers.py b/src/cfdb/api/routers/_helpers.py index e03ae93..ca920fc 100644 --- a/src/cfdb/api/routers/_helpers.py +++ b/src/cfdb/api/routers/_helpers.py @@ -47,11 +47,11 @@ "data_access_level": 1, "size_in_bytes": 1, # Promoted to the top level by every DCC's sync: ENCODE via - # ``_add_extra(doc, "genome_assembly", ...)``, 4DN and HuBMAP via the - # ``top_level_map`` / direct ``update``. The ``extra.*.genome_assembly`` - # fields declared on the enriched models are never written, so this is - # the only path that carries an assembly. Read by the tileset routers to - # derive HiGlass's ``coordSystem``. + # ``_add_extra(doc, "genome_assembly", ...)``, 4DN via the + # ``top_level_map`` / direct ``update``, HuBMAP by its transform. HuBMAP + # also mirrors it onto ``extra.hubmap.genome_assembly``, but the top + # level is the one path every DCC writes, so it is the one read here. + # Read by the tileset routers to derive HiGlass's ``coordSystem``. "genome_assembly": 1, "extra.extra_files": 1, "extra.fourdn.extra_files": 1, @@ -177,8 +177,9 @@ async def resolve_file_doc( detail="File has no access URL", ) - # Defense-in-depth: reject any non-public HuBMAP file that survived - # pruning, before any caller streams upstream bytes, caches them, or + # Defense-in-depth: reject any non-public HuBMAP file -- the loader + # admits only public ones, but a document loaded another way must not + # stream -- before any caller streams upstream bytes, caches them, or # dispatches a workflow. # # Runs after the access-url check so signed/private URLs for diff --git a/src/cfdb/dump/schema.sql b/src/cfdb/dump/schema.sql index 88c6d20..8117adb 100644 --- a/src/cfdb/dump/schema.sql +++ b/src/cfdb/dump/schema.sql @@ -492,7 +492,11 @@ LEFT JOIN file_extra_hubmap AS xh -- The file x collection x biosample x subject grain -- "which files came from -- heart tissue". Explicitly a fan-out view: a file row repeats once per --- biosample/subject path, so never SUM(size_in_bytes) over it. +-- biosample/subject path, so never SUM(size_in_bytes) over it. Biosample- +-- grained by design: a collection with no biosamples (all of HuBMAP, whose +-- anatomy and donors hang off the collection) yields file x collection rows +-- with NULL anatomy and subject; collection_anatomy and +-- subject_in_collection carry those. CREATE VIEW v_file_biosample AS SELECT f.submission, diff --git a/src/cfdb/models.py b/src/cfdb/models.py index 56b8465..85f39d7 100644 --- a/src/cfdb/models.py +++ b/src/cfdb/models.py @@ -506,15 +506,16 @@ class FileMetadataModel(BaseModel): comparison to RAS user-level access control metadata. access_url: - A DRS URI or publicly accessible DRS-compatible URL. + A DRS URI (4DN) or a directly fetchable HTTPS URL (ENCODE + downloads, HuBMAP assets). status: - HuBMAP dataset status (e.g., "Published", "QA") cached from HuBMAP - Search API. + HuBMAP dataset status (e.g., "Published", "QA") from the parent + dataset in the HuBMAP files search index. data_access_level: - HuBMAP data access level ("public", "consortium", "protected") cached - from HuBMAP Search API. + HuBMAP data access level ("public", "consortium", "protected") + from the HuBMAP files search index. extra: DCC-specific file metadata. See EnrichedFile for available fields. diff --git a/src/cfdb/workflows/processors/matrix.py b/src/cfdb/workflows/processors/matrix.py index a230cec..976f479 100644 --- a/src/cfdb/workflows/processors/matrix.py +++ b/src/cfdb/workflows/processors/matrix.py @@ -220,9 +220,9 @@ def _assert_source_within_size_cap(self, file_meta: dict[str, Any]) -> None: return size = file_meta.get("size_in_bytes") if isinstance(size, str): - # 4DN and HuBMAP load size_in_bytes as a string through the - # C2M2 TSV path (the README's BigInt note), and 4DN is the - # only DCC whose contact maps reach this processor — an + # 4DN loads size_in_bytes as a string through the C2M2 TSV + # path (the README's BigInt note), and 4DN is the only DCC + # whose contact maps reach this processor — an # int-only check leaves the cap inert for exactly the corpus # it exists to bound. try: From 70f421ef1246e38eaa4fbdacd03e32a07eedaaf6 Mon Sep 17 00:00:00 2001 From: Conrad Date: Fri, 20 Nov 2026 17:45:52 -0500 Subject: [PATCH 15/37] fix: Map upstream errors to their status before streaming a file 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. --- src/cfdb/api/routers/cache_stream.py | 76 ++++++++++++++++-- src/cfdb/api/routers/data.py | 4 +- src/cfdb/api/routers/index.py | 2 +- tests/test_data.py | 114 +++++++++++++++++++++------ 4 files changed, 164 insertions(+), 32 deletions(-) diff --git a/src/cfdb/api/routers/cache_stream.py b/src/cfdb/api/routers/cache_stream.py index 830f5cc..5193261 100644 --- a/src/cfdb/api/routers/cache_stream.py +++ b/src/cfdb/api/routers/cache_stream.py @@ -11,7 +11,7 @@ from __future__ import annotations import logging -from typing import Any, Optional +from typing import Any, AsyncIterator, Optional from fastapi import HTTPException, Request, status from fastapi.responses import JSONResponse, Response, StreamingResponse @@ -103,7 +103,7 @@ def stream_cache_entry( ) -def stream_upstream_url( +async def stream_upstream_url( download_url: str, file_size: Optional[int], filename: str, @@ -117,8 +117,17 @@ def stream_upstream_url( The upstream-URL twin of :func:`stream_cache_entry`: same parse-range / 200-vs-206 / HEAD ritual, but the bytes come from ``download_url`` via :func:`drs.stream_from_url` instead of a ``CacheBackend``. The - DRS/HTTPS, ENCODE, and 4DN-sidecar paths all delegate here so the - range contract stays in one place. + DRS/HTTPS, direct-URL (ENCODE, HuBMAP), and 4DN-sidecar paths all + delegate here so the range contract stays in one place. + + The upstream request is opened before the response is built: the + first chunk is pulled from the stream here, which follows redirects + and checks the upstream status, so an upstream 403/404/5xx becomes + that status rather than a 200 whose body is cut off. Starlette sends + the status line before it iterates a ``StreamingResponse``, so an + error raised inside the body could only ever reach the client as a + truncated download. HEAD stays a metadata answer and does not + contact upstream. Args: download_url: Absolute URL to stream from (already allowlist-validated @@ -135,6 +144,8 @@ def stream_upstream_url( HTTPException(416): size unknown on a range request, or the range is valid but out of bounds. HTTPException(400): Range header has invalid syntax. + HTTPException(403/404/502/504): upstream refused, lacks, failed, or + timed out on the file -- raised before any byte is sent. """ response_headers = { "Content-Disposition": f'attachment; filename="{filename or "file"}"', @@ -185,14 +196,69 @@ def stream_upstream_url( headers=response_headers, ) + chunks = drs.stream_from_url(download_url, range_to_send) + first = await _open_upstream(chunks, download_url) return StreamingResponse( - drs.stream_from_url(download_url, range_to_send), + _resume_upstream(first, chunks), status_code=status_code, media_type=media_type, headers=response_headers, ) +async def _open_upstream(chunks: AsyncIterator[bytes], url: str) -> bytes: + """Pull the first chunk of an upstream stream, mapping its failures. + + Returns ``b""`` for an empty body. On failure the stream is closed + and the upstream condition is raised as the status the DRS branch of + ``/data`` uses for the same condition. + """ + try: + return await chunks.__anext__() + except StopAsyncIteration: + return b"" + except BaseException as exc: + await chunks.aclose() + if isinstance(exc, drs.DRSNotFound): + logger.warning("Upstream has no file at %s: %s", url, exc) + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="File not found in repository", + ) from exc + if isinstance(exc, drs.DRSForbidden): + logger.warning("Upstream refused %s: %s", url, exc) + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Access denied by upstream repository", + ) from exc + if isinstance(exc, drs.DRSTimeout): + logger.warning("Upstream timed out for %s: %s", url, exc) + raise HTTPException( + status_code=status.HTTP_504_GATEWAY_TIMEOUT, + detail="Upstream repository timeout", + ) from exc + if isinstance(exc, drs.DRSError): + logger.warning("Upstream failed for %s: %s", url, exc) + raise HTTPException( + status_code=status.HTTP_502_BAD_GATEWAY, + detail="Failed to stream file from upstream", + ) from exc + raise + + +async def _resume_upstream( + first: bytes, chunks: AsyncIterator[bytes] +) -> AsyncIterator[bytes]: + """Yield the already-pulled first chunk, then the rest of the stream.""" + try: + if first: + yield first + async for chunk in chunks: + yield chunk + finally: + await chunks.aclose() + + async def serve_workflow_artifact_or_dispatch( file_doc: dict[str, Any], artifact_kind: ArtifactKind, diff --git a/src/cfdb/api/routers/data.py b/src/cfdb/api/routers/data.py index bde532d..fd194b5 100644 --- a/src/cfdb/api/routers/data.py +++ b/src/cfdb/api/routers/data.py @@ -215,7 +215,7 @@ async def stream_file( ) logger.info(f"Streaming HTTPS file: {drs_object.name}") - return stream_upstream_url( + return await stream_upstream_url( download_url, drs_object.size, drs_object.name or "file", @@ -361,7 +361,7 @@ async def _stream_direct_url( media_type = "text/plain" try: - return stream_upstream_url( + return await stream_upstream_url( download_url, file_size, filename, diff --git a/src/cfdb/api/routers/index.py b/src/cfdb/api/routers/index.py index e022936..45b0a18 100644 --- a/src/cfdb/api/routers/index.py +++ b/src/cfdb/api/routers/index.py @@ -372,7 +372,7 @@ async def _try_serve_fourdn_sidecar( logger.info(f"Streaming 4DN sidecar: {filename} from {download_url}") - return stream_upstream_url( + return await stream_upstream_url( download_url, file_size, filename, request, range_header ) diff --git a/tests/test_data.py b/tests/test_data.py index 370f85c..ddde629 100644 --- a/tests/test_data.py +++ b/tests/test_data.py @@ -10,7 +10,6 @@ from wool.runtime.routine.task import do_dispatch from cfdb import api -from cfdb.api.routers import data as data_module from cfdb.api.routers.data import stream_file, stream_file_status from cfdb.services import drs, locks from cfdb.services.ontology_mappings import get_file_format @@ -58,6 +57,23 @@ def _make_file_doc(*, access_level: str = "public") -> dict: } +def _fake_upstream(chunks=(), error=None): + """Stand in for ``drs.stream_from_url`` at the network boundary. + + Yields ``chunks``, or raises ``error`` before the first byte -- which + is where the real stream raises an upstream 403/404/5xx, after + following redirects and reading the status. + """ + + async def stream(url, range_header=None): + if error is not None: + raise error + for chunk in chunks: + yield chunk + + return stream + + class TestStreamFile: @pytest.mark.asyncio async def test_non_public_file_returns_403(self, mock_db, mocker): @@ -69,7 +85,7 @@ async def test_non_public_file_returns_403(self, mock_db, mocker): mocker.patch.object(locks, "wait_for_cutover", return_value=None) mock_db.dcc.docs = [_make_dcc_doc()] - mock_db.file.docs = [_make_file_doc(access_level="consortium")] + mock_db.files.docs = [_make_file_doc(access_level="consortium")] with pytest.raises(HTTPException) as exc_info: await stream_file("hubmap", "file-1", _make_request(), range=None) @@ -87,31 +103,34 @@ async def test_stream_file_should_stream_a_hubmap_assets_url_directly( routing HuBMAP through DRS resolution answered 400 for every file. Given: - A public HuBMAP h5ad document carrying an assets access_url and - no workflow subsystem. + A public HuBMAP h5ad document carrying an assets access_url, no + workflow subsystem, and an upstream serving two chunks. When: - stream_file is called for it. + stream_file is called for it and the body is read. Then: - It should stream the assets URL directly and never consult DRS. + It should answer 200 with the upstream bytes fetched from the + assets URL, and never consult DRS. """ # Arrange mocker.patch.object(locks, "wait_for_cutover", return_value=None) mocker.patch.object(api, "processor_registry", None) mock_db.dcc.docs = [_make_dcc_doc()] - mock_db.file.docs = [_make_file_doc()] + mock_db.files.docs = [_make_file_doc()] fetch_drs = mocker.patch.object(drs, "fetch_drs_object") - stream = mocker.patch.object( - data_module, "stream_upstream_url", return_value="streamed" + upstream = mocker.patch.object( + drs, "stream_from_url", side_effect=_fake_upstream([b"ab", b"cd"]) ) # Act response = await stream_file( "hubmap", "file-1", _make_request(), range=None ) + body = b"".join([chunk async for chunk in response.body_iterator]) # Assert - assert response == "streamed" - assert stream.call_args.args[0] == HUBMAP_ASSETS_URL + assert response.status_code == 200 + assert body == b"abcd" + assert upstream.call_args.args[0] == HUBMAP_ASSETS_URL fetch_drs.assert_not_called() @pytest.mark.asyncio @@ -124,7 +143,7 @@ async def test_stream_file_should_stream_a_hubmap_assets_url_when_raw( A public HuBMAP BED document carrying an assets access_url, a registered processor for it, and raw=True. When: - stream_file is called for it. + stream_file is called for it and the body is read. Then: It should skip the workflow and stream the assets URL directly. """ @@ -140,22 +159,67 @@ async def test_stream_file_should_stream_a_hubmap_assets_url_when_raw( md5=FIXTURE_MD5, ) mock_db.dcc.docs = [_make_dcc_doc()] - mock_db.file.docs = [doc] + mock_db.files.docs = [doc] fetch_drs = mocker.patch.object(drs, "fetch_drs_object") - stream = mocker.patch.object( - data_module, "stream_upstream_url", return_value="streamed" + upstream = mocker.patch.object( + drs, "stream_from_url", side_effect=_fake_upstream([b"chr1\t1\t2\n"]) ) # Act response = await stream_file( "hubmap", "file-1", _make_request(), range=None, raw=True ) + body = b"".join([chunk async for chunk in response.body_iterator]) # Assert - assert response == "streamed" - assert stream.call_args.args[0] == bed_url + assert body == b"chr1\t1\t2\n" + assert upstream.call_args.args[0] == bed_url fetch_drs.assert_not_called() + @pytest.mark.asyncio + @pytest.mark.parametrize( + ("upstream_error", "expected_status"), + [ + (drs.DRSForbidden("upstream 403"), 403), + (drs.DRSNotFound("upstream 404"), 404), + (drs.DRSUpstreamError("upstream 500"), 502), + (drs.DRSTimeout("upstream timed out"), 504), + ], + ) + async def test_stream_file_should_raise_the_upstream_status_before_streaming( + self, mock_db, mocker, upstream_error, expected_status + ): + """Test an upstream refusal becomes its status, not a cut-off 200. + + Starlette sends the status line before it iterates a streaming + body, so an upstream error discovered inside the body could only + ever reach the client as a truncated download. + + Given: + A public HuBMAP document whose assets URL answers with an + upstream error before its first byte. + When: + stream_file is called for it. + Then: + It should raise the mapped HTTP status instead of returning a + response. + """ + # Arrange + mocker.patch.object(locks, "wait_for_cutover", return_value=None) + mocker.patch.object(api, "processor_registry", None) + mock_db.dcc.docs = [_make_dcc_doc()] + mock_db.files.docs = [_make_file_doc()] + mocker.patch.object( + drs, "stream_from_url", side_effect=_fake_upstream(error=upstream_error) + ) + + # Act + with pytest.raises(HTTPException) as exc_info: + await stream_file("hubmap", "file-1", _make_request(), range=None) + + # Assert + assert exc_info.value.status_code == expected_status + @pytest.mark.asyncio async def test_stream_file_should_raise_502_when_direct_url_disallowed( self, mock_db, mocker @@ -172,7 +236,7 @@ async def test_stream_file_should_raise_502_when_direct_url_disallowed( When: stream_file is called for it. Then: - It should raise a 502 without streaming anything. + It should raise a 502 without opening an upstream request. """ # Arrange mocker.patch.object(locks, "wait_for_cutover", return_value=None) @@ -180,8 +244,8 @@ async def test_stream_file_should_raise_502_when_direct_url_disallowed( doc = _make_file_doc() doc["access_url"] = "https://attacker.example/secondary_analysis.h5ad" mock_db.dcc.docs = [_make_dcc_doc()] - mock_db.file.docs = [doc] - stream = mocker.patch.object(data_module, "stream_upstream_url") + mock_db.files.docs = [doc] + upstream = mocker.patch.object(drs, "stream_from_url") # Act with pytest.raises(HTTPException) as exc_info: @@ -189,7 +253,7 @@ async def test_stream_file_should_raise_502_when_direct_url_disallowed( # Assert assert exc_info.value.status_code == 502 - stream.assert_not_called() + upstream.assert_not_called() class TestStreamFileWorkflowPath: @@ -616,7 +680,7 @@ def lookup_for(self, _doc): mocker.patch.object(api, "executor", object()) mock_db.dcc.docs = [_make_dcc_doc()] - mock_db.file.docs = [_make_file_doc(access_level="protected")] + mock_db.files.docs = [_make_file_doc(access_level="protected")] # Act & assert with pytest.raises(HTTPException) as exc_info: @@ -843,7 +907,7 @@ async def test_stream_file_status_should_raise_403_when_hubmap_not_public( # Arrange mocker.patch.object(locks, "wait_for_cutover", return_value=None) mock_db.dcc.docs = [_make_dcc_doc()] - mock_db.file.docs = [_make_file_doc(access_level="consortium")] + mock_db.files.docs = [_make_file_doc(access_level="consortium")] # Act & assert with pytest.raises(HTTPException) as exc_info: @@ -1192,6 +1256,7 @@ async def test_stream_file_should_log_no_error_when_the_request_succeeds( mocker.patch.object(locks, "wait_for_cutover", return_value=None) mocker.patch.object(api, "processor_registry", None) mock_db.file.docs = [_make_encode_file_doc()] + mocker.patch.object(drs, "stream_from_url", _fake_upstream([b"x"])) # Act with caplog.at_level(logging.INFO, logger="cfdb.api.routers.data"): @@ -1223,7 +1288,7 @@ async def test_stream_file_should_log_no_error_when_access_is_refused( mocker.patch.object(locks, "wait_for_cutover", return_value=None) mocker.patch.object(api, "processor_registry", None) mock_db.dcc.docs = [_make_dcc_doc()] - mock_db.file.docs = [_make_file_doc(access_level="consortium")] + mock_db.files.docs = [_make_file_doc(access_level="consortium")] # Act with ( @@ -1310,6 +1375,7 @@ async def test_stream_file_should_carry_the_document_filename_downstream( else: doc["filename"] = filename mock_db.file.docs = [doc] + mocker.patch.object(drs, "stream_from_url", _fake_upstream([b"x"])) # Act response = await stream_file( From 51d91984ec770ea16ff3297657ee4a8f22f8da32 Mon Sep 17 00:00:00 2001 From: Conrad Date: Fri, 20 Nov 2026 17:46:06 -0500 Subject: [PATCH 16/37] refactor: Move the shared ingest helpers out of the ENCODE module 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. --- src/cfdb/services/encode.py | 130 +-------- src/cfdb/services/hubmap.py | 6 +- src/cfdb/services/ingest_common.py | 128 ++++++++ tests/test_encode.py | 371 +---------------------- tests/test_ingest_common.py | 455 +++++++++++++++++++++++++++++ 5 files changed, 600 insertions(+), 490 deletions(-) create mode 100644 src/cfdb/services/ingest_common.py create mode 100644 tests/test_ingest_common.py diff --git a/src/cfdb/services/encode.py b/src/cfdb/services/encode.py index f591aca..90f2c8f 100644 --- a/src/cfdb/services/encode.py +++ b/src/cfdb/services/encode.py @@ -170,12 +170,16 @@ import re from contextlib import aclosing from typing import AsyncGenerator, Optional -from urllib.parse import unquote, urlencode, urlsplit +from urllib.parse import urlencode import aiohttp from cfdb.accessions import normalize_accession from cfdb.dcc_registry import get_dcc_config +from cfdb.services.ingest_common import ( + derive_compression_format, + timeout_from_env, +) from cfdb.services.ontology_mappings import ( get_assay_type, get_data_type, @@ -186,29 +190,6 @@ logger = logging.getLogger(__name__) -def _timeout_from_env(name: str, default: int) -> int: - """Parse a positive-int timeout env var, failing loudly at import. - - A bare ``int(os.getenv(...))`` raises a bare ``ValueError`` from deep in - the import machinery when an operator sets the variable to something - non-numeric, naming neither the variable nor the value. Zero or negative - is rejected too: aiohttp treats a non-positive total as "no timeout", - which would silently turn a misconfiguration into an unbounded request. - """ - raw = os.getenv(name) - if raw is None or raw == "": - return default - try: - parsed = int(raw) - except ValueError as exc: - raise ValueError( - f"Environment variable {name}={raw!r} is not a valid integer" - ) from exc - if parsed <= 0: - raise ValueError(f"Environment variable {name}={parsed} must be > 0") - return parsed - - #: Environment variable overriding the metadata download budget, and the #: default applied when it is unset. Resolved per call rather than at import: #: a malformed value should fail the sync that reads it, not the import of @@ -234,7 +215,7 @@ def metadata_budget_seconds() -> int: shares one deadline across them, rather than granting each stream its own full allowance. """ - return _timeout_from_env( + return timeout_from_env( _METADATA_TIMEOUT_ENV, _METADATA_TIMEOUT_DEFAULT_SECONDS ) @@ -262,7 +243,7 @@ def annotation_types_from_env() -> tuple[str, ...]: is deliberate -- turning the annotation path off is a legitimate operator choice, and having to edit code to make it is worse than honoring an explicitly empty setting. It is also the opposite of what - :func:`_timeout_from_env` does with an empty value, so the empty case + :func:`timeout_from_env` does with an empty value, so the empty case logs a warning rather than leaving the operator to infer it from an absence in the per-phase log. @@ -274,7 +255,7 @@ def annotation_types_from_env() -> tuple[str, ...]: re-sync. Resolved per call rather than at import, matching - :func:`_timeout_from_env`: the value is only meaningful to the sync, so + :func:`timeout_from_env`: the value is only meaningful to the sync, so a bad one should fail the sync rather than the API's import of this module. """ @@ -287,7 +268,7 @@ def annotation_types_from_env() -> tuple[str, ...]: allowlist = tuple(dict.fromkeys(entry for entry in entries if entry)) if not allowlist: - # Warned about because the neighbouring :func:`_timeout_from_env` + # Warned about because the neighbouring :func:`timeout_from_env` # reads an empty value as "unset, use the default" and this one # reads it as "ingest nothing" -- a difference an operator has no # reason to expect between two variables of the same module. Empty @@ -527,99 +508,6 @@ def _parse_int(value: str | None) -> int | None: return None -# Compression suffix to EDAM CV term ID, verified against OLS4: format:3989 is -# "GZIP format" (extensions gz, gzip), format:3615 is "bgzip" (bgz). Beware -# format:3990, which adjoins them and is "AVI", not the bzip2 term it looks -# like. The ENCODE metadata TSV carries no compression column (verified against -# the live 59-column header), so the filename suffix is the only indicator. -# -# Only .gz and .starch actually occur in the released ENCODE corpus; the rest -# are defensive. The suffix cannot distinguish BGZF from plain gzip — ENCODE -# publishes no .bgz and roughly a quarter of its .gz files are BGZF — so -# format:3989 here means "gzip-family stream", not "not bgzip". -COMPRESSION_SUFFIX_TO_EDAM = { - ".gz": "format:3989", - ".gzip": "format:3989", - ".tgz": "format:3989", # gzip-compressed tar; same bytes as .tar.gz - ".bgz": "format:3615", -} - -# Suffixes that mark a file as compressed but that no EDAM term can express. -# EDAM has no bzip2, xz, zstd or starch term. .zip is here despite having one -# (format:3987) because a ZIP holds many members with many formats, so there is -# no single post-decompression file_format to pair it with, and the tabix -# processor rejects the PK magic outright — calling it a named compression -# would invite a consumer to decompress and feed it onward. .starch is a -# BEDOPS-compressed BED archive whose file_format already maps to plain BED. -# -# These resolve to None rather than to UNCOMPRESSED: they are compressed, so -# claiming otherwise would be worse than admitting we cannot say. -UNMAPPABLE_COMPRESSION_SUFFIXES = (".bz2", ".xz", ".zst", ".zip", ".starch") - -# Longest suffix first, so a more specific suffix is never shadowed by a -# shorter one it ends with. -_COMPRESSION_SUFFIXES: tuple[tuple[str, str | None], ...] = tuple( - sorted( - list(COMPRESSION_SUFFIX_TO_EDAM.items()) - + [(suffix, None) for suffix in UNMAPPABLE_COMPRESSION_SUFFIXES], - key=lambda item: len(item[0]), - reverse=True, - ) -) - -# Sentinel for "no compression beyond what file_format already implies", -# mirroring the value 4DN and HuBMAP carry from their upstream C2M2 -# datapackages. It is NOT a claim that the bytes are uncompressed: BAM, bigWig -# and bigBed are internally compressed and carry this value, because their -# file_format names the container rather than its decompressed contents. -# Distinct from None, which means no determination was possible at all. -UNCOMPRESSED = "" - - -def derive_compression_format(filename_or_url: str | None) -> str | None: - """ - Derive the EDAM compression term ID from a filename or download URL. - - Reports only compression that is *extrinsic* to the declared file format — - a wrapper the filename reveals and file_format does not. A .bam is not - reported as compressed even though BGZF underlies it, because its - file_format already names that container; a .starch is not reported as - uncompressed, because its file_format names the BED it decompresses to. - - Args: - filename_or_url: A bare filename or a full download URL. - - Returns: - The EDAM CV term ID for the compression format (e.g. "format:3989" - for gzip); "" when the name carries no compression suffix; or None - when no determination is possible — either because no name was - available, or because the name ends in a compression suffix no EDAM - term can express. - """ - value = _nonempty(filename_or_url) - if value is None: - return None - - # Reduce to a basename. Query strings and fragments are URL syntax, so they - # are stripped only when the value actually is a URL — in a bare filename a - # '?' or '#' is an ordinary character and must not truncate the name. - if "://" in value: - basename = unquote(urlsplit(value).path).rsplit("/", 1)[-1] - else: - basename = value.rsplit("/", 1)[-1] - basename = basename.lower() - if not basename: - # A directory-style URL carries no evidence either way. Reporting it - # as uncompressed would be a positive claim about a file we cannot see. - return None - - for suffix, term_id in _COMPRESSION_SUFFIXES: - if basename.endswith(suffix): - return term_id - - return UNCOMPRESSED - - def _extract_donor_ids(donors_str: str | None) -> list[str]: """ Extract donor accession IDs from the Donor(s) TSV field. diff --git a/src/cfdb/services/hubmap.py b/src/cfdb/services/hubmap.py index 033bd8f..37207a5 100644 --- a/src/cfdb/services/hubmap.py +++ b/src/cfdb/services/hubmap.py @@ -109,11 +109,11 @@ import aiohttp from cfdb.dcc_registry import get_dcc_config -from cfdb.services.encode import ( +from cfdb.services.ingest_common import ( COMPRESSION_SUFFIX_TO_EDAM, UNMAPPABLE_COMPRESSION_SUFFIXES, - _timeout_from_env, derive_compression_format, + timeout_from_env, ) from cfdb.services.ontology_mappings import get_file_format, get_taxonomy @@ -296,7 +296,7 @@ def sync_budget_seconds() -> int: Read per call, like ENCODE's budget, so a malformed value fails the sync that reads it rather than the import of this module. """ - return _timeout_from_env(_SYNC_TIMEOUT_ENV, _SYNC_TIMEOUT_DEFAULT_SECONDS) + return timeout_from_env(_SYNC_TIMEOUT_ENV, _SYNC_TIMEOUT_DEFAULT_SECONDS) class _RetryablePageError(RuntimeError): diff --git a/src/cfdb/services/ingest_common.py b/src/cfdb/services/ingest_common.py new file mode 100644 index 0000000..d573059 --- /dev/null +++ b/src/cfdb/services/ingest_common.py @@ -0,0 +1,128 @@ +"""Ingest helpers shared by the REST-API DCC loaders (ENCODE, HuBMAP). + +DCC-neutral pieces both loaders need: parsing a timeout budget from the +environment, and deriving a compression term from a filename suffix. They +lived in the ENCODE module until HuBMAP needed them too; keeping them in a +neutral home means a refactor of either loader cannot silently change the +other's behavior. +""" + +import os +from urllib.parse import unquote, urlsplit + + +def timeout_from_env(name: str, default: int) -> int: + """Parse a positive-int timeout env var, failing loudly at import. + + A bare ``int(os.getenv(...))`` raises a bare ``ValueError`` from deep in + the import machinery when an operator sets the variable to something + non-numeric, naming neither the variable nor the value. Zero or negative + is rejected too: aiohttp treats a non-positive total as "no timeout", + which would silently turn a misconfiguration into an unbounded request. + """ + raw = os.getenv(name) + if raw is None or raw == "": + return default + try: + parsed = int(raw) + except ValueError as exc: + raise ValueError( + f"Environment variable {name}={raw!r} is not a valid integer" + ) from exc + if parsed <= 0: + raise ValueError(f"Environment variable {name}={parsed} must be > 0") + return parsed + + +# Compression suffix to EDAM CV term ID, verified against OLS4: format:3989 is +# "GZIP format" (extensions gz, gzip), format:3615 is "bgzip" (bgz). Beware +# format:3990, which adjoins them and is "AVI", not the bzip2 term it looks +# like. Neither the ENCODE metadata TSV (verified against its live 59-column +# header) nor the HuBMAP files index carries a compression field, so the +# filename suffix is the only indicator. +# +# Only .gz and .starch actually occur in the released ENCODE corpus; the rest +# are defensive. The suffix cannot distinguish BGZF from plain gzip — ENCODE +# publishes no .bgz and roughly a quarter of its .gz files are BGZF — so +# format:3989 here means "gzip-family stream", not "not bgzip". +COMPRESSION_SUFFIX_TO_EDAM = { + ".gz": "format:3989", + ".gzip": "format:3989", + ".tgz": "format:3989", # gzip-compressed tar; same bytes as .tar.gz + ".bgz": "format:3615", +} + +# Suffixes that mark a file as compressed but that no EDAM term can express. +# EDAM has no bzip2, xz, zstd or starch term. .zip is here despite having one +# (format:3987) because a ZIP holds many members with many formats, so there is +# no single post-decompression file_format to pair it with, and the tabix +# processor rejects the PK magic outright — calling it a named compression +# would invite a consumer to decompress and feed it onward. .starch is a +# BEDOPS-compressed BED archive whose file_format already maps to plain BED. +# +# These resolve to None rather than to UNCOMPRESSED: they are compressed, so +# claiming otherwise would be worse than admitting we cannot say. +UNMAPPABLE_COMPRESSION_SUFFIXES = (".bz2", ".xz", ".zst", ".zip", ".starch") + +# Longest suffix first, so a more specific suffix is never shadowed by a +# shorter one it ends with. +_COMPRESSION_SUFFIXES: tuple[tuple[str, str | None], ...] = tuple( + sorted( + list(COMPRESSION_SUFFIX_TO_EDAM.items()) + + [(suffix, None) for suffix in UNMAPPABLE_COMPRESSION_SUFFIXES], + key=lambda item: len(item[0]), + reverse=True, + ) +) + +# Sentinel for "no compression beyond what file_format already implies", +# mirroring the value 4DN carries from its upstream C2M2 datapackage. It is +# NOT a claim that the bytes are uncompressed: BAM, bigWig and bigBed are +# internally compressed and carry this value, because their file_format +# names the container rather than its decompressed contents. +# Distinct from None, which means no determination was possible at all. +UNCOMPRESSED = "" + + +def derive_compression_format(filename_or_url: str | None) -> str | None: + """ + Derive the EDAM compression term ID from a filename or download URL. + + Reports only compression that is *extrinsic* to the declared file format — + a wrapper the filename reveals and file_format does not. A .bam is not + reported as compressed even though BGZF underlies it, because its + file_format already names that container; a .starch is not reported as + uncompressed, because its file_format names the BED it decompresses to. + + Args: + filename_or_url: A bare filename or a full download URL. + + Returns: + The EDAM CV term ID for the compression format (e.g. "format:3989" + for gzip); "" when the name carries no compression suffix; or None + when no determination is possible — either because no name was + available, or because the name ends in a compression suffix no EDAM + term can express. + """ + value = (filename_or_url or "").strip() + if not value: + return None + + # Reduce to a basename. Query strings and fragments are URL syntax, so they + # are stripped only when the value actually is a URL — in a bare filename a + # '?' or '#' is an ordinary character and must not truncate the name. + if "://" in value: + basename = unquote(urlsplit(value).path).rsplit("/", 1)[-1] + else: + basename = value.rsplit("/", 1)[-1] + basename = basename.lower() + if not basename: + # A directory-style URL carries no evidence either way. Reporting it + # as uncompressed would be a positive claim about a file we cannot see. + return None + + for suffix, term_id in _COMPRESSION_SUFFIXES: + if basename.endswith(suffix): + return term_id + + return UNCOMPRESSED diff --git a/tests/test_encode.py b/tests/test_encode.py index 5c1f08c..b61c15f 100644 --- a/tests/test_encode.py +++ b/tests/test_encode.py @@ -1,4 +1,4 @@ -"""Tests for the ENCODE metadata fetch, compression derivation and transform.""" +"""Tests for the ENCODE metadata fetch and transform.""" from __future__ import annotations @@ -15,16 +15,16 @@ from cfdb.models import FileMetadataModel from cfdb.services import encode as encode_module from cfdb.services.encode import ( - COMPRESSION_SUFFIX_TO_EDAM, - UNCOMPRESSED, - UNMAPPABLE_COMPRESSION_SUFFIXES, annotation_types_from_env, - derive_compression_format, fetch_encode_annotation_metadata, fetch_encode_metadata, transform_annotation_to_c2m2, transform_to_c2m2, ) +from cfdb.services.ingest_common import ( + COMPRESSION_SUFFIX_TO_EDAM, + UNCOMPRESSED, +) #: The variable the metadata fetch reads its budget from. Named here rather #: than imported so the tests pin the operator-facing contract: renaming it in @@ -534,367 +534,6 @@ async def test_fetch_encode_metadata_should_wrap_a_network_error(mocker): [row async for row in fetch_encode_metadata()] -def test_compression_suffix_tables_should_hold_the_verified_edam_terms(): - """Test the suffix vocabulary against literal, externally verified IDs. - - Given: - The EDAM terms resolved against OLS4: format:3989 is "GZIP format" - (extensions gz, gzip), format:3615 is "bgzip", and format:3990 is - "AVI" rather than the bzip2 term it resembles. - When: - The published suffix tables are compared to those literals. - Then: - They should match exactly, so a mistyped or dropped term cannot ship - unnoticed. - """ - # Act & assert - assert COMPRESSION_SUFFIX_TO_EDAM == { - ".gz": "format:3989", - ".gzip": "format:3989", - ".tgz": "format:3989", - ".bgz": "format:3615", - } - assert UNMAPPABLE_COMPRESSION_SUFFIXES == ( - ".bz2", - ".xz", - ".zst", - ".zip", - ".starch", - ) - - -def test_derive_compression_format_should_return_gzip_term_when_url_ends_in_gz(): - """Test the canonical ENCODE download URL for a gzipped file. - - Given: - The real ENCODE download URL shape, whose basename ends in ".bed.gz" - and whose path contains an "@@download" segment. - When: - derive_compression_format is called. - Then: - It should return the EDAM gzip term ID. - """ - # Arrange - url = DOWNLOAD_URL.format(name="ENCFF123ABC.bed.gz") - - # Act - result = derive_compression_format(url) - - # Assert - assert result == "format:3989" - - -@pytest.mark.parametrize( - ("suffix", "term_id"), sorted(COMPRESSION_SUFFIX_TO_EDAM.items()) -) -def test_derive_compression_format_should_return_the_mapped_term_for_every_suffix( - suffix, term_id -): - """Test that every suffix in the mapping table is reachable. - - Given: - A filename ending in each suffix the module publishes. - When: - derive_compression_format is called. - Then: - It should return that suffix's EDAM term ID. - """ - # Act - result = derive_compression_format(f"ENCFF123ABC.bed{suffix}") - - # Assert - assert result == term_id - - -def test_derive_compression_format_should_return_bgzip_term_when_suffix_is_bgz(): - """Test that the gzip suffix does not shadow the bgzip suffix. - - Given: - A filename ending in ".bgz", which contains the letters "gz". - When: - derive_compression_format is called. - Then: - It should return the bgzip term rather than the plain gzip term. - """ - # Act - result = derive_compression_format("ENCFF123ABC.bed.bgz") - - # Assert - assert result == "format:3615" - - -def test_derive_compression_format_should_agree_on_tgz_and_tar_gz(): - """Test that the two spellings of a gzipped tar agree. - - Given: - The same artifact named ".tar.gz" and named ".tgz". - When: - derive_compression_format is called on each. - Then: - Both should return the gzip term, since the compression is identical. - """ - # Act - long_form = derive_compression_format("ENCFF1.tar.gz") - short_form = derive_compression_format("ENCFF1.tgz") - - # Assert - assert long_form == short_form == "format:3989" - - -@pytest.mark.parametrize( - "name", ["ENCFF1.BED.GZ", "ENCFF1.bed.Gz", "ENCFF1.BED.BGZ", "ENCFF1.TGZ"] -) -def test_derive_compression_format_should_ignore_case_of_the_suffix(name): - """Test that suffix matching is case insensitive. - - Given: - A filename whose compression suffix is upper or mixed case. - When: - derive_compression_format is called. - Then: - It should return the same term as the lowercase spelling. - """ - # Act - result = derive_compression_format(name) - - # Assert - assert result == derive_compression_format(name.lower()) - - -def test_derive_compression_format_should_use_the_basename_when_the_query_holds_a_path(): - """Test that a query string containing a slash cannot become the basename. - - Given: - A gzipped download URL whose query string embeds a path ending in a - different, uncompressed filename. - When: - derive_compression_format is called. - Then: - It should return the gzip term from the real basename. - """ - # Act - result = derive_compression_format("https://h/ENCFF1.bed.gz?redirect=/x/y.bam") - - # Assert - assert result == "format:3989" - - -@pytest.mark.parametrize( - "url", ["https://h/ENCFF1.bed?download=y.gz", "https://h/ENCFF1.bed#part.gz"] -) -def test_derive_compression_format_should_ignore_a_suffix_outside_the_basename(url): - """Test that a query string or fragment cannot fabricate a suffix. - - Given: - A URL for an uncompressed file whose query string or fragment ends in - a compression suffix. - When: - derive_compression_format is called. - Then: - It should report no compression. - """ - # Act - result = derive_compression_format(url) - - # Assert - assert result == UNCOMPRESSED - - -@pytest.mark.parametrize("name", ["sample#1.bed.gz", "sample?1.bed.gz"]) -def test_derive_compression_format_should_keep_url_punctuation_in_a_bare_filename(name): - """Test that a bare filename is not truncated at a '#' or '?'. - - Given: - A gzipped bare filename containing a character that would delimit a - query string or fragment in a URL. - When: - derive_compression_format is called. - Then: - It should still return the gzip term, since URL syntax does not apply - to a name that is not a URL. - """ - # Act - result = derive_compression_format(name) - - # Assert - assert result == "format:3989" - - -@pytest.mark.parametrize( - "name", ["ENCFF1.gz.bed", "ENCFF1.bed.gz.txt", "gzfile.bed", "ENCFF1.zip.bam"] -) -def test_derive_compression_format_should_report_uncompressed_when_suffix_is_not_final( - name, -): - """Test that a compression token away from the end does not match. - - Given: - A filename in which a compression token appears somewhere other than - the final suffix. - When: - derive_compression_format is called. - Then: - It should report no compression. - """ - # Act - result = derive_compression_format(name) - - # Assert - assert result == UNCOMPRESSED - - -@pytest.mark.parametrize( - "name", - ["ENCFF1.bed", "ENCFF1.bam", "ENCFF1.bigWig", "ENCFF1.bigBed", "ENCFF1.tar"], -) -def test_derive_compression_format_should_report_uncompressed_when_no_suffix_matches( - name, -): - """Test the sentinel for names carrying no extrinsic compression. - - Given: - Filenames for formats the corpus carries, including BAM, bigWig and - bigBed, whose bytes are internally compressed but whose file_format - already names that container. - When: - derive_compression_format is called. - Then: - It should return the empty-string sentinel, which reports the absence - of compression beyond file_format rather than uncompressed bytes. - """ - # Act - result = derive_compression_format(name) - - # Assert - assert result == UNCOMPRESSED - assert result is not None - - -@pytest.mark.parametrize("suffix", UNMAPPABLE_COMPRESSION_SUFFIXES) -def test_derive_compression_format_should_return_none_when_compression_is_unmappable( - suffix, -): - """Test that a compressed file EDAM cannot name is not called uncompressed. - - Given: - A filename ending in a compression suffix no EDAM term expresses. - When: - derive_compression_format is called. - Then: - It should return None rather than the uncompressed sentinel. - """ - # Act - result = derive_compression_format(f"ENCFF1.bed{suffix}") - - # Assert - assert result is None - - -@pytest.mark.parametrize( - "value", [None, "", " ", "https://h/files/ENCFF1/@@download/", "https://h/"] -) -def test_derive_compression_format_should_return_none_when_no_basename_is_available( - value, -): - """Test that a name-less input yields no determination. - - Given: - An absent, blank, or directory-style value carrying no filename. - When: - derive_compression_format is called. - Then: - It should return None, since there is no evidence either way. - """ - # Act - result = derive_compression_format(value) - - # Assert - assert result is None - - -@given(st.none() | st.text()) -@settings(max_examples=300) -def test_derive_compression_format_should_return_a_value_from_the_closed_vocabulary( - value, -): - """Test that the derived value never escapes its vocabulary. - - Given: - Any text, or no value at all, as a filename or URL. - When: - derive_compression_format is called. - Then: - It should return a mapped EDAM term, the uncompressed sentinel, or - None, and never raise. - """ - # Act - result = derive_compression_format(value) - - # Assert - assert result in DERIVED_VALUES - - -@given( - name=st.text(min_size=1).filter( - lambda s: s == s.strip() and not (set(s) & set("/?#")) - ), - host=st.text(alphabet=st.characters(whitelist_categories=("Ll", "Nd")), min_size=1), - query=st.text().filter(lambda s: not (set(s) & set("?#"))), - fragment=st.text().filter(lambda s: "#" not in s), -) -@settings(max_examples=200) -def test_derive_compression_format_should_ignore_url_decoration( - name, host, query, fragment -): - """Test that wrapping a filename in a URL does not change the answer. - - Given: - Any filename free of the URL-reserved characters that would make it - mean something else inside a URL, plus any host, query string and - fragment to decorate it with. - When: - derive_compression_format is called on the bare name and on the - decorated URL. - Then: - Both should yield the same value. - """ - # Arrange - url = f"https://{host}/p/{name}?{query}#{fragment}" - - # Act - bare_result = derive_compression_format(name) - url_result = derive_compression_format(url) - - # Assert - assert bare_result == url_result - - -@given( - stem=st.text().filter(lambda s: "/" not in s), - suffix=st.sampled_from(sorted(COMPRESSION_SUFFIX_TO_EDAM)), -) -@settings(max_examples=200) -def test_derive_compression_format_should_classify_any_stem_with_a_known_suffix( - stem, suffix -): - """Test that no stem can suppress a recognized compression suffix. - - Given: - Any stem free of path separators, followed by one of the mapped - compression suffixes. - When: - derive_compression_format is called. - Then: - It should return a mapped EDAM term rather than the uncompressed - sentinel or None. - """ - # Act - result = derive_compression_format(stem + suffix) - - # Assert - assert result in set(COMPRESSION_SUFFIX_TO_EDAM.values()) - - def test_transform_to_c2m2_should_set_the_gzip_term_when_the_download_url_is_gzipped(): """Test that a gzipped row carries gzip alongside the uncompressed format. diff --git a/tests/test_ingest_common.py b/tests/test_ingest_common.py new file mode 100644 index 0000000..bd93468 --- /dev/null +++ b/tests/test_ingest_common.py @@ -0,0 +1,455 @@ +"""Tests for the ingest helpers shared by the REST-API DCC loaders.""" + +from __future__ import annotations + +import pytest +from hypothesis import given, settings +from hypothesis import strategies as st + +from cfdb.services.ingest_common import ( + COMPRESSION_SUFFIX_TO_EDAM, + UNCOMPRESSED, + UNMAPPABLE_COMPRESSION_SUFFIXES, + derive_compression_format, + timeout_from_env, +) + +DOWNLOAD_URL = "https://www.encodeproject.org/files/ENCFF123ABC/@@download/{name}" + +# Every value the derivation is allowed to produce, for closed-domain +# assertions. +DERIVED_VALUES = set(COMPRESSION_SUFFIX_TO_EDAM.values()) | {UNCOMPRESSED, None} + +#: A variable name no other test or setting uses, so the timeout tests own it. +TIMEOUT_ENV = "CFDB_TEST_INGEST_TIMEOUT_SECONDS" + + +def test_timeout_from_env_should_return_the_default_when_unset(monkeypatch): + """Test an unset or empty variable falls back to the default. + + Given: + The variable unset, then set to an empty string. + When: + timeout_from_env resolves it. + Then: + It should return the default both times. + """ + # Arrange + monkeypatch.delenv(TIMEOUT_ENV, raising=False) + + # Act + unset = timeout_from_env(TIMEOUT_ENV, 42) + monkeypatch.setenv(TIMEOUT_ENV, "") + empty = timeout_from_env(TIMEOUT_ENV, 42) + + # Assert + assert (unset, empty) == (42, 42) + + +def test_timeout_from_env_should_parse_a_positive_integer(monkeypatch): + """Test a positive integer value overrides the default. + + Given: + The variable set to "90". + When: + timeout_from_env resolves it. + Then: + It should return 90. + """ + # Arrange + monkeypatch.setenv(TIMEOUT_ENV, "90") + + # Act + value = timeout_from_env(TIMEOUT_ENV, 42) + + # Assert + assert value == 90 + + +@pytest.mark.parametrize( + ("raw", "message"), + [("ninety", "not a valid integer"), ("0", "must be > 0"), ("-5", "must be > 0")], +) +def test_timeout_from_env_should_raise_when_the_value_is_unusable( + monkeypatch, raw, message +): + """Test a malformed or non-positive budget fails loudly. + + aiohttp reads a non-positive total as "no timeout", so accepting one + would turn a misconfiguration into an unbounded request. + + Given: + The variable set to a non-integer, zero, or a negative value. + When: + timeout_from_env resolves it. + Then: + It should raise a ValueError naming the variable and the defect. + """ + # Arrange + monkeypatch.setenv(TIMEOUT_ENV, raw) + + # Act & assert + with pytest.raises(ValueError, match=message) as exc_info: + timeout_from_env(TIMEOUT_ENV, 42) + assert TIMEOUT_ENV in str(exc_info.value) + + +def test_compression_suffix_tables_should_hold_the_verified_edam_terms(): + """Test the suffix vocabulary against literal, externally verified IDs. + + Given: + The EDAM terms resolved against OLS4: format:3989 is "GZIP format" + (extensions gz, gzip), format:3615 is "bgzip", and format:3990 is + "AVI" rather than the bzip2 term it resembles. + When: + The published suffix tables are compared to those literals. + Then: + They should match exactly, so a mistyped or dropped term cannot ship + unnoticed. + """ + # Act & assert + assert COMPRESSION_SUFFIX_TO_EDAM == { + ".gz": "format:3989", + ".gzip": "format:3989", + ".tgz": "format:3989", + ".bgz": "format:3615", + } + assert UNMAPPABLE_COMPRESSION_SUFFIXES == ( + ".bz2", + ".xz", + ".zst", + ".zip", + ".starch", + ) + + +def test_derive_compression_format_should_return_gzip_term_when_url_ends_in_gz(): + """Test the canonical ENCODE download URL for a gzipped file. + + Given: + The real ENCODE download URL shape, whose basename ends in ".bed.gz" + and whose path contains an "@@download" segment. + When: + derive_compression_format is called. + Then: + It should return the EDAM gzip term ID. + """ + # Arrange + url = DOWNLOAD_URL.format(name="ENCFF123ABC.bed.gz") + + # Act + result = derive_compression_format(url) + + # Assert + assert result == "format:3989" + + +@pytest.mark.parametrize( + ("suffix", "term_id"), sorted(COMPRESSION_SUFFIX_TO_EDAM.items()) +) +def test_derive_compression_format_should_return_the_mapped_term_for_every_suffix( + suffix, term_id +): + """Test that every suffix in the mapping table is reachable. + + Given: + A filename ending in each suffix the module publishes. + When: + derive_compression_format is called. + Then: + It should return that suffix's EDAM term ID. + """ + # Act + result = derive_compression_format(f"ENCFF123ABC.bed{suffix}") + + # Assert + assert result == term_id + + +def test_derive_compression_format_should_return_bgzip_term_when_suffix_is_bgz(): + """Test that the gzip suffix does not shadow the bgzip suffix. + + Given: + A filename ending in ".bgz", which contains the letters "gz". + When: + derive_compression_format is called. + Then: + It should return the bgzip term rather than the plain gzip term. + """ + # Act + result = derive_compression_format("ENCFF123ABC.bed.bgz") + + # Assert + assert result == "format:3615" + + +def test_derive_compression_format_should_agree_on_tgz_and_tar_gz(): + """Test that the two spellings of a gzipped tar agree. + + Given: + The same artifact named ".tar.gz" and named ".tgz". + When: + derive_compression_format is called on each. + Then: + Both should return the gzip term, since the compression is identical. + """ + # Act + long_form = derive_compression_format("ENCFF1.tar.gz") + short_form = derive_compression_format("ENCFF1.tgz") + + # Assert + assert long_form == short_form == "format:3989" + + +@pytest.mark.parametrize( + "name", ["ENCFF1.BED.GZ", "ENCFF1.bed.Gz", "ENCFF1.BED.BGZ", "ENCFF1.TGZ"] +) +def test_derive_compression_format_should_ignore_case_of_the_suffix(name): + """Test that suffix matching is case insensitive. + + Given: + A filename whose compression suffix is upper or mixed case. + When: + derive_compression_format is called. + Then: + It should return the same term as the lowercase spelling. + """ + # Act + result = derive_compression_format(name) + + # Assert + assert result == derive_compression_format(name.lower()) + + +def test_derive_compression_format_should_use_the_basename_when_the_query_holds_a_path(): + """Test that a query string containing a slash cannot become the basename. + + Given: + A gzipped download URL whose query string embeds a path ending in a + different, uncompressed filename. + When: + derive_compression_format is called. + Then: + It should return the gzip term from the real basename. + """ + # Act + result = derive_compression_format("https://h/ENCFF1.bed.gz?redirect=/x/y.bam") + + # Assert + assert result == "format:3989" + + +@pytest.mark.parametrize( + "url", ["https://h/ENCFF1.bed?download=y.gz", "https://h/ENCFF1.bed#part.gz"] +) +def test_derive_compression_format_should_ignore_a_suffix_outside_the_basename(url): + """Test that a query string or fragment cannot fabricate a suffix. + + Given: + A URL for an uncompressed file whose query string or fragment ends in + a compression suffix. + When: + derive_compression_format is called. + Then: + It should report no compression. + """ + # Act + result = derive_compression_format(url) + + # Assert + assert result == UNCOMPRESSED + + +@pytest.mark.parametrize("name", ["sample#1.bed.gz", "sample?1.bed.gz"]) +def test_derive_compression_format_should_keep_url_punctuation_in_a_bare_filename(name): + """Test that a bare filename is not truncated at a '#' or '?'. + + Given: + A gzipped bare filename containing a character that would delimit a + query string or fragment in a URL. + When: + derive_compression_format is called. + Then: + It should still return the gzip term, since URL syntax does not apply + to a name that is not a URL. + """ + # Act + result = derive_compression_format(name) + + # Assert + assert result == "format:3989" + + +@pytest.mark.parametrize( + "name", ["ENCFF1.gz.bed", "ENCFF1.bed.gz.txt", "gzfile.bed", "ENCFF1.zip.bam"] +) +def test_derive_compression_format_should_report_uncompressed_when_suffix_is_not_final( + name, +): + """Test that a compression token away from the end does not match. + + Given: + A filename in which a compression token appears somewhere other than + the final suffix. + When: + derive_compression_format is called. + Then: + It should report no compression. + """ + # Act + result = derive_compression_format(name) + + # Assert + assert result == UNCOMPRESSED + + +@pytest.mark.parametrize( + "name", + ["ENCFF1.bed", "ENCFF1.bam", "ENCFF1.bigWig", "ENCFF1.bigBed", "ENCFF1.tar"], +) +def test_derive_compression_format_should_report_uncompressed_when_no_suffix_matches( + name, +): + """Test the sentinel for names carrying no extrinsic compression. + + Given: + Filenames for formats the corpus carries, including BAM, bigWig and + bigBed, whose bytes are internally compressed but whose file_format + already names that container. + When: + derive_compression_format is called. + Then: + It should return the empty-string sentinel, which reports the absence + of compression beyond file_format rather than uncompressed bytes. + """ + # Act + result = derive_compression_format(name) + + # Assert + assert result == UNCOMPRESSED + assert result is not None + + +@pytest.mark.parametrize("suffix", UNMAPPABLE_COMPRESSION_SUFFIXES) +def test_derive_compression_format_should_return_none_when_compression_is_unmappable( + suffix, +): + """Test that a compressed file EDAM cannot name is not called uncompressed. + + Given: + A filename ending in a compression suffix no EDAM term expresses. + When: + derive_compression_format is called. + Then: + It should return None rather than the uncompressed sentinel. + """ + # Act + result = derive_compression_format(f"ENCFF1.bed{suffix}") + + # Assert + assert result is None + + +@pytest.mark.parametrize( + "value", [None, "", " ", "https://h/files/ENCFF1/@@download/", "https://h/"] +) +def test_derive_compression_format_should_return_none_when_no_basename_is_available( + value, +): + """Test that a name-less input yields no determination. + + Given: + An absent, blank, or directory-style value carrying no filename. + When: + derive_compression_format is called. + Then: + It should return None, since there is no evidence either way. + """ + # Act + result = derive_compression_format(value) + + # Assert + assert result is None + + +@given(st.none() | st.text()) +@settings(max_examples=300) +def test_derive_compression_format_should_return_a_value_from_the_closed_vocabulary( + value, +): + """Test that the derived value never escapes its vocabulary. + + Given: + Any text, or no value at all, as a filename or URL. + When: + derive_compression_format is called. + Then: + It should return a mapped EDAM term, the uncompressed sentinel, or + None, and never raise. + """ + # Act + result = derive_compression_format(value) + + # Assert + assert result in DERIVED_VALUES + + +@given( + name=st.text(min_size=1).filter( + lambda s: s == s.strip() and not (set(s) & set("/?#")) + ), + host=st.text(alphabet=st.characters(whitelist_categories=("Ll", "Nd")), min_size=1), + query=st.text().filter(lambda s: not (set(s) & set("?#"))), + fragment=st.text().filter(lambda s: "#" not in s), +) +@settings(max_examples=200) +def test_derive_compression_format_should_ignore_url_decoration( + name, host, query, fragment +): + """Test that wrapping a filename in a URL does not change the answer. + + Given: + Any filename free of the URL-reserved characters that would make it + mean something else inside a URL, plus any host, query string and + fragment to decorate it with. + When: + derive_compression_format is called on the bare name and on the + decorated URL. + Then: + Both should yield the same value. + """ + # Arrange + url = f"https://{host}/p/{name}?{query}#{fragment}" + + # Act + bare_result = derive_compression_format(name) + url_result = derive_compression_format(url) + + # Assert + assert bare_result == url_result + + +@given( + stem=st.text().filter(lambda s: "/" not in s), + suffix=st.sampled_from(sorted(COMPRESSION_SUFFIX_TO_EDAM)), +) +@settings(max_examples=200) +def test_derive_compression_format_should_classify_any_stem_with_a_known_suffix( + stem, suffix +): + """Test that no stem can suppress a recognized compression suffix. + + Given: + Any stem free of path separators, followed by one of the mapped + compression suffixes. + When: + derive_compression_format is called. + Then: + It should return a mapped EDAM term rather than the uncompressed + sentinel or None. + """ + # Act + result = derive_compression_format(stem + suffix) + + # Assert + assert result in set(COMPRESSION_SUFFIX_TO_EDAM.values()) From f578c597e990a9fb325985da134016649c9b4298 Mon Sep 17 00:00:00 2001 From: Conrad Date: Fri, 20 Nov 2026 17:46:18 -0500 Subject: [PATCH 17/37] feat: Add a HuBMAP organ-code to UBERON table 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. --- src/cfdb/services/ontology_mappings.py | 63 ++++++++++++++++++++++++++ tests/test_ontology_mappings.py | 54 +++++++++++++++++++++- 2 files changed, 116 insertions(+), 1 deletion(-) diff --git a/src/cfdb/services/ontology_mappings.py b/src/cfdb/services/ontology_mappings.py index b02b800..87820e3 100644 --- a/src/cfdb/services/ontology_mappings.py +++ b/src/cfdb/services/ontology_mappings.py @@ -280,6 +280,69 @@ } +# HuBMAP organ code (``organs[].code`` in the files index, UBKG's +# ``rui_code``) to its UBERON term, named by the UBERON label so an id +# carries the same name here as in ENCODE and 4DN. Snapshot of the UBKG +# organs endpoint (ontology.api.hubmapconsortium.org/organs? +# application_context=HUBMAP) taken 2026-11-20, labels from OLS4. UBKG's +# ``organ_uberon`` holds FMA ids for the lateral knee, mammary gland and +# tonsil codes; those map to their side-neutral UBERON parent, which UBKG +# names under ``category``. A static table rather than a per-sync fetch, as +# the loader's issue allows: a fetch that fails would strip anatomy from the +# whole slice, and UBKG's display terms ("Kidney (Left)") are not UBERON +# labels ("left kidney"). A code that appears upstream later is counted and +# logged as unmapped by the loader until it is added here. +HUBMAP_ORGAN_TO_UBERON = { + "AD": {"id": "UBERON:0001013", "name": "adipose tissue"}, + "BD": {"id": "UBERON:0000178", "name": "blood"}, + "BL": {"id": "UBERON:0001255", "name": "urinary bladder"}, + "BM": {"id": "UBERON:0002371", "name": "bone marrow"}, + "BR": {"id": "UBERON:0000955", "name": "brain"}, + "BV": {"id": "UBERON:0004537", "name": "blood vasculature"}, + "HT": {"id": "UBERON:0000948", "name": "heart"}, + "ID": {"id": "UBERON:0001066", "name": "intervertebral disk"}, + "LA": {"id": "UBERON:0001737", "name": "larynx"}, + "LB": {"id": "UBERON:0002178", "name": "left main bronchus"}, + "LE": {"id": "UBERON:0004548", "name": "left eye"}, + "LF": {"id": "UBERON:0001303", "name": "left fallopian tube"}, + "LI": {"id": "UBERON:0000059", "name": "large intestine"}, + "LK": {"id": "UBERON:0004538", "name": "left kidney"}, + "LL": {"id": "UBERON:0002168", "name": "left lung"}, + "LN": {"id": "UBERON:0001465", "name": "knee"}, # Knee (Left): side-neutral parent; UBKG gives FMA here + "LO": {"id": "UBERON:0002119", "name": "left ovary"}, + "LT": {"id": "UBERON:0002372", "name": "tonsil"}, # Tonsil (Left): side-neutral parent; UBKG gives FMA here + "LU": {"id": "UBERON:0001223", "name": "left ureter"}, + "LV": {"id": "UBERON:0002107", "name": "liver"}, + "LY": {"id": "UBERON:0000029", "name": "lymph node"}, + "MB": {"id": "UBERON:2001553", "name": "manubrium"}, + "MH": {"id": "UBERON:0000165", "name": "mouth"}, + "ML": {"id": "UBERON:0001911", "name": "mammary gland"}, # Mammary Gland (Left): side-neutral parent; UBKG gives FMA here + "MR": {"id": "UBERON:0001911", "name": "mammary gland"}, # Mammary Gland (Right): side-neutral parent; UBKG gives FMA here + "PA": {"id": "UBERON:0001264", "name": "pancreas"}, + "PL": {"id": "UBERON:0001987", "name": "placenta"}, + "PR": {"id": "UBERON:0000079", "name": "male reproductive system"}, # Prostate: UBKG's mapping, kept verbatim + "PV": {"id": "UBERON:0001270", "name": "bony pelvis"}, + "RB": {"id": "UBERON:0002177", "name": "right main bronchus"}, + "RE": {"id": "UBERON:0004549", "name": "right eye"}, + "RF": {"id": "UBERON:0001302", "name": "right fallopian tube"}, + "RK": {"id": "UBERON:0004539", "name": "right kidney"}, + "RL": {"id": "UBERON:0002167", "name": "right lung"}, + "RN": {"id": "UBERON:0001465", "name": "knee"}, # Knee (Right): side-neutral parent; UBKG gives FMA here + "RO": {"id": "UBERON:0002118", "name": "right ovary"}, + "RT": {"id": "UBERON:0002372", "name": "tonsil"}, # Tonsil (Right): side-neutral parent; UBKG gives FMA here + "RU": {"id": "UBERON:0001222", "name": "right ureter"}, + "SC": {"id": "UBERON:0002240", "name": "spinal cord"}, + "SI": {"id": "UBERON:0002108", "name": "small intestine"}, + "SK": {"id": "UBERON:0002097", "name": "skin of body"}, + "SP": {"id": "UBERON:0002106", "name": "spleen"}, + "ST": {"id": "UBERON:0000975", "name": "sternum"}, + "TH": {"id": "UBERON:0002370", "name": "thymus"}, + "TR": {"id": "UBERON:0003126", "name": "trachea"}, + "UT": {"id": "UBERON:0000995", "name": "uterus"}, + "VL": {"id": "UBERON:0004536", "name": "lymph vasculature"}, +} + + def get_file_format(encode_format: str) -> dict | None: """ Map ENCODE file_format to EDAM CV term. diff --git a/tests/test_ontology_mappings.py b/tests/test_ontology_mappings.py index 18abcc8..10e61a8 100644 --- a/tests/test_ontology_mappings.py +++ b/tests/test_ontology_mappings.py @@ -1,4 +1,4 @@ -"""Tests for ENCODE file format mapping in ontology_mappings.""" +"""Tests for the ontology mapping tables and lookups.""" from __future__ import annotations @@ -8,6 +8,7 @@ from cfdb.services.ontology_mappings import ( FILE_FORMAT_TO_EDAM, + HUBMAP_ORGAN_TO_UBERON, MINTED_FORMAT_PREFIX, get_data_type, get_file_format, @@ -443,3 +444,54 @@ def test_get_file_format_return_type_invariant(format_string): assert isinstance(result, dict) assert "id" in result assert "name" in result + + +def test_hubmap_organ_to_uberon_should_hold_only_uberon_terms(): + """Test every HuBMAP organ code maps to a UBERON id with a label. + + The data model promises UBERON anatomy ids, and UBKG's organ_uberon + carries FMA ids for some codes, so the table is where that promise is + kept. + + Given: + The checked-in HuBMAP organ table. + When: + Its entries are inspected. + Then: + Every id should be a UBERON CURIE and every name a non-empty, + lower-case UBERON label. + """ + # Act + entries = list(HUBMAP_ORGAN_TO_UBERON.values()) + + # Assert + assert entries + assert all(entry["id"].startswith("UBERON:") for entry in entries) + assert all(entry["name"] and entry["name"] == entry["name"].lower() for entry in entries) + + +@pytest.mark.parametrize( + ("left", "right", "parent"), + [ + ("LN", "RN", "UBERON:0001465"), + ("ML", "MR", "UBERON:0001911"), + ("LT", "RT", "UBERON:0002372"), + ], +) +def test_hubmap_organ_to_uberon_should_map_fma_only_lateral_organs_to_their_parent( + left, right, parent +): + """Test the organs UBKG gives only FMA ids land on their UBERON parent. + + Given: + A left/right organ pair whose UBKG entries carry FMA ids. + When: + Both codes are looked up in the table. + Then: + Both should map to the side-neutral UBERON parent. + """ + # Act + ids = {HUBMAP_ORGAN_TO_UBERON[left]["id"], HUBMAP_ORGAN_TO_UBERON[right]["id"]} + + # Assert + assert ids == {parent} From 8b921acb2040a61f74a9deb2a8d4e9d7ba48a196 Mon Sep 17 00:00:00 2001 From: Conrad Date: Fri, 20 Nov 2026 17:46:34 -0500 Subject: [PATCH 18/37] test: Record the private-loader exception to the test guide 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. --- tests/test_sync.py | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/tests/test_sync.py b/tests/test_sync.py index 3337475..21459bb 100644 --- a/tests/test_sync.py +++ b/tests/test_sync.py @@ -1,4 +1,13 @@ -"""Tests for sync service pruning and enrichment changes.""" +"""Tests for the sync service: dispatch, per-DCC loaders, and enrichment. + +These tests drive the module's private per-DCC functions (``_sync_dccs``, +``_sync_encode``, ``_sync_hubmap``, ...) directly. That is a deliberate, +module-wide exception to the test guide's rule against referencing private +functions: the only public entry point, ``start_sync``, schedules the run +as a detached background task and returns before it does any work, so no +public seam exists to drive a loader through and observe what it wrote. +New loaders follow the same convention rather than forking it. +""" from __future__ import annotations @@ -383,7 +392,8 @@ async def test__sync_dccs_should_propagate_a_cancellation( # --------------------------------------------------------------------------- -# _sync_hubmap +# _sync_hubmap -- driven directly under the module docstring's recorded +# exception for private per-DCC loaders, like _sync_encode above. # --------------------------------------------------------------------------- From 876b45aaef284c34bb620dae77258343a52b5a49 Mon Sep 17 00:00:00 2001 From: Conrad Date: Fri, 20 Nov 2026 17:47:03 -0500 Subject: [PATCH 19/37] fix: Harden the HuBMAP sync against empty, short and late loads 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. --- src/cfdb/services/hubmap.py | 243 ++++++++------- src/cfdb/services/ontology_mappings.py | 1 - src/cfdb/services/sync.py | 158 +++++++--- tests/test_hubmap.py | 403 ++++++++++++++----------- tests/test_sync.py | 194 ++++++++++-- 5 files changed, 637 insertions(+), 362 deletions(-) diff --git a/src/cfdb/services/hubmap.py b/src/cfdb/services/hubmap.py index 37207a5..2b95198 100644 --- a/src/cfdb/services/hubmap.py +++ b/src/cfdb/services/hubmap.py @@ -17,8 +17,8 @@ Dataset search (search_after pagination, one document per dataset): https://search.api.hubmapconsortium.org/v3/portal/search -Organ code -> UBERON (one request per sync): - https://ontology.api.hubmapconsortium.org/organs?application_context=HUBMAP +Organ code -> UBERON: no request. A checked-in snapshot of the UBKG organs +endpoint, ``HUBMAP_ORGAN_TO_UBERON`` in :mod:`cfdb.services.ontology_mappings`. Field Mapping (HuBMAP files search API -> CFDB) ----------------------------------------------- @@ -53,7 +53,7 @@ portal dataset URL -> collections[].persistent_id dataset_type -> collections[].experiment_type analyte_class -> collections[].analyte_class -organs[] (code -> UBERON via UBKG) -> collections[].anatomy +organs[] (code -> UBERON, static table) -> collections[].anatomy Enriched Collection (dataset index join) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -115,7 +115,11 @@ derive_compression_format, timeout_from_env, ) -from cfdb.services.ontology_mappings import get_file_format, get_taxonomy +from cfdb.services.ontology_mappings import ( + HUBMAP_ORGAN_TO_UBERON, + get_file_format, + get_taxonomy, +) logger = logging.getLogger(__name__) @@ -124,9 +128,6 @@ ASSETS_BASE_URL = "https://assets.hubmapconsortium.org" PORTAL_DATASET_URL = "https://portal.hubmapconsortium.org/browse/dataset/{uuid}" -UBKG_ORGANS_URL = ( - "https://ontology.api.hubmapconsortium.org/organs?application_context=HUBMAP" -) #: Environment variable overriding which file extensions are ingested, and #: the allowlist applied when it is unset. An allowlist rather than a filter @@ -142,8 +143,9 @@ ".h5", ".hdf5", # ".bcf" is deliberately absent: every .bcf in the index is a CODEX - # raw-acquisition sidecar (raw/Cyc1_reg1/1.bcf), not binary VCF, and - # ingesting them would label microscope files as variant calls. + # raw-acquisition sidecar (raw/Cyc1_reg1/1.bcf), not binary VCF. Nor + # does "bcf" map to a format, so an operator who opts them in gets files + # with no file_format rather than ones labelled as variant calls. ".gz", ".mtx", ".arrow", @@ -163,7 +165,7 @@ def file_extensions_from_env() -> tuple[str, ...]: Reads a comma-separated ``HUBMAP_FILE_EXTENSIONS``, stripping each entry, lower-casing it, prefixing a missing leading dot, and dropping blanks — - so ``h5ad, .BCF`` and ``.h5ad,.bcf`` configure the same thing, and what + so ``h5ad, .MTX`` and ``.h5ad,.mtx`` configure the same thing, and what is sent to the search API matches the index's dot-prefixed ``file_extension`` values exactly. An unset variable yields the default allowlist; a variable set to an empty (or all-blank) value yields an @@ -281,11 +283,13 @@ def derive_file_format(filename: str) -> Optional[dict]: #: will refuse again, so it is raised at once. _RETRYABLE_STATUSES = frozenset({429, 500, 502, 503, 504}) -#: Environment variable bounding the HuBMAP files stream, and its default. -#: The stream runs inside the cutover lock, which gates the whole read -#: surface, so it gets one deadline -- the reasoning ENCODE's metadata -#: budget records -- kept well under the sync lock's one-hour stale -#: threshold so a slow upstream cannot admit a second, clearing sync. +#: Environment variable bounding the HuBMAP sync's network fetches, and its +#: default. The file stream runs inside the cutover lock, which gates the +#: whole read surface, so the sync gets one deadline -- the reasoning +#: ENCODE's metadata budget records. The budget alone does not keep the +#: sync lock fresh: that lock's staleness counts from the start of the +#: whole multi-DCC run, so the sync clamps this budget to what is left of +#: it (see ``_stale_safe_deadline`` in :mod:`cfdb.services.sync`). _SYNC_TIMEOUT_ENV = "HUBMAP_SYNC_TIMEOUT_SECONDS" _SYNC_TIMEOUT_DEFAULT_SECONDS = 1800 @@ -303,8 +307,11 @@ class _RetryablePageError(RuntimeError): """A page failure that a fresh attempt at the same page may not repeat.""" -def _page_hits(data: object, label: str) -> list[dict]: - """Return a search response's hits, refusing a partial or malformed page. +def _page_hits(data: object, label: str) -> tuple[list[dict], Optional[int]]: + """Return a search response's hits and exact total, refusing a bad page. + + The total is the index's ``hits.total.value`` when it is exact + (``relation: eq``, which ``track_total_hits`` guarantees), else None. Elasticsearch answers 200 with whatever the healthy shards returned when a shard fails or the query times out, and the walk would then resume @@ -327,7 +334,13 @@ def _page_hits(data: object, label: str) -> list[dict]: f"HuBMAP {label} search had {failed} failed shard(s); the page " "is partial" ) - return hits["hits"] + total = hits.get("total") + exact = ( + total.get("value") + if isinstance(total, dict) and total.get("relation") == "eq" + else None + ) + return hits["hits"], exact if isinstance(exact, int) else None async def _search_page( @@ -337,8 +350,8 @@ async def _search_page( label: str, *, deadline: float | None = None, -) -> list[dict]: - """POST one search page and return its hits, retrying transient failures. +) -> tuple[list[dict], Optional[int]]: + """POST one search page and return its hits and exact total, retrying. Transport errors, timeouts, retryable statuses, and partial or malformed pages are retried up to ``_PAGE_ATTEMPTS`` times with linear backoff; @@ -363,8 +376,9 @@ async def _search_page( remaining = deadline - loop.time() if remaining <= 0: raise asyncio.TimeoutError( - f"HuBMAP {label} fetch did not finish within the " - f"{_SYNC_TIMEOUT_ENV} budget" + f"HuBMAP {label} fetch did not finish within the sync's " + f"deadline ({_SYNC_TIMEOUT_ENV}, clamped to the sync " + "lock's stale threshold)" ) timeout = min(timeout, remaining) @@ -420,11 +434,15 @@ async def _search_page( "metadata", "donor.mapped_metadata", "donor.uuid", + "donors.mapped_metadata", + "donors.uuid", "ingest_metadata.workflow_description", ] -async def fetch_dataset_metadata_bulk() -> dict[str, dict]: +async def fetch_dataset_metadata_bulk( + *, deadline: float | None = None +) -> dict[str, dict]: """ Fetch all HuBMAP dataset metadata from the dataset-level search index. @@ -438,9 +456,15 @@ async def fetch_dataset_metadata_bulk() -> dict[str, dict]: partial map, since a silently partial map would mean silently under-enriched documents. + Args: + deadline: Event-loop clock reading by which the whole fetch must + finish; each page's timeout is clamped to what remains. None + leaves only the per-page timeout. + Returns: {dataset_uuid: {pipeline, processing, group_name, visualization, vitessce_hints, metadata, donor_uuid, donor_metadata, + donors: {donor_uuid: mapped_metadata}, genome_assembly}} """ config = get_dcc_config("hubmap") @@ -463,7 +487,9 @@ async def fetch_dataset_metadata_bulk() -> dict[str, dict]: if search_after is not None: query["search_after"] = search_after - hits = await _search_page(session, search_url, query, "dataset") + hits, _ = await _search_page( + session, search_url, query, "dataset", deadline=deadline + ) await asyncio.sleep(_REQUEST_INTERVAL) @@ -492,7 +518,11 @@ async def fetch_dataset_metadata_bulk() -> dict[str, dict]: if metadata: entry["metadata"] = metadata - # Donor demographics + # Donor demographics. ``donor`` names one donor; a dataset + # pooled from several also lists every one under ``donors``, + # so both feed the per-donor map ``build_donor_lookup`` + # merges -- reading ``donor`` alone covers the others only + # when each happens to be some other dataset's ``donor``. donor = src.get("donor") or {} donor_metadata = donor.get("mapped_metadata") if donor_metadata: @@ -500,6 +530,15 @@ async def fetch_dataset_metadata_bulk() -> dict[str, dict]: donor_uuid = donor.get("uuid") if donor_uuid: entry["donor_uuid"] = donor_uuid + donors = { + d["uuid"]: d["mapped_metadata"] + for d in [donor, *(src.get("donors") or [])] + if isinstance(d, dict) + and d.get("uuid") + and d.get("mapped_metadata") + } + if donors: + entry["donors"] = donors # Genome assembly from workflow description ingest = src.get("ingest_metadata") or {} @@ -525,6 +564,24 @@ async def fetch_dataset_metadata_bulk() -> dict[str, dict]: return results +def build_donor_lookup(dataset_metadata: dict[str, dict]) -> dict[str, dict]: + """Merge every dataset's donors into one demographics map by donor uuid. + + Each dataset entry from :func:`fetch_dataset_metadata_bulk` carries its + donors -- the singular ``donor`` and the plural ``donors`` alike -- so a + donor of a pooled dataset joins even when no dataset names it singly. + The first dataset to name a donor wins; a donor's demographics are the + same wherever it appears. + """ + lookup: dict[str, dict] = {} + for meta in dataset_metadata.values(): + for donor_uuid, donor_metadata in (meta.get("donors") or {}).items(): + lookup.setdefault(donor_uuid, donor_metadata) + if meta.get("donor_uuid") and meta.get("donor_metadata"): + lookup.setdefault(meta["donor_uuid"], meta["donor_metadata"]) + return lookup + + # Fields to request from the files index — the whole per-file surface the # transformation maps. _FILE_SOURCE_FIELDS = [ @@ -567,10 +624,12 @@ async def fetch_file_metadata( Each page is retried on transient failure, and a partial page (failed shards, an upstream timeout, a missing hits envelope) is refused rather - than walked past; see ``_search_page``. A failure that outlasts the - retries still raises mid-stream, and behind the loader's deferred clear - that leaves a partial slice -- loudly rather than silently, but only a - shadow-collection swap would make it atomic. + than walked past; see ``_search_page``. The first page asks for an + exact total, and a walk that ends with fewer documents than it raises. + A failure that outlasts the retries still raises mid-stream, and behind + the loader's deferred clear that leaves a partial slice -- loudly + rather than silently, but only a shadow-collection swap would make it + atomic. Args: extensions: Dot-prefixed, lower-case extension allowlist. @@ -590,7 +649,8 @@ async def fetch_file_metadata( page_size = 1000 search_after: Optional[list] = None - total = 0 + yielded = 0 + expected: Optional[int] = None async with aiohttp.ClientSession() as session: while True: @@ -610,10 +670,16 @@ async def fetch_file_metadata( if search_after is not None: query["search_after"] = search_after + else: + # Exact on the first page only: the count is what the walk + # is checked against when it ends. + query["track_total_hits"] = True - hits = await _search_page( + hits, total = await _search_page( session, search_url, query, "files", deadline=deadline ) + if search_after is None: + expected = total await asyncio.sleep(_REQUEST_INTERVAL) @@ -622,89 +688,22 @@ async def fetch_file_metadata( for hit in hits: yield hit.get("_source", {}) - total += 1 + yielded += 1 - if total % 10000 < page_size: - logger.info(f"HuBMAP file fetch: {total} files fetched so far") + if yielded % 10000 < page_size: + logger.info(f"HuBMAP file fetch: {yielded} files fetched so far") # Prepare next page search_after = hits[-1].get("sort") if not search_after: break - logger.info(f"HuBMAP file fetch: {total} total files fetched") - - -def _uberon_term(organ: dict) -> Optional[dict]: - """The UBERON term for one UBKG organ entry, or None when it has none. - - ``organ_uberon`` is not always UBERON despite its name: the lateral - organs (left/right knee, mammary gland, tonsil) carry FMA ids there, - and their side-neutral parent under ``category`` carries the UBERON - one. Falling back loses the side -- UBERON's knee is side-neutral -- - which is the honest trade: an FMA id stored where the anatomy - contract promises UBERON would not resolve for any consumer. - """ - for source in (organ, organ.get("category")): - if not isinstance(source, dict): - continue - uberon = source.get("organ_uberon") - if isinstance(uberon, str) and uberon.startswith("UBERON:"): - return {"id": uberon, "name": source.get("term") or uberon} - return None - - -async def fetch_organ_map() -> dict[str, dict]: - """ - Fetch the HuBMAP organ-code → UBERON mapping from the UBKG ontology API. - - One small request per sync. Returns ``{rui_code: {"id": uberon_id, - "name": term}}`` for every organ with a UBERON term, taking the - side-neutral ``category`` term where ``organ_uberon`` is not UBERON - (see ``_uberon_term``); a code with no UBERON term at all is left out, - so the transform counts it as unmapped rather than storing a foreign - id. Failure degrades rather than aborts -- anatomy is enrichment, not - identity, so a UBKG outage costs the anatomy terms of one sync, not the - corpus -- and returns an empty map with a warning. That covers a - timeout (a bare ``TimeoutError`` in aiohttp, not a ``ClientError``) - and an undecodable or wrongly shaped body as well as transport errors. - """ - degraded = "HuBMAP collections will carry no anatomy terms this sync" - try: - async with aiohttp.ClientSession() as session: - async with session.get( - UBKG_ORGANS_URL, - timeout=aiohttp.ClientTimeout(total=60), - ) as response: - if response.status != 200: - logger.warning( - f"UBKG organs API error: HTTP {response.status}; " - f"{degraded}" - ) - return {} - organs = await response.json() - except (aiohttp.ClientError, asyncio.TimeoutError, ValueError) as e: - logger.warning(f"UBKG organs API failed ({e!r}); {degraded}") - return {} - - if not isinstance(organs, list): - logger.warning( - f"UBKG organs API returned {type(organs).__name__}, not a list; " - f"{degraded}" + if expected is not None and yielded < expected: + raise RuntimeError( + f"HuBMAP files walk ended short: {yielded} of the {expected} " + "files the index reported on its first page" ) - return {} - - organ_map: dict[str, dict] = {} - for organ in organs: - if not isinstance(organ, dict): - continue - code = organ.get("rui_code") - term = _uberon_term(organ) - if code and term: - organ_map[code] = term - - logger.info(f"UBKG organs: {len(organ_map)} organ codes mapped to UBERON") - return organ_map + logger.info(f"HuBMAP file fetch: {yielded} total files fetched") # Scalar demographics HuBMAP returns as single-element lists; unwrapped to @@ -801,7 +800,7 @@ def transform_file_to_cfdb( *, dataset_metadata: dict[str, dict], donor_lookup: dict[str, dict], - organ_map: dict[str, dict], + organ_map: dict[str, dict] | None = None, stats: Counter | None = None, ) -> Optional[dict]: """ @@ -816,12 +815,13 @@ def transform_file_to_cfdb( than dropping it. donor_lookup: Donor demographics keyed by donor uuid, built from ``dataset_metadata`` by the caller. - organ_map: Organ-code → UBERON mapping from :func:`fetch_organ_map`. - An unmapped code skips that anatomy term rather than fabricating - an id. + organ_map: Organ-code → UBERON term mapping; defaults to the + checked-in ``HUBMAP_ORGAN_TO_UBERON``. An unmapped code skips + that anatomy term rather than fabricating an id. stats: Optional counter the transform reports into — per-extension - document tallies, skip reasons, and unmapped organ codes — so - the sync can log one distribution instead of a line per file. + document tallies, skip reasons, unmapped organ codes, and + datasets or donors absent from the join maps — so the sync can + log one distribution instead of a line per file. Returns: CFDB-compatible dict for insertion into the files collection, or @@ -850,7 +850,14 @@ def transform_file_to_cfdb( except (KeyError, TypeError, ValueError): size_in_bytes = None - dataset_meta = dataset_metadata.get(dataset_uuid) or {} + if organ_map is None: + organ_map = HUBMAP_ORGAN_TO_UBERON + + dataset_meta = dataset_metadata.get(dataset_uuid) + if dataset_meta is None: + if stats is not None: + stats["unjoined_dataset"] += 1 + dataset_meta = {} doc: dict = { "submission": "hubmap", @@ -913,13 +920,15 @@ def transform_file_to_cfdb( if taxonomy: subject["taxonomy"] = taxonomy donor_metadata = donor_lookup.get(donor_uuid) + if not donor_metadata and stats is not None: + stats["unjoined_donor"] += 1 if donor_metadata: donor_extra = _donor_extra(donor_metadata) if donor_extra: subject["extra"] = {"hubmap": donor_extra} subjects.append(subject) - # --- Anatomy, from the file's organs through the UBKG mapping --- + # --- Anatomy, from the file's organs through the organ table --- anatomy = [] seen_codes: set[str] = set() for organ in src.get("organs") or []: @@ -932,9 +941,9 @@ def transform_file_to_cfdb( if stats is not None: stats[f"unmapped_organ:{code}"] += 1 continue - # The UBKG term, not the file's own label: labels drift between - # files for the same code ("Main Bronchus (Right)" vs "Bronchus - # (Right)"), which would give one id two names. + # The table's UBERON label, not the file's own label: labels drift + # between files for the same code ("Main Bronchus (Right)" vs + # "Bronchus (Right)"), which would give one id two names. anatomy.append({"id": term["id"], "name": term["name"]}) # --- Collection, one per file: its parent dataset --- diff --git a/src/cfdb/services/ontology_mappings.py b/src/cfdb/services/ontology_mappings.py index 87820e3..317c3ae 100644 --- a/src/cfdb/services/ontology_mappings.py +++ b/src/cfdb/services/ontology_mappings.py @@ -38,7 +38,6 @@ "bed broadpeak": {"id": "format:3614", "name": "BroadPeak"}, # Variant formats "vcf": {"id": "format:3016", "name": "VCF"}, - "bcf": {"id": "format:3020", "name": "BCF"}, # Annotation formats "gtf": {"id": "format:2306", "name": "GTF"}, "gff": {"id": "format:1975", "name": "GFF"}, diff --git a/src/cfdb/services/sync.py b/src/cfdb/services/sync.py index 3156675..049fcae 100644 --- a/src/cfdb/services/sync.py +++ b/src/cfdb/services/sync.py @@ -11,7 +11,7 @@ from contextlib import aclosing from copy import copy from dataclasses import dataclass, field -from datetime import datetime +from datetime import datetime, timedelta from enum import Enum from functools import partial from pathlib import Path @@ -636,6 +636,7 @@ async def _ingest_rows( counts_by_phase: dict[str, int], stale_filter: dict, tally=None, + clear_on_empty: bool = True, ) -> None: """Transform and batch-insert one upstream metadata stream. @@ -685,6 +686,12 @@ async def _ingest_rows( the row count, it runs per row rather than per batch, so a mid-flight death leaves it ahead of the database by the discarded partial batch. + clear_on_empty: Whether a stream that drains cleanly with no rows + is authoritative and clears the slice. True suits a stream + owning one slice among several, where an empty answer is a + legitimate result; a stream owning a whole submission passes + False, and an empty drain then raises instead of deleting the + submission over what is almost certainly an upstream fault. """ batch: list[dict] = [] count = 0 @@ -765,7 +772,13 @@ async def commit(pending: list[dict]) -> None: # The stream drained without error, so its result is authoritative # even when it is empty: clear here too, or a type the upstream # stopped publishing would keep serving last sync's rows - # indefinitely. + # indefinitely -- unless the caller has said an empty answer from + # this stream is never authoritative. + if count == 0 and not clear_on_empty: + raise RuntimeError( + f"{submission.upper()} {label}: the stream yielded no rows; " + "refusing to clear the existing slice over an empty result" + ) await clear_stale_once() # The clean-path flush: inside the ``try``, so a sink failure with no @@ -1014,6 +1027,35 @@ def tally(doc: dict) -> None: ) from failures[0][1] +#: Margin kept between an in-lock stream's deadline and the moment the sync +#: lock turns stale, so the stream's own teardown fits inside the lock. +_STALE_MARGIN = timedelta(minutes=5) + + +async def _stale_safe_deadline(budget_seconds: int) -> float: + """Event-loop deadline for a sync's network work, clamped to the lock. + + ``budget_seconds`` from now, or the moment the sync lock would turn + stale less ``_STALE_MARGIN``, whichever comes first. The sync lock's + staleness is measured from its ``started_at``, set once for the whole + multi-DCC run, and DCCs run in sorted order -- so a loader late in a + long run can start with little of the hour left, and a budget counted + from its own start would let it outlive the lock and admit a second, + clearing sync. Clamping fails that loader's fetch instead, which its + deferred clear survives. With no sync lock held (a direct call), only + the budget applies. + """ + loop = asyncio.get_running_loop() + deadline = loop.time() + budget_seconds + lock = await locks.get_current_sync_task() + started_at = (lock or {}).get("started_at") + if isinstance(started_at, datetime): + stale_at = started_at + locks.STALE_LOCK_THRESHOLD - _STALE_MARGIN + remaining = (stale_at - datetime.utcnow()).total_seconds() + deadline = min(deadline, loop.time() + remaining) + return deadline + + async def _sync_hubmap(task: SyncTask) -> None: """ Sync HuBMAP data from the files search API. @@ -1021,36 +1063,40 @@ async def _sync_hubmap(task: SyncTask) -> None: Like ENCODE, HuBMAP documents are pre-materialized directly into the files collection -- no C2M2 zip download, no TSV load, and no Rust materializer run. Dataset-level context (donor demographics, pipeline, - genome assembly) and the organ-to-UBERON map are prefetched before the - file stream opens, so every document is emitted fully populated in one - insert pass and no post-load enrichment or pruning stages exist. The - file query itself admits only public files, which is what retired the - pruning pass. + genome assembly) is prefetched before the file stream opens, and organ + codes map through a checked-in UBERON table, so every document is + emitted fully populated in one insert pass and no post-load enrichment + or pruning stages exist. The file query itself admits only public + files, which is what retired the pruning pass. The prefetch runs before the cutover lock is taken: it touches no database state, and the lock gates the whole read surface, so holding it across ~10k datasets of network fetch would fail every API request - for that long. Only the clear and the file stream run under the lock, - and the stream carries one deadline from ``sync_budget_seconds`` so the - lock cannot outlive the sync lock's stale threshold. + for that long. Only the clear and the file stream run under the lock. + Every fetch shares one deadline from ``sync_budget_seconds``, clamped so + it ends before the sync lock -- whose staleness counts from the start + of the whole multi-DCC run -- could turn stale and admit a second sync. + The in-lock stream still holds the read surface for the minutes it + takes; only a staged load would shorten that. A single stream loads the whole submission, so there is no per-phase isolation: any failure propagates and is recorded as this DCC's failure by ``_sync_dccs``, while ``_ingest_rows``'s deferred clear ensures a fetch that dies before delivering rows leaves the previous corpus being - served rather than empty. + served rather than empty. A stream that drains cleanly with no rows is + refused rather than obeyed, and so is an empty dataset map: for a + submission one stream owns, either is an upstream fault, never a real + answer. An empty extension allowlist is a no-op that leaves the existing slice in place -- the same outcome an empty ``ENCODE_ANNOTATION_TYPES`` has - for ENCODE's annotation phases. Draining an empty stream instead would - read as an authoritative empty result and delete the whole slice, and - empty values arrive by accident routinely. + for ENCODE's annotation phases. """ from cfdb.services.hubmap import ( + build_donor_lookup, build_hubmap_dcc_record, fetch_dataset_metadata_bulk, fetch_file_metadata, - fetch_organ_map, file_extensions_from_env, sync_budget_seconds, transform_file_to_cfdb, @@ -1071,34 +1117,55 @@ async def _sync_hubmap(task: SyncTask) -> None: counts_by_phase: dict[str, int] = {} # One counter for everything the transform wants observed -- the - # per-extension document distribution, skip reasons, and unmapped organ - # codes -- logged as distributions below rather than a line per file. + # per-extension document distribution, skip reasons, unmapped organ + # codes, and join misses -- logged as distributions below rather than a + # line per file. stats: Counter[str] = Counter() + # One deadline for every network fetch this sync makes, resolved before + # the first of them and clamped to the sync lock's stale threshold; see + # ``_stale_safe_deadline``. + deadline = await _stale_safe_deadline(sync_budget_seconds()) + # Step 1: Prefetch the dataset-level context the files index does not - # carry, plus the organ-to-UBERON map, outside the cutover lock. ~10k - # datasets held in memory -- small against the file stream they enrich, - # and what makes the single-pass join possible. + # carry, outside the cutover lock. ~10k datasets held in memory -- small + # against the file stream they enrich, and what makes the single-pass + # join possible. Organ codes need no fetch: they map through a checked-in + # table. task.current_step = "fetching" task.progress = "Fetching HuBMAP dataset metadata..." logger.info(task.progress) - dataset_metadata = await fetch_dataset_metadata_bulk() - donor_lookup = { - meta["donor_uuid"]: meta["donor_metadata"] - for meta in dataset_metadata.values() - if meta.get("donor_uuid") and meta.get("donor_metadata") - } - organ_map = await fetch_organ_map() + dataset_metadata = await fetch_dataset_metadata_bulk(deadline=deadline) + if not dataset_metadata: + # Refused before the lock, so the previous slice keeps being served: + # an empty map would load every file without its dataset context or + # donor demographics and report success. + raise RuntimeError( + "HuBMAP dataset index returned no datasets; refusing to load " + "files with no dataset context" + ) + donor_lookup = build_donor_lookup(dataset_metadata) def transform(src: dict) -> Optional[dict]: - return transform_file_to_cfdb( - src, - dataset_metadata=dataset_metadata, - donor_lookup=donor_lookup, - organ_map=organ_map, - stats=stats, - ) + # One malformed upstream document costs that document, not the + # sync: an exception here would otherwise abort the stream after + # the stale clear and leave a partial slice. + try: + return transform_file_to_cfdb( + src, + dataset_metadata=dataset_metadata, + donor_lookup=donor_lookup, + stats=stats, + ) + except Exception: + stats["skipped:malformed"] += 1 + if stats["skipped:malformed"] <= 5: + logger.exception( + "Skipping malformed HuBMAP file document (file_uuid=%r)", + src.get("file_uuid") if isinstance(src, dict) else None, + ) + return None try: async with locks.CutoverLock("hubmap"): @@ -1124,12 +1191,11 @@ def transform(src: dict) -> Optional[dict]: upsert=True, ) - # Step 4: Stream, transform, and insert in one pass, under one - # deadline resolved here so the lock window is bounded. + # Step 4: Stream, transform, and insert in one pass, under the + # deadline resolved above, so the lock window is bounded. task.current_step = "loading" task.progress = "Loading HuBMAP files from the files search API..." logger.info(task.progress) - deadline = asyncio.get_running_loop().time() + sync_budget_seconds() await _ingest_rows( task, @@ -1139,8 +1205,12 @@ def transform(src: dict) -> Optional[dict]: transform, counts_by_phase, # One stream owns the whole submission, so its slice is the - # whole submission. + # whole submission -- and an empty walk is never a real + # answer for it: a mapping change on the index, or an + # allowlist that matches nothing, returns a well-formed + # empty page that would otherwise delete everything. stale_filter={}, + clear_on_empty=False, ) finally: # HuBMAP writes straight into the materialized collection and never @@ -1177,6 +1247,18 @@ def transform(src: dict) -> Optional[dict]: f"HuBMAP ingest: organ codes with no UBERON mapping {unmapped}; " "those anatomy terms were omitted" ) + malformed = stats.get("skipped:malformed", 0) + if malformed: + logger.warning(f"HuBMAP ingest: skipped {malformed} malformed documents") + unjoined = { + key: stats[key] for key in ("unjoined_dataset", "unjoined_donor") if stats[key] + } + if unjoined: + logger.warning( + f"HuBMAP ingest: join misses {unjoined} (file occurrences whose " + "dataset or donor is absent from the dataset index); those " + "documents carry no dataset context or demographics" + ) async def _materialize_files(submission: str) -> None: diff --git a/tests/test_hubmap.py b/tests/test_hubmap.py index 3dcc159..cb8c504 100644 --- a/tests/test_hubmap.py +++ b/tests/test_hubmap.py @@ -4,6 +4,7 @@ import asyncio import os +from urllib.parse import unquote, urlparse import aiohttp import pytest @@ -13,12 +14,12 @@ from cfdb.models import FileMetadataModel from cfdb.services import hubmap as hubmap_module from cfdb.services.hubmap import ( + build_donor_lookup, build_hubmap_dcc_record, derive_file_format, extract_genome_assembly, fetch_dataset_metadata_bulk, fetch_file_metadata, - fetch_organ_map, file_extensions_from_env, transform_file_to_cfdb, ) @@ -131,26 +132,6 @@ def post(self, url, json=None, **kwargs): return _FakeJsonResponse(self._status, payload) -class _OrganSession: - """Fake aiohttp session for the single UBKG organs ``get``.""" - - def __init__(self, payload=None, status=200, error=None): - self._payload = payload or [] - self._status = status - self._error = error - - async def __aenter__(self): - return self - - async def __aexit__(self, *exc): - return False - - def get(self, url, **kwargs): - if self._error is not None: - raise self._error - return _FakeJsonResponse(self._status, self._payload) - - def _page(*sources: dict, sort_key: str = "file_uuid") -> dict: """Wrap ``_source`` dicts in the Elasticsearch page envelope.""" return { @@ -239,13 +220,13 @@ def test_file_extensions_from_env_should_normalize_case_and_missing_dots( the configured order. """ # Arrange - monkeypatch.setenv(EXTENSIONS_ENV, " h5ad, .BCF ,Gz") + monkeypatch.setenv(EXTENSIONS_ENV, " h5ad, .MTX ,Gz") # Act allowlist = file_extensions_from_env() # Assert - assert allowlist == (".h5ad", ".bcf", ".gz") + assert allowlist == (".h5ad", ".mtx", ".gz") def test_file_extensions_from_env_should_return_empty_and_warn_when_set_empty( @@ -286,13 +267,13 @@ def test_file_extensions_from_env_should_collapse_repeats_keeping_order( The first occurrence should win and order should be preserved. """ # Arrange - monkeypatch.setenv(EXTENSIONS_ENV, ".h5ad,bcf,.H5AD,.bcf") + monkeypatch.setenv(EXTENSIONS_ENV, ".h5ad,mtx,.H5AD,.mtx") # Act allowlist = file_extensions_from_env() # Assert - assert allowlist == (".h5ad", ".bcf") + assert allowlist == (".h5ad", ".mtx") @given( @@ -369,7 +350,6 @@ def test_extract_genome_assembly_should_normalize_to_canonical_names( [ ("secondary_analysis.h5ad", "HDF5"), ("reads.fastq.gz", "FASTQ"), - ("variants.bcf", "BCF"), ("matrix.mtx", "MTX"), ("expr.csv", "CSV"), ], @@ -412,6 +392,41 @@ def test_derive_file_format_should_return_none_when_nothing_maps(): assert derive_file_format("README") is None +@given( + base=st.text( + alphabet="abcdefghijklmnopqrstuvwxyz0123456789_-", min_size=1, max_size=12 + ), + extension=st.sampled_from( + ["h5ad", "h5mu", "hdf5", "csv", "tsv", "mtx", "bed", "bam", "fastq"] + ), + compression=st.sampled_from([".gz", ".bz2", ".xz"]), +) +@settings(max_examples=100) +def test_derive_file_format_should_ignore_a_compression_wrapper( + base, extension, compression +): + """Test a compression suffix never changes the derived format. + + Given: + Any plain base name, any mapped extension, and any compression + suffix the derivation strips. + When: + derive_file_format runs on the name with and without the suffix. + Then: + Both should map to the same format term. + """ + # Arrange + name = f"{base}.{extension}" + + # Act + plain = derive_file_format(name) + wrapped = derive_file_format(name + compression) + + # Assert + assert plain is not None + assert wrapped == plain + + def test_transform_file_to_cfdb_should_map_the_file_level_fields(): """Test the per-file surface of the index lands on the document. @@ -502,6 +517,39 @@ def test_transform_file_to_cfdb_should_percent_encode_the_access_url(): ) +@given( + dataset_uuid=st.text(alphabet="0123456789abcdef", min_size=8, max_size=32), + rel_path=st.text( + alphabet=st.characters(blacklist_categories=("Cs",)), + min_size=1, + max_size=40, + ), +) +@settings(max_examples=100) +def test_transform_file_to_cfdb_should_build_an_access_url_that_round_trips( + dataset_uuid, rel_path +): + """Test the assets URL always decodes back to the dataset and path. + + Given: + Any dataset uuid and any rel_path, including spaces, reserved + URL characters, and non-ASCII text. + When: + transform_file_to_cfdb builds the access_url. + Then: + It should point at the assets host, and its unquoted path should + be exactly the dataset uuid followed by the rel_path. + """ + # Act + doc = _transform(_file_doc(dataset_uuid=dataset_uuid, rel_path=rel_path)) + + # Assert + parsed = urlparse(doc["access_url"]) + assert f"{parsed.scheme}://{parsed.netloc}" == hubmap_module.ASSETS_BASE_URL + assert unquote(parsed.path) == f"/{dataset_uuid}/{rel_path}" + assert not parsed.query and not parsed.fragment + + def test_transform_file_to_cfdb_should_join_dataset_and_donor_metadata(): """Test the in-memory join lands demographics and dataset context. @@ -718,6 +766,71 @@ def test_transform_file_to_cfdb_should_count_extensions_into_stats(): assert stats["extension:.h5ad"] == 1 +def test_transform_file_to_cfdb_should_name_anatomy_from_the_uberon_table(): + """Test the default organ table supplies UBERON ids and UBERON labels. + + UBKG's display terms ("Kidney (Left)") are not UBERON labels ("left + kidney"), so naming anatomy by them gave one id different names in + HuBMAP and in the other DCCs. + + Given: + A document naming a plain organ code and a lateral one, with no + organ map supplied. + When: + transform_file_to_cfdb runs. + Then: + The collection should carry each code's UBERON term from the + checked-in table, the lateral knee on its side-neutral parent. + """ + # Arrange + organs = [ + {"code": "TH", "label": "Thymus"}, + {"code": "RN", "label": "Knee (Right)"}, + ] + + # Act + doc = transform_file_to_cfdb( + _file_doc(organs=organs), dataset_metadata={}, donor_lookup={} + ) + + # Assert + assert doc["collections"][0]["anatomy"] == [ + {"id": "UBERON:0002370", "name": "thymus"}, + {"id": "UBERON:0001465", "name": "knee"}, + ] + + +def test_transform_file_to_cfdb_should_count_join_misses(): + """Test a dataset or donor absent from the join maps is counted. + + A wholesale join failure would otherwise load every file without its + dataset context or demographics and look like success. + + Given: + A document whose dataset is absent from the dataset map and whose + donor is absent from the donor lookup, with a stats counter. + When: + transform_file_to_cfdb runs. + Then: + It should still return the document and count one unjoined + dataset and one unjoined donor. + """ + from collections import Counter + + # Arrange + stats: Counter[str] = Counter() + + # Act + doc = transform_file_to_cfdb( + _file_doc(), dataset_metadata={}, donor_lookup={}, stats=stats + ) + + # Assert + assert doc is not None + assert stats["unjoined_dataset"] == 1 + assert stats["unjoined_donor"] == 1 + + def test_transform_file_to_cfdb_should_dedupe_repeated_donors(): """Test a donor the index repeats becomes one subject. @@ -916,11 +1029,11 @@ async def test_fetch_file_metadata_should_filter_extensions_server_side( ) # Act - [doc async for doc in fetch_file_metadata((".h5ad", ".bcf"))] + [doc async for doc in fetch_file_metadata((".h5ad", ".mtx"))] # Assert filters = session.post_bodies[0]["query"]["bool"]["filter"] - assert {"terms": {"file_extension.keyword": [".h5ad", ".bcf"]}} in filters + assert {"terms": {"file_extension.keyword": [".h5ad", ".mtx"]}} in filters @pytest.mark.asyncio @@ -1195,6 +1308,45 @@ async def test_fetch_file_metadata_should_raise_at_once_on_a_client_error_status assert len(session.post_bodies) == 1 +@pytest.mark.asyncio +async def test_fetch_file_metadata_should_raise_when_the_walk_ends_short(mocker): + """Test a walk that delivers less than the index reported is refused. + + Given: + A first page reporting an exact total of 3 but carrying 2 hits, + after which the index serves nothing more. + When: + fetch_file_metadata is drained. + Then: + It should yield the 2 documents, then raise naming the shortfall, + having asked for an exact total on the first page. + """ + # Arrange + first = { + "hits": { + "total": {"value": 3, "relation": "eq"}, + "hits": [ + {"_source": _file_doc(file_uuid="aaa"), "sort": ["aaa"]}, + {"_source": _file_doc(file_uuid="bbb"), "sort": ["bbb"]}, + ], + } + } + session = _SearchSession(pages=[first]) + mocker.patch.object( + hubmap_module.aiohttp, "ClientSession", return_value=session + ) + docs = [] + + # Act + with pytest.raises(RuntimeError, match="2 of the 3"): + async for doc in fetch_file_metadata((".h5ad",)): + docs.append(doc) + + # Assert + assert [doc["file_uuid"] for doc in docs] == ["aaa", "bbb"] + assert session.post_bodies[0]["track_total_hits"] is True + + @pytest.mark.asyncio async def test_fetch_file_metadata_should_raise_when_the_deadline_has_passed( mocker, @@ -1394,197 +1546,98 @@ async def test_fetch_dataset_metadata_bulk_should_stop_when_a_page_has_no_sort( @pytest.mark.asyncio -async def test_fetch_organ_map_should_key_uberon_terms_by_rui_code( - mocker -): - """Test the UBKG payload becomes a code-keyed UBERON lookup. - - Given: - A UBKG organs payload with one complete entry and one missing - its UBERON id. - When: - fetch_organ_map runs. - Then: - Only the complete entry should be mapped. - """ - # Arrange - payload = [ - {"rui_code": "TH", "term": "Thymus", "organ_uberon": "UBERON:0002370"}, - {"rui_code": "XX", "term": "No Uberon", "organ_uberon": None}, - ] - session = _OrganSession(payload=payload) - mocker.patch.object( - hubmap_module.aiohttp, "ClientSession", return_value=session - ) - - # Act - organ_map = await fetch_organ_map() - - # Assert - assert organ_map == {"TH": {"id": "UBERON:0002370", "name": "Thymus"}} - - -@pytest.mark.asyncio -async def test_fetch_organ_map_should_return_empty_and_warn_on_failure( - mocker, caplog -): - """Test a UBKG outage degrades anatomy instead of failing the sync. - - Given: - A UBKG endpoint that raises a client error. - When: - fetch_organ_map runs. - Then: - It should return an empty map and log a warning. - """ - # Arrange - session = _OrganSession(error=aiohttp.ClientError("down")) - mocker.patch.object( - hubmap_module.aiohttp, "ClientSession", return_value=session - ) - - # Act - with caplog.at_level("WARNING"): - organ_map = await fetch_organ_map() - - # Assert - assert organ_map == {} - assert any("UBKG" in record.message for record in caplog.records) - - -@pytest.mark.asyncio -async def test_fetch_organ_map_should_return_empty_and_warn_on_http_error( - mocker, caplog +async def test_fetch_dataset_metadata_bulk_should_collect_every_listed_donor( + mocker, ): - """Test a UBKG error status degrades anatomy like an outage does. + """Test a pooled dataset's donors are all carried, not just the first. Given: - A UBKG endpoint answering HTTP 500. + A dataset whose singular donor is one of the three it lists under + donors, each with demographics. When: - fetch_organ_map runs. + fetch_dataset_metadata_bulk drains the index. Then: - It should return an empty map and log a warning naming UBKG. + The entry's donors map should hold all three donors' demographics. """ # Arrange - session = _OrganSession(status=500) + src = { + "uuid": "ds-uuid-1", + "donor": {"uuid": "d1", "mapped_metadata": {"sex": ["F"]}}, + "donors": [ + {"uuid": "d1", "mapped_metadata": {"sex": ["F"]}}, + {"uuid": "d2", "mapped_metadata": {"sex": ["M"]}}, + {"uuid": "d3", "mapped_metadata": {"sex": ["F"]}}, + ], + } + session = _SearchSession(pages=[_page(src, sort_key="uuid")]) mocker.patch.object( hubmap_module.aiohttp, "ClientSession", return_value=session ) # Act - with caplog.at_level("WARNING"): - organ_map = await fetch_organ_map() + results = await fetch_dataset_metadata_bulk() # Assert - assert organ_map == {} - assert any("HTTP 500" in record.message for record in caplog.records) + assert results["ds-uuid-1"]["donors"] == { + "d1": {"sex": ["F"]}, + "d2": {"sex": ["M"]}, + "d3": {"sex": ["F"]}, + } @pytest.mark.asyncio -async def test_fetch_organ_map_should_fall_back_to_the_category_uberon_term( +async def test_fetch_dataset_metadata_bulk_should_raise_when_the_deadline_has_passed( mocker, ): - """Test a lateral organ's FMA id is replaced by its UBERON parent. - - UBKG puts FMA ids in organ_uberon for the left/right knee, mammary - gland and tonsil, while their side-neutral category carries UBERON. + """Test the dataset prefetch honors the sync's shared deadline. Given: - A UBKG entry whose organ_uberon is FMA and whose category carries a - UBERON id. - When: - fetch_organ_map runs. - Then: - The code should map to the category's UBERON id and term. - """ - # Arrange - payload = [ - { - "rui_code": "RN", - "term": "Knee (Right)", - "organ_uberon": "FMA:24977", - "category": {"organ_uberon": "UBERON:0001465", "term": "Knee"}, - } - ] - session = _OrganSession(payload=payload) - mocker.patch.object( - hubmap_module.aiohttp, "ClientSession", return_value=session - ) - - # Act - organ_map = await fetch_organ_map() - - # Assert - assert organ_map == {"RN": {"id": "UBERON:0001465", "name": "Knee"}} - - -@pytest.mark.asyncio -async def test_fetch_organ_map_should_omit_a_code_with_no_uberon_term(mocker): - """Test a code with no UBERON term anywhere is left unmapped. - - Left out of the map, the transform counts it as an unmapped organ - rather than storing a foreign id where the contract promises UBERON. - - Given: - A UBKG entry with an FMA organ_uberon and no category. + A deadline already behind the event-loop clock. When: - fetch_organ_map runs. + fetch_dataset_metadata_bulk runs. Then: - The code should be absent from the map. + It should raise a timeout without issuing a request. """ # Arrange - payload = [{"rui_code": "LN", "term": "Knee", "organ_uberon": "FMA:24978"}] - session = _OrganSession(payload=payload) + session = _SearchSession(pages=[_page({"uuid": "ds-uuid-1"}, sort_key="uuid")]) mocker.patch.object( hubmap_module.aiohttp, "ClientSession", return_value=session ) + deadline = asyncio.get_running_loop().time() - 1 # Act - organ_map = await fetch_organ_map() + with pytest.raises(asyncio.TimeoutError): + await fetch_dataset_metadata_bulk(deadline=deadline) # Assert - assert organ_map == {} + assert session.post_bodies == [] -@pytest.mark.asyncio -@pytest.mark.parametrize( - ("session_kwargs", "expected"), - [ - ({"error": asyncio.TimeoutError()}, "TimeoutError"), - ({"payload": ValueError("bad json")}, "bad json"), - ({"payload": {"organs": []}}, "not a list"), - ], -) -async def test_fetch_organ_map_should_return_empty_and_warn_on_a_degraded_answer( - mocker, caplog, session_kwargs, expected -): - """Test every failure shape degrades anatomy instead of failing the sync. - - aiohttp raises a bare TimeoutError on an exceeded total, not a - ClientError, and a wrongly shaped body would otherwise fail on - iteration -- both escaped the contract the docstring states. +def test_build_donor_lookup_should_merge_singular_and_plural_donors(): + """Test every donor any dataset names joins, the first naming winning. Given: - A UBKG request that times out, answers undecodable JSON, or - answers a JSON object instead of a list. + One dataset naming a donor only under donors, another naming a + donor only singly, and a third repeating the first donor with + different demographics. When: - fetch_organ_map runs. + build_donor_lookup runs. Then: - It should return an empty map and log a warning describing it. + All three donors should be present, the repeated one keeping the + demographics of the first dataset that named it. """ # Arrange - session = _OrganSession(**session_kwargs) - mocker.patch.object( - hubmap_module.aiohttp, "ClientSession", return_value=session - ) + dataset_metadata = { + "ds1": {"donors": {"d1": {"sex": ["F"]}}}, + "ds2": {"donor_uuid": "d2", "donor_metadata": {"sex": ["M"]}}, + "ds3": {"donors": {"d1": {"sex": ["M"]}}}, + } # Act - with caplog.at_level("WARNING"): - organ_map = await fetch_organ_map() + lookup = build_donor_lookup(dataset_metadata) # Assert - assert organ_map == {} - assert any(expected in record.message for record in caplog.records) + assert lookup == {"d1": {"sex": ["F"]}, "d2": {"sex": ["M"]}} def test_build_hubmap_dcc_record_should_carry_the_static_dcc_fields(): diff --git a/tests/test_sync.py b/tests/test_sync.py index 21459bb..80f3664 100644 --- a/tests/test_sync.py +++ b/tests/test_sync.py @@ -13,6 +13,7 @@ import asyncio import logging +from datetime import datetime, timedelta import pytest from hypothesis import HealthCheck, given, settings @@ -421,22 +422,20 @@ def _hubmap_file_doc(**overrides) -> dict: return doc -def _patch_hubmap_fetches( - mocker, - file_docs, - dataset_metadata=None, - organ_map=None, -): - """Point the three network boundaries of _sync_hubmap at fixed data.""" +def _patch_hubmap_fetches(mocker, file_docs, dataset_metadata=None): + """Point the two network boundaries of _sync_hubmap at fixed data. + + The dataset map defaults to one entry for the fixture's dataset: an + empty map is refused by the sync, so a test wanting that has to say so. + """ mocker.patch.object( hubmap_module, "fetch_dataset_metadata_bulk", - mocker.AsyncMock(return_value=dataset_metadata or {}), - ) - mocker.patch.object( - hubmap_module, - "fetch_organ_map", - mocker.AsyncMock(return_value=organ_map or {}), + mocker.AsyncMock( + return_value={"ds-uuid-1": {}} + if dataset_metadata is None + else dataset_metadata + ), ) mocker.patch.object( hubmap_module, @@ -480,12 +479,10 @@ async def test__sync_hubmap_should_insert_fully_populated_documents( }, } } - organ_map = {"TH": {"id": "UBERON:0002370", "name": "Thymus"}} _patch_hubmap_fetches( mocker, _async_iter([_hubmap_file_doc()]), dataset_metadata=dataset_metadata, - organ_map=organ_map, ) # Act @@ -517,7 +514,7 @@ async def test__sync_hubmap_should_insert_fully_populated_documents( assert collection["experiment_type"] == "RNAseq" assert collection["analyte_class"] == "RNA" assert collection["anatomy"] == [ - {"id": "UBERON:0002370", "name": "Thymus"} + {"id": "UBERON:0002370", "name": "thymus"} ] assert collection["extra"]["hubmap"]["pipeline"] == "Salmon" assert collection["extra"]["hubmap"]["dataset_status"] == "Published" @@ -680,12 +677,12 @@ async def test__sync_hubmap_should_prefetch_outside_the_cutover_lock( the lock would only lengthen the outage. Given: - Dataset and organ fetches that record whether the cutover lock - is active when they run. + A dataset fetch that records whether the cutover lock is active + when it runs. When: _sync_hubmap runs. Then: - Neither fetch should observe an active cutover lock, while the + The fetch should not observe an active cutover lock, while the file stream that follows should. """ # Arrange @@ -697,13 +694,9 @@ async def lock_active() -> bool: ) return bool(lock and lock.get("active")) - async def fetch_datasets(): - observed.append(await lock_active()) - return {} - - async def fetch_organs(): + async def fetch_datasets(**kwargs): observed.append(await lock_active()) - return {} + return {"ds-uuid-1": {}} async def stream_files(): # The control: the stream runs under the lock, so a fake that @@ -718,17 +711,12 @@ async def stream_files(): "fetch_dataset_metadata_bulk", mocker.AsyncMock(side_effect=fetch_datasets), ) - mocker.patch.object( - hubmap_module, - "fetch_organ_map", - mocker.AsyncMock(side_effect=fetch_organs), - ) # Act await _sync_hubmap(SyncTask(id="t1", dcc_names=["hubmap"])) # Assert - assert observed == [False, False, True] + assert observed == [False, True] @pytest.mark.asyncio async def test__sync_hubmap_should_bound_the_file_stream_with_a_deadline( @@ -767,6 +755,150 @@ def open_stream(extensions, *, deadline=None): # Assert assert before + 119 <= opened["deadline"] <= loop.time() + 120 + @pytest.mark.asyncio + async def test__sync_hubmap_should_keep_the_slice_when_the_stream_yields_nothing( + self, mock_db, mocker + ): + """Test an empty upstream walk is refused rather than obeyed. + + A mapping change on the index, or an allowlist matching nothing, + returns a well-formed empty page; obeying it would delete the + whole submission over what is almost certainly a fault. + + Given: + A files collection holding a HuBMAP document and a file stream + that drains cleanly without yielding anything. + When: + _sync_hubmap runs. + Then: + It should raise, and the HuBMAP document should still be + served. + """ + # Arrange + mock_db.files.docs.append( + {"submission": "hubmap", "local_id": "previous-1"} + ) + _patch_hubmap_fetches(mocker, _async_iter([])) + + # Act + with pytest.raises(RuntimeError, match="yielded no rows"): + await _sync_hubmap(SyncTask(id="t1", dcc_names=["hubmap"])) + + # Assert + assert mock_db.files.docs == [ + {"submission": "hubmap", "local_id": "previous-1"} + ] + + @pytest.mark.asyncio + async def test__sync_hubmap_should_refuse_an_empty_dataset_map( + self, mock_db, mocker + ): + """Test an empty dataset index fails the sync before anything clears. + + Loading against an empty map would write every file without its + dataset context or donor demographics and report success. + + Given: + A files collection holding a HuBMAP document and a dataset fetch + that returns no datasets. + When: + _sync_hubmap runs. + Then: + It should raise naming the empty index, and the HuBMAP document + should still be served. + """ + # Arrange + mock_db.files.docs.append( + {"submission": "hubmap", "local_id": "previous-1"} + ) + _patch_hubmap_fetches( + mocker, _async_iter([_hubmap_file_doc()]), dataset_metadata={} + ) + + # Act + with pytest.raises(RuntimeError, match="no datasets"): + await _sync_hubmap(SyncTask(id="t1", dcc_names=["hubmap"])) + + # Assert + assert mock_db.files.docs == [ + {"submission": "hubmap", "local_id": "previous-1"} + ] + + @pytest.mark.asyncio + async def test__sync_hubmap_should_skip_a_malformed_document( + self, mock_db, mocker + ): + """Test one malformed upstream document costs only that document. + + Given: + A file stream carrying a document whose donors are bare strings, + followed by a well-formed document. + When: + _sync_hubmap runs. + Then: + It should complete, inserting only the well-formed document. + """ + # Arrange + malformed = _hubmap_file_doc(file_uuid="bad", donors=["donor-uuid"]) + _patch_hubmap_fetches( + mocker, _async_iter([malformed, _hubmap_file_doc(file_uuid="good")]) + ) + + # Act + await _sync_hubmap(SyncTask(id="t1", dcc_names=["hubmap"])) + + # Assert + loaded = [d["local_id"] for d in mock_db.files.docs if d["submission"] == "hubmap"] + assert loaded == ["good"] + + @pytest.mark.asyncio + async def test__sync_hubmap_should_end_its_deadline_before_the_sync_lock_goes_stale( + self, mock_db, mocker, monkeypatch + ): + """Test the budget is clamped to what is left of the sync lock. + + The sync lock's staleness counts from the start of the whole run, + and HuBMAP runs last; a budget counted from HuBMAP's own start + could outlive the lock and admit a second, clearing sync. + + Given: + A sync lock that started 50 minutes ago, a 1800 s HuBMAP budget, + and a file stream that records the deadline it was opened with. + When: + _sync_hubmap runs. + Then: + The deadline should fall about 5 minutes out -- the hour, less + the 50 minutes spent and a 5 minute margin -- not 30. + """ + # Arrange + monkeypatch.setenv("HUBMAP_SYNC_TIMEOUT_SECONDS", "1800") + await mock_db[locks.LOCKS_COLLECTION].update_one( + {"_id": locks.SYNC_LOCK_ID}, + { + "$set": { + "active": True, + "started_at": datetime.utcnow() - timedelta(minutes=50), + } + }, + upsert=True, + ) + opened: dict = {} + + def open_stream(extensions, *, deadline=None): + opened["deadline"] = deadline + return _async_iter([_hubmap_file_doc()]) + + _patch_hubmap_fetches(mocker, _async_iter([])) + mocker.patch.object(hubmap_module, "fetch_file_metadata", open_stream) + loop = asyncio.get_running_loop() + + # Act + before = loop.time() + await _sync_hubmap(SyncTask(id="t1", dcc_names=["hubmap"])) + + # Assert + assert before + 290 <= opened["deadline"] <= loop.time() + 300 + @pytest.mark.asyncio async def test__sync_hubmap_should_keep_the_slice_when_the_allowlist_is_empty( self, mock_db, mocker, monkeypatch From 11ecff39695c2c8ee48a9fa2710ca0d1e9154fe8 Mon Sep 17 00:00:00 2001 From: Conrad Date: Fri, 20 Nov 2026 17:47:03 -0500 Subject: [PATCH 20/37] docs: Document the HuBMAP loader's refusals, organ table and limits 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. --- ENCODE-SUPPLEMENT.md | 2 +- HUBMAP-SUPPLEMENT.md | 28 ++++++++++++++++------------ README.md | 2 +- 3 files changed, 18 insertions(+), 14 deletions(-) diff --git a/ENCODE-SUPPLEMENT.md b/ENCODE-SUPPLEMENT.md index 108d3f3..a56a7d4 100644 --- a/ENCODE-SUPPLEMENT.md +++ b/ENCODE-SUPPLEMENT.md @@ -59,7 +59,7 @@ ENCODE uses human-readable strings for file formats, assay types, output types, **`bigInteract` loses a working index, but gets tileset serving in exchange.** The two formats were not equally broken before this change. A `bedpe` routed through tabix produced an index that was simply wrong — the second mate of every record was unindexed and invisible. A `bigInteract` routed through `bigBedToBed` produced one that was *range-coherent*: the leading three columns are a genuine interval, so the index answered range queries correctly while silently degrading each interaction to a single locus. Re-typing both means `GET /index/...` now returns 404 for either, so `bigInteract` files that previously returned a usable-if-degraded index return nothing at all, and that applies to `bigInteract` already in the experiment corpus as well as to newly ingested annotation files. The tradeoff is accepted deliberately: a 404 states the truth, where the degraded index quietly answered a question the caller did not ask. `GET /tileset_info` and `GET /tiles` now serve bigInteract files directly (issue #120) — see the README's "Interaction tile serving (bigInteract)" section — which is the capability `/index`'s degraded answer stood in for. `bedpe` has no such replacement yet; its own tileset endpoints remain planned separately, and its `/index` 404 is still a bare regression with no capability behind it. -This applies to `.bedpe` already in the ENCODE experiment corpus, not only to annotation files — but it reaches no further than ENCODE. `FILE_FORMAT_TO_EDAM` and `get_file_format` have exactly one consumer, the ENCODE transform; 4DN and HuBMAP take `file_format` from their upstream C2M2 datapackage or portal API and never consult the table. A 4DN `.bedpe` whose upstream declares BED therefore still carries `file_format.name == "BED"`, is still claimed by `TabixIntervalProcessor`, and still gets an index built from its first mate. Closing that means routing incoming formats from every DCC through the same table, or refusing a `.bedpe` filename at the processor regardless of declared format; both are follow-up work. +This applies to `.bedpe` already in the ENCODE experiment corpus, not only to annotation files, and to HuBMAP, whose loader derives `file_format` from the filename's extension through the same table (`derive_file_format` in `services/hubmap.py`) — so a HuBMAP `.bedpe` is minted correctly and kept out of tabix too. It reaches no further: `FILE_FORMAT_TO_EDAM` and `get_file_format` have two consumers, the ENCODE and HuBMAP transforms, and 4DN takes `file_format` from its upstream C2M2 datapackage without consulting the table. A 4DN `.bedpe` whose upstream declares BED therefore still carries `file_format.name == "BED"`, is still claimed by `TabixIntervalProcessor`, and still gets an index built from its first mate. Closing that means routing incoming formats from every DCC through the same table, or refusing a `.bedpe` filename at the processor regardless of declared format; both are follow-up work. **Cache artifacts left behind.** Files of these two formats that were indexed before the re-typing still have their incorrect `.tbi` artifacts in the workflow cache. Nothing reads them any more — `lookup_for` returns `None` and the router bails before probing the cache — and nothing purges them either, so they are unreachable storage cost until someone sweeps them. They also make a latent cache-key hazard concrete: `cache_key` identifies a processor only by its `processor_version`, not by which processor it is, so a future paired-interval processor sharing a version number with `TabixIntervalProcessor` would derive the same key and read those stale artifacts back as cache hits. A processor identity has to be folded into the key before that processor lands; see the warning on `cfdb.workflows.keys.cache_key`. diff --git a/HUBMAP-SUPPLEMENT.md b/HUBMAP-SUPPLEMENT.md index 67d706a..76bb817 100644 --- a/HUBMAP-SUPPLEMENT.md +++ b/HUBMAP-SUPPLEMENT.md @@ -8,11 +8,14 @@ Field mapping from HuBMAP's file-grain search index to the CFDB data model. HuBM |----------|------|------------| | `POST https://search.api.hubmapconsortium.org/v3/files/search` | One Elasticsearch document per file; the primary stream | `search_after` on `file_uuid.keyword`, batches of 1000 | | `POST https://search.api.hubmapconsortium.org/v3/portal/search` | One document per dataset; prefetched once into an in-memory map keyed by `uuid` | `search_after` on `_id`, batches of 1000 | -| `GET https://ontology.api.hubmapconsortium.org/organs?application_context=HUBMAP` | Organ `rui_code` → UBERON term | One request per sync | The files index is ~9.9M documents, 98% of them `.tif` microscopy tiles, so the loader applies a configurable extension allowlist **server-side** (a `terms` filter on `file_extension.keyword`) and the excluded files never cross the wire. -Every search page is retried up to three times with backoff on a transport error, a timeout, or a 429/5xx, since re-sending the same `search_after` page is idempotent. A 200 that is partial — failed shards, an upstream `timed_out`, or no hits envelope — is treated the same way rather than walked past, because Elasticsearch answers 200 with whatever the healthy shards returned and the walk would otherwise resume past documents it never received. A failure that outlasts the retries raises. +Organ codes need no request: they map through `HUBMAP_ORGAN_TO_UBERON` in `services/ontology_mappings.py`, a checked-in snapshot of the UBKG organs endpoint (`ontology.api.hubmapconsortium.org/organs?application_context=HUBMAP`, taken 2026-11-20) with UBERON labels from OLS4. See [Collection Mapping](#collection-mapping). + +Every search page is attempted up to three times, with backoff, on a transport error, a timeout, or a 429/5xx, since re-sending the same `search_after` page is idempotent. A 200 that is partial — failed shards, an upstream `timed_out`, or no hits envelope — is treated the same way rather than walked past, because Elasticsearch answers 200 with whatever the healthy shards returned and the walk would otherwise resume past documents it never received. A failure that outlasts the attempts raises. + +Two results are refused outright rather than loaded. A files walk that drains cleanly with no documents raises instead of clearing the slice: a mapping change on the index, or an allowlist that matches nothing, returns a well-formed empty page, and for a submission one stream owns an empty answer is a fault, never a result. And the first files page asks for an exact total (`track_total_hits`), so a walk that ends with fewer documents than the index reported raises. An empty dataset map is refused the same way, before the cutover lock, so the previous slice keeps being served. ## Entity Construction @@ -23,7 +26,7 @@ There is no entity matching. The C2M2 path had to join its TSVs to the Search AP | File | The files-index document itself; `local_id` is `file_uuid` | | Collection | The file's parent dataset: `local_id` is `dataset_uuid`, one collection per file | | Subject | The file's `donors[]`: `local_id` is the donor uuid | -| Anatomy | The file's `organs[]`, with UBERON terms from the UBKG organ map | +| Anatomy | The file's `organs[]`, with UBERON terms from the checked-in organ table | Dataset-level context the files index does not carry — donor demographics, pipeline, assay metadata, genome assembly — is prefetched from the dataset index (~10k documents) into memory and joined by `dataset_uuid` during transformation, so documents land fully populated in a single insert pass. A dataset missing from that map degrades its files (no demographics, pipeline, or assembly) rather than dropping them. @@ -37,7 +40,7 @@ Default: `.h5ad`, `.h5mu`, `.h5`, `.hdf5`, `.gz`, `.mtx`, `.arrow`, `.parquet`, - `.csv` (32,396) and `.tsv` (8,809) are mostly imaging-derived tables — roughly 27k of the `.csv` files come from Cell DIVE, CODEX, and MIBI segmentation pipelines. - `.gz` (5,872) is mostly not genomics either: 2,723 are Cell DIVE `.nii.gz` NIfTI masks and 2,524 are salmon `aux_info/fld.gz`, which map to no `file_format`; about 500 are compressed MTX, BED, or CSV. -- `.bcf` is deliberately **not** in the default. Every `.bcf` in the index (1,851) is a CODEX raw-acquisition sidecar (`raw/Cyc1_reg1/1.bcf`), not binary VCF, and ingesting them would label microscope files as variant calls. +- `.bcf` is deliberately **not** in the default. Every `.bcf` in the index (1,851) is a CODEX raw-acquisition sidecar (`raw/Cyc1_reg1/1.bcf`), not binary VCF. `bcf` maps to no format either, so an operator who opts them in gets files with no `file_format` rather than ones labelled as variant calls. ## File Mapping @@ -49,7 +52,7 @@ Default: `.h5ad`, `.h5mu`, `.h5`, `.hdf5`, `.gz`, `.mtx`, `.arrow`, `.parquet`, | `md5` / `sha256` | `md5_checksum` / `sha256_checksum` | Real per-file checksums; the C2M2 TSVs lacked or mistyped both | | `file_format` | filename, compression suffix stripped | EDAM-mapped from the inner extension, so `x.fastq.gz` maps to FASTQ rather than nothing | | `compression_format` | filename suffix | Same derivation and absent-when-undetermined contract as ENCODE | -| `access_url` | `https://assets.hubmapconsortium.org/{dataset_uuid}/{rel_path}` | Path segments percent-encoded. `/data` streams it directly, without DRS resolution. Sampled URLs resolve without authentication, but not every one does: at least one Published CODEX dataset (`HBM366.XKPX.554`) answers 403 and some root-level `*-metadata.tsv` files 404 upstream | +| `access_url` | `https://assets.hubmapconsortium.org/{dataset_uuid}/{rel_path}` | Path segments percent-encoded. `/data` streams it directly, without DRS resolution. Sampled URLs resolve without authentication, but not every one does: at least one Published CODEX dataset (`HBM366.XKPX.554`) answers 403, some root-level `*-metadata.tsv` files 404, and samples have drawn transient 5xx. `/data` returns those as their own status (403, 404, 502), checked before any byte is sent. The assets host also throttles bursts and can block a client by IP, after which every file answers 403 — so a 403 may mean the client is blocked, not that the file is restricted — and it answers 403 to curl's default user agent, so check reachability by hand with another agent | | `status` | `dataset_status` | e.g. `"Published"` | | `data_access_level` | `data_access_level` | `"public"` on every document in this index | | `genome_assembly` | dataset `ingest_metadata.workflow_description` | Regex-extracted and canonicalized; mirrored on `extra.hubmap.genome_assembly`. See below. | @@ -66,9 +69,9 @@ One collection per file: its parent dataset. | `persistent_id` | `https://portal.hubmapconsortium.org/browse/dataset/{dataset_uuid}` | | `experiment_type` | `dataset_type` | | `analyte_class` | `analyte_class` | -| `anatomy[]` | `organs[]` — UBERON id and term from the UBKG organ map by `code`. The name is UBKG's term rather than the document's `label`, which drifts between files for the same code (`Main Bronchus (Right)` vs `Bronchus (Right)`) and would give one id two names | +| `anatomy[]` | `organs[]` — UBERON id and UBERON label from the checked-in organ table by `code`. The name is the UBERON label (`left kidney`), not UBKG's display term (`Kidney (Left)`) or the document's own `label`, which drifts between files for the same code (`Main Bronchus (Right)` vs `Bronchus (Right)`); either would give one id more than one name across files and DCCs | -UBKG's `organ_uberon` is not always UBERON: the lateral organs (left/right knee, mammary gland, tonsil) carry FMA ids there. For those the loader takes the side-neutral UBERON term from the entry's `category` (e.g. `RN` Knee (Right) → `UBERON:0001465` Knee), losing the side rather than storing an id that does not resolve in UBERON. An organ code with no UBERON term at all, or one the map does not know, is skipped and counted rather than given a fabricated id; the sync logs the unmapped codes. A UBKG failure — transport error, timeout, error status, or an undecodable or wrongly shaped body — degrades the same way: collections carry no anatomy that sync, with a warning, because anatomy is enrichment, not identity. +The table is a static snapshot rather than a per-sync UBKG fetch for two reasons: a fetch that failed would have stripped anatomy from the whole slice for a sync, and UBKG's display terms are not UBERON labels. UBKG's `organ_uberon` is not always UBERON either: the lateral organs (left/right knee, mammary gland, tonsil) carry FMA ids there, so the table maps them to the side-neutral UBERON parent UBKG names under `category` (e.g. `RN` Knee (Right) → `UBERON:0001465` knee), losing the side rather than storing an id that does not resolve in UBERON. `PR` (Prostate) maps to `UBERON:0000079` male reproductive system, UBKG's own mapping, kept verbatim. A code the table does not know — one HuBMAP adds later — is skipped and counted rather than given a fabricated id, and the sync logs the unmapped codes until the table is extended. ### `extra.hubmap` (`EnrichedHubmapCollection`), joined from the dataset index @@ -84,7 +87,7 @@ UBKG's `organ_uberon` is not always UBERON: the lateral organs (left/right knee, ## Subject Mapping -One subject per entry in the file's `donors[]`, with `local_id` the donor uuid and `taxonomy` fixed to Homo sapiens (HuBMAP is human-only). Demographics come from the dataset index's `donor.mapped_metadata`, joined by donor uuid; HuBMAP returns most fields as single-element lists, which are unwrapped to scalars. +One subject per entry in the file's `donors[]`, with `local_id` the donor uuid and `taxonomy` fixed to Homo sapiens (HuBMAP is human-only). Demographics come from the dataset index, joined by donor uuid: from each dataset's `donor.mapped_metadata` and from every entry of its `donors[].mapped_metadata`, so a donor of a pooled dataset joins even when no dataset names it singly. HuBMAP returns most fields as single-element lists, which are unwrapped to scalars. A file whose dataset or donor is absent from the dataset index still loads, without that context, and the sync counts and logs these join misses. A document too malformed to transform is skipped and counted rather than failing the sync. Stored on `subjects[].extra.hubmap` (`EnrichedHubmapSubject`): @@ -128,9 +131,8 @@ HuBMAP is human-only, so the vast majority resolve to `GRCh38`. If no pattern ma ## Data Flow ```text -fetch_dataset_metadata_bulk() # dataset index -> {dataset_uuid: context} (outside the cutover lock) -fetch_organ_map() # UBKG -> {rui_code: UBERON term} (outside the cutover lock) - │ +fetch_dataset_metadata_bulk(deadline) # dataset index -> {dataset_uuid: context} (outside the cutover lock) + │ # organ codes map through the checked-in table: no fetch └─> [cutover lock] fetch_file_metadata(allowlist, deadline) # files index, filtered server-side └─ transform_file_to_cfdb(...) # one fully-populated document per file @@ -138,4 +140,6 @@ fetch_organ_map() # UBKG -> {rui_code: UBERON term} ensure_indexes(files) # runs even when the stream fails ``` -The whole pipeline is `_sync_hubmap` in `services/sync.py`, sharing `_ingest_rows` with the ENCODE path. The prefetch runs before the cutover lock is taken, because the lock gates the whole read surface and the prefetch touches no database state. The file stream runs under the lock with one deadline, `HUBMAP_SYNC_TIMEOUT_SECONDS` (default 1800), so the lock cannot outlive the sync lock's one-hour stale threshold. The stale HuBMAP slice is cleared only once replacement rows are in hand, so an upstream failure before the first row leaves the previous corpus being served rather than empty. A failure after that point still leaves a partial slice — loudly, with indexes ensured — and only a shadow-collection swap would make it atomic. +The whole pipeline is `_sync_hubmap` in `services/sync.py`, sharing `_ingest_rows` with the ENCODE path. The prefetch runs before the cutover lock is taken, because the lock gates the whole read surface and the prefetch touches no database state. Every fetch shares one deadline: `HUBMAP_SYNC_TIMEOUT_SECONDS` (default 1800), clamped to end five minutes before the sync lock would turn stale. That clamp matters because the sync lock's one-hour staleness counts from the start of the whole multi-DCC run and HuBMAP runs last, after 4DN and ENCODE, so a budget counted from HuBMAP's own start could outlive the lock and admit a second sync; clamped, the late fetch fails instead, which the deferred clear survives. The stale HuBMAP slice is cleared only once replacement rows are in hand, so an upstream failure before the first row leaves the previous corpus being served rather than empty. + +Two costs remain, shared with ENCODE's identical in-lock design and tracked in [#129](https://github.com/abdenlab/cfdb/issues/129). The file stream holds the cutover lock for the roughly two minutes it takes, and every API request for every DCC that waits longer than the 60-second cutover timeout fails, so a HuBMAP sync is a brief read outage across the whole API. And a failure after the first batch still leaves a partial slice — loudly, with indexes ensured — which only a staged load swapped in under a short lock would make atomic. diff --git a/README.md b/README.md index 3e34c70..e095d89 100644 --- a/README.md +++ b/README.md @@ -96,7 +96,7 @@ Run `./certs/generate-certs.sh --help` for full usage information. | `make api` | Build and start the API container | | `make api-tiles` | Build and start the API container **with matrix tile serving enabled**, on a cache volume shared with the worker (local dev; see [Serving tiles locally](#serving-tiles-locally)) | | `make worker-tiles` | Start a containerized LAN worker pool on that same cache volume | -| `make materialize-files` | Manually materialize all file metadata (usually done via sync) | +| `make materialize-files` | Manually materialize all file metadata (usually done via sync). It drops the whole `files` collection before rebuilding from the raw C2M2 tables, so it deletes every ENCODE and HuBMAP document and writes none back — those DCCs have no raw tables; re-sync them afterwards | | `make materialize-dcc DCC=4dn` | Materialize a single DCC. Only C2M2 DCCs (4DN) are materialized: ENCODE and HuBMAP write the `files` collection directly from their APIs and have no raw tables to rebuild from, so materializing either deletes its documents and writes none back | | `make schema` | Regenerate the checked-in `schema.graphql` from the Strawberry schema | | `make certs` | Generate TLS certificates for production | From 9591e6bd1f7eb87b6857198abc9e22973a959aca Mon Sep 17 00:00:00 2001 From: Conrad Date: Fri, 20 Nov 2026 18:28:20 -0500 Subject: [PATCH 21/37] refactor: Make the HuBMAP loader public and flatten its tests 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. --- HUBMAP-SUPPLEMENT.md | 2 +- src/cfdb/services/sync.py | 4 +- tests/test_sync.py | 949 +++++++++++++++++++------------------- 3 files changed, 481 insertions(+), 474 deletions(-) diff --git a/HUBMAP-SUPPLEMENT.md b/HUBMAP-SUPPLEMENT.md index 76bb817..8c23dfb 100644 --- a/HUBMAP-SUPPLEMENT.md +++ b/HUBMAP-SUPPLEMENT.md @@ -140,6 +140,6 @@ fetch_dataset_metadata_bulk(deadline) # dataset index -> {dataset_uuid: contex ensure_indexes(files) # runs even when the stream fails ``` -The whole pipeline is `_sync_hubmap` in `services/sync.py`, sharing `_ingest_rows` with the ENCODE path. The prefetch runs before the cutover lock is taken, because the lock gates the whole read surface and the prefetch touches no database state. Every fetch shares one deadline: `HUBMAP_SYNC_TIMEOUT_SECONDS` (default 1800), clamped to end five minutes before the sync lock would turn stale. That clamp matters because the sync lock's one-hour staleness counts from the start of the whole multi-DCC run and HuBMAP runs last, after 4DN and ENCODE, so a budget counted from HuBMAP's own start could outlive the lock and admit a second sync; clamped, the late fetch fails instead, which the deferred clear survives. The stale HuBMAP slice is cleared only once replacement rows are in hand, so an upstream failure before the first row leaves the previous corpus being served rather than empty. +The whole pipeline is `sync_hubmap` in `services/sync.py`, sharing `_ingest_rows` with the ENCODE path. The prefetch runs before the cutover lock is taken, because the lock gates the whole read surface and the prefetch touches no database state. Every fetch shares one deadline: `HUBMAP_SYNC_TIMEOUT_SECONDS` (default 1800), clamped to end five minutes before the sync lock would turn stale. That clamp matters because the sync lock's one-hour staleness counts from the start of the whole multi-DCC run and HuBMAP runs last, after 4DN and ENCODE, so a budget counted from HuBMAP's own start could outlive the lock and admit a second sync; clamped, the late fetch fails instead, which the deferred clear survives. The stale HuBMAP slice is cleared only once replacement rows are in hand, so an upstream failure before the first row leaves the previous corpus being served rather than empty. Two costs remain, shared with ENCODE's identical in-lock design and tracked in [#129](https://github.com/abdenlab/cfdb/issues/129). The file stream holds the cutover lock for the roughly two minutes it takes, and every API request for every DCC that waits longer than the 60-second cutover timeout fails, so a HuBMAP sync is a brief read outage across the whole API. And a failure after the first batch still leaves a partial slice — loudly, with indexes ensured — which only a staged load swapped in under a short lock would make atomic. diff --git a/src/cfdb/services/sync.py b/src/cfdb/services/sync.py index 049fcae..804a790 100644 --- a/src/cfdb/services/sync.py +++ b/src/cfdb/services/sync.py @@ -154,7 +154,7 @@ async def _sync_dccs(task: SyncTask) -> None: if dcc_type == "rest_api" and dcc == "encode": await _sync_encode(task) elif dcc_type == "rest_api" and dcc == "hubmap": - await _sync_hubmap(task) + await sync_hubmap(task) else: await _sync_c2m2_zip(task, data_path, downloads_path) except Exception as exc: @@ -1056,7 +1056,7 @@ async def _stale_safe_deadline(budget_seconds: int) -> float: return deadline -async def _sync_hubmap(task: SyncTask) -> None: +async def sync_hubmap(task: SyncTask) -> None: """ Sync HuBMAP data from the files search API. diff --git a/tests/test_sync.py b/tests/test_sync.py index 80f3664..018c632 100644 --- a/tests/test_sync.py +++ b/tests/test_sync.py @@ -1,12 +1,11 @@ """Tests for the sync service: dispatch, per-DCC loaders, and enrichment. -These tests drive the module's private per-DCC functions (``_sync_dccs``, -``_sync_encode``, ``_sync_hubmap``, ...) directly. That is a deliberate, -module-wide exception to the test guide's rule against referencing private -functions: the only public entry point, ``start_sync``, schedules the run -as a detached background task and returns before it does any work, so no -public seam exists to drive a loader through and observe what it wrote. -New loaders follow the same convention rather than forking it. +The older tests here drive the module's private per-DCC functions +(``_sync_dccs``, ``_sync_encode``, ...) directly; that convention predates +the test guide's rule against referencing private functions and is left as +it is rather than rewritten in passing. New loaders do not extend it: the +HuBMAP loader is public (``sync_hubmap``) and its tests are module-level +functions that drive it through that public name. """ from __future__ import annotations @@ -34,7 +33,7 @@ _stamp_4dn_file_accessions, _sync_dccs, _sync_encode, - _sync_hubmap, + sync_hubmap, ) from cfdb.indexes import data_index_specs, materialized_files_index_specs from tests.conftest import FakeDB @@ -226,7 +225,7 @@ async def test__sync_dccs_should_sync_the_remaining_dccs_when_one_fails( sync_module, "_sync_c2m2_zip", mocker.AsyncMock() ) hubmap_sync = mocker.patch.object( - sync_module, "_sync_hubmap", mocker.AsyncMock() + sync_module, "sync_hubmap", mocker.AsyncMock() ) mocker.patch.object(sync_module, "ensure_indexes", mocker.AsyncMock()) mocker.patch.object( @@ -266,7 +265,7 @@ async def test__sync_dccs_should_ensure_data_indexes_when_a_dcc_failed( "_sync_encode", mocker.AsyncMock(side_effect=RuntimeError("encode died")), ) - mocker.patch.object(sync_module, "_sync_hubmap", mocker.AsyncMock()) + mocker.patch.object(sync_module, "sync_hubmap", mocker.AsyncMock()) ensure_mock = mocker.patch.object( sync_module, "ensure_indexes", mocker.AsyncMock() ) @@ -303,7 +302,7 @@ async def test__sync_dccs_should_not_report_a_failed_dcc_as_synced( "_sync_encode", mocker.AsyncMock(side_effect=RuntimeError("encode died")), ) - mocker.patch.object(sync_module, "_sync_hubmap", mocker.AsyncMock()) + mocker.patch.object(sync_module, "sync_hubmap", mocker.AsyncMock()) mocker.patch.object(sync_module, "ensure_indexes", mocker.AsyncMock()) coverage = mocker.patch.object( sync_module, "_log_accession_coverage", mocker.AsyncMock() @@ -339,7 +338,7 @@ async def test__sync_dccs_should_chain_the_first_dcc_failure_as_the_cause( sync_module, "_sync_encode", mocker.AsyncMock(side_effect=first) ) mocker.patch.object( - sync_module, "_sync_hubmap", mocker.AsyncMock(side_effect=second) + sync_module, "sync_hubmap", mocker.AsyncMock(side_effect=second) ) mocker.patch.object(sync_module, "ensure_indexes", mocker.AsyncMock()) mocker.patch.object( @@ -380,7 +379,7 @@ async def test__sync_dccs_should_propagate_a_cancellation( mocker.AsyncMock(side_effect=asyncio.CancelledError()), ) hubmap_sync = mocker.patch.object( - sync_module, "_sync_hubmap", mocker.AsyncMock() + sync_module, "sync_hubmap", mocker.AsyncMock() ) mocker.patch.object(sync_module, "ensure_indexes", mocker.AsyncMock()) task = SyncTask(id="t1", dcc_names=["encode", "hubmap"]) @@ -393,8 +392,7 @@ async def test__sync_dccs_should_propagate_a_cancellation( # --------------------------------------------------------------------------- -# _sync_hubmap -- driven directly under the module docstring's recorded -# exception for private per-DCC loaders, like _sync_encode above. +# sync_hubmap # --------------------------------------------------------------------------- @@ -423,7 +421,7 @@ def _hubmap_file_doc(**overrides) -> dict: def _patch_hubmap_fetches(mocker, file_docs, dataset_metadata=None): - """Point the two network boundaries of _sync_hubmap at fixed data. + """Point the two network boundaries of sync_hubmap at fixed data. The dataset map defaults to one entry for the fixture's dataset: an empty map is refused by the sync, so a test wanting that has to say so. @@ -444,497 +442,506 @@ def _patch_hubmap_fetches(mocker, file_docs, dataset_metadata=None): ) -class TestSyncHubmap: - @pytest.mark.asyncio - async def test__sync_hubmap_should_insert_fully_populated_documents( - self, mock_db, mocker - ): - """Test the single-pass load joins everything into one document. - - HuBMAP writes the files collection directly with no post-load - enrichment, so this pipeline is the only writer of dataset context, - donor demographics, and anatomy for that DCC. - - Given: - One files-index document whose dataset carries pipeline context, - donor demographics, and a mappable organ code. - When: - _sync_hubmap runs the fetch-transform-insert pipeline. - Then: - The inserted document should carry the file fields, the joined - dataset and donor metadata, the UBERON anatomy term, and the - DCC record should be upserted. - """ - # Arrange - dataset_metadata = { - "ds-uuid-1": { - "pipeline": "Salmon", - "processing": "processed", - "genome_assembly": "GRCh38", - "donor_uuid": "donor-1", - "donor_metadata": { - "sex": ["Female"], - "age_value": [67.0], - "medical_history": ["Diabetes"], - }, - } +@pytest.mark.asyncio +async def test_sync_hubmap_should_insert_fully_populated_documents( + mock_db, mocker +): + """Test the single-pass load joins everything into one document. + + HuBMAP writes the files collection directly with no post-load + enrichment, so this pipeline is the only writer of dataset context, + donor demographics, and anatomy for that DCC. + + Given: + One files-index document whose dataset carries pipeline context, + donor demographics, and a mappable organ code. + When: + sync_hubmap runs the fetch-transform-insert pipeline. + Then: + The inserted document should carry the file fields, the joined + dataset and donor metadata, the UBERON anatomy term, and the + DCC record should be upserted. + """ + # Arrange + dataset_metadata = { + "ds-uuid-1": { + "pipeline": "Salmon", + "processing": "processed", + "genome_assembly": "GRCh38", + "donor_uuid": "donor-1", + "donor_metadata": { + "sex": ["Female"], + "age_value": [67.0], + "medical_history": ["Diabetes"], + }, } - _patch_hubmap_fetches( - mocker, - _async_iter([_hubmap_file_doc()]), - dataset_metadata=dataset_metadata, - ) - - # Act - await _sync_hubmap(SyncTask(id="t1", dcc_names=["hubmap"])) - - # Assert - doc = next(d for d in mock_db.files.docs if d["submission"] == "hubmap") - assert doc["local_id"] == "abc123" - assert doc["accession_id"] is None - assert doc["filename"] == "secondary_analysis.h5ad" - assert doc["size_in_bytes"] == 5529765 - assert isinstance(doc["size_in_bytes"], int) - assert doc["md5"] == "0b05f823fd4b3cc86204366c6f71eae9" - assert doc["sha256"].startswith("f51518c924f3") - assert doc["access_url"] == ( - "https://assets.hubmapconsortium.org/ds-uuid-1/" - "processed/expr%20matrix/secondary_analysis.h5ad" - ) - assert doc["status"] == "Published" - assert doc["data_access_level"] == "public" - assert doc["genome_assembly"] == "GRCh38" - assert doc["file_format"]["name"] == "HDF5" - assert doc["extra"]["hubmap"]["rel_path"] == ( - "processed/expr matrix/secondary_analysis.h5ad" - ) - collection = doc["collections"][0] - assert collection["local_id"] == "ds-uuid-1" - assert collection["name"] == "HBM339.XXWC.842" - assert collection["experiment_type"] == "RNAseq" - assert collection["analyte_class"] == "RNA" - assert collection["anatomy"] == [ - {"id": "UBERON:0002370", "name": "thymus"} - ] - assert collection["extra"]["hubmap"]["pipeline"] == "Salmon" - assert collection["extra"]["hubmap"]["dataset_status"] == "Published" - subject = collection["subjects"][0] - assert subject["local_id"] == "donor-1" - assert subject["extra"]["hubmap"]["sex"] == "Female" - assert subject["extra"]["hubmap"]["age_value"] == 67.0 - assert subject["extra"]["hubmap"]["medical_history"] == ["Diabetes"] - dcc_doc = next( - d for d in mock_db.dcc.docs if d["submission"] == "hubmap" - ) - assert dcc_doc["dcc_abbreviation"] == "HuBMAP" - - @pytest.mark.asyncio - async def test__sync_hubmap_should_replace_only_the_hubmap_slice( - self, mock_db, mocker - ): - """Test the stale clear is scoped to the submission being reloaded. - - Given: - A files collection holding a stale HuBMAP document and a 4DN - document, and a stream delivering one replacement file. - When: - _sync_hubmap runs. - Then: - The stale HuBMAP document should be gone, the replacement - present, and the 4DN document untouched. - """ - # Arrange - mock_db.files.docs.extend( - [ - {"submission": "hubmap", "local_id": "stale-1"}, - {"submission": "4dn", "local_id": "keep-1"}, - ] - ) - _patch_hubmap_fetches(mocker, _async_iter([_hubmap_file_doc()])) - - # Act - await _sync_hubmap(SyncTask(id="t1", dcc_names=["hubmap"])) - - # Assert - ids = {(d["submission"], d["local_id"]) for d in mock_db.files.docs} - assert ("hubmap", "stale-1") not in ids - assert ("hubmap", "abc123") in ids - assert ("4dn", "keep-1") in ids - - @pytest.mark.asyncio - async def test__sync_hubmap_should_keep_previous_corpus_when_fetch_dies_early( - self, mock_db, mocker - ): - """Test a fetch that fails before delivering rows clears nothing. - - The deferred stale clear exists for exactly this shape: an upstream - failure before the first row would otherwise empty the slice with - nothing to put back. - - Given: - A files collection holding a HuBMAP document and a file stream - that raises before yielding anything. - When: - _sync_hubmap runs. - Then: - The error should propagate and the previous HuBMAP document - should still be served. - """ - # Arrange - mock_db.files.docs.append( - {"submission": "hubmap", "local_id": "previous-1"} - ) - _patch_hubmap_fetches( - mocker, _async_raise(RuntimeError("files index down")) - ) - - # Act & assert - with pytest.raises(RuntimeError, match="files index down"): - await _sync_hubmap(SyncTask(id="t1", dcc_names=["hubmap"])) - - assert mock_db.files.docs == [ - {"submission": "hubmap", "local_id": "previous-1"} - ] - - @pytest.mark.asyncio - async def test__sync_hubmap_should_ensure_materialized_files_indexes( - self, mock_db, mocker - ): - """Test the load ends by ensuring the files collection indexes. - - HuBMAP writes straight into the materialized collection and never - runs the materializer, the only other creator of files indexes, so - skipping this leaves accession and submission lookups scanning. - - Given: - A sync whose stream delivers one file document. - When: - _sync_hubmap runs. - Then: - It should ensure the materialized files index specs once. - """ - # Arrange - _patch_hubmap_fetches(mocker, _async_iter([_hubmap_file_doc()])) - ensure_mock = mocker.patch.object( - sync_module, "ensure_indexes", mocker.AsyncMock() - ) - - # Act - await _sync_hubmap(SyncTask(id="t1", dcc_names=["hubmap"])) + } + _patch_hubmap_fetches( + mocker, + _async_iter([_hubmap_file_doc()]), + dataset_metadata=dataset_metadata, + ) - # Assert - ensure_mock.assert_awaited_once() - specs = ensure_mock.await_args.args[1] - assert [spec.name for spec in specs] == [ - spec.name for spec in materialized_files_index_specs() + # Act + await sync_hubmap(SyncTask(id="t1", dcc_names=["hubmap"])) + + # Assert + doc = next(d for d in mock_db.files.docs if d["submission"] == "hubmap") + assert doc["local_id"] == "abc123" + assert doc["accession_id"] is None + assert doc["filename"] == "secondary_analysis.h5ad" + assert doc["size_in_bytes"] == 5529765 + assert isinstance(doc["size_in_bytes"], int) + assert doc["md5"] == "0b05f823fd4b3cc86204366c6f71eae9" + assert doc["sha256"].startswith("f51518c924f3") + assert doc["access_url"] == ( + "https://assets.hubmapconsortium.org/ds-uuid-1/" + "processed/expr%20matrix/secondary_analysis.h5ad" + ) + assert doc["status"] == "Published" + assert doc["data_access_level"] == "public" + assert doc["genome_assembly"] == "GRCh38" + assert doc["file_format"]["name"] == "HDF5" + assert doc["extra"]["hubmap"]["rel_path"] == ( + "processed/expr matrix/secondary_analysis.h5ad" + ) + collection = doc["collections"][0] + assert collection["local_id"] == "ds-uuid-1" + assert collection["name"] == "HBM339.XXWC.842" + assert collection["experiment_type"] == "RNAseq" + assert collection["analyte_class"] == "RNA" + assert collection["anatomy"] == [ + {"id": "UBERON:0002370", "name": "thymus"} + ] + assert collection["extra"]["hubmap"]["pipeline"] == "Salmon" + assert collection["extra"]["hubmap"]["dataset_status"] == "Published" + subject = collection["subjects"][0] + assert subject["local_id"] == "donor-1" + assert subject["extra"]["hubmap"]["sex"] == "Female" + assert subject["extra"]["hubmap"]["age_value"] == 67.0 + assert subject["extra"]["hubmap"]["medical_history"] == ["Diabetes"] + dcc_doc = next( + d for d in mock_db.dcc.docs if d["submission"] == "hubmap" + ) + assert dcc_doc["dcc_abbreviation"] == "HuBMAP" + + +@pytest.mark.asyncio +async def test_sync_hubmap_should_replace_only_the_hubmap_slice( + mock_db, mocker +): + """Test the stale clear is scoped to the submission being reloaded. + + Given: + A files collection holding a stale HuBMAP document and a 4DN + document, and a stream delivering one replacement file. + When: + sync_hubmap runs. + Then: + The stale HuBMAP document should be gone, the replacement + present, and the 4DN document untouched. + """ + # Arrange + mock_db.files.docs.extend( + [ + {"submission": "hubmap", "local_id": "stale-1"}, + {"submission": "4dn", "local_id": "keep-1"}, ] + ) + _patch_hubmap_fetches(mocker, _async_iter([_hubmap_file_doc()])) + + # Act + await sync_hubmap(SyncTask(id="t1", dcc_names=["hubmap"])) + + # Assert + ids = {(d["submission"], d["local_id"]) for d in mock_db.files.docs} + assert ("hubmap", "stale-1") not in ids + assert ("hubmap", "abc123") in ids + assert ("4dn", "keep-1") in ids + + +@pytest.mark.asyncio +async def test_sync_hubmap_should_keep_previous_corpus_when_fetch_dies_early( + mock_db, mocker +): + """Test a fetch that fails before delivering rows clears nothing. + + The deferred stale clear exists for exactly this shape: an upstream + failure before the first row would otherwise empty the slice with + nothing to put back. + + Given: + A files collection holding a HuBMAP document and a file stream + that raises before yielding anything. + When: + sync_hubmap runs. + Then: + The error should propagate and the previous HuBMAP document + should still be served. + """ + # Arrange + mock_db.files.docs.append( + {"submission": "hubmap", "local_id": "previous-1"} + ) + _patch_hubmap_fetches( + mocker, _async_raise(RuntimeError("files index down")) + ) + # Act & assert + with pytest.raises(RuntimeError, match="files index down"): + await sync_hubmap(SyncTask(id="t1", dcc_names=["hubmap"])) - @pytest.mark.asyncio - async def test__sync_hubmap_should_ensure_indexes_when_the_stream_fails( - self, mock_db, mocker - ): - """Test a failed load still leaves its slice indexed. - - A stream that dies mid-load has already committed rows; leaving - them unindexed would make every lookup against the partial slice a - full scan until the next successful sync. - - Given: - A file stream that delivers one document and then raises. - When: - _sync_hubmap runs. - Then: - The failure should propagate and the materialized files indexes - should still be ensured. - """ - # Arrange - _patch_hubmap_fetches( - mocker, - _async_iter_then_raise( - [_hubmap_file_doc()], RuntimeError("files index reset") - ), - ) - ensure_mock = mocker.patch.object( - sync_module, "ensure_indexes", mocker.AsyncMock() - ) - - # Act - with pytest.raises(RuntimeError, match="files index reset"): - await _sync_hubmap(SyncTask(id="t1", dcc_names=["hubmap"])) - - # Assert - ensure_mock.assert_awaited_once() - - @pytest.mark.asyncio - async def test__sync_hubmap_should_prefetch_outside_the_cutover_lock( - self, mock_db, mocker - ): - """Test the network prefetch does not hold the read surface hostage. - - The cutover lock blocks every API request, and the dataset and - organ prefetches touch no database state, so running them under - the lock would only lengthen the outage. - - Given: - A dataset fetch that records whether the cutover lock is active - when it runs. - When: - _sync_hubmap runs. - Then: - The fetch should not observe an active cutover lock, while the - file stream that follows should. - """ - # Arrange - observed: list[bool] = [] - - async def lock_active() -> bool: - lock = await mock_db[locks.LOCKS_COLLECTION].find_one( - {"_id": locks.CUTOVER_LOCK_ID} - ) - return bool(lock and lock.get("active")) - - async def fetch_datasets(**kwargs): - observed.append(await lock_active()) - return {"ds-uuid-1": {}} - - async def stream_files(): - # The control: the stream runs under the lock, so a fake that - # never recorded the lock would fail here instead of passing - # vacuously above. - observed.append(await lock_active()) - yield _hubmap_file_doc() - - _patch_hubmap_fetches(mocker, stream_files()) - mocker.patch.object( - hubmap_module, - "fetch_dataset_metadata_bulk", - mocker.AsyncMock(side_effect=fetch_datasets), - ) - - # Act - await _sync_hubmap(SyncTask(id="t1", dcc_names=["hubmap"])) - - # Assert - assert observed == [False, True] - - @pytest.mark.asyncio - async def test__sync_hubmap_should_bound_the_file_stream_with_a_deadline( - self, mock_db, mocker, monkeypatch - ): - """Test the in-lock stream carries the configured budget. - - The stream runs under the cutover lock, so an unbounded one could - outlive the sync lock's stale threshold and admit a second sync. - - Given: - HUBMAP_SYNC_TIMEOUT_SECONDS set to 120 and a file stream that - records the deadline it was opened with. - When: - _sync_hubmap runs. - Then: - The stream should be opened with a deadline about 120 seconds - ahead on the event-loop clock. - """ - # Arrange - monkeypatch.setenv("HUBMAP_SYNC_TIMEOUT_SECONDS", "120") - opened: dict = {} + assert mock_db.files.docs == [ + {"submission": "hubmap", "local_id": "previous-1"} + ] - def open_stream(extensions, *, deadline=None): - opened["deadline"] = deadline - return _async_iter([_hubmap_file_doc()]) - _patch_hubmap_fetches(mocker, _async_iter([])) - mocker.patch.object(hubmap_module, "fetch_file_metadata", open_stream) - loop = asyncio.get_running_loop() +@pytest.mark.asyncio +async def test_sync_hubmap_should_ensure_materialized_files_indexes( + mock_db, mocker +): + """Test the load ends by ensuring the files collection indexes. - # Act - before = loop.time() - await _sync_hubmap(SyncTask(id="t1", dcc_names=["hubmap"])) + HuBMAP writes straight into the materialized collection and never + runs the materializer, the only other creator of files indexes, so + skipping this leaves accession and submission lookups scanning. - # Assert - assert before + 119 <= opened["deadline"] <= loop.time() + 120 + Given: + A sync whose stream delivers one file document. + When: + sync_hubmap runs. + Then: + It should ensure the materialized files index specs once. + """ + # Arrange + _patch_hubmap_fetches(mocker, _async_iter([_hubmap_file_doc()])) + ensure_mock = mocker.patch.object( + sync_module, "ensure_indexes", mocker.AsyncMock() + ) - @pytest.mark.asyncio - async def test__sync_hubmap_should_keep_the_slice_when_the_stream_yields_nothing( - self, mock_db, mocker - ): - """Test an empty upstream walk is refused rather than obeyed. + # Act + await sync_hubmap(SyncTask(id="t1", dcc_names=["hubmap"])) + + # Assert + ensure_mock.assert_awaited_once() + specs = ensure_mock.await_args.args[1] + assert [spec.name for spec in specs] == [ + spec.name for spec in materialized_files_index_specs() + ] + + +@pytest.mark.asyncio +async def test_sync_hubmap_should_ensure_indexes_when_the_stream_fails( + mock_db, mocker +): + """Test a failed load still leaves its slice indexed. + + A stream that dies mid-load has already committed rows; leaving + them unindexed would make every lookup against the partial slice a + full scan until the next successful sync. + + Given: + A file stream that delivers one document and then raises. + When: + sync_hubmap runs. + Then: + The failure should propagate and the materialized files indexes + should still be ensured. + """ + # Arrange + _patch_hubmap_fetches( + mocker, + _async_iter_then_raise( + [_hubmap_file_doc()], RuntimeError("files index reset") + ), + ) + ensure_mock = mocker.patch.object( + sync_module, "ensure_indexes", mocker.AsyncMock() + ) - A mapping change on the index, or an allowlist matching nothing, - returns a well-formed empty page; obeying it would delete the - whole submission over what is almost certainly a fault. + # Act + with pytest.raises(RuntimeError, match="files index reset"): + await sync_hubmap(SyncTask(id="t1", dcc_names=["hubmap"])) - Given: - A files collection holding a HuBMAP document and a file stream - that drains cleanly without yielding anything. - When: - _sync_hubmap runs. - Then: - It should raise, and the HuBMAP document should still be - served. - """ - # Arrange - mock_db.files.docs.append( - {"submission": "hubmap", "local_id": "previous-1"} - ) - _patch_hubmap_fetches(mocker, _async_iter([])) + # Assert + ensure_mock.assert_awaited_once() - # Act - with pytest.raises(RuntimeError, match="yielded no rows"): - await _sync_hubmap(SyncTask(id="t1", dcc_names=["hubmap"])) - # Assert - assert mock_db.files.docs == [ - {"submission": "hubmap", "local_id": "previous-1"} - ] +@pytest.mark.asyncio +async def test_sync_hubmap_should_prefetch_outside_the_cutover_lock( + mock_db, mocker +): + """Test the network prefetch does not hold the read surface hostage. - @pytest.mark.asyncio - async def test__sync_hubmap_should_refuse_an_empty_dataset_map( - self, mock_db, mocker - ): - """Test an empty dataset index fails the sync before anything clears. + The cutover lock blocks every API request, and the dataset and + organ prefetches touch no database state, so running them under + the lock would only lengthen the outage. - Loading against an empty map would write every file without its - dataset context or donor demographics and report success. + Given: + A dataset fetch that records whether the cutover lock is active + when it runs. + When: + sync_hubmap runs. + Then: + The fetch should not observe an active cutover lock, while the + file stream that follows should. + """ + # Arrange + observed: list[bool] = [] - Given: - A files collection holding a HuBMAP document and a dataset fetch - that returns no datasets. - When: - _sync_hubmap runs. - Then: - It should raise naming the empty index, and the HuBMAP document - should still be served. - """ - # Arrange - mock_db.files.docs.append( - {"submission": "hubmap", "local_id": "previous-1"} - ) - _patch_hubmap_fetches( - mocker, _async_iter([_hubmap_file_doc()]), dataset_metadata={} + async def lock_active() -> bool: + lock = await mock_db[locks.LOCKS_COLLECTION].find_one( + {"_id": locks.CUTOVER_LOCK_ID} ) + return bool(lock and lock.get("active")) - # Act - with pytest.raises(RuntimeError, match="no datasets"): - await _sync_hubmap(SyncTask(id="t1", dcc_names=["hubmap"])) + async def fetch_datasets(**kwargs): + observed.append(await lock_active()) + return {"ds-uuid-1": {}} - # Assert - assert mock_db.files.docs == [ - {"submission": "hubmap", "local_id": "previous-1"} - ] + async def stream_files(): + # The control: the stream runs under the lock, so a fake that + # never recorded the lock would fail here instead of passing + # vacuously above. + observed.append(await lock_active()) + yield _hubmap_file_doc() - @pytest.mark.asyncio - async def test__sync_hubmap_should_skip_a_malformed_document( - self, mock_db, mocker - ): - """Test one malformed upstream document costs only that document. + _patch_hubmap_fetches(mocker, stream_files()) + mocker.patch.object( + hubmap_module, + "fetch_dataset_metadata_bulk", + mocker.AsyncMock(side_effect=fetch_datasets), + ) - Given: - A file stream carrying a document whose donors are bare strings, - followed by a well-formed document. - When: - _sync_hubmap runs. - Then: - It should complete, inserting only the well-formed document. - """ - # Arrange - malformed = _hubmap_file_doc(file_uuid="bad", donors=["donor-uuid"]) - _patch_hubmap_fetches( - mocker, _async_iter([malformed, _hubmap_file_doc(file_uuid="good")]) - ) + # Act + await sync_hubmap(SyncTask(id="t1", dcc_names=["hubmap"])) - # Act - await _sync_hubmap(SyncTask(id="t1", dcc_names=["hubmap"])) + # Assert + assert observed == [False, True] - # Assert - loaded = [d["local_id"] for d in mock_db.files.docs if d["submission"] == "hubmap"] - assert loaded == ["good"] - @pytest.mark.asyncio - async def test__sync_hubmap_should_end_its_deadline_before_the_sync_lock_goes_stale( - self, mock_db, mocker, monkeypatch - ): - """Test the budget is clamped to what is left of the sync lock. +@pytest.mark.asyncio +async def test_sync_hubmap_should_bound_the_file_stream_with_a_deadline( + mock_db, mocker, monkeypatch +): + """Test the in-lock stream carries the configured budget. - The sync lock's staleness counts from the start of the whole run, - and HuBMAP runs last; a budget counted from HuBMAP's own start - could outlive the lock and admit a second, clearing sync. + The stream runs under the cutover lock, so an unbounded one could + outlive the sync lock's stale threshold and admit a second sync. - Given: - A sync lock that started 50 minutes ago, a 1800 s HuBMAP budget, - and a file stream that records the deadline it was opened with. - When: - _sync_hubmap runs. - Then: - The deadline should fall about 5 minutes out -- the hour, less - the 50 minutes spent and a 5 minute margin -- not 30. - """ - # Arrange - monkeypatch.setenv("HUBMAP_SYNC_TIMEOUT_SECONDS", "1800") - await mock_db[locks.LOCKS_COLLECTION].update_one( - {"_id": locks.SYNC_LOCK_ID}, - { - "$set": { - "active": True, - "started_at": datetime.utcnow() - timedelta(minutes=50), - } - }, - upsert=True, - ) - opened: dict = {} + Given: + HUBMAP_SYNC_TIMEOUT_SECONDS set to 120 and a file stream that + records the deadline it was opened with. + When: + sync_hubmap runs. + Then: + The stream should be opened with a deadline about 120 seconds + ahead on the event-loop clock. + """ + # Arrange + monkeypatch.setenv("HUBMAP_SYNC_TIMEOUT_SECONDS", "120") + opened: dict = {} + + def open_stream(extensions, *, deadline=None): + opened["deadline"] = deadline + return _async_iter([_hubmap_file_doc()]) + + _patch_hubmap_fetches(mocker, _async_iter([])) + mocker.patch.object(hubmap_module, "fetch_file_metadata", open_stream) + loop = asyncio.get_running_loop() + + # Act + before = loop.time() + await sync_hubmap(SyncTask(id="t1", dcc_names=["hubmap"])) + + # Assert + assert before + 119 <= opened["deadline"] <= loop.time() + 120 + + +@pytest.mark.asyncio +async def test_sync_hubmap_should_keep_the_slice_when_the_stream_yields_nothing( + mock_db, mocker +): + """Test an empty upstream walk is refused rather than obeyed. + + A mapping change on the index, or an allowlist matching nothing, + returns a well-formed empty page; obeying it would delete the + whole submission over what is almost certainly a fault. + + Given: + A files collection holding a HuBMAP document and a file stream + that drains cleanly without yielding anything. + When: + sync_hubmap runs. + Then: + It should raise, and the HuBMAP document should still be + served. + """ + # Arrange + mock_db.files.docs.append( + {"submission": "hubmap", "local_id": "previous-1"} + ) + _patch_hubmap_fetches(mocker, _async_iter([])) + + # Act + with pytest.raises(RuntimeError, match="yielded no rows"): + await sync_hubmap(SyncTask(id="t1", dcc_names=["hubmap"])) + + # Assert + assert mock_db.files.docs == [ + {"submission": "hubmap", "local_id": "previous-1"} + ] + + +@pytest.mark.asyncio +async def test_sync_hubmap_should_refuse_an_empty_dataset_map( + mock_db, mocker +): + """Test an empty dataset index fails the sync before anything clears. + + Loading against an empty map would write every file without its + dataset context or donor demographics and report success. + + Given: + A files collection holding a HuBMAP document and a dataset fetch + that returns no datasets. + When: + sync_hubmap runs. + Then: + It should raise naming the empty index, and the HuBMAP document + should still be served. + """ + # Arrange + mock_db.files.docs.append( + {"submission": "hubmap", "local_id": "previous-1"} + ) + _patch_hubmap_fetches( + mocker, _async_iter([_hubmap_file_doc()]), dataset_metadata={} + ) - def open_stream(extensions, *, deadline=None): - opened["deadline"] = deadline - return _async_iter([_hubmap_file_doc()]) + # Act + with pytest.raises(RuntimeError, match="no datasets"): + await sync_hubmap(SyncTask(id="t1", dcc_names=["hubmap"])) + + # Assert + assert mock_db.files.docs == [ + {"submission": "hubmap", "local_id": "previous-1"} + ] + + +@pytest.mark.asyncio +async def test_sync_hubmap_should_skip_a_malformed_document( + mock_db, mocker +): + """Test one malformed upstream document costs only that document. + + Given: + A file stream carrying a document whose donors are bare strings, + followed by a well-formed document. + When: + sync_hubmap runs. + Then: + It should complete, inserting only the well-formed document. + """ + # Arrange + malformed = _hubmap_file_doc(file_uuid="bad", donors=["donor-uuid"]) + _patch_hubmap_fetches( + mocker, _async_iter([malformed, _hubmap_file_doc(file_uuid="good")]) + ) - _patch_hubmap_fetches(mocker, _async_iter([])) - mocker.patch.object(hubmap_module, "fetch_file_metadata", open_stream) - loop = asyncio.get_running_loop() + # Act + await sync_hubmap(SyncTask(id="t1", dcc_names=["hubmap"])) - # Act - before = loop.time() - await _sync_hubmap(SyncTask(id="t1", dcc_names=["hubmap"])) + # Assert + loaded = [d["local_id"] for d in mock_db.files.docs if d["submission"] == "hubmap"] + assert loaded == ["good"] - # Assert - assert before + 290 <= opened["deadline"] <= loop.time() + 300 - @pytest.mark.asyncio - async def test__sync_hubmap_should_keep_the_slice_when_the_allowlist_is_empty( - self, mock_db, mocker, monkeypatch - ): - """Test an empty allowlist is a no-op, not a purge. +@pytest.mark.asyncio +async def test_sync_hubmap_should_end_its_deadline_before_the_sync_lock_goes_stale( + mock_db, mocker, monkeypatch +): + """Test the budget is clamped to what is left of the sync lock. - An empty value arrives by accident routinely; draining an empty - stream would read as an authoritative empty result and delete the - whole HuBMAP slice. + The sync lock's staleness counts from the start of the whole run, + and HuBMAP runs last; a budget counted from HuBMAP's own start + could outlive the lock and admit a second, clearing sync. - Given: - A files collection holding a HuBMAP document and - HUBMAP_FILE_EXTENSIONS set to an empty value. - When: - _sync_hubmap runs. - Then: - The HuBMAP document should remain and no upstream fetch should - be made. - """ - # Arrange - monkeypatch.setenv("HUBMAP_FILE_EXTENSIONS", "") - mock_db.files.docs.append( - {"submission": "hubmap", "local_id": "previous-1"} - ) - fetch_datasets = mocker.patch.object( - hubmap_module, "fetch_dataset_metadata_bulk", mocker.AsyncMock() - ) + Given: + A sync lock that started 50 minutes ago, a 1800 s HuBMAP budget, + and a file stream that records the deadline it was opened with. + When: + sync_hubmap runs. + Then: + The deadline should fall about 5 minutes out -- the hour, less + the 50 minutes spent and a 5 minute margin -- not 30. + """ + # Arrange + monkeypatch.setenv("HUBMAP_SYNC_TIMEOUT_SECONDS", "1800") + await mock_db[locks.LOCKS_COLLECTION].update_one( + {"_id": locks.SYNC_LOCK_ID}, + { + "$set": { + "active": True, + "started_at": datetime.utcnow() - timedelta(minutes=50), + } + }, + upsert=True, + ) + opened: dict = {} + + def open_stream(extensions, *, deadline=None): + opened["deadline"] = deadline + return _async_iter([_hubmap_file_doc()]) + + _patch_hubmap_fetches(mocker, _async_iter([])) + mocker.patch.object(hubmap_module, "fetch_file_metadata", open_stream) + loop = asyncio.get_running_loop() + + # Act + before = loop.time() + await sync_hubmap(SyncTask(id="t1", dcc_names=["hubmap"])) + + # Assert + assert before + 290 <= opened["deadline"] <= loop.time() + 300 + + +@pytest.mark.asyncio +async def test_sync_hubmap_should_keep_the_slice_when_the_allowlist_is_empty( + mock_db, mocker, monkeypatch +): + """Test an empty allowlist is a no-op, not a purge. + + An empty value arrives by accident routinely; draining an empty + stream would read as an authoritative empty result and delete the + whole HuBMAP slice. + + Given: + A files collection holding a HuBMAP document and + HUBMAP_FILE_EXTENSIONS set to an empty value. + When: + sync_hubmap runs. + Then: + The HuBMAP document should remain and no upstream fetch should + be made. + """ + # Arrange + monkeypatch.setenv("HUBMAP_FILE_EXTENSIONS", "") + mock_db.files.docs.append( + {"submission": "hubmap", "local_id": "previous-1"} + ) + fetch_datasets = mocker.patch.object( + hubmap_module, "fetch_dataset_metadata_bulk", mocker.AsyncMock() + ) - # Act - await _sync_hubmap(SyncTask(id="t1", dcc_names=["hubmap"])) + # Act + await sync_hubmap(SyncTask(id="t1", dcc_names=["hubmap"])) - # Assert - assert mock_db.files.docs == [ - {"submission": "hubmap", "local_id": "previous-1"} - ] - fetch_datasets.assert_not_awaited() + # Assert + assert mock_db.files.docs == [ + {"submission": "hubmap", "local_id": "previous-1"} + ] + fetch_datasets.assert_not_awaited() # --------------------------------------------------------------------------- From 7ec8abffc1166a43e61fee5eec31a8b15eaf2ed3 Mon Sep 17 00:00:00 2001 From: Conrad Date: Fri, 20 Nov 2026 18:28:44 -0500 Subject: [PATCH 22/37] test: Zero the HuBMAP pacing constants instead of stubbing asyncio.sleep 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. --- src/cfdb/services/hubmap.py | 12 ++++++------ tests/test_hubmap.py | 13 +++++++------ tests/test_sync.py | 6 +++--- 3 files changed, 16 insertions(+), 15 deletions(-) diff --git a/src/cfdb/services/hubmap.py b/src/cfdb/services/hubmap.py index 2b95198..580c87d 100644 --- a/src/cfdb/services/hubmap.py +++ b/src/cfdb/services/hubmap.py @@ -123,8 +123,8 @@ logger = logging.getLogger(__name__) -# Rate limit: max 10 requests/second → 100ms between requests -_REQUEST_INTERVAL = 0.1 +#: Pause between search requests: at most 10 requests a second. +REQUEST_INTERVAL_SECONDS = 0.1 ASSETS_BASE_URL = "https://assets.hubmapconsortium.org" PORTAL_DATASET_URL = "https://portal.hubmapconsortium.org/browse/dataset/{uuid}" @@ -277,7 +277,7 @@ def derive_file_format(filename: str) -> Optional[dict]: #: the old slice is gone; re-sending the same ``search_after`` page is #: idempotent, which is what makes retrying safe. _PAGE_ATTEMPTS = 3 -_RETRY_BACKOFF_SECONDS = 2.0 +RETRY_BACKOFF_SECONDS = 2.0 #: Upstream statuses worth retrying. Anything else is a request the server #: will refuse again, so it is raised at once. @@ -416,7 +416,7 @@ async def _search_page( f"HuBMAP {label} search page failed (attempt {attempt} of " f"{_PAGE_ATTEMPTS}): {e!r}; retrying" ) - await asyncio.sleep(_RETRY_BACKOFF_SECONDS * attempt) + await asyncio.sleep(RETRY_BACKOFF_SECONDS * attempt) raise AssertionError("unreachable: the last attempt returns or raises") @@ -491,7 +491,7 @@ async def fetch_dataset_metadata_bulk( session, search_url, query, "dataset", deadline=deadline ) - await asyncio.sleep(_REQUEST_INTERVAL) + await asyncio.sleep(REQUEST_INTERVAL_SECONDS) if not hits: break @@ -681,7 +681,7 @@ async def fetch_file_metadata( if search_after is None: expected = total - await asyncio.sleep(_REQUEST_INTERVAL) + await asyncio.sleep(REQUEST_INTERVAL_SECONDS) if not hits: break diff --git a/tests/test_hubmap.py b/tests/test_hubmap.py index cb8c504..3e59f3f 100644 --- a/tests/test_hubmap.py +++ b/tests/test_hubmap.py @@ -148,11 +148,12 @@ def _page(*sources: dict, sort_key: str = "file_uuid") -> dict: def no_backoff(mocker): """Make the fetchers' retry backoff and rate-limit pauses instant. - Returns the mock, so a test can count the pauses it took. + Zeroes the loader's own pacing constants rather than stubbing + ``asyncio.sleep``, which is the shared module attribute every coroutine + running during the test would see. """ - return mocker.patch.object( - hubmap_module.asyncio, "sleep", mocker.AsyncMock() - ) + mocker.patch.object(hubmap_module, "RETRY_BACKOFF_SECONDS", 0) + mocker.patch.object(hubmap_module, "REQUEST_INTERVAL_SECONDS", 0) def test_file_extensions_from_env_should_return_default_when_unset( @@ -648,7 +649,7 @@ def test_transform_file_to_cfdb_should_degrade_when_dataset_unknown(): def test_transform_file_to_cfdb_should_map_organs_through_the_organ_map( ): - """Test anatomy terms come from the UBKG mapping, never fabricated. + """Test anatomy terms come from the organ map, never fabricated. Given: One mappable organ code, one unmapped, and one duplicated, with @@ -657,7 +658,7 @@ def test_transform_file_to_cfdb_should_map_organs_through_the_organ_map( transform_file_to_cfdb runs. Then: The collection should carry exactly one UBERON term, named by - the UBKG term rather than the document's drifting label, and + the organ map's term rather than the document's drifting label, and the unmapped code should be counted. """ from collections import Counter diff --git a/tests/test_sync.py b/tests/test_sync.py index 018c632..8767680 100644 --- a/tests/test_sync.py +++ b/tests/test_sync.py @@ -673,9 +673,9 @@ async def test_sync_hubmap_should_prefetch_outside_the_cutover_lock( ): """Test the network prefetch does not hold the read surface hostage. - The cutover lock blocks every API request, and the dataset and - organ prefetches touch no database state, so running them under - the lock would only lengthen the outage. + The cutover lock blocks every API request, and the dataset + prefetch touches no database state, so running it under the lock + would only lengthen the outage. Given: A dataset fetch that records whether the cutover lock is active From 8251c445f4e90a5e10e6e828371064efcc559ff6 Mon Sep 17 00:00:00 2001 From: Conrad Date: Fri, 20 Nov 2026 18:28:48 -0500 Subject: [PATCH 23/37] fix: Heartbeat the sync lock at each DCC boundary 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. --- src/cfdb/services/locks.py | 47 ++++++++- src/cfdb/services/sync.py | 23 ++--- tests/test_locks.py | 190 +++++++++++++++++++++++++++++++++++++ tests/test_sync.py | 129 ++++++++++++++++++++----- 4 files changed, 352 insertions(+), 37 deletions(-) create mode 100644 tests/test_locks.py diff --git a/src/cfdb/services/locks.py b/src/cfdb/services/locks.py index 35f1375..533833e 100644 --- a/src/cfdb/services/locks.py +++ b/src/cfdb/services/locks.py @@ -17,7 +17,10 @@ CUTOVER_WAIT_TIMEOUT = 60.0 # seconds CUTOVER_POLL_INTERVAL = 0.1 # seconds -# Stale lock threshold - if a lock is older than this, consider it abandoned +# Stale lock threshold - if a lock has shown no sign of life for longer than +# this, consider it abandoned. "Sign of life" is its ``heartbeat_at``, which +# the sync refreshes at each DCC boundary (see ``heartbeat_sync_lock``); a +# lock written before heartbeats existed falls back to its ``started_at``. STALE_LOCK_THRESHOLD = timedelta(hours=1) @@ -48,7 +51,11 @@ async def try_acquire_sync_lock(task_id: str, dcc_names: list[str]) -> bool: "$or": [ {"active": False}, {"active": {"$exists": False}}, - {"started_at": {"$lt": stale_threshold}}, + {"heartbeat_at": {"$lt": stale_threshold}}, + { + "heartbeat_at": {"$exists": False}, + "started_at": {"$lt": stale_threshold}, + }, ], }, { @@ -57,6 +64,7 @@ async def try_acquire_sync_lock(task_id: str, dcc_names: list[str]) -> bool: "task_id": task_id, "dcc_names": dcc_names, "started_at": now, + "heartbeat_at": now, "updated_at": now, }, "$unset": {"completed_at": ""}, @@ -115,14 +123,45 @@ async def is_sync_running() -> bool: return False # Check if lock is stale - started_at = lock.get("started_at") - if started_at and datetime.utcnow() - started_at > STALE_LOCK_THRESHOLD: + alive_at = sync_lock_alive_at(lock) + if alive_at and datetime.utcnow() - alive_at > STALE_LOCK_THRESHOLD: logger.warning("Found stale sync lock, considering it inactive") return False return True +def sync_lock_alive_at(lock: dict) -> Optional[datetime]: + """When a sync lock last showed it was alive: its heartbeat, else its start. + + Staleness is judged from this, so a long multi-DCC run that keeps + heartbeating is never mistaken for an abandoned one, while a crashed run + still goes stale ``STALE_LOCK_THRESHOLD`` after its last heartbeat. + """ + return lock.get("heartbeat_at") or lock.get("started_at") + + +async def heartbeat_sync_lock(task_id: str) -> None: + """Record that the running sync is alive, restarting its stale clock. + + Called at each DCC boundary. Without it a lock's staleness counted from + the start of the whole run, so whichever DCC ran last inherited what the + earlier ones left of the hour -- or none of it. Scoped to ``task_id``, so + a run whose lock went stale and was taken over cannot keep its + successor's lock alive. + + Args: + task_id: The task ID that holds the lock. + """ + if api.db is None: + raise RuntimeError("Database not initialized") + + await api.db[LOCKS_COLLECTION].update_one( + {"_id": SYNC_LOCK_ID, "task_id": task_id, "active": True}, + {"$set": {"heartbeat_at": datetime.utcnow()}}, + ) + + async def get_current_sync_task() -> Optional[dict]: """Get information about the currently running sync task.""" if api.db is None: diff --git a/src/cfdb/services/sync.py b/src/cfdb/services/sync.py index 804a790..4533794 100644 --- a/src/cfdb/services/sync.py +++ b/src/cfdb/services/sync.py @@ -148,6 +148,9 @@ async def _sync_dccs(task: SyncTask) -> None: for dcc in task.dcc_names: task.current_dcc = dcc dcc_type = get_dcc_type(dcc) + # Each DCC starts the sync lock's stale clock afresh, so a loader + # late in a long run is not starved of the hour by the ones before. + await locks.heartbeat_sync_lock(task.id) try: # Branch on DCC type @@ -1036,21 +1039,19 @@ async def _stale_safe_deadline(budget_seconds: int) -> float: """Event-loop deadline for a sync's network work, clamped to the lock. ``budget_seconds`` from now, or the moment the sync lock would turn - stale less ``_STALE_MARGIN``, whichever comes first. The sync lock's - staleness is measured from its ``started_at``, set once for the whole - multi-DCC run, and DCCs run in sorted order -- so a loader late in a - long run can start with little of the hour left, and a budget counted - from its own start would let it outlive the lock and admit a second, - clearing sync. Clamping fails that loader's fetch instead, which its - deferred clear survives. With no sync lock held (a direct call), only - the budget applies. + stale less ``_STALE_MARGIN``, whichever comes first. Staleness counts + from the lock's last heartbeat, which ``_sync_dccs`` refreshes as each + DCC starts, so the clamp normally leaves the whole budget; it binds only + when the budget itself would outlive the lock, or when no heartbeat has + been recorded since a long run began. With no sync lock held (a direct + call), only the budget applies. """ loop = asyncio.get_running_loop() deadline = loop.time() + budget_seconds lock = await locks.get_current_sync_task() - started_at = (lock or {}).get("started_at") - if isinstance(started_at, datetime): - stale_at = started_at + locks.STALE_LOCK_THRESHOLD - _STALE_MARGIN + alive_at = locks.sync_lock_alive_at(lock) if lock else None + if isinstance(alive_at, datetime): + stale_at = alive_at + locks.STALE_LOCK_THRESHOLD - _STALE_MARGIN remaining = (stale_at - datetime.utcnow()).total_seconds() deadline = min(deadline, loop.time() + remaining) return deadline diff --git a/tests/test_locks.py b/tests/test_locks.py new file mode 100644 index 0000000..105c24a --- /dev/null +++ b/tests/test_locks.py @@ -0,0 +1,190 @@ +"""Tests for the MongoDB-backed sync and cutover locks.""" + +from __future__ import annotations + +from datetime import datetime, timedelta + +import pytest + +from cfdb.services import locks + + +async def _seed_sync_lock(mock_db, **fields): + """Write the sync lock document with the given fields.""" + await mock_db[locks.LOCKS_COLLECTION].update_one( + {"_id": locks.SYNC_LOCK_ID}, {"$set": fields}, upsert=True + ) + + +def test_sync_lock_alive_at_should_prefer_the_heartbeat(): + """Test a heartbeat, when present, is the lock's last sign of life. + + Given: + A lock with both a start time and a later heartbeat. + When: + sync_lock_alive_at reads it. + Then: + It should return the heartbeat. + """ + # Arrange + started = datetime(2026, 1, 1, 0, 0) + heartbeat = datetime(2026, 1, 1, 0, 50) + + # Act + alive_at = locks.sync_lock_alive_at( + {"started_at": started, "heartbeat_at": heartbeat} + ) + + # Assert + assert alive_at == heartbeat + + +def test_sync_lock_alive_at_should_fall_back_to_the_start_without_a_heartbeat(): + """Test a lock written before heartbeats existed still has an age. + + Given: + A lock with a start time and no heartbeat. + When: + sync_lock_alive_at reads it. + Then: + It should return the start time. + """ + # Arrange + started = datetime(2026, 1, 1, 0, 0) + + # Act + alive_at = locks.sync_lock_alive_at({"started_at": started}) + + # Assert + assert alive_at == started + + +@pytest.mark.asyncio +async def test_heartbeat_sync_lock_should_refresh_an_active_lock(mock_db): + """Test a heartbeat restarts an active lock's stale clock. + + Given: + An active sync lock last heartbeated an hour ago. + When: + heartbeat_sync_lock runs. + Then: + The lock's heartbeat should be moments old. + """ + # Arrange + await _seed_sync_lock( + mock_db, + active=True, + task_id="t1", + heartbeat_at=datetime.utcnow() - timedelta(hours=1), + ) + + # Act + await locks.heartbeat_sync_lock("t1") + + # Assert + lock = await mock_db[locks.LOCKS_COLLECTION].find_one({"_id": locks.SYNC_LOCK_ID}) + assert datetime.utcnow() - lock["heartbeat_at"] < timedelta(seconds=5) + + +@pytest.mark.asyncio +async def test_heartbeat_sync_lock_should_leave_a_released_lock_alone(mock_db): + """Test a heartbeat never revives a released lock. + + Given: + A released (inactive) sync lock with an old heartbeat. + When: + heartbeat_sync_lock runs. + Then: + The heartbeat should be unchanged. + """ + # Arrange + old = datetime.utcnow() - timedelta(hours=2) + await _seed_sync_lock(mock_db, active=False, task_id="t1", heartbeat_at=old) + + # Act + await locks.heartbeat_sync_lock("t1") + + # Assert + lock = await mock_db[locks.LOCKS_COLLECTION].find_one({"_id": locks.SYNC_LOCK_ID}) + assert lock["heartbeat_at"] == old + + +@pytest.mark.asyncio +async def test_heartbeat_sync_lock_should_leave_another_tasks_lock_alone(mock_db): + """Test a run whose lock was taken over cannot keep the new one alive. + + Given: + An active sync lock held by task "second" with an old heartbeat. + When: + Task "first" heartbeats. + Then: + The heartbeat should be unchanged. + """ + # Arrange + old = datetime.utcnow() - timedelta(minutes=30) + await _seed_sync_lock(mock_db, active=True, task_id="second", heartbeat_at=old) + + # Act + await locks.heartbeat_sync_lock("first") + + # Assert + lock = await mock_db[locks.LOCKS_COLLECTION].find_one({"_id": locks.SYNC_LOCK_ID}) + assert lock["heartbeat_at"] == old + + +@pytest.mark.asyncio +async def test_try_acquire_sync_lock_should_take_over_when_the_heartbeat_is_stale( + mock_db, +): + """Test a lock silent past the threshold is treated as abandoned. + + Given: + An active sync lock whose last heartbeat is older than the stale + threshold. + When: + A second sync tries to acquire the lock. + Then: + It should acquire it, stamping a fresh start and heartbeat. + """ + # Arrange + old = datetime.utcnow() - locks.STALE_LOCK_THRESHOLD - timedelta(minutes=1) + await _seed_sync_lock( + mock_db, active=True, task_id="first", started_at=old, heartbeat_at=old + ) + + # Act + acquired = await locks.try_acquire_sync_lock("second", ["hubmap"]) + + # Assert + lock = await mock_db[locks.LOCKS_COLLECTION].find_one({"_id": locks.SYNC_LOCK_ID}) + assert acquired is True + assert lock["task_id"] == "second" + assert lock["heartbeat_at"] > old + + +@pytest.mark.asyncio +async def test_is_sync_running_should_judge_staleness_by_the_heartbeat(mock_db): + """Test a long, heartbeating run still reports as running. + + Given: + An active sync lock started two hours ago but heartbeated a minute + ago. + When: + is_sync_running checks it. + Then: + It should report the sync as running. + """ + # Arrange + now = datetime.utcnow() + await _seed_sync_lock( + mock_db, + active=True, + started_at=now - timedelta(hours=2), + heartbeat_at=now - timedelta(minutes=1), + ) + + # Act + running = await locks.is_sync_running() + + # Assert + assert running is True diff --git a/tests/test_sync.py b/tests/test_sync.py index 8767680..b1074ab 100644 --- a/tests/test_sync.py +++ b/tests/test_sync.py @@ -33,6 +33,7 @@ _stamp_4dn_file_accessions, _sync_dccs, _sync_encode, + start_sync, sync_hubmap, ) from cfdb.indexes import data_index_specs, materialized_files_index_specs @@ -391,6 +392,50 @@ async def test__sync_dccs_should_propagate_a_cancellation( hubmap_sync.assert_not_awaited() +@pytest.mark.asyncio +async def test_start_sync_should_heartbeat_the_sync_lock_as_each_dcc_starts( + mock_db, mocker +): + """Test each DCC restarts the sync lock's stale clock. + + Staleness counts from the last heartbeat, so a loader late in a long + run keeps the whole hour rather than what the earlier ones left. + + Given: + A sync started for HuBMAP whose lock heartbeat is rewound an hour + before the run begins, and a HuBMAP loader that records the lock's + heartbeat when it is called. + When: + The sync runs to completion. + Then: + The loader should see a heartbeat refreshed after the rewind. + """ + # Arrange + seen: dict = {} + + async def record_heartbeat(task): + lock = await mock_db[locks.LOCKS_COLLECTION].find_one( + {"_id": locks.SYNC_LOCK_ID} + ) + seen["heartbeat_at"] = lock["heartbeat_at"] + + mocker.patch.object( + sync_module, "sync_hubmap", mocker.AsyncMock(side_effect=record_heartbeat) + ) + rewound = datetime.utcnow() - timedelta(hours=1) + + # Act + task = await start_sync("t-heartbeat", ["hubmap"]) + await mock_db[locks.LOCKS_COLLECTION].update_one( + {"_id": locks.SYNC_LOCK_ID}, {"$set": {"heartbeat_at": rewound}} + ) + while task.completed_at is None: + await asyncio.sleep(0) + + # Assert + assert seen["heartbeat_at"] > rewound + timedelta(minutes=59) + + # --------------------------------------------------------------------------- # sync_hubmap # --------------------------------------------------------------------------- @@ -857,45 +902,85 @@ async def test_sync_hubmap_should_skip_a_malformed_document( assert loaded == ["good"] +async def _seed_sync_lock(mock_db, *, started_ago, heartbeat_ago=None): + """Write an active sync lock started (and optionally heartbeated) so long ago.""" + fields = {"active": True, "started_at": datetime.utcnow() - started_ago} + if heartbeat_ago is not None: + fields["heartbeat_at"] = datetime.utcnow() - heartbeat_ago + await mock_db[locks.LOCKS_COLLECTION].update_one( + {"_id": locks.SYNC_LOCK_ID}, {"$set": fields}, upsert=True + ) + + +def _recording_stream(opened: dict): + """A fetch_file_metadata stand-in recording the deadline it was opened with.""" + + def open_stream(extensions, *, deadline=None): + opened["deadline"] = deadline + return _async_iter([_hubmap_file_doc()]) + + return open_stream + + @pytest.mark.asyncio async def test_sync_hubmap_should_end_its_deadline_before_the_sync_lock_goes_stale( mock_db, mocker, monkeypatch ): """Test the budget is clamped to what is left of the sync lock. - The sync lock's staleness counts from the start of the whole run, - and HuBMAP runs last; a budget counted from HuBMAP's own start - could outlive the lock and admit a second, clearing sync. + A budget that would outlive the sync lock would let a second, + clearing sync be admitted while this one is still writing. Given: - A sync lock that started 50 minutes ago, a 1800 s HuBMAP budget, - and a file stream that records the deadline it was opened with. + A sync lock last alive 40 minutes ago, a 1800 s HuBMAP budget, and + a file stream that records the deadline it was opened with. When: sync_hubmap runs. Then: - The deadline should fall about 5 minutes out -- the hour, less - the 50 minutes spent and a 5 minute margin -- not 30. + The deadline should fall about 15 minutes out -- the hour, less the + 40 minutes spent and a 5 minute margin -- not 30. """ # Arrange monkeypatch.setenv("HUBMAP_SYNC_TIMEOUT_SECONDS", "1800") - await mock_db[locks.LOCKS_COLLECTION].update_one( - {"_id": locks.SYNC_LOCK_ID}, - { - "$set": { - "active": True, - "started_at": datetime.utcnow() - timedelta(minutes=50), - } - }, - upsert=True, - ) + await _seed_sync_lock(mock_db, started_ago=timedelta(minutes=40)) opened: dict = {} + _patch_hubmap_fetches(mocker, _async_iter([])) + mocker.patch.object(hubmap_module, "fetch_file_metadata", _recording_stream(opened)) + loop = asyncio.get_running_loop() - def open_stream(extensions, *, deadline=None): - opened["deadline"] = deadline - return _async_iter([_hubmap_file_doc()]) + # Act + before = loop.time() + await sync_hubmap(SyncTask(id="t1", dcc_names=["hubmap"])) + + # Assert + assert before + 890 <= opened["deadline"] <= loop.time() + 900 + +@pytest.mark.asyncio +async def test_sync_hubmap_should_count_the_lock_clock_from_its_heartbeat( + mock_db, mocker, monkeypatch +): + """Test a recent heartbeat gives HuBMAP its whole budget. + + The sync lock's stale clock restarts at each DCC's heartbeat, so a + loader late in a long run is not starved by the ones before it. + + Given: + A sync lock started 58 minutes ago but heartbeated just now, and a + 1800 s HuBMAP budget. + When: + sync_hubmap runs. + Then: + The file stream should be opened with the full 1800 s deadline. + """ + # Arrange + monkeypatch.setenv("HUBMAP_SYNC_TIMEOUT_SECONDS", "1800") + await _seed_sync_lock( + mock_db, started_ago=timedelta(minutes=58), heartbeat_ago=timedelta(0) + ) + opened: dict = {} _patch_hubmap_fetches(mocker, _async_iter([])) - mocker.patch.object(hubmap_module, "fetch_file_metadata", open_stream) + mocker.patch.object(hubmap_module, "fetch_file_metadata", _recording_stream(opened)) loop = asyncio.get_running_loop() # Act @@ -903,7 +988,7 @@ def open_stream(extensions, *, deadline=None): await sync_hubmap(SyncTask(id="t1", dcc_names=["hubmap"])) # Assert - assert before + 290 <= opened["deadline"] <= loop.time() + 300 + assert before + 1790 <= opened["deadline"] <= loop.time() + 1800 @pytest.mark.asyncio From 308e9c9d0c0d418f5c08268fcc736f00d2ccdf7b Mon Sep 17 00:00:00 2001 From: Conrad Date: Fri, 20 Nov 2026 18:29:03 -0500 Subject: [PATCH 24/37] fix: Refuse a HuBMAP stream that cannot finish before its deadline 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. --- src/cfdb/services/sync.py | 20 ++++++++++++++++++++ tests/test_sync.py | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+) diff --git a/src/cfdb/services/sync.py b/src/cfdb/services/sync.py index 4533794..9373575 100644 --- a/src/cfdb/services/sync.py +++ b/src/cfdb/services/sync.py @@ -1034,6 +1034,12 @@ def tally(doc: dict) -> None: #: lock turns stale, so the stream's own teardown fits inside the lock. _STALE_MARGIN = timedelta(minutes=5) +#: The least time the HuBMAP file stream is allowed to start with. The +#: stream's slice is cleared at its first committed batch, so a deadline that +#: expires mid-walk leaves a truncated slice; refusing to start with less than +#: this keeps the previous slice instead. A full walk takes one to two minutes. +_MIN_STREAM_SECONDS = 300 + async def _stale_safe_deadline(budget_seconds: int) -> float: """Event-loop deadline for a sync's network work, clamped to the lock. @@ -1168,6 +1174,20 @@ def transform(src: dict) -> Optional[dict]: ) return None + # The stream's slice is cleared at its first committed batch, so a + # deadline that expires mid-walk leaves a truncated slice. Refuse here, + # before the lock and before any clear, unless enough of the deadline is + # left for the walk -- the previous slice is then kept untouched. + remaining = deadline - asyncio.get_running_loop().time() + floor = min(_MIN_STREAM_SECONDS, sync_budget_seconds() / 2) + logger.info("HuBMAP file stream: %.0f s of the sync's deadline remain", remaining) + if remaining < floor: + raise RuntimeError( + f"HuBMAP sync: only {max(remaining, 0):.0f} s of its deadline remain, " + f"less than the {floor:.0f} s the file stream needs; refusing to " + "start it, so the existing HuBMAP slice is kept" + ) + try: async with locks.CutoverLock("hubmap"): # Step 2: Clear existing raw HuBMAP data. ``files`` is diff --git a/tests/test_sync.py b/tests/test_sync.py index b1074ab..c266244 100644 --- a/tests/test_sync.py +++ b/tests/test_sync.py @@ -991,6 +991,41 @@ async def test_sync_hubmap_should_count_the_lock_clock_from_its_heartbeat( assert before + 1790 <= opened["deadline"] <= loop.time() + 1800 +@pytest.mark.asyncio +async def test_sync_hubmap_should_refuse_to_start_the_stream_without_enough_deadline( + mock_db, mocker, monkeypatch +): + """Test a nearly spent deadline is refused before anything is cleared. + + The slice is cleared at the stream's first committed batch, so a + deadline expiring mid-walk would leave a truncated slice. + + Given: + A files collection holding a HuBMAP document, and a sync lock last + alive 54 minutes ago -- leaving about a minute before the margin. + When: + sync_hubmap runs. + Then: + It should raise without opening the file stream, and the HuBMAP + document should still be served. + """ + # Arrange + monkeypatch.setenv("HUBMAP_SYNC_TIMEOUT_SECONDS", "1800") + await _seed_sync_lock(mock_db, started_ago=timedelta(minutes=54)) + mock_db.files.docs.append({"submission": "hubmap", "local_id": "previous-1"}) + opened: dict = {} + _patch_hubmap_fetches(mocker, _async_iter([])) + mocker.patch.object(hubmap_module, "fetch_file_metadata", _recording_stream(opened)) + + # Act + with pytest.raises(RuntimeError, match="refusing to start it"): + await sync_hubmap(SyncTask(id="t1", dcc_names=["hubmap"])) + + # Assert + assert opened == {} + assert mock_db.files.docs == [{"submission": "hubmap", "local_id": "previous-1"}] + + @pytest.mark.asyncio async def test_sync_hubmap_should_keep_the_slice_when_the_allowlist_is_empty( mock_db, mocker, monkeypatch From a2c7ea82692fdea551163703e0afe240ac752364 Mon Sep 17 00:00:00 2001 From: Conrad Date: Fri, 20 Nov 2026 18:29:07 -0500 Subject: [PATCH 25/37] fix: Validate each HuBMAP document before storing it 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. --- src/cfdb/services/sync.py | 16 ++++++++++++--- tests/test_sync.py | 42 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+), 3 deletions(-) diff --git a/src/cfdb/services/sync.py b/src/cfdb/services/sync.py index 9373575..7e66180 100644 --- a/src/cfdb/services/sync.py +++ b/src/cfdb/services/sync.py @@ -1099,6 +1099,7 @@ async def sync_hubmap(task: SyncTask) -> None: in place -- the same outcome an empty ``ENCODE_ANNOTATION_TYPES`` has for ENCODE's annotation phases. """ + from cfdb.models import FileMetadataModel from cfdb.services.hubmap import ( build_donor_lookup, build_hubmap_dcc_record, @@ -1157,14 +1158,20 @@ async def sync_hubmap(task: SyncTask) -> None: def transform(src: dict) -> Optional[dict]: # One malformed upstream document costs that document, not the # sync: an exception here would otherwise abort the stream after - # the stale clear and leave a partial slice. + # the stale clear and leave a partial slice. The model check is part + # of the same guard -- a document that transforms but does not + # validate (an upstream field that changed type) would otherwise be + # stored, and every API page holding it would then fail to build. try: - return transform_file_to_cfdb( + doc = transform_file_to_cfdb( src, dataset_metadata=dataset_metadata, donor_lookup=donor_lookup, stats=stats, ) + if doc is not None: + FileMetadataModel(**doc) + return doc except Exception: stats["skipped:malformed"] += 1 if stats["skipped:malformed"] <= 5: @@ -1270,7 +1277,10 @@ def transform(src: dict) -> Optional[dict]: ) malformed = stats.get("skipped:malformed", 0) if malformed: - logger.warning(f"HuBMAP ingest: skipped {malformed} malformed documents") + logger.warning( + f"HuBMAP ingest: skipped {malformed} documents that failed to " + "transform or to validate" + ) unjoined = { key: stats[key] for key in ("unjoined_dataset", "unjoined_donor") if stats[key] } diff --git a/tests/test_sync.py b/tests/test_sync.py index c266244..46efa9e 100644 --- a/tests/test_sync.py +++ b/tests/test_sync.py @@ -902,6 +902,48 @@ async def test_sync_hubmap_should_skip_a_malformed_document( assert loaded == ["good"] +@pytest.mark.asyncio +async def test_sync_hubmap_should_skip_a_document_that_fails_model_validation( + mock_db, mocker +): + """Test a document that transforms but would not validate is not stored. + + The API builds the model for every document on a page, so one stored + document of the wrong shape would fail every page that holds it. + + Given: + A dataset whose donor reports two races -- which the transform + stores as a list where the model expects one string -- referenced + by one file, followed by a file whose dataset is well-formed. + When: + sync_hubmap runs. + Then: + Only the well-formed file should be inserted. + """ + # Arrange + dataset_metadata = { + "ds-bad": {"donors": {"donor-2": {"race": ["White", "Asian"]}}}, + "ds-uuid-1": {}, + } + bad = _hubmap_file_doc( + file_uuid="bad", + dataset_uuid="ds-bad", + donors=[{"entity_type": "Donor", "uuid": "donor-2"}], + ) + _patch_hubmap_fetches( + mocker, + _async_iter([bad, _hubmap_file_doc(file_uuid="good")]), + dataset_metadata=dataset_metadata, + ) + + # Act + await sync_hubmap(SyncTask(id="t1", dcc_names=["hubmap"])) + + # Assert + loaded = [d["local_id"] for d in mock_db.files.docs if d["submission"] == "hubmap"] + assert loaded == ["good"] + + async def _seed_sync_lock(mock_db, *, started_ago, heartbeat_ago=None): """Write an active sync lock started (and optionally heartbeated) so long ago.""" fields = {"active": True, "started_at": datetime.utcnow() - started_ago} From 38355684d37a2d2ea3d8ea4a9175f304a63bc14a Mon Sep 17 00:00:00 2001 From: Conrad Date: Fri, 20 Nov 2026 18:29:11 -0500 Subject: [PATCH 26/37] feat: Count HuBMAP files missing a size or checksum 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. --- src/cfdb/services/hubmap.py | 8 ++++++++ src/cfdb/services/sync.py | 10 ++++++++++ tests/test_hubmap.py | 33 +++++++++++++++++++++++++++++++++ 3 files changed, 51 insertions(+) diff --git a/src/cfdb/services/hubmap.py b/src/cfdb/services/hubmap.py index 580c87d..2da7972 100644 --- a/src/cfdb/services/hubmap.py +++ b/src/cfdb/services/hubmap.py @@ -849,6 +849,14 @@ def transform_file_to_cfdb( size_in_bytes = int(src["size"]) except (KeyError, TypeError, ValueError): size_in_bytes = None + if stats is not None: + # Counted so the "real size and checksums on every file" promise is + # observable per sync rather than assumed. + if size_in_bytes is None: + stats["missing:size"] += 1 + for field in ("md5_checksum", "sha256_checksum"): + if not src.get(field): + stats[f"missing:{field.removesuffix('_checksum')}"] += 1 if organ_map is None: organ_map = HUBMAP_ORGAN_TO_UBERON diff --git a/src/cfdb/services/sync.py b/src/cfdb/services/sync.py index 7e66180..011a84a 100644 --- a/src/cfdb/services/sync.py +++ b/src/cfdb/services/sync.py @@ -1281,6 +1281,16 @@ def transform(src: dict) -> Optional[dict]: f"HuBMAP ingest: skipped {malformed} documents that failed to " "transform or to validate" ) + missing = { + key.removeprefix("missing:"): n + for key, n in stats.items() + if key.startswith("missing:") + } + if missing: + logger.warning( + f"HuBMAP ingest: files missing upstream integrity fields {missing}; " + "those fields were stored as null" + ) unjoined = { key: stats[key] for key in ("unjoined_dataset", "unjoined_donor") if stats[key] } diff --git a/tests/test_hubmap.py b/tests/test_hubmap.py index 3e59f3f..1b6f341 100644 --- a/tests/test_hubmap.py +++ b/tests/test_hubmap.py @@ -767,6 +767,39 @@ def test_transform_file_to_cfdb_should_count_extensions_into_stats(): assert stats["extension:.h5ad"] == 1 +def test_transform_file_to_cfdb_should_count_missing_size_and_checksums(): + """Test absent integrity fields are counted, not silently nulled. + + Real sizes and checksums on every file is a promise of the loader, so + each shortfall has to be visible in the sync's counters. + + Given: + One document with no size and no md5, and one complete document, + sharing a stats counter. + When: + transform_file_to_cfdb runs over both. + Then: + The counter should record one missing size and one missing md5, + and no missing sha256. + """ + from collections import Counter + + # Arrange + stats: Counter = Counter() + incomplete = _file_doc(file_uuid="a", size=None, md5_checksum=None) + + # Act + for src in (incomplete, _file_doc(file_uuid="b")): + transform_file_to_cfdb( + src, dataset_metadata={}, donor_lookup={}, stats=stats + ) + + # Assert + assert stats["missing:size"] == 1 + assert stats["missing:md5"] == 1 + assert stats["missing:sha256"] == 0 + + def test_transform_file_to_cfdb_should_name_anatomy_from_the_uberon_table(): """Test the default organ table supplies UBERON ids and UBERON labels. From 7c390723645194cb5e3772f5dc9d483dd8adc584 Mon Sep 17 00:00:00 2001 From: Conrad Date: Fri, 20 Nov 2026 18:29:16 -0500 Subject: [PATCH 27/37] fix: Refuse a HuBMAP dataset walk that ends short 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. --- src/cfdb/services/hubmap.py | 17 +++++++++++++-- tests/test_hubmap.py | 41 +++++++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 2 deletions(-) diff --git a/src/cfdb/services/hubmap.py b/src/cfdb/services/hubmap.py index 2da7972..9907a64 100644 --- a/src/cfdb/services/hubmap.py +++ b/src/cfdb/services/hubmap.py @@ -454,7 +454,8 @@ async def fetch_dataset_metadata_bulk( Each page is retried on transient failure (see ``_search_page``); a failure that outlasts the retries raises rather than returning the partial map, since a silently partial map would mean silently - under-enriched documents. + under-enriched documents. For the same reason the first page asks for + an exact total, and a walk that ends with fewer datasets than it raises. Args: deadline: Event-loop clock reading by which the whole fetch must @@ -474,6 +475,8 @@ async def fetch_dataset_metadata_bulk( results: dict[str, dict] = {} page_size = 1000 search_after: Optional[list] = None + seen = 0 + expected: Optional[int] = None async with aiohttp.ClientSession() as session: while True: @@ -486,10 +489,15 @@ async def fetch_dataset_metadata_bulk( if search_after is not None: query["search_after"] = search_after + else: + query["track_total_hits"] = True - hits, _ = await _search_page( + hits, total = await _search_page( session, search_url, query, "dataset", deadline=deadline ) + if search_after is None: + expected = total + seen += len(hits) await asyncio.sleep(REQUEST_INTERVAL_SECONDS) @@ -560,6 +568,11 @@ async def fetch_dataset_metadata_bulk( f"HuBMAP dataset fetch: {len(results)} datasets fetched so far" ) + if expected is not None and seen < expected: + raise RuntimeError( + f"HuBMAP dataset walk ended short: {seen} of the {expected} " + "datasets the index reported on its first page" + ) logger.info(f"HuBMAP dataset fetch: {len(results)} total datasets fetched") return results diff --git a/tests/test_hubmap.py b/tests/test_hubmap.py index 1b6f341..931674d 100644 --- a/tests/test_hubmap.py +++ b/tests/test_hubmap.py @@ -1458,6 +1458,47 @@ async def test_fetch_dataset_metadata_bulk_should_key_results_by_uuid( assert entry["genome_assembly"] == "GRCh38" +@pytest.mark.asyncio +async def test_fetch_dataset_metadata_bulk_should_raise_when_the_walk_ends_short( + mocker, +): + """Test a dataset walk that delivers less than the index reported is refused. + + A partial map would load documents with silently missing dataset + context, so the walk is held to the total it was promised. + + Given: + A first page reporting an exact total of 3 datasets but carrying + 2, after which the index serves nothing more. + When: + fetch_dataset_metadata_bulk drains the index. + Then: + It should raise naming the shortfall, having asked for an exact + total on the first page. + """ + # Arrange + first = { + "hits": { + "total": {"value": 3, "relation": "eq"}, + "hits": [ + {"_source": {"uuid": "ds-1"}, "sort": ["ds-1"]}, + {"_source": {"uuid": "ds-2"}, "sort": ["ds-2"]}, + ], + } + } + session = _SearchSession(pages=[first]) + mocker.patch.object( + hubmap_module.aiohttp, "ClientSession", return_value=session + ) + + # Act + with pytest.raises(RuntimeError, match="2 of the 3"): + await fetch_dataset_metadata_bulk() + + # Assert + assert session.post_bodies[0]["track_total_hits"] is True + + @pytest.mark.asyncio async def test_fetch_dataset_metadata_bulk_should_raise_on_http_error(mocker, no_backoff): """Test a partial dataset map is refused rather than returned. From 23bf9328e5182a8cde3337804003fb0ee3c23b52 Mon Sep 17 00:00:00 2001 From: Conrad Date: Fri, 20 Nov 2026 18:29:29 -0500 Subject: [PATCH 28/37] fix: Correct the HuBMAP manubrium and prostate organ terms 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. --- src/cfdb/services/ontology_mappings.py | 4 ++-- tests/test_ontology_mappings.py | 29 ++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/src/cfdb/services/ontology_mappings.py b/src/cfdb/services/ontology_mappings.py index 317c3ae..7daa317 100644 --- a/src/cfdb/services/ontology_mappings.py +++ b/src/cfdb/services/ontology_mappings.py @@ -313,13 +313,13 @@ "LU": {"id": "UBERON:0001223", "name": "left ureter"}, "LV": {"id": "UBERON:0002107", "name": "liver"}, "LY": {"id": "UBERON:0000029", "name": "lymph node"}, - "MB": {"id": "UBERON:2001553", "name": "manubrium"}, + "MB": {"id": "UBERON:0002205", "name": "manubrium of sternum"}, # Manubrium: UBKG gives UBERON:2001553, a teleost term "MH": {"id": "UBERON:0000165", "name": "mouth"}, "ML": {"id": "UBERON:0001911", "name": "mammary gland"}, # Mammary Gland (Left): side-neutral parent; UBKG gives FMA here "MR": {"id": "UBERON:0001911", "name": "mammary gland"}, # Mammary Gland (Right): side-neutral parent; UBKG gives FMA here "PA": {"id": "UBERON:0001264", "name": "pancreas"}, "PL": {"id": "UBERON:0001987", "name": "placenta"}, - "PR": {"id": "UBERON:0000079", "name": "male reproductive system"}, # Prostate: UBKG's mapping, kept verbatim + "PR": {"id": "UBERON:0002367", "name": "prostate gland"}, # Prostate: UBKG gives UBERON:0000079, the whole male reproductive system "PV": {"id": "UBERON:0001270", "name": "bony pelvis"}, "RB": {"id": "UBERON:0002177", "name": "right main bronchus"}, "RE": {"id": "UBERON:0004549", "name": "right eye"}, diff --git a/tests/test_ontology_mappings.py b/tests/test_ontology_mappings.py index 10e61a8..de57c87 100644 --- a/tests/test_ontology_mappings.py +++ b/tests/test_ontology_mappings.py @@ -495,3 +495,32 @@ def test_hubmap_organ_to_uberon_should_map_fma_only_lateral_organs_to_their_pare # Assert assert ids == {parent} + + +@pytest.mark.parametrize( + ("code", "uberon_id", "name"), + [ + ("MB", "UBERON:0002205", "manubrium of sternum"), + ("PR", "UBERON:0002367", "prostate gland"), + ], +) +def test_hubmap_organ_to_uberon_should_correct_ubkg_where_its_term_is_wrong( + code, uberon_id, name +): + """Test the codes whose UBKG term names the wrong anatomy are corrected. + + UBKG maps the manubrium to a teleost term and the prostate to the whole + male reproductive system; the table holds the human organ instead. + + Given: + An organ code whose UBKG entry names the wrong UBERON term. + When: + The code is looked up in the table. + Then: + It should map to the human organ's UBERON id and label. + """ + # Act + term = HUBMAP_ORGAN_TO_UBERON[code] + + # Assert + assert term == {"id": uberon_id, "name": name} From 88b1a743ae14af6e6d46eddf488aa53dc6e1710f Mon Sep 17 00:00:00 2001 From: Conrad Date: Fri, 20 Nov 2026 18:29:34 -0500 Subject: [PATCH 29/37] test: Cover upstream status mapping on the index sidecar path 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. --- tests/test_index.py | 46 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/tests/test_index.py b/tests/test_index.py index 12a10c5..8684c61 100644 --- a/tests/test_index.py +++ b/tests/test_index.py @@ -266,6 +266,52 @@ async def fake_stream(_url, _range): assert resp.headers["content-range"] == "bytes 0-49/100" + @pytest.mark.asyncio + @pytest.mark.parametrize( + ("upstream_error", "expected_status"), + [ + (drs.DRSForbidden("upstream 403"), 403), + (drs.DRSNotFound("upstream 404"), 404), + (drs.DRSUpstreamError("upstream 500"), 502), + (drs.DRSTimeout("upstream timed out"), 504), + ], + ) + async def test_stream_index_file_should_raise_the_upstream_status_for_a_sidecar( + self, mock_db, mocker, upstream_error, expected_status + ): + """Test a sidecar the upstream refuses becomes its status, not a cut-off 200. + + Given: + A 4DN BED whose extra_files sidecar answers with an upstream + error before its first byte. + When: + stream_index_file is called. + Then: + It should raise the mapped HTTP status instead of returning a + response. + """ + # Arrange + mocker.patch.object(locks, "wait_for_cutover", return_value=None) + + async def fake_stream(url, _range): + raise upstream_error + yield b"" # pragma: no cover - makes this an async generator + + mocker.patch.object(drs, "stream_from_url", fake_stream) + mock_db.files.docs = [] + mock_db.file.docs = [ + _make_file_doc( + extra={"extra_files": [{"href": "/x/abc.tbi", "file_size": 100}]} + ) + ] + + # Act + with pytest.raises(HTTPException) as exc_info: + await stream_index_file("4dn", "4DNFIBED01", _make_request(), range=None) + + # Assert + assert exc_info.value.status_code == expected_status + @pytest.mark.asyncio async def test_stream_index_file_should_serve_fourdn_sidecar_when_extra_files_present( self, mock_db, mocker From ab5edb4b9ba56e5d2ff1ad4b22c031c8a79e1216 Mon Sep 17 00:00:00 2001 From: Conrad Date: Fri, 20 Nov 2026 18:29:38 -0500 Subject: [PATCH 30/37] docs: Document the HuBMAP deadline floor, heartbeat and rollback 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. --- HUBMAP-SUPPLEMENT.md | 16 +++++++++++----- README.md | 7 ++++--- 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/HUBMAP-SUPPLEMENT.md b/HUBMAP-SUPPLEMENT.md index 8c23dfb..23eb2fd 100644 --- a/HUBMAP-SUPPLEMENT.md +++ b/HUBMAP-SUPPLEMENT.md @@ -15,7 +15,9 @@ Organ codes need no request: they map through `HUBMAP_ORGAN_TO_UBERON` in `servi Every search page is attempted up to three times, with backoff, on a transport error, a timeout, or a 429/5xx, since re-sending the same `search_after` page is idempotent. A 200 that is partial — failed shards, an upstream `timed_out`, or no hits envelope — is treated the same way rather than walked past, because Elasticsearch answers 200 with whatever the healthy shards returned and the walk would otherwise resume past documents it never received. A failure that outlasts the attempts raises. -Two results are refused outright rather than loaded. A files walk that drains cleanly with no documents raises instead of clearing the slice: a mapping change on the index, or an allowlist that matches nothing, returns a well-formed empty page, and for a submission one stream owns an empty answer is a fault, never a result. And the first files page asks for an exact total (`track_total_hits`), so a walk that ends with fewer documents than the index reported raises. An empty dataset map is refused the same way, before the cutover lock, so the previous slice keeps being served. +Two results are refused outright rather than loaded. A files walk that drains cleanly with no documents raises instead of clearing the slice: a mapping change on the index, or an allowlist that matches nothing, returns a well-formed empty page, and for a submission one stream owns an empty answer is a fault, never a result. And the first page of each walk — files and datasets alike — asks for an exact total (`track_total_hits`), so a walk that ends with fewer documents than the index reported raises. An empty dataset map is refused the same way, before the cutover lock, so the previous slice keeps being served, and so is a partial one. + +One malformed document costs only itself. Each document is transformed and then validated against `FileMetadataModel` before it is stored; one that fails either step is skipped and counted, and the sync logs the count. Validation matters here because the API builds the model for every document on a page, so one stored document of the wrong shape — an upstream field that changed type, such as a donor reporting two races where one string is expected — would fail every page holding it. Files the index lists with no `size`, `md5_checksum` or `sha256_checksum` are stored with that field null and counted per field, so the sync log shows the shortfall (4 of 51,816 allowlisted files had no size when the loader was written). ## Entity Construction @@ -48,7 +50,7 @@ Default: `.h5ad`, `.h5mu`, `.h5`, `.hdf5`, `.gz`, `.mtx`, `.arrow`, `.parquet`, |------------|--------|-------| | `local_id` | `file_uuid` | HuBMAP issues no file accessions; `accession_id` is explicitly null ([#102](https://github.com/abdenlab/cfdb/issues/102)) | | `filename` | `rel_path` basename | Full path kept on `extra.hubmap.rel_path` | -| `size_in_bytes` | `size` | Stored as int64 — the C2M2 TSV path stored it as a string, which left size filters inert | +| `size_in_bytes` | `size` | Stored as a BSON integer (int32 or int64 by magnitude), never a string — the C2M2 TSV path stored it as a string, which left size filters inert | | `md5` / `sha256` | `md5_checksum` / `sha256_checksum` | Real per-file checksums; the C2M2 TSVs lacked or mistyped both | | `file_format` | filename, compression suffix stripped | EDAM-mapped from the inner extension, so `x.fastq.gz` maps to FASTQ rather than nothing | | `compression_format` | filename suffix | Same derivation and absent-when-undetermined contract as ENCODE | @@ -71,7 +73,7 @@ One collection per file: its parent dataset. | `analyte_class` | `analyte_class` | | `anatomy[]` | `organs[]` — UBERON id and UBERON label from the checked-in organ table by `code`. The name is the UBERON label (`left kidney`), not UBKG's display term (`Kidney (Left)`) or the document's own `label`, which drifts between files for the same code (`Main Bronchus (Right)` vs `Bronchus (Right)`); either would give one id more than one name across files and DCCs | -The table is a static snapshot rather than a per-sync UBKG fetch for two reasons: a fetch that failed would have stripped anatomy from the whole slice for a sync, and UBKG's display terms are not UBERON labels. UBKG's `organ_uberon` is not always UBERON either: the lateral organs (left/right knee, mammary gland, tonsil) carry FMA ids there, so the table maps them to the side-neutral UBERON parent UBKG names under `category` (e.g. `RN` Knee (Right) → `UBERON:0001465` knee), losing the side rather than storing an id that does not resolve in UBERON. `PR` (Prostate) maps to `UBERON:0000079` male reproductive system, UBKG's own mapping, kept verbatim. A code the table does not know — one HuBMAP adds later — is skipped and counted rather than given a fabricated id, and the sync logs the unmapped codes until the table is extended. +The table is a static snapshot rather than a per-sync UBKG fetch for two reasons: a fetch that failed would have stripped anatomy from the whole slice for a sync, and UBKG's display terms are not UBERON labels. UBKG's `organ_uberon` is not always UBERON either: the lateral organs (left/right knee, mammary gland, tonsil) carry FMA ids there, so the table maps them to the side-neutral UBERON parent UBKG names under `category` (e.g. `RN` Knee (Right) → `UBERON:0001465` knee), losing the side rather than storing an id that does not resolve in UBERON. Two UBKG terms name the wrong anatomy outright and are corrected: `MB` (Manubrium) maps to `UBERON:0002205` manubrium of sternum, where UBKG gives `UBERON:2001553`, a teleost term; and `PR` (Prostate) maps to `UBERON:0002367` prostate gland, where UBKG gives `UBERON:0000079`, the whole male reproductive system. A code the table does not know — one HuBMAP adds later — is skipped and counted rather than given a fabricated id, and the sync logs the unmapped codes until the table is extended. ### `extra.hubmap` (`EnrichedHubmapCollection`), joined from the dataset index @@ -140,6 +142,10 @@ fetch_dataset_metadata_bulk(deadline) # dataset index -> {dataset_uuid: contex ensure_indexes(files) # runs even when the stream fails ``` -The whole pipeline is `sync_hubmap` in `services/sync.py`, sharing `_ingest_rows` with the ENCODE path. The prefetch runs before the cutover lock is taken, because the lock gates the whole read surface and the prefetch touches no database state. Every fetch shares one deadline: `HUBMAP_SYNC_TIMEOUT_SECONDS` (default 1800), clamped to end five minutes before the sync lock would turn stale. That clamp matters because the sync lock's one-hour staleness counts from the start of the whole multi-DCC run and HuBMAP runs last, after 4DN and ENCODE, so a budget counted from HuBMAP's own start could outlive the lock and admit a second sync; clamped, the late fetch fails instead, which the deferred clear survives. The stale HuBMAP slice is cleared only once replacement rows are in hand, so an upstream failure before the first row leaves the previous corpus being served rather than empty. +The whole pipeline is `sync_hubmap` in `services/sync.py`, sharing `_ingest_rows` with the ENCODE path. The prefetch runs before the cutover lock is taken, because the lock gates the whole read surface and the prefetch touches no database state. Every fetch shares one deadline: `HUBMAP_SYNC_TIMEOUT_SECONDS` (default 1800), clamped to end five minutes before the sync lock would turn stale, so a slow upstream can never hold HuBMAP's load past the point where a second sync would be admitted. The sync lock's one-hour staleness counts from its last heartbeat, which the sync records as each DCC starts, so HuBMAP — which runs last, after 4DN and ENCODE — has the full hour to itself rather than whatever the earlier DCCs left of it, and the clamp binds only when the budget is set above the threshold. The stale HuBMAP slice is cleared at the first committed batch of replacement rows, so an upstream failure before that row leaves the previous corpus being served rather than empty. A deadline that expires after it does not: the slice is left truncated. So before taking the cutover lock the sync checks how much of the deadline remains, and refuses — logging the remainder and leaving the slice untouched — unless it covers the walk (five minutes, or half the budget when the budget is set lower). + +Two costs remain, shared with ENCODE's identical in-lock design and tracked in [#129](https://github.com/abdenlab/cfdb/issues/129). The file stream holds the cutover lock for as long as it runs — one to two minutes against a healthy upstream, but up to the whole deadline (30 minutes by default) against a degraded one, since each page may be retried until the deadline — and every API request for every DCC that waits longer than the 60-second cutover timeout fails, so a HuBMAP sync is a read outage across the whole API for that long. And a failure after the first batch still leaves a partial slice — loudly, with indexes ensured — which only a staged load swapped in under a short lock would make atomic. + +## Rolling back -Two costs remain, shared with ENCODE's identical in-lock design and tracked in [#129](https://github.com/abdenlab/cfdb/issues/129). The file stream holds the cutover lock for the roughly two minutes it takes, and every API request for every DCC that waits longer than the 60-second cutover timeout fails, so a HuBMAP sync is a brief read outage across the whole API. And a failure after the first batch still leaves a partial slice — loudly, with indexes ensured — which only a staged load swapped in under a short lock would make atomic. +Rolling the API back past this loader after a HuBMAP sync breaks every HuBMAP `/data` request. Earlier images send every non-ENCODE file through DRS, whose URI parser answers anything that is not `drs://` with 400, while the documents this loader wrote carry `https://assets.hubmapconsortium.org/...` URLs, and the re-tag that rolls back the image does not touch Mongo. After such a rollback, re-sync HuBMAP on the older image (`cfdb sync hubmap`) to restore the C2M2-shaped documents it expects. diff --git a/README.md b/README.md index e095d89..ec77a5d 100644 --- a/README.md +++ b/README.md @@ -184,7 +184,7 @@ Because both prod task definitions already reference `:prod`, this doubles as th Production never advances automatically. `.github/workflows/promote-to-prod.yml` is `workflow_dispatch`-only and gated on the `prod` GitHub Environment's required reviewers. Dispatch it with the 8-character `:` tag that the dev pipeline already built, scanned, and shipped; it verifies that tag exists in **both** `cfdb` and `cfdb-wool`, re-tags each onto `:prod` by copying the ECR manifest, rolls the prod API service, and waits for `services-stable`. -Promotion re-tags rather than rebuilds, so prod runs bytes byte-identical to what dev validated. **Rollback is the same operation with an older SHA:** dispatch the workflow again naming the previous `:`. As on dev, the worker fleet needs no ECS step — the prod worker task def also references `:prod` and workers are ephemeral, so the next `EcsProvisioner` `RunTask` pulls the new image. That does mean the API rolls immediately while in-flight workers may still run the prior image until they drain, so keep the API↔worker dispatch contract compatible across adjacent promotions. +Promotion re-tags rather than rebuilds, so prod runs bytes byte-identical to what dev validated. **Rollback is the same operation with an older SHA:** dispatch the workflow again naming the previous `:`. As on dev, the worker fleet needs no ECS step — the prod worker task def also references `:prod` and workers are ephemeral, so the next `EcsProvisioner` `RunTask` pulls the new image. That does mean the API rolls immediately while in-flight workers may still run the prior image until they drain, so keep the API↔worker dispatch contract compatible across adjacent promotions. Rolling back past the HuBMAP files-API loader is the one rollback that also needs data: documents it wrote carry assets URLs that older images refuse, so re-sync HuBMAP after such a rollback (see `HUBMAP-SUPPLEMENT.md`, Rolling back). Prod requires this one-time setup before the first promotion: @@ -831,12 +831,13 @@ Stream index files (e.g., `.px2`, `.bai`) associated with DCC data files. | 202 | Index not yet cached — workflow accepted. `Location: /jobs/{id}` and `Retry-After` headers point to the polling endpoint. Under load the job may sit `pending` in the durable queue before a worker picks it up; poll `/jobs/{id}` for progress. | | 206 | Partial content (Range request) | | 400 | Invalid DCC, path-param shape, or Range header | -| 403 | File requires consortium/protected access (HuBMAP) | -| 404 | File not found, format has no index (CSV/TSV/bigWig), or HEAD probe of a not-yet-cached index | +| 403 | File requires consortium/protected access (HuBMAP), or the upstream host refused the sidecar | +| 404 | File not found, format has no index (CSV/TSV/bigWig), HEAD probe of a not-yet-cached index, or the sidecar is missing upstream | | 416 | Range not satisfiable | | 429 | Too many active preprocessing jobs — the active-workflow ceiling (`CFDB_WORKFLOW_MAX_ACTIVE`) is reached; `Retry-After` header set. Retry shortly. | | 502 | Upstream service error or malformed sidecar | | 503 | Workflow subsystem disabled (set `SYNC_DATA_DIR`) for a processable format, or shutting down (`Retry-After`) | +| 504 | Upstream timed out before sending the sidecar | ```bash # Download an index file From 37a12586f5c525a91bb386f4504c1592133db4fa Mon Sep 17 00:00:00 2001 From: Conrad Date: Mon, 23 Nov 2026 11:36:22 -0500 Subject: [PATCH 31/37] fix: Store the HuBMAP index's 32-bit size ceiling as an unknown size 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. --- src/cfdb/services/hubmap.py | 16 ++++++++++++++-- src/cfdb/services/sync.py | 6 ++++++ tests/test_hubmap.py | 29 +++++++++++++++++++++++++++++ 3 files changed, 49 insertions(+), 2 deletions(-) diff --git a/src/cfdb/services/hubmap.py b/src/cfdb/services/hubmap.py index 9907a64..8c23b99 100644 --- a/src/cfdb/services/hubmap.py +++ b/src/cfdb/services/hubmap.py @@ -28,7 +28,8 @@ file_uuid -> local_id (HuBMAP issues no file accessions; accession_id stays null) rel_path (basename) -> filename -size -> size_in_bytes (stored as int64) +size -> size_in_bytes (stored as int64; + null when the index caps it) md5_checksum -> md5 sha256_checksum -> sha256 filename (compression suffix stripped) -> file_format (EDAM-mapped) @@ -268,6 +269,13 @@ def derive_file_format(filename: str) -> Optional[dict]: return get_file_format(base.rsplit(".", 1)[-1]) +#: The ``size`` the files index reports for a file it could not size in 32 +#: bits. 263 public files carry exactly this value, and a sampled one (a +#: ``.qptiff``) is really 3,287,888,901 bytes, so it is a clamp rather than +#: a size. Stored as one, it would make ``/data`` refuse every Range request +#: past 2 GiB of a larger file. +_INDEX_SIZE_CEILING = 2**31 - 1 + #: Per-request timeout for one search page, in seconds. _PAGE_TIMEOUT_SECONDS = 60 @@ -865,11 +873,15 @@ def transform_file_to_cfdb( if stats is not None: # Counted so the "real size and checksums on every file" promise is # observable per sync rather than assumed. - if size_in_bytes is None: + if size_in_bytes == _INDEX_SIZE_CEILING: + stats["capped:size"] += 1 + elif size_in_bytes is None: stats["missing:size"] += 1 for field in ("md5_checksum", "sha256_checksum"): if not src.get(field): stats[f"missing:{field.removesuffix('_checksum')}"] += 1 + if size_in_bytes == _INDEX_SIZE_CEILING: + size_in_bytes = None if organ_map is None: organ_map = HUBMAP_ORGAN_TO_UBERON diff --git a/src/cfdb/services/sync.py b/src/cfdb/services/sync.py index 011a84a..a4173f4 100644 --- a/src/cfdb/services/sync.py +++ b/src/cfdb/services/sync.py @@ -1259,6 +1259,12 @@ def transform(src: dict) -> Optional[dict]: if key.startswith("extension:") }, ) + capped = stats.get("capped:size", 0) + if capped: + logger.warning( + f"HuBMAP ingest: {capped} files carry the index's 32-bit size " + f"ceiling ({2**31 - 1}) rather than a size; stored as null" + ) skipped = stats.get("skipped:incomplete", 0) if skipped: logger.warning( diff --git a/tests/test_hubmap.py b/tests/test_hubmap.py index 931674d..31658ea 100644 --- a/tests/test_hubmap.py +++ b/tests/test_hubmap.py @@ -800,6 +800,35 @@ def test_transform_file_to_cfdb_should_count_missing_size_and_checksums(): assert stats["missing:sha256"] == 0 +def test_transform_file_to_cfdb_should_null_a_size_at_the_index_ceiling(): + """Test the index's 32-bit size clamp is not stored as a size. + + The files index reports 2,147,483,647 for files it could not size in + 32 bits; one sampled .qptiff carrying it is really 3.3 GB. Stored, the + value would make /data refuse Range requests past 2 GiB. + + Given: + A document whose size is exactly 2**31 - 1, with a stats counter. + When: + transform_file_to_cfdb runs. + Then: + size_in_bytes should be None, counted as capped rather than as + missing. + """ + from collections import Counter + + # Arrange + stats: Counter[str] = Counter() + + # Act + doc = _transform(_file_doc(size=2**31 - 1), stats=stats) + + # Assert + assert doc["size_in_bytes"] is None + assert stats["capped:size"] == 1 + assert stats["missing:size"] == 0 + + def test_transform_file_to_cfdb_should_name_anatomy_from_the_uberon_table(): """Test the default organ table supplies UBERON ids and UBERON labels. From 719a97273f7c1d125663efab0c4bcc03141f7d81 Mon Sep 17 00:00:00 2001 From: Conrad Date: Mon, 23 Nov 2026 11:36:33 -0500 Subject: [PATCH 32/37] fix: Walk HuBMAP Support entities alongside Datasets 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. --- src/cfdb/services/hubmap.py | 16 +++++++++++++++- tests/test_hubmap.py | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/src/cfdb/services/hubmap.py b/src/cfdb/services/hubmap.py index 8c23b99..f25ec6b 100644 --- a/src/cfdb/services/hubmap.py +++ b/src/cfdb/services/hubmap.py @@ -448,6 +448,11 @@ async def _search_page( ] +#: The portal-index entity types a files-index ``dataset_uuid`` can name; +#: see :func:`fetch_dataset_metadata_bulk`. +_DATASET_ENTITY_TYPES = ("Dataset", "Support") + + async def fetch_dataset_metadata_bulk( *, deadline: float | None = None ) -> dict[str, dict]: @@ -459,6 +464,13 @@ async def fetch_dataset_metadata_bulk( transformation can join on the ``dataset_uuid`` every files-index document carries. + "Dataset" here covers both entity types a file's ``dataset_uuid`` can + name: ``Dataset`` and ``Support``. HuBMAP files its image pyramids -- + the viewer-ready OME-TIFFs, ~1.6k entities -- as ``Support`` entities + with the same processing, pipeline and donor fields, so walking only + ``Dataset`` would leave every pyramid's files unjoined, and the + processed-only rule would then drop exactly the images worth loading. + Each page is retried on transient failure (see ``_search_page``); a failure that outlasts the retries raises rather than returning the partial map, since a silently partial map would mean silently @@ -489,7 +501,9 @@ async def fetch_dataset_metadata_bulk( async with aiohttp.ClientSession() as session: while True: query: dict = { - "query": {"term": {"entity_type.keyword": "Dataset"}}, + "query": { + "terms": {"entity_type.keyword": list(_DATASET_ENTITY_TYPES)} + }, "size": page_size, "_source": _DATASET_SOURCE_FIELDS, "sort": [{"_id": "asc"}], diff --git a/tests/test_hubmap.py b/tests/test_hubmap.py index 31658ea..fdedc1f 100644 --- a/tests/test_hubmap.py +++ b/tests/test_hubmap.py @@ -1487,6 +1487,38 @@ async def test_fetch_dataset_metadata_bulk_should_key_results_by_uuid( assert entry["genome_assembly"] == "GRCh38" +@pytest.mark.asyncio +async def test_fetch_dataset_metadata_bulk_should_walk_datasets_and_supports( + mocker +): + """Test the dataset walk requests Support entities alongside Datasets. + + HuBMAP files its image pyramids as Support entities; a walk over + Dataset alone leaves their files unjoined, and the processed-only rule + then drops them. + + Given: + A search session answering with no hits. + When: + fetch_dataset_metadata_bulk issues its first request. + Then: + The query should match entity_type Dataset or Support. + """ + # Arrange + session = _SearchSession() + mocker.patch.object( + hubmap_module.aiohttp, "ClientSession", return_value=session + ) + + # Act + await fetch_dataset_metadata_bulk() + + # Assert + assert session.post_bodies[0]["query"] == { + "terms": {"entity_type.keyword": ["Dataset", "Support"]} + } + + @pytest.mark.asyncio async def test_fetch_dataset_metadata_bulk_should_raise_when_the_walk_ends_short( mocker, From 6ba0b6c87754216d59e91d16c5bcfebf9919860e Mon Sep 17 00:00:00 2001 From: Conrad Date: Mon, 23 Nov 2026 11:36:45 -0500 Subject: [PATCH 33/37] feat: Map microscopy image formats to EDAM terms 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. --- README.md | 2 +- src/cfdb/services/hubmap.py | 11 +++++++++-- src/cfdb/services/ontology_mappings.py | 19 +++++++++++++++++++ tests/test_hubmap.py | 6 ++++++ 4 files changed, 35 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index ec77a5d..ce2d450 100644 --- a/README.md +++ b/README.md @@ -579,7 +579,7 @@ Anatomy, FileFormat, DataType, and AssayType share an identical schema: `id` (st | AssayType | OBI (Ontology for Biomedical Investigations) | | NcbiTaxonomy | NCBI Taxonomy Database | -Every `id` above resolves in its source ontology except the minted `FileFormat` tokens. EDAM has no term for a few formats cfdb ingests — `bedpe`, `bigInteract`, `arrow` and `parquet` at present — and aliasing them onto the nearest EDAM term would make each indistinguishable from the format it was aliased to, so a `cfdb:` token is minted instead. A client resolving `file_format.id` against EDAM should skip ids carrying that prefix rather than treat them as resolvable. +Every `id` above resolves in its source ontology except the minted `FileFormat` tokens. EDAM has no term for a few formats cfdb ingests — `bedpe`, `bigInteract`, `arrow`, `parquet`, and the vendor microscopy formats `qptiff`, `svs`, `ndpi`, `scn`, `czi`, `vsi` and `ets` at present — and aliasing them onto the nearest EDAM term would make each indistinguishable from the format it was aliased to, so a `cfdb:` token is minted instead. A client resolving `file_format.id` against EDAM should skip ids carrying that prefix rather than treat them as resolvable. #### Subject diff --git a/src/cfdb/services/hubmap.py b/src/cfdb/services/hubmap.py index f25ec6b..99e11c8 100644 --- a/src/cfdb/services/hubmap.py +++ b/src/cfdb/services/hubmap.py @@ -257,7 +257,9 @@ def derive_file_format(filename: str) -> Optional[dict]: for a ``.fastq.gz`` is the compression wrapper rather than the format — so the derivation strips one known compression suffix from the filename first, then maps whatever extension remains through the shared - EDAM table. ``None`` when no extension remains or none maps. + EDAM table -- its last two segments first, so ``.ome.tif`` resolves to + OME-TIFF rather than to plain TIFF. ``None`` when no extension remains + or none maps. """ base = filename.lower().rsplit("/", 1)[-1] for suffix in _STRIPPABLE_COMPRESSION_SUFFIXES: @@ -266,7 +268,12 @@ def derive_file_format(filename: str) -> Optional[dict]: break if "." not in base: return None - return get_file_format(base.rsplit(".", 1)[-1]) + segments = base.split(".") + if len(segments) > 2: + compound = get_file_format(".".join(segments[-2:])) + if compound: + return compound + return get_file_format(segments[-1]) #: The ``size`` the files index reports for a file it could not size in 32 diff --git a/src/cfdb/services/ontology_mappings.py b/src/cfdb/services/ontology_mappings.py index 7daa317..32197a7 100644 --- a/src/cfdb/services/ontology_mappings.py +++ b/src/cfdb/services/ontology_mappings.py @@ -59,6 +59,13 @@ "pdf": {"id": "format:3508", "name": "PDF"}, "png": {"id": "format:3603", "name": "PNG"}, "jpg": {"id": "format:3579", "name": "JPG"}, + "jpeg": {"id": "format:3579", "name": "JPG"}, + # Microscopy images. "ome.tif" is a compound key: OME-TIFF is a TIFF + # carrying OME-XML metadata, and EDAM names it separately (format:3727). + "tif": {"id": "format:3591", "name": "TIFF"}, + "tiff": {"id": "format:3591", "name": "TIFF"}, + "ome.tif": {"id": "format:3727", "name": "OME-TIFF"}, + "ome.tiff": {"id": "format:3727", "name": "OME-TIFF"}, "hic": {"id": "format:3590", "name": "HDF5"}, # .hic files are HDF5-based "pairs": {"id": "format:2330", "name": "Plain text"}, # 4DN pairs format "cool": {"id": "format:3590", "name": "HDF5"}, # cooler format is HDF5-based @@ -96,6 +103,18 @@ # are minted — same reasoning as "bedpe" above. "arrow": {"id": f"{MINTED_FORMAT_PREFIX}arrow", "name": "Arrow"}, "parquet": {"id": f"{MINTED_FORMAT_PREFIX}parquet", "name": "Parquet"}, + # Vendor whole-slide and microscope formats. EDAM has a term for none of + # them (OLS4 returns nothing for CZI, SVS, NDPI, SCN, VSI, ETS or + # QPTIFF). Several are TIFF containers underneath, but a client choosing + # a reader needs the vendor layout, so they are minted rather than + # aliased onto TIFF. + "qptiff": {"id": f"{MINTED_FORMAT_PREFIX}qptiff", "name": "QPTIFF"}, + "svs": {"id": f"{MINTED_FORMAT_PREFIX}svs", "name": "Aperio SVS"}, + "ndpi": {"id": f"{MINTED_FORMAT_PREFIX}ndpi", "name": "Hamamatsu NDPI"}, + "scn": {"id": f"{MINTED_FORMAT_PREFIX}scn", "name": "Leica SCN"}, + "czi": {"id": f"{MINTED_FORMAT_PREFIX}czi", "name": "Zeiss CZI"}, + "vsi": {"id": f"{MINTED_FORMAT_PREFIX}vsi", "name": "Olympus VSI"}, + "ets": {"id": f"{MINTED_FORMAT_PREFIX}ets", "name": "Olympus ETS"}, } # ENCODE output_type to EDAM data CV terms diff --git a/tests/test_hubmap.py b/tests/test_hubmap.py index fdedc1f..30c8c89 100644 --- a/tests/test_hubmap.py +++ b/tests/test_hubmap.py @@ -353,6 +353,12 @@ def test_extract_genome_assembly_should_normalize_to_canonical_names( ("reads.fastq.gz", "FASTQ"), ("matrix.mtx", "MTX"), ("expr.csv", "CSV"), + ("region_008.ome.tif", "OME-TIFF"), + ("Thymus.OME.TIFF", "OME-TIFF"), + ("mask.tif", "TIFF"), + ("scan.qptiff", "QPTIFF"), + ("slide.svs", "Aperio SVS"), + ("thumbnail.png", "PNG"), ], ) def test_derive_file_format_should_map_the_inner_extension( From 1a0786628fd82b6c30225ead8b438ffe9b824b51 Mon Sep 17 00:00:00 2001 From: Conrad Date: Mon, 23 Nov 2026 11:36:57 -0500 Subject: [PATCH 34/37] feat: Match compound filename suffixes in the HuBMAP allowlist 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. --- src/cfdb/services/hubmap.py | 50 ++++++++++++++++++++++++++---- tests/test_hubmap.py | 62 +++++++++++++++++++++++++++++++++++-- 2 files changed, 103 insertions(+), 9 deletions(-) diff --git a/src/cfdb/services/hubmap.py b/src/cfdb/services/hubmap.py index 99e11c8..6aa2e3a 100644 --- a/src/cfdb/services/hubmap.py +++ b/src/cfdb/services/hubmap.py @@ -162,13 +162,17 @@ def file_extensions_from_env() -> tuple[str, ...]: - """Resolve the file-extension allowlist to ingest. + """Resolve the filename-suffix allowlist to ingest. Reads a comma-separated ``HUBMAP_FILE_EXTENSIONS``, stripping each entry, lower-casing it, prefixing a missing leading dot, and dropping blanks — so ``h5ad, .MTX`` and ``.h5ad,.mtx`` configure the same thing, and what is sent to the search API matches the index's dot-prefixed - ``file_extension`` values exactly. An unset variable yields the default + ``file_extension`` values exactly. An entry with more than one dot, such + as ``.ome.tif``, is a compound suffix: it matches files whose + ``file_extension`` is its last segment and whose path ends with the + whole suffix (see :func:`_suffix_filter`). An unset variable yields the + default allowlist; a variable set to an empty (or all-blank) value yields an empty tuple, on which the sync skips HuBMAP and leaves the existing slice in place — the same outcome an empty ``ENCODE_ANNOTATION_TYPES`` @@ -645,6 +649,40 @@ def build_donor_lookup(dataset_metadata: dict[str, dict]) -> dict[str, dict]: ] +def _suffix_filter(suffixes: tuple[str, ...]) -> dict: + """Build the search-API clause that admits files ending in ``suffixes``. + + A single-segment suffix is matched on ``file_extension``, which the + index keeps as the outermost dot-suffix. A compound one (``.ome.tif``) + cannot be, since the index records only its last segment, so it is + matched as that extension plus a case-insensitive ``rel_path`` suffix. + The ``file_extension`` term keeps the wildcard from scanning the whole + index. + """ + simple = [suffix for suffix in suffixes if suffix.count(".") == 1] + clauses: list[dict] = [] + if simple: + clauses.append({"terms": {"file_extension.keyword": simple}}) + for suffix in suffixes: + if suffix.count(".") == 1: + continue + # ``*``, ``?`` and ``\`` are wildcard syntax; a suffix is literal. + literal = re.sub(r"([*?\\])", r"\\\1", suffix) + extension = "." + suffix.rsplit(".", 1)[-1] + wildcard = {"value": "*" + literal, "case_insensitive": True} + clauses.append( + { + "bool": { + "filter": [ + {"term": {"file_extension.keyword": extension}}, + {"wildcard": {"rel_path.keyword": wildcard}}, + ] + } + } + ) + return {"bool": {"should": clauses, "minimum_should_match": 1}} + + async def fetch_file_metadata( extensions: tuple[str, ...], *, @@ -655,8 +693,8 @@ async def fetch_file_metadata( Uses ``search_after`` pagination on ``file_uuid.keyword`` in batches of 1000. When ``extensions`` is non-empty, the allowlist is applied - server-side as a ``terms`` filter on ``file_extension.keyword``, so the - excluded 9.7M microscopy tiles never cross the wire. The query also + server-side (see :func:`_suffix_filter`), so the excluded 9.7M + microscopy tiles never cross the wire. The query also filters on ``data_access_level: public``: the index holds only public files today, which is what retired the C2M2 path's pruning pass, and the filter makes that an invariant of the load rather than an @@ -674,7 +712,7 @@ async def fetch_file_metadata( atomic. Args: - extensions: Dot-prefixed, lower-case extension allowlist. + extensions: Dot-prefixed, lower-case filename-suffix allowlist. deadline: Event-loop clock reading by which the whole stream must finish; each page's timeout is clamped to what remains. None leaves only the per-page timeout. @@ -700,7 +738,7 @@ async def fetch_file_metadata( "query": { "bool": { "filter": [ - {"terms": {"file_extension.keyword": list(extensions)}}, + _suffix_filter(extensions), {"term": {"data_access_level.keyword": "public"}}, ] } diff --git a/tests/test_hubmap.py b/tests/test_hubmap.py index 30c8c89..d873a4f 100644 --- a/tests/test_hubmap.py +++ b/tests/test_hubmap.py @@ -1088,8 +1088,8 @@ async def test_fetch_file_metadata_should_filter_extensions_server_side( When: fetch_file_metadata issues its first request. Then: - The body should carry a terms filter on file_extension.keyword - with exactly those values. + The body should require a match on a terms filter over + file_extension.keyword with exactly those values. """ # Arrange session = _SearchSession() @@ -1102,7 +1102,63 @@ async def test_fetch_file_metadata_should_filter_extensions_server_side( # Assert filters = session.post_bodies[0]["query"]["bool"]["filter"] - assert {"terms": {"file_extension.keyword": [".h5ad", ".mtx"]}} in filters + assert { + "bool": { + "should": [{"terms": {"file_extension.keyword": [".h5ad", ".mtx"]}}], + "minimum_should_match": 1, + } + } in filters + + +@pytest.mark.asyncio +async def test_fetch_file_metadata_should_match_a_compound_suffix_on_the_path( + mocker +): + """Test a compound suffix filters on its extension and the path. + + The index records only a file's last suffix, so .ome.tif images and + 9.7M plain .tif acquisition tiles share file_extension ".tif"; only + the path tells them apart. + + Given: + An allowlist of one plain extension and the compound .ome.tif. + When: + fetch_file_metadata issues its first request. + Then: + The body should admit .h5ad by extension, and .ome.tif only as + extension ".tif" with a case-insensitive rel_path suffix. + """ + # Arrange + session = _SearchSession() + mocker.patch.object( + hubmap_module.aiohttp, "ClientSession", return_value=session + ) + + # Act + [doc async for doc in fetch_file_metadata((".h5ad", ".ome.tif"))] + + # Assert + filters = session.post_bodies[0]["query"]["bool"]["filter"] + suffix_clause = filters[0]["bool"] + assert suffix_clause["minimum_should_match"] == 1 + assert suffix_clause["should"] == [ + {"terms": {"file_extension.keyword": [".h5ad"]}}, + { + "bool": { + "filter": [ + {"term": {"file_extension.keyword": ".tif"}}, + { + "wildcard": { + "rel_path.keyword": { + "value": "*.ome.tif", + "case_insensitive": True, + } + } + }, + ] + } + }, + ] @pytest.mark.asyncio From 4adf9fc63a4c8a5196e4c93f88f870e052dc15f2 Mon Sep 17 00:00:00 2001 From: Conrad Date: Mon, 23 Nov 2026 11:37:08 -0500 Subject: [PATCH 35/37] feat: Ingest HuBMAP image formats by default 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. --- src/cfdb/services/hubmap.py | 24 +++++++++++++++++++----- tests/test_hubmap.py | 27 +++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 5 deletions(-) diff --git a/src/cfdb/services/hubmap.py b/src/cfdb/services/hubmap.py index 6aa2e3a..ee68929 100644 --- a/src/cfdb/services/hubmap.py +++ b/src/cfdb/services/hubmap.py @@ -130,13 +130,14 @@ ASSETS_BASE_URL = "https://assets.hubmapconsortium.org" PORTAL_DATASET_URL = "https://portal.hubmapconsortium.org/browse/dataset/{uuid}" -#: Environment variable overriding which file extensions are ingested, and +#: Environment variable overriding which filename suffixes are ingested, and #: the allowlist applied when it is unset. An allowlist rather than a filter #: retrofitted later: the files index holds 9.9M documents and 98% of them -#: are ``.tif`` microscopy tiles the API cannot serve meaningfully, so -#: ingesting the extension space wholesale would grow the corpus ~11x with -#: dead weight. The default is the genomics, tabular, and imaging-derived -#: table tail of the live distribution, ~52k files. +#: are ``.tif`` microscopy tiles, so ingesting the extension space wholesale +#: would grow the corpus ~150x. The default covers the genomics, tabular and +#: image formats, with ``.tif`` admitted only as ``.ome.tif``: the index +#: names every TIFF ``.tif``, OME-TIFF images and 9.7M acquisition tiles +#: alike, so the compound suffix is what tells them apart. _FILE_EXTENSIONS_ENV = "HUBMAP_FILE_EXTENSIONS" _FILE_EXTENSIONS_DEFAULT: tuple[str, ...] = ( ".h5ad", @@ -158,6 +159,19 @@ ".snap", ".csv", ".tsv", + # Images. OME-TIFF and the slide-scanner formats are what a viewer reads; + # .png and .jpg are mostly rendered previews and QC figures. + ".ome.tif", + ".tiff", + ".qptiff", + ".svs", + ".ndpi", + ".scn", + ".czi", + ".vsi", + ".ets", + ".png", + ".jpg", ) diff --git a/tests/test_hubmap.py b/tests/test_hubmap.py index d873a4f..85a3610 100644 --- a/tests/test_hubmap.py +++ b/tests/test_hubmap.py @@ -203,6 +203,33 @@ def test_file_extensions_from_env_should_exclude_bcf_by_default(monkeypatch): assert ".bcf" not in allowlist +def test_file_extensions_from_env_should_admit_tif_only_as_ome_tif_by_default( + monkeypatch +): + """Test the default takes OME-TIFF images but not plain .tif tiles. + + 9.7M of the index's 9.9M files are .tif acquisition tiles; admitting + the bare extension would grow the corpus ~150x. + + Given: + No HUBMAP_FILE_EXTENSIONS in the environment. + When: + file_extensions_from_env resolves the allowlist. + Then: + It should include .ome.tif and the slide-scanner formats, and not + .tif. + """ + # Arrange + monkeypatch.delenv(EXTENSIONS_ENV, raising=False) + + # Act + allowlist = file_extensions_from_env() + + # Assert + assert ".tif" not in allowlist + assert {".ome.tif", ".qptiff", ".svs", ".czi"} <= set(allowlist) + + def test_file_extensions_from_env_should_normalize_case_and_missing_dots( monkeypatch ): From a647c832a4cd75bef521f5a70247434b92985c45 Mon Sep 17 00:00:00 2001 From: Conrad Date: Mon, 23 Nov 2026 11:37:20 -0500 Subject: [PATCH 36/37] feat: Load only files from processed HuBMAP datasets 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. --- src/cfdb/services/hubmap.py | 46 ++++++++++------ src/cfdb/services/sync.py | 23 +++++--- tests/test_dump.py | 2 +- tests/test_hubmap.py | 102 +++++++++++++++++++++++++++--------- tests/test_sync.py | 64 +++++++++++++++++++--- 5 files changed, 181 insertions(+), 56 deletions(-) diff --git a/src/cfdb/services/hubmap.py b/src/cfdb/services/hubmap.py index ee68929..2610135 100644 --- a/src/cfdb/services/hubmap.py +++ b/src/cfdb/services/hubmap.py @@ -3,11 +3,13 @@ Builds CFDB file documents directly from HuBMAP's file-grain search index, following the precedent ENCODE set in :mod:`cfdb.services.encode`. One index document is one file; every document in the index is public, so no pruning -pass exists. Dataset-level context the files index does not carry — donor -demographics, pipeline, genome assembly — is prefetched once from the -dataset-level index into an in-memory map keyed by ``dataset_uuid`` and -joined during transformation, so documents land fully populated in a single -insert pass with no post-load enrichment. +pass exists. Only files from datasets the dataset index marks ``processed`` +are loaded: raw acquisitions are left to the portal. Dataset-level context +the files index does not carry — donor demographics, pipeline, genome +assembly — is prefetched once from the dataset-level index into an +in-memory map keyed by ``dataset_uuid`` and joined during transformation, +so documents land fully populated in a single insert pass with no +post-load enrichment. API URLs -------- @@ -137,7 +139,8 @@ #: would grow the corpus ~150x. The default covers the genomics, tabular and #: image formats, with ``.tif`` admitted only as ``.ome.tif``: the index #: names every TIFF ``.tif``, OME-TIFF images and 9.7M acquisition tiles -#: alike, so the compound suffix is what tells them apart. +#: alike, so the compound suffix is what tells them apart. Everything here is +#: further restricted to processed datasets (see ``transform_file_to_cfdb``). _FILE_EXTENSIONS_ENV = "HUBMAP_FILE_EXTENSIONS" _FILE_EXTENSIONS_DEFAULT: tuple[str, ...] = ( ".h5ad", @@ -301,6 +304,9 @@ def derive_file_format(filename: str) -> Optional[dict]: #: past 2 GiB of a larger file. _INDEX_SIZE_CEILING = 2**31 - 1 +#: The dataset-index ``processing`` value of the datasets whose files load. +_PROCESSED = "processed" + #: Per-request timeout for one search page, in seconds. _PAGE_TIMEOUT_SECONDS = 60 @@ -904,9 +910,9 @@ def transform_file_to_cfdb( src: The ``_source`` dict of a files-index document, as yielded by :func:`fetch_file_metadata`. dataset_metadata: Dataset-level context keyed by dataset uuid, from - :func:`fetch_dataset_metadata_bulk`. A missing dataset degrades - the document (no demographics, pipeline, or assembly) rather - than dropping it. + :func:`fetch_dataset_metadata_bulk`. Only files whose dataset it + marks ``processed`` are loaded; a file whose dataset it lacks is + skipped too, since nothing then says the dataset is processed. donor_lookup: Donor demographics keyed by donor uuid, built from ``dataset_metadata`` by the caller. organ_map: Organ-code → UBERON term mapping; defaults to the @@ -920,7 +926,8 @@ def transform_file_to_cfdb( Returns: CFDB-compatible dict for insertion into the files collection, or None for a document missing the fields that make it addressable - (``file_uuid``, ``rel_path``, ``dataset_uuid``). + (``file_uuid``, ``rel_path``, ``dataset_uuid``) or belonging to a + dataset that is not processed. """ config = get_dcc_config("hubmap") id_namespace = config["id_namespace"] @@ -937,6 +944,19 @@ def transform_file_to_cfdb( ) return None + # Raw acquisitions are left to the portal: a processed dataset is where + # the viewable images and analysis outputs live. Checked before any + # other counter, so the integrity tallies describe only loaded files. + dataset_meta = dataset_metadata.get(dataset_uuid) + if dataset_meta is None: + if stats is not None: + stats["skipped:unjoined_dataset"] += 1 + return None + if dataset_meta.get("processing") != _PROCESSED: + if stats is not None: + stats["skipped:unprocessed_dataset"] += 1 + return None + filename = rel_path.rsplit("/", 1)[-1] try: @@ -959,12 +979,6 @@ def transform_file_to_cfdb( if organ_map is None: organ_map = HUBMAP_ORGAN_TO_UBERON - dataset_meta = dataset_metadata.get(dataset_uuid) - if dataset_meta is None: - if stats is not None: - stats["unjoined_dataset"] += 1 - dataset_meta = {} - doc: dict = { "submission": "hubmap", "id_namespace": id_namespace, diff --git a/src/cfdb/services/sync.py b/src/cfdb/services/sync.py index a4173f4..85b05cf 100644 --- a/src/cfdb/services/sync.py +++ b/src/cfdb/services/sync.py @@ -1259,6 +1259,18 @@ def transform(src: dict) -> Optional[dict]: if key.startswith("extension:") }, ) + unprocessed = stats.get("skipped:unprocessed_dataset", 0) + if unprocessed: + logger.info( + f"HuBMAP ingest: skipped {unprocessed} files from datasets that " + "are not processed" + ) + unjoined_dataset = stats.get("skipped:unjoined_dataset", 0) + if unjoined_dataset: + logger.warning( + f"HuBMAP ingest: skipped {unjoined_dataset} files whose dataset is " + "absent from the dataset index, so cannot be confirmed processed" + ) capped = stats.get("capped:size", 0) if capped: logger.warning( @@ -1297,14 +1309,11 @@ def transform(src: dict) -> Optional[dict]: f"HuBMAP ingest: files missing upstream integrity fields {missing}; " "those fields were stored as null" ) - unjoined = { - key: stats[key] for key in ("unjoined_dataset", "unjoined_donor") if stats[key] - } - if unjoined: + unjoined_donor = stats.get("unjoined_donor", 0) + if unjoined_donor: logger.warning( - f"HuBMAP ingest: join misses {unjoined} (file occurrences whose " - "dataset or donor is absent from the dataset index); those " - "documents carry no dataset context or demographics" + f"HuBMAP ingest: {unjoined_donor} donor occurrences are absent from " + "the dataset index; those subjects carry no demographics" ) diff --git a/tests/test_dump.py b/tests/test_dump.py index 2af7f26..590dea9 100644 --- a/tests/test_dump.py +++ b/tests/test_dump.py @@ -1317,7 +1317,7 @@ def test_dump_files_should_load_a_document_built_by_the_hubmap_transform(): } doc = transform_file_to_cfdb( src, - dataset_metadata={"ds1": {"pipeline": "Salmon"}}, + dataset_metadata={"ds1": {"pipeline": "Salmon", "processing": "processed"}}, donor_lookup={"donor-1": {"sex": ["Female"]}}, organ_map={"TH": {"id": "UBERON:0002370", "name": "thymus"}}, ) diff --git a/tests/test_hubmap.py b/tests/test_hubmap.py index 85a3610..63dc672 100644 --- a/tests/test_hubmap.py +++ b/tests/test_hubmap.py @@ -55,10 +55,16 @@ def _file_doc(**overrides) -> dict: return doc +#: The dataset map a test passes when it needs the file to load but cares +#: about none of the dataset's context: the transform loads only files from +#: processed datasets. +_PROCESSED_DATASETS = {"ds-uuid-1": {"processing": "processed"}} + + def _transform(src: dict, **overrides) -> dict | None: - """Run the transform with empty join inputs unless a test supplies them.""" + """Run the transform against one processed dataset and no other join data.""" kwargs = { - "dataset_metadata": {}, + "dataset_metadata": _PROCESSED_DATASETS, "donor_lookup": {}, "organ_map": {}, } @@ -510,6 +516,7 @@ def test_transform_file_to_cfdb_should_produce_a_valid_model(): dataset_metadata = { "ds-uuid-1": { "pipeline": "Salmon", + "processing": "processed", "genome_assembly": "GRCh38", "donor_uuid": "donor-1", "donor_metadata": {"sex": ["Female"]}, @@ -575,7 +582,10 @@ def test_transform_file_to_cfdb_should_build_an_access_url_that_round_trips( be exactly the dataset uuid followed by the rel_path. """ # Act - doc = _transform(_file_doc(dataset_uuid=dataset_uuid, rel_path=rel_path)) + doc = _transform( + _file_doc(dataset_uuid=dataset_uuid, rel_path=rel_path), + dataset_metadata={dataset_uuid: {"processing": "processed"}}, + ) # Assert parsed = urlparse(doc["access_url"]) @@ -654,21 +664,20 @@ def test_transform_file_to_cfdb_should_join_dataset_and_donor_metadata(): ] -def test_transform_file_to_cfdb_should_degrade_when_dataset_unknown(): - """Test a file whose dataset is missing from the map still loads. +def test_transform_file_to_cfdb_should_load_a_processed_dataset_without_context(): + """Test a processed dataset with no other context still loads its files. - The dataset map is prefetched from a different index, so a dataset - the files index knows and the dataset index does not must degrade - the document rather than drop it. + The dataset index omits pipeline, assembly and donors for some + datasets; that degrades the document rather than dropping it. Given: - Empty join inputs. + A dataset map that says only that the file's dataset is processed. When: transform_file_to_cfdb runs. Then: The document should carry the file fields, no genome_assembly, - a subject without demographics, and a collection without the - dataset-index extras. + a subject without demographics, and a collection whose extras are + the processing state and the file's dataset status. """ # Act doc = _transform(_file_doc()) @@ -676,10 +685,53 @@ def test_transform_file_to_cfdb_should_degrade_when_dataset_unknown(): # Assert assert "genome_assembly" not in doc collection = doc["collections"][0] - assert collection["extra"]["hubmap"] == {"dataset_status": "Published"} + assert collection["extra"]["hubmap"] == { + "processing": "processed", + "dataset_status": "Published", + } assert "extra" not in collection["subjects"][0] +@pytest.mark.parametrize( + ("dataset_metadata", "reason"), + [ + ({"ds-uuid-1": {"processing": "raw"}}, "skipped:unprocessed_dataset"), + ({"ds-uuid-1": {"pipeline": "Salmon"}}, "skipped:unprocessed_dataset"), + ({}, "skipped:unjoined_dataset"), + ], + ids=["raw", "processing-absent", "dataset-unknown"], +) +def test_transform_file_to_cfdb_should_skip_a_file_not_from_a_processed_dataset( + dataset_metadata, reason +): + """Test only files from datasets marked processed are loaded. + + Raw acquisitions stay with the portal. A dataset the dataset index + lacks cannot be confirmed processed, so its files are skipped too, and + under a separate reason so a broken join stays visible. + + Given: + A file whose dataset is raw, carries no processing state, or is + absent from the dataset map, with a stats counter. + When: + transform_file_to_cfdb runs. + Then: + It should return None and count the file under the matching skip + reason, before any integrity or extension tally. + """ + from collections import Counter + + # Arrange + stats: Counter[str] = Counter() + + # Act + doc = _transform(_file_doc(), dataset_metadata=dataset_metadata, stats=stats) + + # Assert + assert doc is None + assert stats == Counter({reason: 1}) + + def test_transform_file_to_cfdb_should_map_organs_through_the_organ_map( ): """Test anatomy terms come from the organ map, never fabricated. @@ -707,7 +759,7 @@ def test_transform_file_to_cfdb_should_map_organs_through_the_organ_map( # Act doc = transform_file_to_cfdb( _file_doc(organs=organs), - dataset_metadata={}, + dataset_metadata=_PROCESSED_DATASETS, donor_lookup={}, organ_map={"TH": {"id": "UBERON:0002370", "name": "Thymus"}}, stats=stats, @@ -744,7 +796,7 @@ def test_transform_file_to_cfdb_should_return_none_when_unaddressable( # Act doc = transform_file_to_cfdb( _file_doc(**{missing: None}), - dataset_metadata={}, + dataset_metadata=_PROCESSED_DATASETS, donor_lookup={}, organ_map={}, stats=stats, @@ -790,7 +842,7 @@ def test_transform_file_to_cfdb_should_count_extensions_into_stats(): # Act transform_file_to_cfdb( _file_doc(), - dataset_metadata={}, + dataset_metadata=_PROCESSED_DATASETS, donor_lookup={}, organ_map={}, stats=stats, @@ -824,7 +876,7 @@ def test_transform_file_to_cfdb_should_count_missing_size_and_checksums(): # Act for src in (incomplete, _file_doc(file_uuid="b")): transform_file_to_cfdb( - src, dataset_metadata={}, donor_lookup={}, stats=stats + src, dataset_metadata=_PROCESSED_DATASETS, donor_lookup={}, stats=stats ) # Assert @@ -886,7 +938,7 @@ def test_transform_file_to_cfdb_should_name_anatomy_from_the_uberon_table(): # Act doc = transform_file_to_cfdb( - _file_doc(organs=organs), dataset_metadata={}, donor_lookup={} + _file_doc(organs=organs), dataset_metadata=_PROCESSED_DATASETS, donor_lookup={} ) # Assert @@ -896,20 +948,19 @@ def test_transform_file_to_cfdb_should_name_anatomy_from_the_uberon_table(): ] -def test_transform_file_to_cfdb_should_count_join_misses(): - """Test a dataset or donor absent from the join maps is counted. +def test_transform_file_to_cfdb_should_count_donor_join_misses(): + """Test a donor absent from the donor lookup is counted. A wholesale join failure would otherwise load every file without its - dataset context or demographics and look like success. + demographics and look like success. Given: - A document whose dataset is absent from the dataset map and whose - donor is absent from the donor lookup, with a stats counter. + A document from a processed dataset whose donor is absent from the + donor lookup, with a stats counter. When: transform_file_to_cfdb runs. Then: - It should still return the document and count one unjoined - dataset and one unjoined donor. + It should still return the document and count one unjoined donor. """ from collections import Counter @@ -918,12 +969,11 @@ def test_transform_file_to_cfdb_should_count_join_misses(): # Act doc = transform_file_to_cfdb( - _file_doc(), dataset_metadata={}, donor_lookup={}, stats=stats + _file_doc(), dataset_metadata=_PROCESSED_DATASETS, donor_lookup={}, stats=stats ) # Assert assert doc is not None - assert stats["unjoined_dataset"] == 1 assert stats["unjoined_donor"] == 1 diff --git a/tests/test_sync.py b/tests/test_sync.py index 46efa9e..0124690 100644 --- a/tests/test_sync.py +++ b/tests/test_sync.py @@ -468,14 +468,15 @@ def _hubmap_file_doc(**overrides) -> dict: def _patch_hubmap_fetches(mocker, file_docs, dataset_metadata=None): """Point the two network boundaries of sync_hubmap at fixed data. - The dataset map defaults to one entry for the fixture's dataset: an - empty map is refused by the sync, so a test wanting that has to say so. + The dataset map defaults to one processed entry for the fixture's + dataset: an empty map is refused by the sync, and only processed + datasets' files load, so a test wanting either has to say so. """ mocker.patch.object( hubmap_module, "fetch_dataset_metadata_bulk", mocker.AsyncMock( - return_value={"ds-uuid-1": {}} + return_value={"ds-uuid-1": {"processing": "processed"}} if dataset_metadata is None else dataset_metadata ), @@ -571,6 +572,54 @@ async def test_sync_hubmap_should_insert_fully_populated_documents( assert dcc_doc["dcc_abbreviation"] == "HuBMAP" +@pytest.mark.asyncio +async def test_sync_hubmap_should_load_only_files_from_processed_datasets( + mock_db, mocker, caplog +): + """Test the sync stores processed datasets' files and reports the rest. + + Raw acquisitions are left to the portal; the skip is policy rather + than an upstream fault, while a dataset missing from the dataset index + is a join failure and is warned about. + + Given: + Three files: one from a processed dataset, one from a raw dataset, + and one whose dataset the dataset index lacks. + When: + sync_hubmap runs. + Then: + Only the processed dataset's file should be stored, and the log + should count one skipped raw file and warn about one unconfirmable + file. + """ + # Arrange + dataset_metadata = { + "ds-uuid-1": {"processing": "processed"}, + "ds-raw": {"processing": "raw"}, + } + files = [ + _hubmap_file_doc(file_uuid="kept"), + _hubmap_file_doc(file_uuid="raw", dataset_uuid="ds-raw"), + _hubmap_file_doc(file_uuid="orphan", dataset_uuid="ds-missing"), + ] + _patch_hubmap_fetches( + mocker, _async_iter(files), dataset_metadata=dataset_metadata + ) + + # Act + with caplog.at_level(logging.INFO, logger="cfdb.services.sync"): + await sync_hubmap(SyncTask(id="t1", dcc_names=["hubmap"])) + + # Assert + loaded = [d["local_id"] for d in mock_db.files.docs if d["submission"] == "hubmap"] + assert loaded == ["kept"] + assert "skipped 1 files from datasets that are not processed" in caplog.text + assert any( + r.levelno == logging.WARNING and "cannot be confirmed processed" in r.message + for r in caplog.records + ) + + @pytest.mark.asyncio async def test_sync_hubmap_should_replace_only_the_hubmap_slice( mock_db, mocker @@ -742,7 +791,7 @@ async def lock_active() -> bool: async def fetch_datasets(**kwargs): observed.append(await lock_active()) - return {"ds-uuid-1": {}} + return {"ds-uuid-1": {"processing": "processed"}} async def stream_files(): # The control: the stream runs under the lock, so a fake that @@ -922,8 +971,11 @@ async def test_sync_hubmap_should_skip_a_document_that_fails_model_validation( """ # Arrange dataset_metadata = { - "ds-bad": {"donors": {"donor-2": {"race": ["White", "Asian"]}}}, - "ds-uuid-1": {}, + "ds-bad": { + "processing": "processed", + "donors": {"donor-2": {"race": ["White", "Asian"]}}, + }, + "ds-uuid-1": {"processing": "processed"}, } bad = _hubmap_file_doc( file_uuid="bad", From 0ab9b84fe5ad7be599cae25f3aefb414efe35143 Mon Sep 17 00:00:00 2001 From: Conrad Date: Mon, 23 Nov 2026 11:37:37 -0500 Subject: [PATCH 37/37] docs: Document the HuBMAP image scope and processed-only rule 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. --- HUBMAP-SUPPLEMENT.md | 31 +++++++++++++++++++------------ 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/HUBMAP-SUPPLEMENT.md b/HUBMAP-SUPPLEMENT.md index 23eb2fd..9b67ed3 100644 --- a/HUBMAP-SUPPLEMENT.md +++ b/HUBMAP-SUPPLEMENT.md @@ -1,15 +1,15 @@ # HuBMAP Files Search API Dataloader -Field mapping from HuBMAP's file-grain search index to the CFDB data model. HuBMAP is a `rest_api` DCC: `cfdb sync hubmap` builds documents directly from the live index — no C2M2 zip download, no TSV load, no Rust materializer run, and no post-load enrichment or pruning stages. The file query filters on `data_access_level: public` server-side, which is what retired the pruning pass the C2M2 path needed: the index holds only public files today, and the filter keeps that true of the load if the index ever admits others. +Field mapping from HuBMAP's file-grain search index to the CFDB data model. HuBMAP is a `rest_api` DCC: `cfdb sync hubmap` builds documents directly from the live index — no C2M2 zip download, no TSV load, no Rust materializer run, and no post-load enrichment or pruning stages. The file query filters on `data_access_level: public` server-side, which is what retired the pruning pass the C2M2 path needed: the index holds only public files today, and the filter keeps that true of the load if the index ever admits others. Only files from **processed** datasets are loaded; see [Processed datasets only](#processed-datasets-only). ## Source Endpoints | Endpoint | Role | Pagination | |----------|------|------------| | `POST https://search.api.hubmapconsortium.org/v3/files/search` | One Elasticsearch document per file; the primary stream | `search_after` on `file_uuid.keyword`, batches of 1000 | -| `POST https://search.api.hubmapconsortium.org/v3/portal/search` | One document per dataset; prefetched once into an in-memory map keyed by `uuid` | `search_after` on `_id`, batches of 1000 | +| `POST https://search.api.hubmapconsortium.org/v3/portal/search` | One document per dataset, walking entity types `Dataset` and `Support`; prefetched once into an in-memory map keyed by `uuid` | `search_after` on `_id`, batches of 1000 | -The files index is ~9.9M documents, 98% of them `.tif` microscopy tiles, so the loader applies a configurable extension allowlist **server-side** (a `terms` filter on `file_extension.keyword`) and the excluded files never cross the wire. +The files index is ~9.9M documents, 98% of them `.tif` microscopy tiles, so the loader applies a configurable filename-suffix allowlist **server-side** (a `terms` filter on `file_extension.keyword`, plus a `rel_path` suffix match for compound suffixes such as `.ome.tif`) and the excluded files never cross the wire. Organ codes need no request: they map through `HUBMAP_ORGAN_TO_UBERON` in `services/ontology_mappings.py`, a checked-in snapshot of the UBKG organs endpoint (`ontology.api.hubmapconsortium.org/organs?application_context=HUBMAP`, taken 2026-11-20) with UBERON labels from OLS4. See [Collection Mapping](#collection-mapping). @@ -17,7 +17,7 @@ Every search page is attempted up to three times, with backoff, on a transport e Two results are refused outright rather than loaded. A files walk that drains cleanly with no documents raises instead of clearing the slice: a mapping change on the index, or an allowlist that matches nothing, returns a well-formed empty page, and for a submission one stream owns an empty answer is a fault, never a result. And the first page of each walk — files and datasets alike — asks for an exact total (`track_total_hits`), so a walk that ends with fewer documents than the index reported raises. An empty dataset map is refused the same way, before the cutover lock, so the previous slice keeps being served, and so is a partial one. -One malformed document costs only itself. Each document is transformed and then validated against `FileMetadataModel` before it is stored; one that fails either step is skipped and counted, and the sync logs the count. Validation matters here because the API builds the model for every document on a page, so one stored document of the wrong shape — an upstream field that changed type, such as a donor reporting two races where one string is expected — would fail every page holding it. Files the index lists with no `size`, `md5_checksum` or `sha256_checksum` are stored with that field null and counted per field, so the sync log shows the shortfall (4 of 51,816 allowlisted files had no size when the loader was written). +One malformed document costs only itself. Each document is transformed and then validated against `FileMetadataModel` before it is stored; one that fails either step is skipped and counted, and the sync logs the count. Validation matters here because the API builds the model for every document on a page, so one stored document of the wrong shape — an upstream field that changed type, such as a donor reporting two races where one string is expected — would fail every page holding it. Files the index lists with no `size`, `md5_checksum` or `sha256_checksum` are stored with that field null and counted per field, so the sync log shows the shortfall (4 of 51,816 allowlisted files had no size when the loader was written; none survives the processed-only rule). A `size` of exactly 2,147,483,647 is stored as null too, and counted separately: it is the index's 32-bit ceiling rather than a size — 263 public files carry it, and a sampled `.qptiff` among them is really 3,287,888,901 bytes — and stored as a size it would make `/data` refuse every Range request past 2 GiB. ## Entity Construction @@ -30,18 +30,25 @@ There is no entity matching. The C2M2 path had to join its TSVs to the Search AP | Subject | The file's `donors[]`: `local_id` is the donor uuid | | Anatomy | The file's `organs[]`, with UBERON terms from the checked-in organ table | -Dataset-level context the files index does not carry — donor demographics, pipeline, assay metadata, genome assembly — is prefetched from the dataset index (~10k documents) into memory and joined by `dataset_uuid` during transformation, so documents land fully populated in a single insert pass. A dataset missing from that map degrades its files (no demographics, pipeline, or assembly) rather than dropping them. +Dataset-level context the files index does not carry — donor demographics, pipeline, assay metadata, genome assembly — is prefetched from the dataset index (~11.8k documents) into memory and joined by `dataset_uuid` during transformation, so documents land fully populated in a single insert pass. The walk covers two entity types, because a file's `dataset_uuid` can name either: `Dataset`, and `Support`, which is how HuBMAP files its image pyramids (1,585 entities, every one processed). A Support entity carries the same pipeline, processing and donor fields as a Dataset. A dataset whose context is sparse still loads its files, without the missing fields. + +## Processed datasets only + +A file is loaded only when its dataset's `processing` is `processed`. Raw datasets hold acquisitions — instrument tiles, slide scans, per-channel stacks — that the portal serves and analysis starts from, while processed ones hold the pipeline outputs and the viewer-ready image pyramids. The dataset index is the only source of that state (the files index carries no processing field), so the rule runs in the transform, after the allowlist has been applied server-side. Two kinds of file are skipped and counted separately in the sync log: those from a dataset that is not processed (54,781 of the 117,438 allowlisted files on 2026-11-23, logged at info, since it is policy), and those whose dataset is absent from the dataset map, which cannot be confirmed processed (11, logged as a warning, since a large count means a broken join). The previous slice is the reference point: 15,054 of its 51,816 files came from raw datasets, including all 2,723 `.nii.gz` NIfTI masks, whose assets URLs answer 404. The `id_namespace` is `https://hubmapconsortium.org` (configured in `dcc_registry.py`), mirroring the ENCODE convention of using the portal URL rather than the C2M2 tag-URI. Every sync clears and rebuilds the HuBMAP slice, so the namespace change has no continuity cost. ## Extension Allowlist -`HUBMAP_FILE_EXTENSIONS` — comma-separated, case-insensitive, leading dot optional (`h5ad, .MTX` and `.h5ad,.mtx` configure the same thing). Unset applies the default below. Set-but-empty skips the HuBMAP sync entirely with a warning and leaves the existing HuBMAP slice in place, the same outcome an empty `ENCODE_ANNOTATION_TYPES` has for ENCODE's annotation phases; draining an empty stream instead would read as an authoritative empty result and delete the slice. +`HUBMAP_FILE_EXTENSIONS` — comma-separated filename suffixes, case-insensitive, leading dot optional (`h5ad, .MTX` and `.h5ad,.mtx` configure the same thing). A suffix with more than one dot is compound: the index records only a file's last suffix, so `.ome.tif` matches files whose `file_extension` is `.tif` and whose `rel_path` ends in `.ome.tif`, ignoring case. Unset applies the default below. Set-but-empty skips the HuBMAP sync entirely with a warning and leaves the existing HuBMAP slice in place, the same outcome an empty `ENCODE_ANNOTATION_TYPES` has for ENCODE's annotation phases; draining an empty stream instead would read as an authoritative empty result and delete the slice. -Default: `.h5ad`, `.h5mu`, `.h5`, `.hdf5`, `.gz`, `.mtx`, `.arrow`, `.parquet`, `.bed`, `.narrowpeak`, `.bam`, `.sf`, `.snap`, `.csv`, `.tsv` — 51,816 files as of 2026-11-20, against the 9.7M `.tif` tiles the default excludes. It is not purely genomics, because an outer extension cannot say what a file holds: +Default: `.h5ad`, `.h5mu`, `.h5`, `.hdf5`, `.gz`, `.mtx`, `.arrow`, `.parquet`, `.bed`, `.narrowpeak`, `.bam`, `.sf`, `.snap`, `.csv`, `.tsv`, and the image formats `.ome.tif`, `.tiff`, `.qptiff`, `.svs`, `.ndpi`, `.scn`, `.czi`, `.vsi`, `.ets`, `.png`, `.jpg`. On 2026-11-23 that matched 117,438 public files, of which the processed-only rule kept 62,646, against the 9.7M `.tif` files the default excludes. It is not purely genomics, because an outer extension cannot say what a file holds: -- `.csv` (32,396) and `.tsv` (8,809) are mostly imaging-derived tables — roughly 27k of the `.csv` files come from Cell DIVE, CODEX, and MIBI segmentation pipelines. -- `.gz` (5,872) is mostly not genomics either: 2,723 are Cell DIVE `.nii.gz` NIfTI masks and 2,524 are salmon `aux_info/fld.gz`, which map to no `file_format`; about 500 are compressed MTX, BED, or CSV. +- `.tif` is admitted only as `.ome.tif`. The index names every TIFF `.tif`, so OME-TIFF images (7,529 loaded, 4,670 of them pyramids from Support entities) and 9.7M acquisition tiles share an extension, and only the compound suffix separates them. `.tiff` needs no such guard: its 3,126 processed files are all `.ome.tiff`. +- The slide-scanner formats (`.qptiff`, `.svs`, `.ndpi`, `.scn`, `.czi`, `.vsi`, `.ets`) are in the allowlist but load nothing today: every one sits in a raw dataset. They are listed so a processed scan is taken when one appears. +- `.png` (15,236 loaded) is mostly rendered previews and QC figures from the segmentation pipelines rather than primary images. +- `.csv` (28,567 loaded) is mostly imaging-derived tables from the Cell DIVE, CODEX and MIBI segmentation pipelines. +- `.gz` is mostly not genomics either: 2,524 of the 3,089 loaded are salmon `aux_info/fld.gz`, which map to no `file_format`; the rest are compressed MTX, BED or CSV. - `.bcf` is deliberately **not** in the default. Every `.bcf` in the index (1,851) is a CODEX raw-acquisition sidecar (`raw/Cyc1_reg1/1.bcf`), not binary VCF. `bcf` maps to no format either, so an operator who opts them in gets files with no `file_format` rather than ones labelled as variant calls. ## File Mapping @@ -50,11 +57,11 @@ Default: `.h5ad`, `.h5mu`, `.h5`, `.hdf5`, `.gz`, `.mtx`, `.arrow`, `.parquet`, |------------|--------|-------| | `local_id` | `file_uuid` | HuBMAP issues no file accessions; `accession_id` is explicitly null ([#102](https://github.com/abdenlab/cfdb/issues/102)) | | `filename` | `rel_path` basename | Full path kept on `extra.hubmap.rel_path` | -| `size_in_bytes` | `size` | Stored as a BSON integer (int32 or int64 by magnitude), never a string — the C2M2 TSV path stored it as a string, which left size filters inert | +| `size_in_bytes` | `size` | Stored as a BSON integer (int32 or int64 by magnitude), never a string — the C2M2 TSV path stored it as a string, which left size filters inert. Null when the index reports its 32-bit ceiling, 2,147,483,647, in place of a size | | `md5` / `sha256` | `md5_checksum` / `sha256_checksum` | Real per-file checksums; the C2M2 TSVs lacked or mistyped both | -| `file_format` | filename, compression suffix stripped | EDAM-mapped from the inner extension, so `x.fastq.gz` maps to FASTQ rather than nothing | +| `file_format` | filename, compression suffix stripped | EDAM-mapped from the inner extension, so `x.fastq.gz` maps to FASTQ rather than nothing. The last two segments are tried first, so `x.ome.tif` maps to OME-TIFF (`format:3727`) rather than TIFF. The vendor slide formats have no EDAM term and carry minted `cfdb:` tokens | | `compression_format` | filename suffix | Same derivation and absent-when-undetermined contract as ENCODE | -| `access_url` | `https://assets.hubmapconsortium.org/{dataset_uuid}/{rel_path}` | Path segments percent-encoded. `/data` streams it directly, without DRS resolution. Sampled URLs resolve without authentication, but not every one does: at least one Published CODEX dataset (`HBM366.XKPX.554`) answers 403, some root-level `*-metadata.tsv` files 404, and samples have drawn transient 5xx. `/data` returns those as their own status (403, 404, 502), checked before any byte is sent. The assets host also throttles bursts and can block a client by IP, after which every file answers 403 — so a 403 may mean the client is blocked, not that the file is restricted — and it answers 403 to curl's default user agent, so check reachability by hand with another agent | +| `access_url` | `https://assets.hubmapconsortium.org/{dataset_uuid}/{rel_path}` | Path segments percent-encoded. `/data` streams it directly, without DRS resolution. Sampled URLs resolve without authentication, but not every one does: at least one Published CODEX dataset (`HBM366.XKPX.554`) answers 403, some root-level `*-metadata.tsv` files 404, and samples have drawn transient 5xx. `/data` returns those as their own status (403, 404, 502), checked before any byte is sent. The assets host answers 403 to curl's default user agent and serves the same file to any other, so check reachability by hand with `-A` set; a 403 seen from curl says nothing about the file. Every Cell DIVE `.nii.gz` sampled answered 404, which is one reason the loader takes processed datasets only | | `status` | `dataset_status` | e.g. `"Published"` | | `data_access_level` | `data_access_level` | `"public"` on every document in this index | | `genome_assembly` | dataset `ingest_metadata.workflow_description` | Regex-extracted and canonicalized; mirrored on `extra.hubmap.genome_assembly`. See below. |