imednet.orchestration package¶
Multi-study orchestration engine for iMednet SDK.
Provides MultiStudyOrchestrator for executing pipeline functions
concurrently across multiple iMednet study boundaries with fault isolation,
telemetry context propagation, and normalized result reporting.
Quick start¶
from typing import Any
from imednet import ImednetSDK, MultiStudyOrchestrator
def my_pipeline(
study_key: str,
sdk_client: Any,
logger: Any,
*args: Any,
**kwargs: Any,
) -> dict[str, int]:
logger.info("Processing study")
subjects = sdk_client.subjects.list(study_key=study_key)
return {"subject_count": len(list(subjects))}
with ImednetSDK() as sdk:
orchestrator = MultiStudyOrchestrator(sdk, max_workers=4)
results = orchestrator.execute_pipeline(my_pipeline)
for study_key, result in results.items():
if result["status"] == "SUCCESS":
print(f"{study_key}: {result['data']}")
else:
print(f"{study_key}: FAILED — {result['error']}")
Public API¶
MultiStudyOrchestrator— main orchestration engineStudyContextLogAdapter— per-study log adaptermake_study_logger()— factory for study-bound loggersOrchestratorResult— per-study result schema (TypedDict)StudyWorkerCallable— protocol for pipeline callables
Errors¶
OrchestratorError— base orchestration errorFilterConflictError— raised when both whitelist and blacklist are provided simultaneously
Submodules¶
imednet.orchestration.logging module¶
Per-study logging adapter for the MultiStudyOrchestrator engine.
This module provides StudyContextLogAdapter, which enriches every log
record emitted by a worker thread with study_key and studyKey fields.
When combined
with a JSON formatter (e.g. configure_json_logging()),
each log line carries structured metadata that can be indexed by log
aggregation systems such as Splunk, Datadog, or CloudWatch Logs.
Example JSON output¶
With JSON logging enabled the adapter produces records like:
{
"timestamp": "2024-01-15T10:23:45.123456Z",
"level": "INFO",
"logger": "imednet.orchestration",
"message": "Starting data extraction",
"study_key": "PROT-01",
"studyKey": "PROT-01"
}
Usage:
from imednet.orchestration.logging import make_study_logger
study_logger = make_study_logger("PROT-01")
study_logger.info("Starting data extraction")
# → emits a record with extra={"study_key": "PROT-01", "studyKey": "PROT-01"}
- class imednet.orchestration.logging.StudyContextLogAdapter[source]¶
Bases:
LoggerAdapterA logger adapter that enriches records with a bound study key.
- __init__(logger, study_key)[source]¶
Initialize the study context log adapter.
- Parameters:
logger (Logger) – The underlying logger to wrap.
study_key (str) – The study identifier to inject into every log record.
- Return type:
None
- process(msg, kwargs)[source]¶
Inject
study_keyandstudyKeyinto the log recordextramapping.- Parameters:
msg (Any) –
kwargs (MutableMapping[str, Any]) –
- Return type:
tuple[Any, MutableMapping[str, Any]]
- property study_key: str¶
The study identifier bound to this adapter.
- imednet.orchestration.logging.make_study_logger(study_key)[source]¶
Create a
StudyContextLogAdapterfor a study key.- Parameters:
study_key (str) – The study identifier to bind to log records.
- Returns:
A logger adapter that enriches records with the study key.
- Return type:
imednet.orchestration.orchestrator module¶
MultiStudyOrchestrator: concurrent multi-study pipeline engine.
This module provides the MultiStudyOrchestrator class, which drives
parallel execution of a user-supplied pipeline function across all active
iMednet study boundaries discovered via the SDK’s studies endpoint.
Three-step usage¶
Construct the orchestrator with a live SDK instance:
orchestrator = MultiStudyOrchestrator(sdk, max_workers=8)
Define a pipeline callable that conforms to
StudyWorkerCallable:def my_pipeline(study_key, sdk, study_logger, **kwargs): study_logger.info("Running pipeline for %s", study_key) subjects = sdk.subjects.list(study_key=study_key) return {"count": len(list(subjects))}
Execute and inspect results:
results = orchestrator.execute_pipeline( my_pipeline, whitelist={"PROT-01", "PROT-02"}, ) for study_key, r in results.items(): print(study_key, r["status"], r["duration_seconds"])
Each study runs in its own study_context(),
so context-sensitive SDK calls resolve the correct study automatically.
Per-study failures are captured in the result dict (status="FAILED")
and never propagate as exceptions, ensuring fault isolation.
- class imednet.orchestration.orchestrator.AsyncMultiStudyOrchestrator[source]¶
Bases:
objectCanonical asynchronous multi-study pipeline engine.
Executes asynchronous pipeline coroutines concurrently across active clinical studies resolved via
AsyncImednetFacade, enforcing per-taskstudy_contextisolation, adaptive latency-based backpressure, and fault isolation.- __init__(sdk, max_workers=4)[source]¶
Initialize the asynchronous multi-study orchestrator.
- Parameters:
sdk (AsyncImednetFacade) – An initialized
AsyncImednetSDKorAsyncImednetFacade.max_workers (int) – Maximum number of concurrent study tasks. Defaults to 4.
- Return type:
None
- async execute_pipeline(pipeline_func, whitelist=None, blacklist=None, *args, **kwargs)[source]¶
Asynchronously execute a pipeline coroutine concurrently across resolved studies.
- Parameters:
pipeline_func (AsyncStudyWorkerCallable[T_Output] | Callable[..., Awaitable[T_Output]]) –
whitelist (set[str] | None) –
blacklist (set[str] | None) –
args (Any) –
kwargs (Any) –
- Return type:
dict[str, OrchestratorResult]
- property max_workers: int¶
Maximum number of concurrent study tasks.
- async resolve_active_studies(whitelist=None, blacklist=None)[source]¶
Asynchronously query the iMednet study registry and apply filtering rules.
- Parameters:
whitelist (set[str] | None) –
blacklist (set[str] | None) –
- Return type:
list[str]
- property sdk: AsyncImednetFacade¶
The shared read-only asynchronous SDK facade.
- class imednet.orchestration.orchestrator.MultiStudyOrchestrator[source]¶
Bases:
objectSynchronous multi-study orchestrator wrapping
AsyncMultiStudyOrchestrator.Strictly typed against
ImednetFacadewhile sharing the canonical async execution, study filtering, context isolation, and adaptive backpressure engine. Safely executes even when called from an active event loop in Jupyter or Pyodide.- __init__(sdk, max_workers=4)[source]¶
Initialize the multi-study orchestrator.
- Parameters:
sdk (ImednetFacade) – An initialized synchronous
ImednetSDKorImednetFacade.max_workers (int) – Maximum number of concurrent worker threads. Defaults to 4.
- Raises:
ValueError – If
max_workers < 1.TypeError – If an
AsyncImednetSDKor async facade is provided.
- Return type:
None
- execute_pipeline(pipeline_func, whitelist=None, blacklist=None, *args, **kwargs)[source]¶
Execute a synchronous pipeline function concurrently across resolved studies.
- Parameters:
pipeline_func (StudyWorkerCallable[T_Output] | Callable[..., T_Output]) –
whitelist (set[str] | None) –
blacklist (set[str] | None) –
args (Any) –
kwargs (Any) –
- Return type:
dict[str, OrchestratorResult]
- property max_workers: int¶
Maximum number of concurrent worker threads.
- resolve_active_studies(whitelist=None, blacklist=None)[source]¶
Query the iMednet registry and apply whitelist/blacklist filtering rules.
- Parameters:
whitelist (set[str] | None) –
blacklist (set[str] | None) –
- Return type:
list[str]
- property sdk: ImednetFacade¶
The shared read-only synchronous SDK facade.
imednet.orchestration.types module¶
Type protocols and result schemas for the MultiStudyOrchestrator engine.
This module exports:
StudyWorkerCallable— atyping.Protocolthat pipeline functions must conform to in order to be accepted byexecute_pipeline().OrchestratorResult— atyping.TypedDictthat describes the per-study result entry returned byexecute_pipeline.T_Output— a covariantTypeVarused to parameterizeStudyWorkerCallable.
StudyWorkerCallable protocol¶
Any callable passed to execute_pipeline must accept at minimum:
def my_pipeline(
study_key: str, # the study identifier for this worker
sdk_client: ImednetSDK, # shared (read-only) SDK instance
logger: Any, # StudyContextLogAdapter bound to study_key
*args: Any,
**kwargs: Any,
) -> Any: ...
Example:
from imednet.orchestration import StudyWorkerCallable
def count_subjects(study_key, sdk_client, logger, **kwargs):
subjects = sdk_client.subjects.list(study_key=study_key)
return len(list(subjects))
# Runtime check via @runtime_checkable:
assert isinstance(count_subjects, StudyWorkerCallable)
OrchestratorResult schema¶
Each entry in the dict returned by execute_pipeline is an
OrchestratorResult TypedDict with the following fields:
status"SUCCESS"or"FAILED".dataThe value returned by the pipeline callable on success, or
Noneon failure.errorrepr()of the exception on failure, orNoneon success.duration_secondsWall-clock time (seconds, rounded to 4 decimal places) for this study.
Example:
results = orchestrator.execute_pipeline(count_subjects)
for study_key, r in results.items():
if r["status"] == "SUCCESS":
print(f"{study_key}: {r['data']} subjects ({r['duration_seconds']:.2f}s)")
- class imednet.orchestration.types.AsyncStudyWorkerCallable[source]¶
Bases:
Protocol[T_Output]Defines the explicit signature required for injected asynchronous pipeline tasks.
Pipeline callables injected into
AsyncMultiStudyOrchestrator.execute_pipelinemust conform to this protocol.- async __call__(study_key, sdk_client, logger, *args, **kwargs)[source]¶
Asynchronously invoke the pipeline task for a specific study context.
- Parameters:
study_key (str) – The identifier of the study being processed.
sdk_client (AsyncImednetFacade) – A shared (read-only) asynchronous SDK facade instance.
logger (StudyContextLogAdapter) – A study-specific logger instance.
*args (Any) – Variable positional arguments passed to the pipeline.
**kwargs (Any) – Variable keyword arguments passed to the pipeline.
- Returns:
The output of the pipeline task of type T_Output.
- Return type:
T_Output
- class imednet.orchestration.types.OrchestratorResult[source]¶
Bases:
TypedDictNormalized result entry returned per study by
execute_pipeline.- status: str¶
Optional.
- data: Any | None¶
Optional.
- error: str | None¶
Optional.
- duration_seconds: float¶
Optional.
- class imednet.orchestration.types.StudyWorkerCallable[source]¶
Bases:
Protocol[T_Output]Defines the explicit signature required for injected synchronous pipeline tasks.
Pipeline callables injected into
MultiStudyOrchestrator.execute_pipelinemust conform to this protocol.- __call__(study_key, sdk_client, logger, *args, **kwargs)[source]¶
Invoke the pipeline task for a specific study context.
- Parameters:
study_key (str) – The identifier of the study being processed.
sdk_client (ImednetFacade) – A shared (read-only) synchronous SDK facade instance.
logger (StudyContextLogAdapter) – A study-specific logger instance.
*args (Any) – Variable positional arguments passed to the pipeline.
**kwargs (Any) – Variable keyword arguments passed to the pipeline.
- Returns:
The output of the pipeline task of type T_Output.
- Return type:
T_Output