Python

Python durable runs

Create typed runs and resume progress, events, partial results, errors, and cancellation.

Suggest an edit

A run is durable, observable execution. Once the service accepts it, it keeps going if your client disconnects, reports progress per item, keeps partial results, and can be cancelled. Runs are retained for 30 days.

There are two kinds:

KindUse it for
selection_batchone selection template applied independently to many query molecules (1–1000 items)
selectionone selection you want executed durably

Do not loop over many queries with search(): put them in one selection_batch so progress, partial results, cancellation, and per-item errors stay visible. The sections below follow the life of one run. Selections themselves are covered in the Selection builder; the HTTP routes and limits are in the runs API guide.

The examples below are shown as they appear in a Jupyter notebook. They assume you are signed in (see the Python quickstart).

1. Describe the work: a batch

One template, with a named reference slot (query), and one item per molecule that fills the slot. Item IDs are yours (letters, digits, ., _, -; up to 128 characters) and come back with each result.

import pandas as pd
from deepmedchem import Client, Run, Selection

template = (
    Selection.from_database("enamine-real-v5a")
    .ranked()
    .require_preset("lipinski-ro5/v1")
    .maximize_similarity("rdkit.ecfp4_tanimoto", reference="query")   # "query" is filled per item
    .limit(5)
)

leads = {
    "aspirin":     "CC(=O)Oc1ccccc1C(=O)O",
    "ibuprofen":   "CC(C)Cc1ccc(C(C)C(=O)O)cc1",
    "paracetamol": "CC(=O)Nc1ccc(O)cc1",
    "broken":      "not-a-smiles",          # one bad input on purpose
}
spec = Run.selection_batch(
    template=template,
    items={item_id: {"query": smiles} for item_id, smiles in leads.items()},
    metadata={"campaign": "lead-expansion-demo"},
)
spec.to_dict()["kind"], len(spec.to_dict()["items"])
('selection_batch', 4)

One item as it will be sent:

spec.to_dict()["items"][0]
{'id': 'aspirin',
 'references': [{'id': 'query',
   'structure': {'format': 'smiles', 'value': 'CC(=O)Oc1ccccc1C(=O)O'}}]}

2. Estimate

Ask before you submit. admissible says whether the service will accept it; limits and work show the budgets and what the run would reserve. Runs are created through a Client (client.runs); Client() is your signed-in connection to the API, and it sends no request until you call something.

client = Client()

est = client.runs.estimate(spec)
est["admissible"], est["limits"]
(True, {'items': 1000, 'body_bytes': 5242880, 'result_cells': 100000})
est["work"]
{'items': 4,
 'result_cells': 20,
 'reservation': {'active_runs': 1,
  'queued_items': 4,
  'work_units': 4.0,
  'result_bytes': 40960,
  'model_calls': 0}}

3. Create

create returns after the run is durably accepted, not when it finishes. An idempotency_key is required: it makes the call safe to repeat (see section 9).

run = client.runs.create(spec, idempotency_key="docs-runs-leads-v1")
run.id, run.kind, run.status, run.progress.model_dump()
('run_808b5d37276f409c9aa256229c',
 'selection_batch',
 'queued',
 {'total': 4,
  'pending': 4,
  'running': 0,
  'succeeded': 0,
  'failed': 0,
  'cancelled': 0})

Calling create again with the same key returns the same run, so the status you see may already be final.

4. Follow the events

watch yields events until the run is terminal. Every event carries the progress counters at that moment. Besides the milestones shown here (queued, each item succeeded or failed, completed), the service also emits finer events such as item.started, and item.retrying when it retries an item. after= resumes from a sequence number, so a restarted notebook or script does not replay what it has seen.

MILESTONES = {"run.queued", "item.succeeded", "item.failed", "run.completed"}

rows = [
    (e.sequence, e.type, e.item_id, e.status)
    for e in client.runs.watch(run.id, after=0)
    if e.type in MILESTONES
]
pd.DataFrame(rows, columns=["seq", "event", "item", "status"])
   seq           event         item                 status
0    1      run.queued          NaN                 queued
1    6  item.succeeded      aspirin              succeeded
2    7  item.succeeded    ibuprofen              succeeded
3    8  item.succeeded  paracetamol              succeeded
4   13     item.failed       broken                 failed
5   14   run.completed          NaN  completed_with_errors

To resume, pass the last sequence number you stored:

# resume: only events after the last one you stored (here: the third milestone)
last_seen = rows[2][0]
[(e.sequence, e.type, e.item_id) for e in client.runs.events(run.id, after=last_seen) if e.type in MILESTONES]
[(8, 'item.succeeded', 'paracetamol'),
 (13, 'item.failed', 'broken'),
 (14, 'run.completed', None)]

5. Wait for the end

wait blocks until the run is terminal. Terminal states are completed, completed_with_errors, failed, and cancelled. completed_with_errors is a normal outcome: successful items are kept and no exception is raised. Pass timeout= (seconds) to stop waiting without stopping the run; it raises a DeepMedChemError with code client_timeout.

final = client.runs.wait(run.id)
final.status, final.terminal, final.progress.model_dump()
('completed_with_errors',
 True,
 {'total': 4,
  'pending': 0,
  'running': 0,
  'succeeded': 3,
  'failed': 1,
  'cancelled': 0})

6. Read the results

Each entry has an id (the item ID you gave), a status, and either a result (the same structure as a selection result) or an error. order="completion" (default) can be consumed while the run is active; order="input" returns your original order once it is terminal. The iterator fetches further pages for you.

rows = []
for item in client.runs.iter_results(run.id, order="input"):
    if item.ok:
        top = item.result["results"][0]
        rows.append((item.id, item.status, len(item.result["results"]), top["smiles"], round(top["score"], 2)))
    else:
        rows.append((item.id, item.status, 0, None, None))
pd.DataFrame(rows, columns=["item", "status", "hits", "best hit", "ecfp4"])
          item     status  hits                                 best hit  ecfp4
0      aspirin  succeeded     5                    O=C(O)Oc1ccccc1C(=O)O   0.70
1    ibuprofen  succeeded     5  CC(C(=O)O)c1ccc(CC(Cc2ccccc2)C(=O)O)cc1   0.69
2  paracetamol  succeeded     5            CC(=O)Nc1ccc(-c2ccc(O)cc2)cc1   0.87
3       broken     failed     0                                      NaN    NaN

A failed item keeps its own error

One invalid molecule does not affect its siblings. The error says what failed and for which item:

failed = [item for item in client.runs.iter_results(run.id) if not item.ok]
[(item.id, item.error["message"]) for item in failed], sorted(failed[0].error)
([('broken', 'invalid SMILES')],
 ['attempt_count',
  'code',
  'field',
  'item_id',
  'message',
  'retry_after_seconds',
  'retryable',
  'run_id'])

7. Item status view

iter_items(status=...) lists items by status without their (large) results. Always pass a status.

{
    status: [item.id for item in client.runs.iter_items(run.id, status=status)]
    for status in ("succeeded", "failed")
}
{'succeeded': ['aspirin', 'ibuprofen', 'paracetamol'], 'failed': ['broken']}

8. Run resource and retention

retrieve returns the current state at any time, from any process, as long as you have the run ID.

again = client.runs.retrieve(run.id)
again.status, again.raw["created_at"], again.raw["expires_at"]
('completed_with_errors',
 '2026-10-05T04:36:22.846471Z',
 '2026-11-04T04:36:22.846471Z')

9. Safe retries: idempotency

The same key with the same content returns the original run (no duplicate work). The same key with different content is refused.

from deepmedchem import DeepMedChemError

same = client.runs.create(spec, idempotency_key="docs-runs-leads-v1")
print("same run returned:", same.id == run.id)

other = Run.selection_batch(template=template, items={"ethanol": {"query": "CCO"}})
try:
    client.runs.create(other, idempotency_key="docs-runs-leads-v1")
except DeepMedChemError as e:
    print(e.code, e.status_code, "-", e)
same run returned: True
idempotency_conflict 409 - Idempotency-Key was already used with a different request

10. Cancel

cancel stops queued items; items already running finish. The call returns at once with status cancelling; wait then reports cancelled. Successful items keep their results. Cancelling a finished run is harmless.

import time

molecules = ["CCO", "CCN", "CCC", "CCCC", "c1ccccc1", "CC(=O)O", "CCOC", "CCS", "CCCl", "CCBr",
             "CC#N", "CC=O", "CCCO", "CCCN", "c1ccncc1", "C1CCCCC1", "CC(C)O", "CC(C)N", "OCCO", "NCCN"]
shape_template = (
    Selection.from_database("enamine-real-v5a").ranked()
    .maximize_similarity("cheese.shape", reference="q").limit(20)
)
big = Run.selection_batch(template=shape_template, items={f"m{i:02d}": {"q": s} for i, s in enumerate(molecules)})

slow = client.runs.create(big, idempotency_key="docs-runs-cancel-v1")
time.sleep(2)
cancelling = client.runs.cancel(slow.id)
print("right after cancel:", cancelling.status, cancelling.progress.model_dump())
right after cancel: cancelling {'total': 20, 'pending': 0, 'running': 7, 'succeeded': 1, 'failed': 0, 'cancelled': 12}
done = client.runs.wait(slow.id)
done.status, done.progress.model_dump()
('cancelled',
 {'total': 20,
  'pending': 0,
  'running': 0,
  'succeeded': 8,
  'failed': 0,
  'cancelled': 12})
pd.Series([item.status for item in client.runs.iter_results(slow.id)]).value_counts()
cancelled    12
succeeded     8
Name: count, dtype: int64

11. One selection as a run

Run.selection runs a single selection durably: it keeps going if your client disconnects, and you follow it with the same watch, wait, and iter_results calls. When selections.estimate says a selection is durable, its reusable_run_request is a ready-made run/1 request that you can pass to runs.create.

single = (
    Selection.from_database("enamine-real-v5a")
    .reference("aspirin", smiles=leads["aspirin"]).ranked()
    .maximize_similarity("rdkit.ecfp4_tanimoto", reference="aspirin")
    .limit(50)
)
one = client.runs.create(Run.selection(single), idempotency_key="docs-runs-single-v1")
client.runs.wait(one.id).status
'completed'
item = next(iter(client.runs.iter_results(one.id)))
item.id, item.ok, len(item.result["results"]), item.result["results"][0]["smiles"]
('selection', True, 50, 'O=C(O)Oc1ccccc1C(=O)O')

12. Async

AsyncClient has the same runs methods; iterators use async for.

from deepmedchem import AsyncClient

async with AsyncClient() as aclient:
    state = await aclient.runs.retrieve(run.id)
    ids = [i.id async for i in aclient.runs.iter_results(run.id, order="input")]
state.status, ids
('completed_with_errors', ['aspirin', 'ibuprofen', 'paracetamol', 'broken'])

13. Run errors

problems = {
    "unknown run":       lambda: client.runs.retrieve("run_doesnotexist"),
    "bad item ID":       lambda: client.runs.create(
        Run.selection_batch(template=template, items={"has space": {"query": "CCO"}}),
        idempotency_key="docs-runs-badid-v1"),
    "no idempotency key": lambda: client.runs.create(spec, idempotency_key=""),
}
for label, call in problems.items():
    try:
        call()
    except DeepMedChemError as e:
        print(f"{label:20} {e.code} (HTTP {e.status_code}): {str(e)[:70]}")
    except ValueError as e:
        print(f"{label:20} ValueError (raised locally): {e}")
unknown run          run_not_found (HTTP 404): Run not found.
bad item ID          invalid_schema (HTTP 422): String should match pattern '^[A-Za-z0-9._-]{1,128}$'
no idempotency key   ValueError (raised locally): idempotency_key is required by the supported SDK
client.close()

On this page