Job Polling Mechanism¶
JobPoller and
AsyncJobPoller wait for background Job
executions to reach a terminal state or raise on timeout.
Single-Job Polling¶
ImednetSDK provides a convenience method poll_job that blocks until a
single Job finishes. AsyncImednetSDK exposes poll_job as an
awaitable coroutine for asynchronous callers:
from imednet import AsyncImednetSDK, ImednetSDK
# Synchronous single-Job polling
sdk = ImednetSDK()
status = sdk.poll_job("STUDY", "BATCH", interval=0.05, timeout=10)
# Asynchronous single-Job polling
async def wait_async() -> None:
async with AsyncImednetSDK() as async_sdk:
await async_sdk.poll_job("STUDY", "BATCH", interval=0.05, timeout=10)
Chunked Batch Submission and Multi-Job Polling¶
Large Record writes should be split into bounded chunks so a single payload
never exceeds API request limits and schema validation runs once across the full
submission:
Endpoint chunking:
sdk.records.create_batch(study_key, records_data, *, chunk_size=100, schema=None)(andawait async_sdk.records.create_batch(...)) validatesRecorditems once and submits bounded POST chunks viaBatchCoordinatororAsyncBatchCoordinator, returning aBatchSubmissionSummary.SDK convenience orchestration:
sdk.create_records_batch(..., wait_for_completion=True)(andawait async_sdk.create_records_batch(...)) combinesBatchCoordinatorchunk submission withsdk.poll_jobs/await async_sdk.poll_jobs(...)so every submittedbatch_idis polled to completion and attached tosummary.poll_summary.Direct coordinator control: Instantiate
BatchCoordinator(chunk_size=...)orAsyncBatchCoordinator(chunk_size=...)directly when wrapping custom chunk submission callables while preserving single-pass validation andBatchSubmissionSummaryreporting (jobs,batch_ids,chunk_sizes,total_records,skipped_count,last_job, andall_successful).Concurrent multi-Job polling:
sdk.poll_jobs(study_key, batch_ids, *, interval=5.0, timeout=300.0, fail_fast=False, resolve_results=False)andsdk.jobs.poll_many(...)poll multipleJobIDs concurrently, optionally resolve terminalresultUrlpayloads whenresolve_results=True, and return aJobPollSummarycontainingresultsandfailuresdictionaries.
import asyncio
from imednet import AsyncImednetSDK, ImednetSDK
from imednet.simulation import reset_default_simulation_state
from imednet.utils.batch_coordinator import AsyncBatchCoordinator, BatchCoordinator
batch_sdk = ImednetSDK(simulation_mode=True)
records_payload = [
{
"formKey": "F_VS",
"siteName": "SITE",
"subjectKey": "SUB1",
"intervalName": "Baseline",
"data": {"V_WEIGHT": 70.5},
},
{
"formKey": "F_VS",
"siteName": "SITE",
"subjectKey": "SUB1",
"intervalName": "Baseline",
"data": {"V_WEIGHT": 71.2},
},
]
# 1. Endpoint-level create_batch + explicit poll_jobs
endpoint_summary = batch_sdk.records.create_batch("STUDY", records_payload, chunk_size=1)
poll_summary = batch_sdk.poll_jobs("STUDY", endpoint_summary.batch_ids, interval=0.05, timeout=10.0)
assert endpoint_summary.chunk_count == 2
assert poll_summary.all_successful is True
print(endpoint_summary.chunk_count, poll_summary.all_successful)
# 2. One-step convenience batch submission with polling
convenience_summary = batch_sdk.create_records_batch(
"STUDY",
records_payload,
chunk_size=1,
wait_for_completion=True,
interval=0.05,
timeout=10.0,
)
assert convenience_summary.total_records == 2
assert convenience_summary.all_successful is True
print(convenience_summary.total_records, convenience_summary.all_successful)
# 3. Direct BatchCoordinator and AsyncBatchCoordinator usage
coordinator = BatchCoordinator(chunk_size=1)
coord_summary = coordinator.submit(
"STUDY",
records_payload,
lambda chunk: batch_sdk.records.create("STUDY", chunk),
)
assert len(coord_summary.batch_ids) == 2
print(len(coord_summary.batch_ids))
async def submit_async_batches() -> None:
async with AsyncImednetSDK(simulation_mode=True) as async_batch_sdk:
async_coord = AsyncBatchCoordinator(chunk_size=1)
summary = await async_coord.submit(
"STUDY",
records_payload,
lambda chunk: async_batch_sdk.records.create("STUDY", chunk),
)
async_poll = await async_batch_sdk.poll_jobs("STUDY", summary.batch_ids, interval=0.05)
assert async_poll.all_successful is True
asyncio.run(submit_async_batches())
reset_default_simulation_state()
Inspecting JobStatus Record Counts and Partial Failures¶
In the iMednet REST API, a batch Job can report a top-level state of
COMPLETED even when individual Record items inside the batch failed
validation or rule checks. Aligned with
Endpoint composition and shared job polling,
JobStatus exposes normalized record-level counters
and partial-failure predicates:
status.total_records: TotalRecordentries processed in the batch (derived fromresultsentries ortotalRecords).status.successful_records: Count ofRecordentries that succeeded (PASS,SUCCESS, orCOMPLETEDentries orsuccessfulRecords).status.failed_records: Count ofRecordentries rejected withFAIL,FAILED,ERROR, per-entryerror/errorsdetails, orfailedRecords.status.result_error: Top-level error string attached when fetching or evaluating the batchresultUrlpayload (resultError).status.is_failed/status.is_successful:status.is_failedevaluates toTruenot only whenstateisFAILED,CANCELLED, orTIMEOUT, but also whenever a terminalCOMPLETEDJobhasfailed_records > 0or a non-emptyresult_error. Conversely,status.is_successfulisTrueonly whenfailed_records == 0andresult_erroris empty.
from imednet.models.jobs import JobStatus
partial_failure = JobStatus.model_validate(
{
"batchId": "BATCH-PARTIAL-01",
"state": "COMPLETED",
"totalRecords": 3,
"successfulRecords": 2,
"failedRecords": 1,
"resultError": "1 Record rejected by Range Check",
}
)
assert partial_failure.total_records == 3
assert partial_failure.successful_records == 2
assert partial_failure.failed_records == 1
assert partial_failure.result_error == "1 Record rejected by Range Check"
assert partial_failure.is_failed is True
assert partial_failure.is_successful is False
Mid-Batch Errors, Sibling Settlement, and Validation Modes¶
Chunked write helpers (create_batch(),
BatchCoordinator, and
AsyncBatchCoordinator) preserve full batch
state when partial progress occurs before an error:
Mid-batch write errors: If chunk N fails after earlier chunks were accepted by the API, any accepted
batch_idvalues are settled to terminal states whenwait_for_completion=Trueand aBatchSubmissionSummaryis attached toexc.partial_summary(along withexc.unsubmitted_chunks). Credentials are redacted and clinical PHI fields are masked on all attached diagnostic payloads without mutating caller input dictionaries.Sibling settlement on polling failures: When
wait_for_completion=Truepolls multiple chunks and oneJobends in a failed state, all siblingbatch_idvalues are settled to terminal states beforeJobFailedErroris raised. Callers can inspectexc.poll_summary(includingexc.poll_summary.terminal_statuses) andexc.partial_summaryto reconcile which chunks succeeded and which failed; in accordance with Endpoint composition and shared job polling, local errors never imply server-sideJobcancellation.Dry-run and skipped validation semantics: Calling
submit(..., dry_run=True)returns theBatchValidationReportonsummary.validation_reportwithout raisingValidationError, andsummary.all_successfulreflectsreport.is_valid. Passingskip_validation=Trueleavessummary.validation_reportasNoneso unvalidated batches never claim validRecordcounts.
Typed Endpoint Interface and Terminal Semantics¶
sdk.jobs.poll(study_key, batch_id, on_progress=callback, resolve_results=False) and
sdk.jobs.poll_many(study_key, batch_ids, resolve_results=False) use the core pollers
(isolation of cached terminal JobStatus entries is keyed by (study_key, batch_id)).
Pass resolve_results=True on poll, poll_many, poll_job, or
poll_jobs to fetch terminal resultUrl payloads and
raise or record JobFailedError when individual
Record entries fail. Await these
methods on AsyncImednetSDK. SDK convenience methods accept the same optional
callback, which accepts either a single JobStatusEvent or the legacy
(batch_id, status, elapsed) positional arguments. Callback exceptions
propagate immediately during single-Job polling; batch polling collects per-Job
failures in JobPollSummary.failures by default, while fail_fast=True
wakes or cancels sibling pollers and raises the triggering JobFailedError
or JobTimeoutError directly.
Recognized successful terminal state aliases are COMPLETED, COMPLETE, and
SUCCESS; FAILED, CANCELLED, and TIMEOUT (as well as terminal
partial failures where JobStatus.is_failed is True) raise
JobFailedError in single-Job polling and populate JobPollSummary.failures
in poll_many. Missing states remain non-terminal, unknown states fail
validation, and local timeout raises JobTimeoutError. Local task cancellation
does not cancel a server-side Job. See
Endpoint composition and shared job polling for full contract details.