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 f311dd8..9b67ed3 100644 --- a/HUBMAP-SUPPLEMENT.md +++ b/HUBMAP-SUPPLEMENT.md @@ -1,84 +1,122 @@ -# 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 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). -## 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, walking entity types `Dataset` and `Support`; prefetched once into an in-memory map keyed by `uuid` | `search_after` on `_id`, batches of 1000 | -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 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. -## Collection Enrichment +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). -Stored on `collection.extra.hubmap` (`EnrichedHubmapCollection`). Runs pre-materialization. +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. -| 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) | +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. -### Assay-Specific Metadata Keys +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. -The `metadata` dict is stored verbatim. Common keys for sequencing assays: +## Entity Construction -| 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` | +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: -## Subject Enrichment +| 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 terms from the checked-in organ table | -Stored on `subject.extra.hubmap` (`EnrichedHubmapSubject`). Runs pre-materialization. +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. -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. +## Processed datasets only -| 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"` | +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. -## File Enrichment +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. -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`. +## Extension Allowlist -| 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}` | +`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. -### Genome Assembly Extraction +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: -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: +- `.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 + +| 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 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. 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 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. | +| `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` | + +## Collection Mapping + +One collection per file: its parent dataset. + +| 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 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. 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 + +| 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, 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`): + +| 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 +131,28 @@ 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 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 | -## Sync Hooks +## Data Flow -All enrichment uses a single bulk fetch from the Search API. No per-entity API calls. +```text +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 + └─ insert into files # single pass, deferred stale clear + ensure_indexes(files) # runs even when the stream fails +``` -| Hook | Phase | Function | -|------|-------|----------| -| Collection + Subject enrichment | Pre-materialization | `_enrich_hubmap_collections_and_subjects()` | -| File enrichment | Post-materialization | `_enrich_hubmap_files()` | +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). -### Data Flow +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. -```text -fetch_dataset_metadata_bulk() # Single bulk Elasticsearch query - │ # Returns dict keyed by doi_url - │ - ├─> _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) -``` +## Rolling back + +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 1405bfc..ce2d450 100644 --- a/README.md +++ b/README.md @@ -96,8 +96,8 @@ 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-dcc DCC=hubmap` | Materialize a single DCC | +| `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 | | `make mongodb-prod` | Start MongoDB with TLS/X.509 authentication | @@ -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: @@ -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 @@ -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`, `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 @@ -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 @@ -830,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 @@ -1178,7 +1180,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:** @@ -1260,7 +1262,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. @@ -1288,4 +1290,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/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/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/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 1759947..fd194b5 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: @@ -210,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", @@ -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.) @@ -345,7 +361,7 @@ async def _stream_encode_file( media_type = "text/plain" try: - return stream_upstream_url( + return await stream_upstream_url( download_url, file_size, filename, @@ -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/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/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/dump/loader.py b/src/cfdb/dump/loader.py index cf24528..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 @@ -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..8117adb 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) @@ -491,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 bb7d09d..85f39d7 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): @@ -505,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/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 e1aa78e..2610135 100644 --- a/src/cfdb/services/hubmap.py +++ b/src/cfdb/services/hubmap.py @@ -1,101 +1,233 @@ -"""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. 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 -------- -Bulk dataset search (search_after pagination): +File search (search_after pagination, one document per file): + https://search.api.hubmapconsortium.org/v3/files/search + +Dataset search (search_after pagination, one document per dataset): 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 +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 Search API → CFDB) ------------------------------------------- +Field Mapping (HuBMAP files search API -> CFDB) +----------------------------------------------- -File (post-materialization) -~~~~~~~~~~~~~~~~~~~~~~~~~~~ -data_access_level → data_access_level -ingest_metadata.workflow_description → genome_assembly (regex-derived) +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; + null when the index caps it) +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, static table) -> 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.ingest_common import ( + COMPRESSION_SUFFIX_TO_EDAM, + UNMAPPABLE_COMPRESSION_SUFFIXES, + derive_compression_format, + timeout_from_env, +) +from cfdb.services.ontology_mappings import ( + HUBMAP_ORGAN_TO_UBERON, + get_file_format, + get_taxonomy, +) 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 -# 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}" + +#: 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, 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. 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", + ".h5mu", + ".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. 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", + ".parquet", + ".bed", + ".narrowpeak", + ".bam", + ".sf", + ".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", +) + + +def file_extensions_from_env() -> tuple[str, ...]: + """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 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`` + 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 + 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)) -_GENOME_ASSEMBLY_RE = re.compile(r"\b(GRCh38|hg38|GRCh37|hg19|GRCm39|mm10)\b", re.IGNORECASE) + if not allowlist: + logger.warning( + "%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), + ) + + return allowlist + + +_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 +249,275 @@ def extract_genome_assembly(workflow_description: str) -> Optional[str]: return None -async def fetch_dataset_metadata_bulk() -> dict[str, dict]: +# 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 -- 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: + if base.endswith(suffix): + base = base[: -len(suffix)] + break + if "." not in base: + return None + 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 +#: 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 + +#: 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 + +#: 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 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 + + +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) -> 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 + 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. """ - Fetch all published HuBMAP dataset metadata from the Search API. + 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" + ) + 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 - 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``. + +async def _search_page( + session: aiohttp.ClientSession, + url: str, + query: dict, + label: str, + *, + deadline: float | None = None, +) -> 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; + 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 sync's " + f"deadline ({_SYNC_TIMEOUT_ENV}, clamped to the sync " + "lock's stale threshold)" + ) + 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. +_DATASET_SOURCE_FIELDS = [ + "uuid", + "pipeline", + "processing", + "group_name", + "visualization", + "vitessce-hints", + "metadata", + "donor.mapped_metadata", + "donor.uuid", + "donors.mapped_metadata", + "donors.uuid", + "ingest_metadata.workflow_description", +] + + +#: 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]: + """ + Fetch all HuBMAP dataset metadata from the dataset-level search index. + + 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. + + "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 + 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 + finish; each page's timeout is clamped to what remains. None + leaves only the per-page timeout. 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, + donors: {donor_uuid: mapped_metadata}, + genome_assembly}} """ config = get_dcc_config("hubmap") api_base = config["api_base"] @@ -138,69 +526,46 @@ async def fetch_dataset_metadata_bulk() -> dict[str, dict]: 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: query: dict = { "query": { - "bool": { - "must": [ - {"term": {"entity_type.keyword": "Dataset"}}, - {"exists": {"field": "doi_url"}}, - ] - } + "terms": {"entity_type.keyword": list(_DATASET_ENTITY_TYPES)} }, "size": page_size, - "_source": _BULK_SOURCE_FIELDS, + "_source": _DATASET_SOURCE_FIELDS, "sort": [{"_id": "asc"}], } if search_after is not None: query["search_after"] = search_after + else: + query["track_total_hits"] = True - 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: - logger.error( - f"HuBMAP Search API error: HTTP {response.status}" - ) - break - - data = await response.json() - - except aiohttp.ClientError as e: - logger.error(f"HuBMAP Search API network error: {e}") - break + 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) + await asyncio.sleep(REQUEST_INTERVAL_SECONDS) - hits = data.get("hits", {}).get("hits", []) if not hits: break 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,12 +579,11 @@ 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 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: @@ -227,6 +591,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 {} @@ -236,8 +609,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 +618,496 @@ 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") + 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 + + +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 = [ + "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", +] + + +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, ...], + *, + deadline: float | None = None, +) -> 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 (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 + assumption about a beta index. An empty allowlist yields nothing — the + explicit-empty configuration documented on + :func:`file_extensions_from_env`. + + 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``. 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 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. + + 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 + yielded = 0 + expected: Optional[int] = None + + async with aiohttp.ClientSession() as session: + while True: + query: dict = { + "query": { + "bool": { + "filter": [ + _suffix_filter(extensions), + {"term": {"data_access_level.keyword": "public"}}, + ] + } + }, + "size": page_size, + "_source": _FILE_SOURCE_FIELDS, + "sort": [{"file_uuid.keyword": "asc"}], + } + + 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, total = await _search_page( + session, search_url, query, "files", deadline=deadline + ) + if search_after is None: + expected = total + + await asyncio.sleep(REQUEST_INTERVAL_SECONDS) + + if not hits: + break + + for hit in hits: + yield hit.get("_source", {}) + yielded += 1 + + 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 + + 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" + ) + logger.info(f"HuBMAP file fetch: {yielded} total files fetched") + + +# 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] | None = None, + 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`. 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 + 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, 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 + None for a document missing the fields that make it addressable + (``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"] + + 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 + + # 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: + 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 == _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 + + 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 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 organ table --- + 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 + # 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 --- + 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/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/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/ontology_mappings.py b/src/cfdb/services/ontology_mappings.py index adebb0c..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 @@ -85,6 +92,29 @@ "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"}, + # 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 @@ -268,6 +298,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: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: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"}, + "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/src/cfdb/services/sync.py b/src/cfdb/services/sync.py index 0f506e2..85b05cf 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 @@ -148,11 +148,16 @@ 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 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 +294,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 +308,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,438 +630,24 @@ 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_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, + clear_on_empty: bool = True, ) -> 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 +657,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 +671,30 @@ 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. + 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 @@ -1112,7 +704,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 +717,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 +742,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 +766,22 @@ 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 -- 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 @@ -1209,12 +810,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 +948,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 @@ -1417,6 +1030,293 @@ async def _sync_encode(task: SyncTask) -> 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) + +#: 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. + + ``budget_seconds`` from now, or the moment the sync lock would turn + 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() + 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 + + +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) 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. + 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. 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. + """ + from cfdb.models import FileMetadataModel + from cfdb.services.hubmap import ( + build_donor_lookup, + build_hubmap_dcc_record, + fetch_dataset_metadata_bulk, + fetch_file_metadata, + 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, 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, 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(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]: + # 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 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: + 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: + logger.exception( + "Skipping malformed HuBMAP file document (file_uuid=%r)", + src.get("file_uuid") if isinstance(src, dict) else None, + ) + 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 + # 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, + ) + + # 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) + + 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 -- 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 + # 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" + 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:") + }, + ) + 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( + 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( + 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" + ) + malformed = stats.get("skipped:malformed", 0) + if malformed: + logger.warning( + 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_donor = stats.get("unjoined_donor", 0) + if unjoined_donor: + logger.warning( + f"HuBMAP ingest: {unjoined_donor} donor occurrences are absent from " + "the dataset index; those subjects carry no demographics" + ) + + 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/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: 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..ddde629 100644 --- a/tests/test_data.py +++ b/tests/test_data.py @@ -33,21 +33,47 @@ 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", } +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): @@ -59,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) @@ -68,27 +94,166 @@ 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, no + workflow subsystem, and an upstream serving two chunks. + When: + stream_file is called for it and the body is read. + Then: + 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.files.docs = [_make_file_doc()] + fetch_drs = mocker.patch.object(drs, "fetch_drs_object") + 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.status_code == 200 + assert body == b"abcd" + assert upstream.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 and the body is read. + 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.files.docs = [doc] + fetch_drs = mocker.patch.object(drs, "fetch_drs_object") + 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 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. - # Let it fail at DRS resolution (proves it passed the access check) + 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, "fetch_drs_object", side_effect=Exception("DRS unavailable") + 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) - # Should fail at DRS, not at access control - assert exc_info.value.status_code != 403 + # 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 + ): + """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 opening an upstream request. + """ + # 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.files.docs = [doc] + upstream = mocker.patch.object(drs, "stream_from_url") + + # 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 == 502 + upstream.assert_not_called() class TestStreamFileWorkflowPath: @@ -515,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: @@ -742,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: @@ -1091,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"): @@ -1122,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 ( @@ -1209,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( diff --git a/tests/test_dump.py b/tests/test_dump.py index 9daad2b..590dea9 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"} @@ -1256,6 +1257,94 @@ 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_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", "processing": "processed"}}, + 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. 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_hubmap.py b/tests/test_hubmap.py new file mode 100644 index 0000000..63dc672 --- /dev/null +++ b/tests/test_hubmap.py @@ -0,0 +1,1938 @@ +"""Tests for the HuBMAP files search API fetches and transform.""" + +from __future__ import annotations + +import asyncio +import os +from urllib.parse import unquote, urlparse + +import aiohttp +import pytest +from hypothesis import HealthCheck, given, settings +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_donor_lookup, + build_hubmap_dcc_record, + derive_file_format, + extract_genome_assembly, + fetch_dataset_metadata_bulk, + fetch_file_metadata, + 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 + + +#: 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 against one processed dataset and no other join data.""" + kwargs = { + "dataset_metadata": _PROCESSED_DATASETS, + "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): + if isinstance(self._payload, Exception): + raise self._payload + 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. + + ``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, 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] = [] + + 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._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: + payload = self._pages.pop(0) + else: + payload = {"hits": {"hits": []}} + return _FakeJsonResponse(self._status, 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 + ] + } + } + + +@pytest.fixture +def no_backoff(mocker): + """Make the fetchers' retry backoff and rate-limit pauses instant. + + 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. + """ + 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( + 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_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_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 +): + """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, .MTX ,Gz") + + # Act + allowlist = file_extensions_from_env() + + # Assert + assert allowlist == (".h5ad", ".mtx", ".gz") + + +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 == () + assert any(EXTENSIONS_ENV in record.message for record in caplog.records) + + +def test_file_extensions_from_env_should_collapse_repeats_keeping_order( + 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,mtx,.H5AD,.mtx") + + # Act + allowlist = file_extensions_from_env() + + # Assert + assert allowlist == (".h5ad", ".mtx") + + +@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, + ) +) +@settings( + max_examples=50, + suppress_health_check=[HealthCheck.function_scoped_fixture], +) +def test_file_extensions_from_env_should_emit_index_shaped_entries( + entries, mocker +): + """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. + """ + # Arrange + 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) + 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"), + ("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( + 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 + + +@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. + + 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(): + """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", + "processing": "processed", + "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(): + """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" + ) + + +@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), + dataset_metadata={dataset_uuid: {"processing": "processed"}}, + ) + + # 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. + + 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_load_a_processed_dataset_without_context(): + """Test a processed dataset with no other context still loads its files. + + The dataset index omits pipeline, assembly and donors for some + datasets; that degrades the document rather than dropping it. + + Given: + 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 whose extras are + the processing state and the file's dataset status. + """ + # Act + doc = _transform(_file_doc()) + + # Assert + assert "genome_assembly" not in doc + collection = doc["collections"][0] + 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. + + 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 organ map's 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 (Lobe)"}, + {"code": "TH", "label": "Thymus"}, + {"code": "ZZ", "label": "Mystery"}, + ] + stats: Counter[str] = Counter() + + # Act + doc = transform_file_to_cfdb( + _file_doc(organs=organs), + dataset_metadata=_PROCESSED_DATASETS, + 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( + 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=_PROCESSED_DATASETS, + 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(): + """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(): + """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=_PROCESSED_DATASETS, + donor_lookup={}, + organ_map={}, + stats=stats, + ) + + # Assert + 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=_PROCESSED_DATASETS, 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_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. + + 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=_PROCESSED_DATASETS, 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_donor_join_misses(): + """Test a donor absent from the donor lookup is counted. + + A wholesale join failure would otherwise load every file without its + demographics and look like success. + + Given: + 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 donor. + """ + from collections import Counter + + # Arrange + stats: Counter[str] = Counter() + + # Act + doc = transform_file_to_cfdb( + _file_doc(), dataset_metadata=_PROCESSED_DATASETS, donor_lookup={}, stats=stats + ) + + # Assert + assert doc is not None + assert stats["unjoined_donor"] == 1 + + +def test_transform_file_to_cfdb_should_dedupe_repeated_donors(): + """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(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)) + + # 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 + ) + + # 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( + 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 require a match on a terms filter over + 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", ".mtx"))] + + # Assert + filters = session.post_bodies[0]["query"]["bool"]["filter"] + 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 +async def test_fetch_file_metadata_should_yield_nothing_when_allowlist_empty( + 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(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 + early would silently shrink the corpus. + + Given: + A files search endpoint answering HTTP 503. + When: + fetch_file_metadata is drained. + Then: + It should retry the page, then raise rather than end the + stream. + """ + # Arrange + session = _SearchSession(status=503) + mocker.patch.object( + hubmap_module.aiohttp, "ClientSession", return_value=session + ) + + # 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( + 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(mocker, no_backoff): + """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 once the page's retries + are spent. + """ + # Arrange + session = _SearchSession(error=aiohttp.ClientError("reset")) + mocker.patch.object( + hubmap_module.aiohttp, "ClientSession", return_value=session + ) + + # 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( + 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 + + +@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_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, +): + """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 +): + """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_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, +): + """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. + + 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 retry the page, then 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 + 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( + 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, no_backoff): + """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 once the page's retries + are spent. + """ + # Arrange + session = _SearchSession(error=aiohttp.ClientError("reset")) + mocker.patch.object( + hubmap_module.aiohttp, "ClientSession", return_value=session + ) + + # 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( + 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_dataset_metadata_bulk_should_collect_every_listed_donor( + mocker, +): + """Test a pooled dataset's donors are all carried, not just the first. + + Given: + A dataset whose singular donor is one of the three it lists under + donors, each with demographics. + When: + fetch_dataset_metadata_bulk drains the index. + Then: + The entry's donors map should hold all three donors' demographics. + """ + # Arrange + 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 + results = await fetch_dataset_metadata_bulk() + + # Assert + assert results["ds-uuid-1"]["donors"] == { + "d1": {"sex": ["F"]}, + "d2": {"sex": ["M"]}, + "d3": {"sex": ["F"]}, + } + + +@pytest.mark.asyncio +async def test_fetch_dataset_metadata_bulk_should_raise_when_the_deadline_has_passed( + mocker, +): + """Test the dataset prefetch honors the sync's shared deadline. + + Given: + A deadline already behind the event-loop clock. + When: + fetch_dataset_metadata_bulk runs. + Then: + It should raise a timeout without issuing a request. + """ + # Arrange + 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 + with pytest.raises(asyncio.TimeoutError): + await fetch_dataset_metadata_bulk(deadline=deadline) + + # Assert + assert session.post_bodies == [] + + +def test_build_donor_lookup_should_merge_singular_and_plural_donors(): + """Test every donor any dataset names joins, the first naming winning. + + Given: + 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: + build_donor_lookup runs. + Then: + All three donors should be present, the repeated one keeping the + demographics of the first dataset that named it. + """ + # Arrange + dataset_metadata = { + "ds1": {"donors": {"d1": {"sex": ["F"]}}}, + "ds2": {"donor_uuid": "d2", "donor_metadata": {"sex": ["M"]}}, + "ds3": {"donors": {"d1": {"sex": ["M"]}}}, + } + + # Act + lookup = build_donor_lookup(dataset_metadata) + + # Assert + assert lookup == {"d1": {"sex": ["F"]}, "d2": {"sex": ["M"]}} + + +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" 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 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()) 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_ontology_mappings.py b/tests/test_ontology_mappings.py index 18abcc8..de57c87 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,83 @@ 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} + + +@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} diff --git a/tests/test_sync.py b/tests/test_sync.py index 3f1c4c8..0124690 100644 --- a/tests/test_sync.py +++ b/tests/test_sync.py @@ -1,9 +1,18 @@ -"""Tests for sync service pruning and enrichment changes.""" +"""Tests for the sync service: dispatch, per-DCC loaders, and enrichment. + +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 import asyncio import logging +from datetime import datetime, timedelta import pytest from hypothesis import HealthCheck, given, settings @@ -12,21 +21,22 @@ 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 locks 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, + start_sync, + 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 +225,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 +238,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 +266,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 +303,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 +339,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 +379,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 +389,773 @@ 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() + + +@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) # --------------------------------------------------------------------------- -# _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"}, - } +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 - 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) +def _patch_hubmap_fetches(mocker, file_docs, dataset_metadata=None): + """Point the two network boundaries of sync_hubmap at fixed data. - # 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" + 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": {"processing": "processed"}} + if dataset_metadata is None + else dataset_metadata + ), + ) + mocker.patch.object( + hubmap_module, + "fetch_file_metadata", + lambda extensions, **kwargs: 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" - @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"}, +@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, + ) - 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"}, + # 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_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 +): + """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")) + ) - await _prune_non_public_hubmap_raw_records(dataset_metadata) + # Act & assert + with pytest.raises(RuntimeError, match="files index down"): + await sync_hubmap(SyncTask(id="t1", dcc_names=["hubmap"])) - assert len(mock_db.file_in_collection.docs) == 1 - assert len(mock_db.file.docs) == 1 + assert mock_db.files.docs == [ + {"submission": "hubmap", "local_id": "previous-1"} + ] - @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 - """ - dataset_metadata = { - "https://doi.org/a": {"data_access_level": "consortium"}, - "https://doi.org/b": {"data_access_level": "protected"}, - } - 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"}, - ] +@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. - await _prune_non_public_hubmap_raw_records(dataset_metadata) + 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 len(mock_db.file_in_collection.docs) == 0 - assert len(mock_db.file.docs) == 0 + 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_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"])) + + # 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() + ) - 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"}, - ] + # Act + with pytest.raises(RuntimeError, match="files index reset"): + await sync_hubmap(SyncTask(id="t1", dcc_names=["hubmap"])) - await _prune_non_public_hubmap_raw_records(dataset_metadata) + # Assert + ensure_mock.assert_awaited_once() - # 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 +@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_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"}, - } + 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. - 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"}, - ] + 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": {"processing": "processed"}} + + 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), + ) - await _prune_non_public_hubmap_raw_records(dataset_metadata) + # Act + await sync_hubmap(SyncTask(id="t1", dcc_names=["hubmap"])) - assert len(mock_db.file_in_collection.docs) == 0 - assert len(mock_db.file.docs) == 0 + # Assert + assert observed == [False, True] - @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 - """ - 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"}, - ] +@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 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_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={} + ) - await _prune_non_public_hubmap_raw_records(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( + 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")]) + ) - assert len(mock_db.file.docs) == 0 + # 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"] -# --------------------------------------------------------------------------- -# _enrich_hubmap_collections_and_subjects -# --------------------------------------------------------------------------- +@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. -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 - """ - 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, - ) + 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. - # Need at least an empty collection cursor to iterate - mock_db.collection.docs = [] - mock_db.subject.docs = [] + 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": { + "processing": "processed", + "donors": {"donor-2": {"race": ["White", "Asian"]}}, + }, + "ds-uuid-1": {"processing": "processed"}, + } + 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, + ) - result = await _enrich_hubmap_collections_and_subjects() + # Act + await sync_hubmap(SyncTask(id="t1", dcc_names=["hubmap"])) - assert result is sample + # Assert + loaded = [d["local_id"] for d in mock_db.files.docs if d["submission"] == "hubmap"] + assert loaded == ["good"] -# --------------------------------------------------------------------------- -# _enrich_hubmap_files -# --------------------------------------------------------------------------- +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 + ) -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" - """ - 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 = [] +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. - await _enrich_hubmap_files({}) + 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 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 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 _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() + + # 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", _recording_stream(opened)) + loop = asyncio.get_running_loop() + + # Act + before = loop.time() + await sync_hubmap(SyncTask(id="t1", dcc_names=["hubmap"])) + + # Assert + 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 +): + """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() + ) - # 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 + assert mock_db.files.docs == [ + {"submission": "hubmap", "local_id": "previous-1"} + ] + fetch_datasets.assert_not_awaited() # --------------------------------------------------------------------------- @@ -1580,7 +2109,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")