Architecture Overview¶
The SDK is organized around a core HTTP client layer, endpoint wrappers that model the iMednet API, workflow helpers that combine multiple endpoint calls, and a CLI built on top of those pieces.
Components¶
Core Client¶
The synchronous Client implements authentication,
retry handling, and JSON serialization for each API request. It inherits from
HTTPClientBase and is shared by all endpoint classes. HTTP transport is
handled by httpx.
HTTP Transport Contract¶
The transport layer in imednet.core.http provides the following guarantees:
Retry policy¶
Retries are evaluated by
imednet.core.retry.DefaultRetryPolicy.Idempotent methods (
GET,PUT,DELETE,HEAD,OPTIONS) retry on:httpx.RequestErrornetwork failuresHTTP
408and5xxresponses
All methods (including
POST/PATCH) retry on HTTP429rate limits.Non-idempotent methods do not retry on network errors,
408, or5xxresponses.Maximum attempts and backoff are configured via
retry_config(RetryConfig) onClientandAsyncClient, or viaretry_config,retries, andbackoff_factoronImednetSDKandAsyncImednetSDK.Backoff uses Tenacity’s randomized exponential wait strategy with
backoff_factoras the multiplier.Paginators call the requester directly. The HTTP transport is the sole retry, circuit-breaker accounting and request-telemetry owner for each page, including endpoints returning a raw JSON list. Custom requesters must own their own retry policy; paginators do not replay their exceptions.
If a retriable response includes
Retry-After, that delay overrides the backoff schedule and is bounded byRetryConfig.max_retry_after(default60.0seconds).
Timeouts¶
timeoutis forwarded directly intohttpx.Client/httpx.AsyncClient.You can pass either a float (single timeout applied to all phases) or
httpx.Timeoutfor per-phase timeouts.
Circuit breaker and probe leases¶
HTTPClientBaseinitializes a dedicatedCircuitBreakerper client instance (failure_threshold=5,recovery_timeout=10.0seconds,half_open_max_probes=1), isolatingCircuitStateacross independentStudyclients, alongside an LRU-bounded origin-keyedCircuitBreakermap for terminal external redirect hops.Each execution attempt acquires its own
ProbeLease.CircuitStateprogresses throughCLOSED,OPEN, andHALF_OPEN: five consecutivehttpx.RequestError, HTTP408, or HTTP5xxoutcomes viarecord_failure()open the breaker, aborting pending retries and causing new requests to fail immediately withimednet.errors.CircuitBreakerError(subclassingimednet.errors.ImednetErrordirectly withattempt_count=0onimednet.errors.DiagnosticContext).After
recovery_timeoutelapses, the next attempt transitions the breaker toHALF_OPENand acquires aProbeLease(enforcinghalf_open_max_probes=1). Only an HTTP2xxresponse callsrecord_success()(returning the breaker toCLOSEDand advancing its monotonic epoch); HTTP408,5xx, or network errors re-open it; and early exits (task cancellation,3xxredirects, or other non-4294xxresponses) leave the lease unsettled forProbeLease.release()so in-flight probe capacity is never leaked andHALF_OPENis not prematurely closed.HTTP
429responses invokerecord_rate_limit()rather thanrecord_failure(): inCLOSEDstate they leave the consecutive failure counter untouched so rate-limitedSubject,Site,Form,Record,Visit,Interval,Variable,Query,Data Dictionary, andJobtraffic is paced byRetry-Afterwithout opening the circuit, whereas inHALF_OPENstate an HTTP429immediately re-opens the breaker.
Status-code error mapping¶
Response errors are mapped via imednet.errors.get_error_class():
Status code |
Raised exception |
|---|---|
400 |
|
401 |
|
403 |
|
404 |
|
409 |
|
429 |
|
500-599 |
|
other |
Credential redaction¶
Transport logs and formatted errors never include raw credential headers.
URLs logged by request monitoring or attached to
imednet.errors.DiagnosticContextare sanitized throughimednet.utils.url.redact_url_query(), redacting sensitive query params such asapi_key,security_key,token,secret, andpassword.Both retried and unretried transport failures raise
imednet.errors.RequestErrorwith structuredimednet.errors.DiagnosticContextand chained causes, open circuit breakers raiseimednet.errors.CircuitBreakerError, and credential configuration errors raiseimednet.errors.ConfigurationErrorso callers can catch all SDK failures viaimednet.errors.ImednetError.
Async Client¶
AsyncClient powers a unified async-first
execution engine shared across Data Dictionary loaders, study orchestrators,
all nine built-in workflows, and streaming export sinks. The public SDK surface
exposes two strictly typed client facades with symmetric unprefixed method
names:
ImednetSDK(ImednetFacade) for synchronous scripts, CLI commands, and interactive notebooks. Synchronous wrappers delegate to canonicalasyncengines via an event-loop-aware bridge that detects activeasyncioloops (including Jupyter,pytest-asyncio, and single-threaded WebAssembly/Pyodide runtimes) so callers never hitRuntimeError.AsyncImednetSDK(AsyncImednetFacade) for nativeasync/awaitservices, exposing symmetric coroutines (for exampleawait sdk.get_records(...),await sdk.create_records_batch(...),await sdk.poll_jobs(...),await async_load_from_api(sdk, ...), andAsyncMultiStudyOrchestrator). Legacyasync_*convenience methods remain available onAsyncImednetSDKas deprecated compatibility aliases.
Manage asynchronous client lifecycles with async with AsyncImednetSDK(...) as sdk:
or await sdk.aclose().
Endpoints¶
Each endpoint, such as StudiesEndpoint,
wraps a related set of API operations. Endpoints now use composition:
GenericListGetEndpoint composes operation classes (for example
ListOperation and FilterGetOperation) rather than inheriting deep
operation mixin chains. This keeps method resolution straightforward, improves
IDE autocomplete, and avoids MRO-related typing ambiguity. Endpoints expose
list/get methods that return typed models.
Workflows¶
Workflows orchestrate several endpoints over shared async cores to perform
higher-level clinical operations—for example,
RecordUpdateWorkflow and
AsyncRecordUpdateWorkflow validate
record payloads, submit bounded batches, and poll resulting jobs. All nine
built-in workflows expose symmetric unprefixed methods under sdk.workflows
on both ImednetSDK
(SyncWorkflowsNamespaceProtocol) and
AsyncImednetSDK
(AsyncWorkflowsNamespaceProtocol), while sdk.sinks
binds SinksNamespace and
AsyncSinksNamespace over native synchronous and
asynchronous sink drivers.
Caching¶
Caching Behavior describes how schema metadata and local record caches
work. Cached schema metadata can be reloaded by calling schema.refresh() on
a SchemaCache instance.
CLI¶
The Command Line Interface (CLI) uses standard-library argparse to expose common workflows on the command line. Each
command creates an ImednetSDK instance, invokes a workflow,
and closes the SDK when finished.
Data Flow¶
Extension Points¶
Adding New Endpoints¶
Subclass
GenericEndpointorGenericListGetEndpoint.Register the class in
_ENDPOINT_REGISTRYwithinimednet.sdksoImednetSDKexposes it.Document the endpoint in
docs/endpoints/and add tests.
Adding New Workflows¶
Implement a canonical
Async*workflow againstAsyncImednetFacadeunderpackages/plugins-workflows/src/imednet_workflowsand wrap synchronousImednetFacadecalls over it.Register the synchronous adapter in
imednet.workflowsand the asynchronous adapter inimednet.async_workflows.Add CLI commands or examples that demonstrate the workflow.
Update documentation and tests.
Export Sink Architecture¶
The SDK supports four distinct export paths. Choose the right path based on the shape of data you want to land at the destination.
Export Path Decision Matrix¶
Path |
When to use |
Key components |
|---|---|---|
Tabular |
Destination is a flat/columnar store (CSV, Excel, JSON, SQL, DuckDB,
Parquet). All variables for a form or CDISC SDTM domain can be
represented as columns using |
|
Document |
Destination is a document store (for example MongoDB) and should keep
nested |
|
Graph |
Destination models relationships natively (for example Neo4j),
preserving Study → Subject → Visit → Record for scheduled |
|
Warehouse |
Destination is a cloud data warehouse with a native bulk loader.
|
|
Data flow diagram¶
Streaming checkpoints and state provider SPI¶
Incremental exports decouple destination sinks from checkpoint persistence through
StateProviderProtocol and
get_state_provider():
StateProviderProtocoldefines the runtime-checkable contract for reading and committing per-Studystream watermarks:get_last_timestamp(study_key, stream_name),set_last_timestamp(...),transaction(study_key, stream_name, fallback_timestamp=None),read_state(), anddelete_entry(study_key, stream_name=None).get_state_provider(ledger_path=None, *, provider_name=None)resolves plugins registered under theimednet.state_providersentry-point group (shipped byimednet-workflows), routing explicitledger_patharguments directly toFileStateProvidereven underdefaultorairflowprovider settings:default→imednet_workflows.state_ledger.get_state_provider()(returnsFileStateProviderfor explicit custom paths before checkingAIRFLOW_CTX_TASK_IDorUSE_AIRFLOW_STATE_PROVIDER).file→imednet_workflows.state_ledger.FileStateProvider(also exported as the backward-compatible aliasimednet_workflows.ExtractionStateLedger).airflow→imednet_workflows.state_ledger.AirflowStateProvider(persists consolidated per-Studystream watermarks in AirflowVariablestorage using optimistic SQL compare-and-swap outsideRuntimeTaskInstance,lease_token/lease_idlease fencing viaairflow.sdk.VariableinsideRuntimeTaskInstance, monotonic watermarks, and wildcard-escaped exactStudydeletes).
run_streaming_export()orchestrates end-to-end streaming writes across everyExportSink:Opens
provider.transaction(...)whenincremental=Trueorstate_provideris set, resolving the active watermark from the storedlast_timestampormodified_sincefallback.Streams paginated
Recorditems viaiter_filtered_sdk_records(), combiningwatermark,record_filter, andrecord_data_filterinto AND-safe query branches.Observes
Recordmodification timestamps while routing voided (deleted=True) items tosink.reconcile_deleted(...)on incremental idempotent runs (and full idempotent runs for persistent sinks settingreconciles_deleted_on_full_sync = True) wheninclude_deleted=False(with multi-Formtabular helpers routing single-passRecordstreams throughBoundedFormBufferRouter).Applies
apply_quality_gate()and streams fixed-size chunks intosink.write_batch(...). Whenquality_gate_enabled=Trueandapply_quality_gatedrops low-readinessRecorditems, bothrun_streaming_exportand multi-Formtabular streaming cap the candidatemax_tswatermark atmin_rejected_ts(selecting the highest exportedRecordtimestamp<= min_rejected_ts, or leavingmax_tsasNonewhen no exported timestamp precedesmin_rejected_tsor any rejectedRecordlacks a timestamp) so rejectedRecorditems are re-evaluated on subsequent incremental runs.Flushes and closes the sink before exiting
provider.transaction(...), ensuring the capped high-water mark commits only after every batch, delete reconciliation, andsink.flush()succeed.
Error propagation¶
Transient errors are retried up to
max_retriestimes with exponential back-off.max_retriescounts retries after the first attempt: zero means one execution, and two means at most three executions. Sink backoff starts atretry_backoffand doubles for each retry. Negative/non-integral retry counts and non-finite/negative backoff values are rejected at configuration.Every
ExportSinkinstance owns an isolated per-sinkCircuitBreaker(failure_threshold=5,recovery_timeout=10.0seconds,half_open_max_probes=1) passed toUniversalExecutorinsideExportSink._execute_with_retry, ensuring a failing warehouse or document target never trips sibling sinks or HTTP API clients.Sink configuration and input validation errors are not replayed and do not poison the sink
CircuitBreaker. Driver exception messages are replaced before entering operation telemetry, because they may contain connection strings or payloads. Export errors report the actual number of destination calls—including0attempts when an open sinkCircuitBreakerblocks execution before invoking the driver—and retainbatch_idwhile chaining the sanitizedCircuitBreakerErrorwithout copying the raw driver message.After all retries are exhausted (or when blocked by an open sink breaker), sinks raise
ExportBatchError(carriesbatch_id) so that callers can log and resume partial exports.Misconfiguration (missing credentials, invalid URIs) raises
ExportConfigurationErrorimmediately before any data is written.Credentials and connection URIs are never written to logs. Pass URIs through
redact_uri()before logging them.
Optional dependency conventions¶
Each sink module calls
imednet.spi.sinks.require_optional_dep at
connection time (not at import time). This means:
import imednet_sinks.graphnever raises even whenneo4jis not installed.The error is raised when the first sink instance is created.
The error message tells the user which
imednet[<extra>]to install.
Extras naming:
# Install all tabular export dependencies
pip install "imednet[export]"
# Or install destination-specific extras
pip install "imednet[duckdb]"
pip install "imednet[mongodb]"
pip install "imednet[neo4j]"
pip install "imednet[snowflake]"
Public API exposure¶
imednet.integrationsregisters all 12 tabular and CDISC exchange helpers onExportRegistry, whileimednet.spi.sinks(andimednet.spi.sink_base) defines shared sink contracts (SinkConfig,ExportSink, andBoundedFormBufferRouter).Document, graph, and warehouse sinks are exposed from
imednet_sinks(and dynamically viasdk.sinkswhenimednet-plugins-sinksis installed) or directly from their submodules:apache_airflow_providers_imednet.exportwraps all 12 tabular and CDISC exchange helpers (export_to_csv,export_to_dataset_json,export_to_duckdb,export_to_duckdb_by_form,export_to_excel,export_to_hive_parquet,export_to_json,export_to_long_sql,export_to_odm,export_to_parquet,export_to_sql, andexport_to_sql_by_form).ImednetExportOperatordispatches those 12 core targets alongsidemongodb,neo4j, andsnowflakeplugin sinks resolved dynamically viasdk.sinksat runtime (keepingapache_airflow_providers_imednetdecoupled fromimednet_sinks), whileresolve_destination_connection()resolvesdestination_conn_idsettings forsnowflake,neo4j,mongodb,duckdb,duckdb_by_form,hive_parquet,sql,sql_by_form, andlong_sql.
Adding New Export Sinks¶
Create a module under
packages/plugins-sinks/src/imednet_sinks/.Subclass
imednet.spi.sinks.ExportSinkand implementwrite_batch,flush, andclose.Call
imednet.spi.sinks.require_optional_depinside the constructor (not at module level).Add the optional dependency to
packages/plugins-sinks/pyproject.tomlunderproject.optional-dependencies; add a core extra only for a supported install recipe.Expose it through
imednet_sinksand its plugin entry points without adding static plugin imports to core.Add unit tests; run the canonical verification tasks in Verification Loop.
Restricted AST Business Logic Sandbox¶
User-authored MappingRule business_logic
expressions run inside RestrictedAstEvaluator (via
parse_expression(), validate_ast(),
and evaluate_expression()) rather than Python eval:
Explicit AST node allowlist: Only pure scalar, arithmetic, boolean, comparison, ternary
IfExp, container literal, subscript/slice, public attribute read, and allowlisted call nodes are permitted; statements, lambdas, comprehensions,await, and f-strings (JoinedStr/FormattedValue) raiseRestrictedEvaluationError.Bounded call surface: Free function calls are restricted to
DEFAULT_SAFE_FUNCTIONS(float,int,str,bool,len), and method calls are restricted toDEFAULT_SAFE_METHODS(read-only string,dict,list/tuple, andsetinspection helpers). Private_attributes,.format/.format_map(which could otherwise traverse object attributes via format strings), and mutating methods (such asclear,pop,update, orappend) are rejected before execution so rule evaluation cannot escape the sandbox or mutate sharedRecordpayloads.Non-fatal pipeline fallback:
EnrichmentPipeline,transform_records_to_sdtm_rows(), andextract_canonical_recordscatchRestrictedEvaluationError(and runtimeEvaluationError) per rule, log a warning, and preserve the raw or configured fallbackVariablevalue.
from imednet.errors import EvaluationError, RestrictedEvaluationError
from imednet.utils import (
RestrictedAstEvaluator,
evaluate_expression,
parse_expression,
)
from imednet.utils.evaluator import (
DEFAULT_SAFE_FUNCTIONS,
DEFAULT_SAFE_METHODS,
validate_ast,
)
assert set(DEFAULT_SAFE_FUNCTIONS) == {"float", "int", "str", "bool", "len"}
assert "format" not in DEFAULT_SAFE_METHODS
assert "format_map" not in DEFAULT_SAFE_METHODS
assert "clear" not in DEFAULT_SAFE_METHODS
parsed_tree = parse_expression("float(value.strip()) * 2.2")
validate_ast(parsed_tree)
evaluator = RestrictedAstEvaluator("float(value.strip()) * 2.2")
assert round(evaluator.evaluate({"value": " 70.0 "}), 1) == 154.0
assert evaluate_expression("payload.get('UNIT', 'kg').upper()", {"payload": {"UNIT": "kg"}}) == "KG"
for blocked_expr in ("'{0.__class__}'.format(value)", "f'{value}'", "payload.clear()"):
blocked = False
try:
evaluate_expression(
blocked_expr,
{"value": "70", "payload": {"UNIT": "kg"}},
raise_on_error=True,
)
except RestrictedEvaluationError:
blocked = True
assert blocked
runtime_failed = False
try:
evaluate_expression("int(value)", {"value": "bad"}, raise_on_error=True)
except EvaluationError:
runtime_failed = True
assert runtime_failed
Static boundary checks¶
The repository guard scans core, workflows, sinks and Airflow source roots.
It resolves relative imports before checking segment-aware package boundaries;
missing source trees fail explicitly. Type-only references follow the same
layering rules, without executing optional modules. Core’s SPI is an intentional
CLI composition root. Dynamic entry points and legacy lazy import shims require
separate runtime tests. New sink implementations use imednet.spi.sinks;
legacy imednet.spi.sink_base and imednet.integrations remain compatible.