# Async jobs

> Run a large table call in the background and fetch its result when it is done.

A table call can take minutes. Sent with `"async": true` (or `?async=true`), it runs in the background instead: the reply comes
at once, and you fetch the result when the job is done. A fit or one-shot predict past its preset's direct size (`fast` 100,000
training rows x 100 columns, `medium` and `pro` 25,000 x 100; [Limits](https://yhatlabs.com/models/docs/resources/limits)) must run this way: sent
directly, it answers `413` with error type `async_required`.

| Method and path | What it does |
|---|---|
| `POST /v1/table/predict`, `POST /v1/table/fits` with `"async": true` | queues the call: `202 {"id": "job_...", "object": "job", "status": "queued"}` |
| `GET /v1/jobs/{id}` | its status, and once it succeeded its `result`: the same reply the direct call gives |
| `GET /v1/jobs` | the project's last 100 jobs |
| `DELETE /v1/jobs/{id}` | cancels a queued or running job: `{"id": ..., "object": "job", "status": "canceled"}` |

```sh
curl https://api.yhatlabs.com/v1/table/fits -H "Authorization: Bearer $YHAT_API_KEY" -H "Content-Type: application/json" \
  -d '{"train": [...], "target": "y", "preset": "pro", "async": true}'
# {"id": "job_3f1c...", "object": "job", "kind": "fit", "model": "chakra-tab", "status": "queued", "created_at": 1761300000}

curl https://api.yhatlabs.com/v1/jobs/job_3f1c... -H "Authorization: Bearer $YHAT_API_KEY"
# {"id": "job_3f1c...", "status": "succeeded", "result": {"id": "fit_...", "object": "fit", ...}, ...}
```

A job goes `queued`, `running`, then `succeeded`, `failed` (with an `error` like any other) or `canceled`. Poll every few
seconds; a job that waits in the queue for 12 hours expires. Canceling a job that has already finished answers `409`. Its
credits are held when it is queued and settled when it ends; a job that fails on our side costs nothing. Jobs show on the
project's Saved models page, under Jobs.

A direct table call that is still running after about 20 minutes comes back as a job too: a `202` with
`{"object": "job", "id": "job_...", ...}` instead of the result. Check `object` and poll `GET /v1/jobs/{id}` as above.

## In Python

The library does all of this for you. A table past the direct size is sent as a job and waited for, and so is a call that
comes back as a job, so `fit` and `predict` return the same result either way. `background=True` returns a `Job` at once:

```python
job = yh.fit(train, "target", preset="pro", background=True)
job.status()             # "queued", "running", "succeeded", "failed" or "canceled"
model = job.wait()       # the fitted model; waits up to two hours by default (timeout=None: as long as it takes)
job.cancel()             # True when it was canceled
```

`job.result()` is the same as `job.wait()`. A failed or canceled job raises `JobFailedError`, whose `job_id` names it.
