Concepts API#

Fetching variable definitions from the CORR Concepts API.

A variable definition has two halves: a declarative json config (what vars.json holds locally) and an optional py transformation function (what mapping/variables.py holds locally). The Concepts API serves both, per concept and per source, together with the data files a definition needs and the version metadata describing exactly what was served.

The package is organised as:

  • routing — the packaged routing.toml, deciding per source whether definitions come from an endpoint or stay local.

  • spec — parsing [taxonomy/]var_name[::version].

  • client — the HTTP client and response types.

  • files — the content-addressed file cache.

  • compile — executing served py snippets.

  • resolver — the per-cohort façade over all of it.

Warning

Sources routed to an endpoint never fall back to the bundled vars.json. A cohort assembled from a stale local definition while recording a remote version number would misdescribe its own data, which is the problem the API exists to solve. Every failure is therefore fatal.

Warning

reprodicu is routed to the API but its definitions have not been imported there yet, so every reprodicu concept resolves to nothing until that import lands. This is a deliberate staging decision, not a bug.

Routing#

src/corr_vars/concepts/routing.toml ships with the package and decides, per source, where definitions come from. It is not user-scoped: there is no config file or environment variable that rewrites it.

Source

Definitions

charite_demo, reprodicu

The public demo Concepts API (https://demo-concepts.corr.icu/api)

local_datasource

Pinned local: the source’s bundled mapping module, no network, no key

any other source

The wildcard endpoint; point a cohort at your own with Cohort(concepts_api_url=...)

Selecting a version#

A cohort authenticates against its endpoint on construction, so a missing project or a bad key fails before the data load. Every variable records the exact version it was served in cohort.concept_versions.

from corr_vars import Cohort

cohort = Cohort(
    obs_level="icu_stay",
    sources={"charite_demo": {}},
    project="demo",
    api_key="cak_demo_0d2b53ac",
    date="2025-06-30",          # freeze every definition to a day
)
cohort.add_variable("blood_sodium::v3")   # pin one variable
cohort.add_variable("corr_v1/heart_rate") # explicit taxonomy

A reference has the form [taxonomy/]var_name[::version], where the version is latest, vN, YYYY-MM-DD or draftNNNN. The key comes from api_key=, else the CORR_CONCEPTS_API_KEY environment variable (corr login stores it for you, see The corr command line).

Reference#

corr_vars.concepts.routing.load_routing()[source]#

Load and validate the packaged routing configuration.

Returns:

The global routing table, identical for every user of the package.

Return type:

ConceptRouting

class corr_vars.concepts.routing.ConceptRouting(taxonomy, version, local_sources, endpoints)[source]#

Resolved contents of the packaged routing configuration.

A source resolves to the first matching rule: pinned-local first, then the ordered endpoint list, then local as the fallback for anything unmatched.

Warning

reprodicu matches the wildcard endpoint and therefore routes to the Concepts API — but its definitions have not been imported there yet. Together with the hard-fail policy (a routed source never falls back to the bundled vars.json) this means every reprodicu variable resolves to nothing until that import lands, and a reprodicu-only variable raises ConceptNotFoundError. This is a deliberate, approved staging decision — not a bug to debug.

Parameters:
  • taxonomy (str) – Default taxonomy for unqualified variable references.

  • version (str) – Default version selector for references without ::.

  • local_sources (tuple[str, ...]) – Sources pinned to their bundled mapping.

  • endpoints (tuple[Endpoint, ...]) – Endpoint rules in file order.

resolve(source)[source]#

Route a single source.

Parameters:

source (str) – Source name, e.g. "reprodicu".

Returns:

ApiRoute when an endpoint claims the source, LocalRoute when it is pinned or unmatched.

Return type:

Route

resolve_all(sources)[source]#

Route every source in sources.

Parameters:

sources (Iterable[str]) – Source names to route.

Returns:

Mapping from source name to its route.

Return type:

dict[str, Route]

with_overrides(*, taxonomy=None, version=None, api_url=None)[source]#

Return a copy with Cohort keyword arguments applied.

This is the only supported way to deviate from the packaged file.

Parameters:
  • taxonomy (str | None) – Replacement default taxonomy.

  • version (str | None) – Replacement default version selector.

  • api_url (str | None) – Replacement base URL for every endpoint, for pointing a cohort at a staging or on-premise deployment. Pinned-local sources are unaffected.

Returns:

A new routing object; the receiver is unchanged.

Return type:

ConceptRouting

corr_vars.concepts.spec.parse_variable_spec(reference, *, default_taxonomy, default_version=VersionSelector(kind='latest', value=None))[source]#

Parse a [taxonomy/]var_name[::version] reference.

Missing parts fall back to the cohort defaults, which themselves default to the values in the packaged routing configuration (corr_v1 / latest).

Parameters:
  • reference (str) – The reference to parse, e.g. "blood_sodium", "corr_v1/blood_sodium", or "blood_sodium::v3".

  • default_taxonomy (str) – Taxonomy used when the reference has no /.

  • default_version (VersionSelector) – Selector used when the reference has no :: suffix. Defaults to LATEST_SELECTOR.

Returns:

The reference with every part filled in.

Return type:

VariableSpec

Raises:

ValueError – If the reference is empty, carries more than one :: or /, has an empty taxonomy or name, or has an unparsable version.

corr_vars.concepts.spec.parse_version_selector(text)[source]#

Parse the part of a reference that follows ::.

Parameters:

text (str) – One of latest, vN, YYYY-MM-DD, or draftNNNN.

Returns:

The parsed selector.

Return type:

VersionSelector

Raises:

ValueError – If text is empty, uses an unknown form, carries a non-positive number, or looks like a date but is not a real one.

class corr_vars.concepts.client.ConceptsApiClient(base_url, *, project, api_key=None, timeout=None, max_retries=3, backoff=0.5, transport=None)[source]#

Thin HTTP client for the Concepts API.

One instance serves one endpoint for one project. Concept documents are memoised in-process under (endpoint, taxonomy, name, selector) because requires chains request the same concepts over and over — without the cache a single derived variable would re-fetch each dependency for every parent that declares it. One cache entry holds the whole list a name resolves to, so a grouped name costs a single request too.

Every failure is fatal: a source routed to an endpoint is never satisfied from the bundled vars.json, so callers get a ConceptsApiError rather than a cohort whose recorded version metadata does not describe its data.

Parameters:
  • base_url (str) – Endpoint base URL, e.g. "https://concepts.example.edu/api".

  • project (str) – Project name; the API requires it on every read.

  • api_key (str | None) – Bearer token. Falls back to the CORR_CONCEPTS_API_KEY environment variable, then to ~/.config/corr/.env (see corr_vars.concepts.credentials).

  • timeout (httpx.Timeout | float | None) – Per-request timeouts.

  • max_retries (int) – Attempts for transient failures (network errors and the retryable status codes in RETRY_STATUS_CODES).

  • backoff (float) – Base delay in seconds for exponential backoff.

  • transport (httpx.BaseTransport | None) – Injected transport, used by the test suite to serve responses without a live API.

Raises:

ConceptsApiConfigurationError – If project is empty or no API key is available.

property http: Client#

The lazily created underlying HTTP client.

Returns:

A client carrying the bearer token and base URL.

Return type:

httpx.Client

close()[source]#

Close the underlying HTTP client, if one was created.

Return type:

None

list_projects()[source]#

Fetch the projects this API key may read.

Returns:

One row per project, or None when the deployment does not serve the listing (404) or refuses it to this key (403). None means “cannot tell”, never “no projects”.

Return type:

list[dict[str, Any]] | None

Raises:
  • ConceptsApiError – If the key itself is rejected (401), or the endpoint cannot be reached at all.

  • ConceptsLicenseError – If the refusal names the CORR license.

verify_access()[source]#

Authenticate the key and check the project exists, before any read.

One request. It answers the two questions a misconfigured cohort would otherwise ask far too late: is the key accepted, and does this project exist for it. Both are checked up front because the endpoint answers a read for an unknown project with the same 404 it uses for an unknown concept — which the resolver treats as “this source does not define the variable” and turns into an empty cohort.

The result is remembered, so repeated calls across a cohort’s sources cost a single request.

Raises:
  • ConceptsApiError – If the key is rejected or the endpoint cannot be reached.

  • ProjectNotFoundError – If the endpoint has no project of this name.

  • ConceptsLicenseError – If the project exists but its CORR license approval is missing or outdated.

Return type:

None

get_concepts(taxonomy, name, version)[source]#

Fetch every concept a name resolves to, serving repeats from the cache.

A name normally resolves to exactly one concept. It resolves to several when the taxonomy files a group of them under one identifier, in which case every member is returned, ordered by concept id.

Parameters:
  • taxonomy (str) – Taxonomy to resolve in.

  • name (str) – Concept name.

  • version (VersionSelector) – Which version to request.

Returns:

The parsed documents, one per resolved concept.

Return type:

list[Concept]

Raises:
  • ConceptNotFoundError – If the name resolves to nothing.

  • AmbiguousConceptError – If version pins a version and the name resolves to several concepts.

  • ConceptsApiError – On any other API or transport failure, including a body that is not the documented list.

list_concept_names(taxonomy, *, source=None)[source]#

List the fully-qualified names of a taxonomy’s live concepts.

Deprecated rows are dropped: they are still served so that an existing pin keeps resolving, but nothing new should be written against them. Names are returned fully qualified ("<taxonomy>/<name>") because a bare name only addresses a concept once a taxonomy is known, and de-duplicated in order, since a taxonomy may file several concepts under one name.

The listing is memoised in-process under (endpoint, taxonomy, source), like the concept documents are.

Parameters:
  • taxonomy (str) – Taxonomy to list.

  • source (str | None) – When given, keep only concepts that carry a definition for this source key.

Returns:

The fully-qualified names, in the order the API served them.

Return type:

list[str]

Raises:
  • ConceptNotFoundError – If the taxonomy is unknown to the endpoint.

  • ConceptsLicenseError – If the project may not read concepts.

  • ConceptsApiError – On any other API or transport failure, including a body that is not the documented list.

search(query, *, taxonomy=None, status=(), source=(), types=(), page_size=50)[source]#

Search concepts like the concept browser does (GET /concepts/table).

Matches identifiers and display names (separator-insensitive, with a small typo budget), the description and the clinical, implementation and caveat documentation, ranked by relevance. Not the py or json definitions.

Parameters:
  • query (str) – Search term, e.g. "lactate".

  • taxonomy (str | None) – Taxonomy to search, default the API’s.

  • status (Sequence[str]) – Keep only these doc_status values.

  • source (Sequence[str]) – Keep only concepts configured for these sources.

  • types (Sequence[str]) – Keep only concepts of these config types.

  • page_size (int) – Rows to return (the API allows up to 200).

Returns:

The first page as served: rows (name, types, sources, doc_status, doc_clinical_excerpt, …), total and the statuses / sources / types facets.

Return type:

dict[str, Any]

Raises:

ConceptsApiError – On any API or transport failure, including a body that is not the documented page.

get_history(concept_id)[source]#

Fetch the version history of one concept.

Addressed by id rather than by name, since a name may point at several concepts and a history belongs to exactly one of them.

Parameters:

concept_id (str | int) – Upstream concept id.

Returns:

The history entries as returned by the API.

Return type:

list[dict[str, Any]]

Raises:
  • ConceptNotFoundError – If the concept does not exist.

  • ConceptsApiError – On any other API or transport failure.

fetch_file(taxonomy, name, version, file, concept_id=None)[source]#

Download one file of a source config’s manifest.

Downloads are addressed by file uuid, never by path: a file belongs to the source’s library and the config version pins one of its versions, so the path is a layout hint and nothing more.

The url on the file record is used verbatim when present. The API pins it to the version that was actually served — reconstructing the URL from taxonomy, name and version would be both redundant and wrong, since a date selector re-resolved later can point at other bytes. Only project is merged in, since the API requires it on every read. A record without a url is fetched from the id route when concept_id is known, since a name may point at several concepts.

Parameters:
  • taxonomy (str) – Taxonomy to resolve in.

  • name (str) – Concept name.

  • version (VersionSelector) – Version the file belongs to. Used only when the record carries no url.

  • file (ConceptFile) – The manifest entry from the concept document.

  • concept_id (str | int | None) – Id of the concept the file belongs to. Used only when the record carries no url.

Returns:

The raw file content.

Return type:

bytes

Raises:
  • ConceptNotFoundError – If the file does not exist.

  • ConceptsLicenseError – If the project may not read concepts.

  • ConceptsApiError – On any other API or transport failure, or if the record carries neither a url nor a uuid to build one from.

class corr_vars.concepts.client.Concept(id, taxonomy, name, version=None, requested=<factory>, sources=<factory>, pointer=None, deprecated_at=None, successor_id=None, doc_clinical=None, doc_implementation=None, doc_caveats=None, doc_status=None, notion_url=None)[source]#

One element of the list served by GET /concept/{taxonomy}/{name}.

Parameters:
  • id (str | int | None) – Upstream concept id, which is the concept’s identity — a name may resolve to several of them.

  • taxonomy (str) – Taxonomy the concept lives in.

  • name (str) – Concept name.

  • version (int | None) – Version number of the served document.

  • requested (dict[str, Any]) – Echo of the selector the API resolved.

  • sources (dict[str, SourceConcept]) – Per-source definitions.

  • pointer (ConceptPointer | None) – The taxonomy entry this element resolved through.

  • deprecated_at (str | None) – ISO timestamp the concept itself was deprecated, or None.

  • successor_id (str | int | None) – Concept that replaces a deprecated one, already resolved to the final successor.

  • doc_clinical (str | None) – Clinical documentation.

  • doc_implementation (str | None) – Implementation notes.

  • doc_caveats (str | None) – Known caveats.

  • doc_status (str | None) – Documentation status.

  • notion_url (str | None) – Link to the upstream Notion page.

property deprecated: bool#

Report whether the concept itself has been deprecated.

Returns:

True when the concept carries a deprecated_at.

Return type:

bool

classmethod from_payload(payload)[source]#

Build a concept from one element of a decoded API response body.

Parameters:

payload (Mapping[str, Any]) – The decoded JSON object.

Returns:

The parsed document.

Return type:

Concept

class corr_vars.concepts.resolver.ConceptResolver(*, project=None, api_key=None, taxonomy=None, version=None, date=None, api_url=None, routing=None, client_factory=None)[source]#

Routes per-source variable definitions to an endpoint or the local mapping.

One resolver belongs to one cohort. It owns the routing table, the cohort’s spec defaults, and one ConceptsApiClient per endpoint. The clients memoise concept documents, so a requires chain that walks the same dependency from several parents costs one request.

Warning

reprodicu routes to the Concepts API, but its definitions have not been imported there yet. Since a routed source never falls back to the bundled vars.json, every reprodicu concept resolves to nothing until that import lands. This is a deliberate staging decision.

Parameters:
  • project (str) – Project name, required by the API on every read.

  • api_key (str | None) – Bearer token; falls back to CORR_CONCEPTS_API_KEY.

  • taxonomy (str | None) – Overrides the packaged default taxonomy.

  • version (str | None) – Overrides the packaged default version selector.

  • date (str | datetime.date | None) – Global as-of date. Mutually exclusive with an explicit non-latest version.

  • api_url (str | None) – Overrides the endpoint URL from the routing file.

  • routing (ConceptRouting | None) – Injected routing table; loaded from the packaged routing.toml when None.

  • client_factory (Any) – Callable (url) -> ConceptsApiClient, injected by the test suite to avoid a live API.

Raises:

ValueError – If both version and date select a version.

route(source)[source]#

Route a single source.

Parameters:

source (str) – Source name.

Returns:

The resolved route.

Return type:

Route

is_remote(source)[source]#

Report whether source is served by a Concepts API endpoint.

Parameters:

source (str) – Source name.

Returns:

True for API-routed sources.

Return type:

bool

client_for(route)[source]#

Return the (cached) client for an endpoint.

Parameters:

route (ApiRoute) – The endpoint to talk to.

Returns:

A client bound to the endpoint and project.

Return type:

ConceptsApiClient

Raises:

ConceptsApiConfigurationError – If no project or API key is available.

verify_credentials(sources)[source]#

Check that every API-routed source in sources has usable credentials.

Building the client validates the project name and resolves the API key — including the CORR_CONCEPTS_API_KEY fallback — without issuing a request. Calling this while the cohort is being created turns a misconfiguration into an immediate, actionable error instead of one that surfaces on the first variable: after the (slow) initial data load, and after load_default_vars has swallowed the same error once per variable.

Only the presence of the credentials is checked. Whether the endpoint accepts them is not, since that would need a request per cohort.

Parameters:

sources (Iterable[str]) – Source names configured on the cohort. Sources routed local are ignored, so a cohort built only from those needs neither a project nor a key.

Raises:

ConceptsApiConfigurationError – If a source served by an endpoint has no project name, or no API key is available.

Return type:

None

authenticate(sources)[source]#

Verify credentials, then prove them against every endpoint in use.

Runs verify_credentials() first, so a missing project or key is reported without a request, and then asks each endpoint that actually serves one of sources to confirm the key is accepted and the project exists. One request per endpoint, and only for endpoints in use — a cohort built solely from locally routed sources still touches no network.

Parameters:

sources (Iterable[str]) – Source names configured on the cohort.

Raises:
  • ConceptsApiConfigurationError – If a source served by an endpoint has no project name, or no API key is available.

  • ProjectNotFoundError – If an endpoint has no project of this name.

  • ConceptsLicenseError – If the project’s CORR license approval is missing or outdated.

  • ConceptsApiError – If an endpoint rejects the key or cannot be reached.

Return type:

None

parse(reference)[source]#

Parse a variable reference against this cohort’s defaults.

Parameters:

reference (str) – [taxonomy/]var_name[::version].

Returns:

The fully resolved reference.

Return type:

VariableSpec

Raises:

ValueError – If the reference is malformed.

default_spec(var_name)[source]#

Build the spec a bare variable name resolves to.

Used for requires dependencies, which always resolve at the cohort default rather than inheriting a pinned parent version.

Parameters:

var_name (str) – Bare concept name.

Returns:

The reference with cohort defaults filled in.

Return type:

VariableSpec

fetch_configs(spec, sources)[source]#

Fetch the definition of spec for every API-routed source in sources.

The API serves one document per concept covering every source, so the sources sharing an endpoint cost a single request.

A name resolving to several concepts is a group, and each member is expanded into its own contributor for every source it defines — the same shape an extra data source takes, so the frames concatenate downstream under identical column names. Members are keyed by contributor_key(), and each member’s py snippet is compiled on its own.

Parameters:
  • spec (VariableSpec) – The resolved variable reference.

  • sources (Iterable[str]) – Sources to fetch; locally routed ones are ignored.

Returns:

Per-contributor configuration and provenance. A source the concept does not define is absent, exactly as a source whose vars.json lacks the entry would be — but a concept the endpoint does not publish at all is logged at warning level, since that silently narrows a multi-source variable.

Return type:

dict[str, FetchedConfig]

Raises:
  • AmbiguousConceptError – If spec pins a version and the name is a group. latest and ::date expand instead.

  • ConceptsApiError – On any transport, auth, or server failure. A routed source is never satisfied from the bundled vars.json.

settings()[source]#

Return the JSON-serialisable settings needed to rebuild the resolver.

The API key is deliberately excluded so it never reaches a saved cohort.

Returns:

Project, taxonomy, and the default version selector.

Return type:

dict[str, Any]

corr_vars.concepts.standards.check_source(source, *, only=None)[source]#

Run every source-scoped standard against source.

Parameters:
  • source (str) – Source key, e.g. "reprodicu".

  • only (Iterable[str] | None) – Restrict to these standard names.

Returns:

All findings, errors first, then sorted for stable output.

Return type:

list[Finding]

corr_vars.concepts.standards.format_findings(findings)[source]#

Render findings as one line each, for a test failure or a CLI.

Parameters:

findings (Sequence[Finding]) – What to render.

Returns:

One line per finding, or a short note when there are none.

Return type:

str