# Safe automation

Keep track of submissions, recover from timeouts, and decide when to retry, cancel, or resume work.

Keep a record of what you submitted and the job ID Phi returned. A network failure tells you that your script did not receive an answer. It does not tell you whether Phi started the job.

## Check the price before submitting

Use `POST /v1/jobs/estimate` with the same `job_type`, `inputs`, and `params` you intend to submit. An estimate does not start work. Review its price and your organization's balance before approving a submission. The [HTTP reference](/docs/api/jobs) describes both requests, and [Billing](/docs/billing) explains credit reservations.

The example below starts one ESMFold job when you run it for the first time. It is a billable submission, not an estimate.

## Save the request before sending it

Give each intended submission its own explicit idempotency key. Save the key and the exact request before making the call. Save the returned job ID immediately afterward. Keep that record across process restarts.

Do not generate a fresh key inside a retry loop. Do not change the inputs while reusing a key: a key identifies a submission, not a model or a project.

The CLI and SDK can derive a key when one is omitted. Use an explicit, saved key for automation so that a clock boundary or a change to the request does not silently change its identity.

## Know what reusing a key does

| Existing work for the same organization and key | What a repeat submission does | What your script should do |
| --- | --- | --- |
| No existing run | Starts a new run | Save its returned ID |
| Pending or running | Returns the existing run | Follow that ID |
| Completed | Returns the existing run | Read its results |
| Failed | Can start a new attempt because Phi releases the failed run's key | Inspect the failure and approve another attempt first |
| Cancelled or in error | Returns the existing run while it still owns the key | Inspect the run before deciding on a new submission |
| Deleted | Returns a conflict for a key still owned by deleted work | Decide whether to restore the run or intentionally start new work |

A key is not an unconditional guarantee that work executes only once. In particular, a retry after a failed run may start another run. If the first response was lost and you do not know its ID, inspect Work or your recent jobs before submitting again. Do not blindly replay an uncertain submission.

## Continue a known job after restarting

This single-worker example keeps a local journal. On a restart, it follows a saved job ID. If a previous submit may have been sent but its answer was not saved, it stops for investigation instead of submitting again.

The request timeout and wait timeout below are example choices for this script, not service limits. Keep the journal with the project. Use a transactional store and one owner per submission when several workers share the work.

```python

from pathlib import Path
from uuid import uuid4

from phi import PhiClient, PhiTimeoutError

journal = Path("phi-submission.json")

def save(state):
    temporary = journal.with_suffix(".tmp")
    temporary.write_text(json.dumps(state, indent=2))
    temporary.replace(journal)

if journal.exists():
    state = json.loads(journal.read_text())
else:
    state = {
        "attempted": False,
        "request": {
            "job_type": "ESMFOLD",
            "inputs": {"sequences": ["NLYIQWLKDGGPSSGRPPPS"]},
            "idempotency_key": str(uuid4()),
        },
    }
    save(state)

with PhiClient(base_url="https://api.dynophi.com", timeout=60) as phi:
    if "job_id" not in state:
        if state["attempted"]:
            raise SystemExit(
                "Submission outcome unknown. Inspect Work before trying again. "
                "Keep phi-submission.json for investigation."
            )
        state["attempted"] = True
        save(state)
        submitted = phi.jobs.submit(**state["request"])
        state["job_id"] = submitted.job_id
        save(state)

    try:
        job = phi.jobs.wait(state["job_id"], timeout=300)
    except PhiTimeoutError:
        raise SystemExit(
            f"Stopped waiting for {state['job_id']}. The job may still be running. "
            "Run this script again to check the same job."
        )

    if job.status != "COMPLETED":
        raise SystemExit(
            f"Job {state['job_id']} ended as {job.status}. "
            "Inspect its error before starting more work."
        )

    artifacts = phi.artifacts.list(state["job_id"])
    manifest = phi.artifacts.download(artifacts, "results")
    print(manifest)
```

Do not delete the journal to recover from an error. Removing it makes the next invocation a new submission. After reviewing a completed or failed request, archive its journal and use a new journal for intentionally new work.

## Separate the two timeouts

`PhiClient(timeout=...)` limits HTTP requests. A request timeout can happen while Phi is still accepting a submit, reading a status, or serving a download. A transport failure may have no HTTP status or response body.

`phi.jobs.wait(..., timeout=...)` limits how long your script waits for the job. It does not cancel the job. Keep its ID and check it again later. A wait can also raise after repeated transport or server failures; that is not evidence that the job itself failed.

The waiter returns a failed or cancelled job rather than raising for its terminal status. Check `job.status` before reading results. [Errors and retries](/docs/reference/errors) describes the client's automatic read retries.

## Cancel or resume deliberately

Cancel a pending or running job with `phi jobs cancel JOB_ID`, then read its status to confirm the outcome. Cancellation can race with completion. A completed job cannot be cancelled, and a client timeout does not cancel it for you.

`phi runs resume RUN_ID` asks Phi to resume an eligible failed run. It is a write that can restart computation. Inspect the run's error, timeline, and input first. The API accepts only `FAILED` runs for resume and may reject an older run that lacks the snapshot needed to resume safely. Cancellation and resume are not interchangeable with submitting a new job.

Deleting a completed run does not undo its charge. Failed and cancelled runs return their whole credit hold; [Billing](/docs/billing) explains the balance you can spend.

## Recover a result download

An expired artifact URL does not mean the run has disappeared. List that run's artifacts again to obtain fresh URLs, then download the files. Retrying a download is separate from submitting the model again. See the [artifacts SDK reference](/docs/sdk/artifacts).

---
Source: https://dynophi.com/docs/guides/safe-automation
