Operations Layer
The operations layer (fhir4ds.operations) defines every user-facing engine
capability once, with typed, versioned result envelopes. All interfaces —
the Python API, the CLI, and the
MCP server — are thin adapters over the same operations, so any
surface produces identical results for the same inputs.
Capabilities (v1)
| Operation | Purpose |
|---|---|
parse_cql | Parse/validate CQL; library, definition, parameter, and include metadata. include_ast=True additionally returns statement-level AST trees (the browser AST pane surface) |
translate_cql | Emit the generated SQL for a library. audit_mode selects the shape (none = one-row CTE SQL, population = one-row-per-patient plain booleans, full = audit structs with optional patient_ids pushdown); output_columns aliases result columns to CQL defines |
evaluate_library | Evaluate populations; one row per patient; column_types carries CQL types |
run_tests | Run declarative test cases (the fhir4ds verify core) |
fhirpath_eval | Evaluate a FHIRPath expression against one resource |
load_dataset | Load inline resources or NDJSON/Bundle files; per-type counts |
explain_patient | Audit-evidence drill-in: why a patient is in/out of each population |
validate_resource | Loader-identity validation (resourceType/id rules, JSON-safety guards) — a resource that passes always loads cleanly |
resource_schema | FHIR R4 StructureDefinition-driven field metadata (types, cardinality, choices, reference targets) for a resource type |
compare_evidence | Strict diff of two evidence payloads with moved/added/removed/flipped classifications per patient × population |
The CLI exposes evidence workflows via fhir4ds verify --evidence PATH
(write a baseline artifact) and --baseline PATH (print the delta); MCP
exposes the same as compare_evidence_tool. The browser workbench
(CQL Cleanroom) is the third adapter —
a three-way matrix test asserts identical envelopes across CLI, MCP, and
the browser for run_tests and compare_evidence.
Envelopes
Every operation returns a frozen dataclass carrying shared fields:
| Field | Meaning |
|---|---|
schema | Envelope contract version (currently 1) |
ok | Execution succeeded — the envelope is trustworthy |
passed | Test assertions held (run_tests only; None elsewhere) |
diagnostics | Typed diagnostic list (may be non-empty even when ok) |
ok and passed are deliberately distinct: a run can execute cleanly
(ok: true) while a test case fails (passed: false). Agents should branch
on passed for red/green and on ok for retryable execution failures.
Diagnostics
Diagnostics are the machine contract. Each carries:
code— one ofparse_error,translation_error,evaluation_error,input_error,dataset_error,not_found,unsupported_feature(timeoutis reserved for future use);severity—error,warning, orinfo;message— stable human-readable text;location— structuredstart_line/start_column(+ optional end and library) lifted from engine parser positions, ready for editor squiggles;data— structured engine fields verbatim (expected/foundfrom parse errors,symbol/expected_type/actual_typefrom semantic errors, and so on), so tools never regex error strings.
Library resolution
include statements resolve through one chain, applied identically by every
adapter:
- Inline libraries supplied by the caller (explicit wins — an inline library always overrides a bundled library of the same name);
- Bundled standards shipped in the wheel (
FHIRHelpers,QICoreCommon,Statusunderfhir4ds/cql/resources/cql/), read viaimportlib.resources— this also works in Pyodide/WASM builds; - Adapter sources (CLI
--include-dir, MCP session cache); - otherwise a typed
not_founddiagnostic naming the missing alias and the tiers consulted — never a silent miss.
Python usage
from fhir4ds import create_connection
from fhir4ds.operations import (
LibraryText, DatasetSpec, tests_input_from_dict,
run_tests,
)
main = LibraryText(name="Simple", text="""
library Simple version '1.0.0'
using FHIR version '4.0.1'
include FHIRHelpers version '4.4.000' called FHIRHelpers
define "Initial Population":
exists([Patient] P where P.gender = 'female')
""")
dataset = DatasetSpec(resources=[
{"resourceType": "Patient", "id": "p1", "gender": "female"},
{"resourceType": "Patient", "id": "p2", "gender": "male"},
])
cases = tests_input_from_dict({
"schema": 1,
"cases": [
{"patient": "p1", "population": "Initial Population", "expect": True},
{"patient": "p2", "population": "Initial Population", "expect": False},
],
})
conn = create_connection()
result = run_tests([main], main, dataset, cases, conn)
print(result.to_dict())
Operations are stateless functions over (inputs, conn): supply your own
DuckDB connection (fhir4ds.create_connection() registers the engine's
UDFs), pass dataset=None to evaluate against data already loaded on the
connection.