Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
37 commits
Select commit Hold shift + click to select a range
88db029
feat: Map BCF, MTX, salmon sf, HDF5 variants, Arrow and Parquet
conradbzura Nov 20, 2026
8c25e2e
feat: Add dataset_status to the HuBMAP collection enrichment
conradbzura Nov 20, 2026
8bd0b57
refactor: Generalize the ENCODE row ingest for any REST API DCC
conradbzura Nov 20, 2026
ffef63f
feat: Build HuBMAP documents from the files search API
conradbzura Nov 20, 2026
c17d8f7
feat: Carry HuBMAP dataset_status in the DuckDB dump
conradbzura Nov 20, 2026
8e44fb4
docs: Document the HuBMAP files search API dataloader
conradbzura Nov 20, 2026
b72c948
test: Cover HuBMAP donor dedupe, flag parsing, and fetch edges
conradbzura Nov 20, 2026
338e4c5
test: Cover the HuBMAP dataset_status column in the DuckDB dump
conradbzura Nov 20, 2026
1350665
test: Flatten HuBMAP tests to module-level functions
conradbzura Nov 20, 2026
663520d
fix: Stream direct HTTPS access URLs without DRS resolution
conradbzura Nov 20, 2026
e4b5078
fix: Harden the HuBMAP fetchers against what the live index serves
conradbzura Nov 20, 2026
2ae3a12
fix: Bound the HuBMAP sync's cutover window and keep the slice on empty
conradbzura Nov 20, 2026
324e546
test: Dump a document built by the HuBMAP transform
conradbzura Nov 20, 2026
025b0a1
docs: Correct HuBMAP docs and comments against the live index
conradbzura Nov 20, 2026
70f421e
fix: Map upstream errors to their status before streaming a file
conradbzura Nov 20, 2026
51d9198
refactor: Move the shared ingest helpers out of the ENCODE module
conradbzura Nov 20, 2026
f578c59
feat: Add a HuBMAP organ-code to UBERON table
conradbzura Nov 20, 2026
8b921ac
test: Record the private-loader exception to the test guide
conradbzura Nov 20, 2026
876b45a
fix: Harden the HuBMAP sync against empty, short and late loads
conradbzura Nov 20, 2026
11ecff3
docs: Document the HuBMAP loader's refusals, organ table and limits
conradbzura Nov 20, 2026
9591e6b
refactor: Make the HuBMAP loader public and flatten its tests
conradbzura Nov 20, 2026
7ec8abf
test: Zero the HuBMAP pacing constants instead of stubbing asyncio.sleep
conradbzura Nov 20, 2026
8251c44
fix: Heartbeat the sync lock at each DCC boundary
conradbzura Nov 20, 2026
308e9c9
fix: Refuse a HuBMAP stream that cannot finish before its deadline
conradbzura Nov 20, 2026
a2c7ea8
fix: Validate each HuBMAP document before storing it
conradbzura Nov 20, 2026
3835568
feat: Count HuBMAP files missing a size or checksum
conradbzura Nov 20, 2026
7c39072
fix: Refuse a HuBMAP dataset walk that ends short
conradbzura Nov 20, 2026
23bf932
fix: Correct the HuBMAP manubrium and prostate organ terms
conradbzura Nov 20, 2026
88b1a74
test: Cover upstream status mapping on the index sidecar path
conradbzura Nov 20, 2026
ab5edb4
docs: Document the HuBMAP deadline floor, heartbeat and rollback
conradbzura Nov 20, 2026
37a1258
fix: Store the HuBMAP index's 32-bit size ceiling as an unknown size
conradbzura Nov 23, 2026
719a972
fix: Walk HuBMAP Support entities alongside Datasets
conradbzura Nov 23, 2026
6ba0b6c
feat: Map microscopy image formats to EDAM terms
conradbzura Nov 23, 2026
1a07866
feat: Match compound filename suffixes in the HuBMAP allowlist
conradbzura Nov 23, 2026
4adf9fc
feat: Ingest HuBMAP image formats by default
conradbzura Nov 23, 2026
a647c83
feat: Load only files from processed HuBMAP datasets
conradbzura Nov 23, 2026
0ab9b84
docs: Document the HuBMAP image scope and processed-only rule
conradbzura Nov 23, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion ENCODE-SUPPLEMENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.

Expand Down
209 changes: 120 additions & 89 deletions HUBMAP-SUPPLEMENT.md

Large diffs are not rendered by default.

28 changes: 15 additions & 13 deletions README.md

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions schema.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -351,6 +351,7 @@ input EnrichedHubmapCollectionInput {
groupName: [String!] = null
analyteClass: [String!] = null
visualization: [Boolean!] = null
datasetStatus: [String!] = null
}

type EnrichedHubmapCollectionType {
Expand All @@ -360,6 +361,7 @@ type EnrichedHubmapCollectionType {
visualization: Boolean
vitessceHints: [String!]
metadata: JSON
datasetStatus: String
}

input EnrichedHubmapFileInput {
Expand Down
1 change: 1 addition & 0 deletions src/cfdb/api/gql/inputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
15 changes: 8 additions & 7 deletions src/cfdb/api/routers/_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down
76 changes: 71 additions & 5 deletions src/cfdb/api/routers/cache_stream.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand All @@ -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
Expand All @@ -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"}"',
Expand Down Expand Up @@ -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,
Expand Down
40 changes: 28 additions & 12 deletions src/cfdb/api/routers/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
DRSUpstreamError,
)
from cfdb.workflows.models import ArtifactKind
from cfdb.workflows.urlsafe import UnsafeOutboundURL, validate_outbound_url

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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
Expand All @@ -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.)
Expand All @@ -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,
Expand All @@ -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(
Expand Down
2 changes: 1 addition & 1 deletion src/cfdb/api/routers/index.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
)

Expand Down
5 changes: 2 additions & 3 deletions src/cfdb/dcc_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
11 changes: 6 additions & 5 deletions src/cfdb/dump/loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
9 changes: 7 additions & 2 deletions src/cfdb/dump/schema.sql
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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,
Expand Down
12 changes: 7 additions & 5 deletions src/cfdb/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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.
Expand Down
Loading
Loading