# Preparation

> Wait for an upload's preparation, read what it found, confirm its task names and decide its split proposals

Every upload is prepared after it lands. The prepare run sorts the takes into
tasks (task discovery) and gives each task a Task: a published one it matched,
or a draft. It reads the task names the dataset's own metadata gives. Where it
finds idle gaps inside a take, it proposes a split of that take. Everything it
does is a proposal or a flag: every take stays one episode, nothing is removed
and no Task is published. A person or an API key accepts or rejects each split
([below](#review-the-proposed-splits)). `client.preparation` reads and changes
what the dataset page's **Tasks** tab shows.

An older upload can hold splits preparation published itself, as episodes,
before it proposed them. [Undo an old split](#undo-an-old-split) restores those
takes.

Every method takes a dataset id, its full name
(`accounts/{account}/datasets/{dataset}`) or the preparation's name
(`.../preparation`). A merged dataset or a mixture has no run of its own: its
uploads are prepared one by one, so `get` answers state `NONE`. Nothing here
starts a run. `client.preparation` is in qualia-sdk 0.8.0rc12 and later; on
0.8.0rc11 it raises `AttributeError`.

## Read what preparation found

```python
from qualia import Qualia

client = Qualia()

prep = client.preparation.get(dataset_id)
print(prep.state, prep.run_id, prep.error)
for warning in prep.warnings:
    print("warning:", warning)

found = prep.discovery  # None on runs from before discovery
for task in found.tasks if found else []:
    # task_id: the matched Task or the draft ("" when no draft was made);
    # linked_tasks, below, says which
    print(task.name, task.episode_count, task.health_flag, task.task_id)
    print("  references:", task.reference_episode_ids)

names = prep.task_strings  # the dataset's own task names
for c in names.candidates if names else []:
    print(c.key, c.text, c.episode_count, c.blocked_reason, c.confirmation)
```

`state` is `NONE`, `QUEUED`, `RUNNING`, `SUCCEEDED`, `FAILED` or `SKIPPED`.
`discovery.status` is `RUNNING`, `DONE`, `FAILED` or `FALLBACK` (one task for
the whole dataset). A run discovery did not split has its one Task in
`task_match` instead.

A found task with a `task_id` is a Task you can read, edit and publish with
`client.tasks`. One without a Task can become one:

```python
task = client.tasks.create(
    found.tasks[0].name[:32],
    references=[
        {"role": "SUCCESS", "episode": f"{dataset_name}/episodes/{episode}"}
        for episode in found.tasks[0].reference_episode_ids[:3]
    ],
)
client.datasets.update(dataset_name, linked_task=task.name)
```

## Tell an existing Task from a new draft

Preparation links each found task's episodes to a Task: one that already
existed in the account, when it matches, else a draft it writes. The
preparation names the Task (`task_id`) without saying which it is. Only the one
Task of a run that discovery did not split carries `task_match.matched`.
`linked_tasks` reads each named Task's published revisions once and tells them
apart where a publication predates queueing or the server explicitly matched
a published revision. Otherwise a published Task's origin is `UNKNOWN`:

```python
prep = client.preparation.get(dataset_id)
for linked in client.preparation.linked_tasks(dataset_id, preparation=prep):
    print(linked.display_name, linked.origin, linked.revision, linked.publish_time)
    if linked.origin == "EXISTING":
        print("  episodes linked to it now:", linked.linked_episode_count)
        print("  revisions checks use:", linked.linked_revisions)
        print("  their task labels:", linked.labels)
```

| `origin`    | The Task                                                                                                                                                       |
| ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `EXISTING`  | Had a published revision before the prepare run was queued, or the server explicitly matched a published revision. Checks use the stored link revisions        |
| `NEW_DRAFT` | Has no published revision: a draft a prepare run wrote for this upload (this run, or an earlier run of the upload whose draft was kept; the two read the same) |
| `MISSING`   | Cannot be read any more: deleted, or out of the key's reach                                                                                                    |
| `UNKNOWN`   | The available data cannot establish the origin: no known publication predates queueing, or timestamps are missing                                              |

The API has no stable completion timestamp. `update_time` is the last change
and can advance after success when calibration finishes. It cannot distinguish
a draft published after preparation from a Task published during preparation.
`DRAFT_PUBLISHED` and `PUBLISHED_DURING_PREPARATION` remain accepted origin values
for compatibility, but are no longer inferred from that mutable timestamp.

`revision` is the Task's newest published revision (0 for none) and
`publish_time` when that was published; `episode_count` is how many takes the
run sorted into the task. For an `EXISTING` Task, `linked_tasks` reads every
page of its current episode links: `linked_episode_count` is how many are linked to
it now (they may have been linked elsewhere since the run), and `labels` the
task labels they carry with their counts, including the empty label.
`linked_revisions` gives `(revision, episode_count)` pairs from the stored
links, including inherited links; 0 means a draft link. Checks use those
revisions even when `revision` names a newer publication. To judge those
episodes against a Task of your own while keeping every label, including an
empty one, use `link_task`:

```python
cursor = None
while True:
    page = client.episodes.list(
        dataset_id, filter=f'linked_task = "{linked.task}"', cursor=cursor
    )
    for episode in page.items:
        client.episodes.link_task(episode.name, my_task.name)
    if not page.page_info.has_next:
        break
    cursor = page.page_info.end_cursor
```

`linked_tasks` is in qualia-sdk 0.8.0rc14 and later; on 0.8.0rc13 it raises
`AttributeError`.

## Wait for preparation to end

Preparation starts by itself after an upload and takes minutes. The free
checks run on every upload; no setting switches them off. Paid video (VLM)
checks default on and spend credits; an organization, workspace or dataset can
turn them off. An eligible paid check may run after preparation if the current
policy still enables it and admission succeeds.

`wait` covers preparation only. It reads the preparation every `interval`
seconds until it has ended, and returns that reading:

```python
dataset_id = client.data.upload("./takes", "box-pick")["dataset_id"]

prep = client.preparation.wait(
    dataset_id,
    timeout=1800,  # seconds; the default is 3600
    on_progress=lambda p: print(p.state, p.discovery.status if p.discovery else ""),
)
if prep.state == "FAILED":
    raise SystemExit(prep.error)
for warning in prep.warnings:  # for example, task discovery fell back
    print("warning:", warning)
```

| What `get` reads                                                         | What `wait` does                                                                                                                                                                             |
| ------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `NONE`: no prepare run                                                   | Reads again for up to 30 seconds, then returns it. An upload's run is queued as the upload settles; a merged dataset, a mixture and a deployment that does not prepare uploads never get one |
| `QUEUED` or `RUNNING`                                                    | Reads again                                                                                                                                                                                  |
| `QUEUED` or `RUNNING`, `discovery.status` already `FAILED` or `FALLBACK` | Reads again: the run goes on without task discovery. `on_progress` gets this reading at once, and a timeout's message carries `discovery.reason`                                             |
| `SUCCEEDED`                                                              | Returns it. With `discovery.status` `FAILED` or `FALLBACK` it ended with a fallback: `warnings` and `discovery.reason` say why, so check the tasks before publishing one                     |
| `FAILED`                                                                 | Returns it, never raises: `error` says why                                                                                                                                                   |
| `SKIPPED`                                                                | Returns it: there was nothing to prepare                                                                                                                                                     |
| An ended state, `discovery.status` `RUNNING`                             | Reads again: task discovery is running again, after `confirm_task_strings`                                                                                                                   |

`on_progress` is called with each reading whose `state`, `discovery.status` or
`discovery.reason` differs from the one before, the first reading included.
After `timeout` seconds `wait` raises `TimeoutError`, whose message says what
the last reading showed: the state, task discovery's status and reason, the
run and when it last changed. Timing out stops nothing: the run goes on, and
`get` or another `wait` reads it later. A failed read that is transient (a
5xx, a timeout) is retried, as in [`checks.wait`](https://docs.qualia.dev/sdk/resources/checks.md).

`wait` is in qualia-sdk 0.8.0rc14 and later; on 0.8.0rc13 it raises `AttributeError`.

## Confirm the dataset's task names

When `task_strings.confirmable` is true, a person decides which of the
dataset's own task names to use as tasks. The set you send replaces the
decisions on the run's names: a name not listed is cleared, and `[]` clears
them all. Send one choice per usable name, as the Tasks tab does: the ones to
use `confirmed=True` with a Task name of at most 32 characters, the rest
`confirmed=False`.

```python
prep = client.preparation.get(dataset_id)
usable = [
    c for c in prep.task_strings.candidates
    if not c.blocked and not c.looks_like_code
]
client.preparation.confirm_task_strings(
    dataset_id,
    prep.run_id,
    [{"key": c.key, "display_name": "Fold the towel", "confirmed": True}
     for c in usable],
)
```

Confirmed names start task discovery again, which drafts a Task for each.
Read the preparation again to see them, or `wait` for the re-run to end.

| Refusal                   | Why                                                                       |
| ------------------------- | ------------------------------------------------------------------------- |
| 409 `ABORTED`             | A newer run replaced the names you read: read again and decide again      |
| 400 `FAILED_PRECONDITION` | A blocked name (outcome words, a code, already a task label), or no names |
| 400 `INVALID_ARGUMENT`    | A key the run does not have, a key twice, or a name over 32 characters    |
| 403 `PERMISSION_DENIED`   | A workspace's service key: a person decides on task names                 |

A personal API key decides as the person who made it, and the decision records
the key.

## Review the proposed splits

A split proposal names one take and the windows preparation would keep, two
or more, in seconds from the take's start. The gaps between them are the idle
stretches it found. Each of its `cuts`, one per boundary between two windows,
says why preparation would cut there: `start_seconds` (where the next window
starts), the model's `confidence` (`MEDIUM` or `HIGH`) and its `reason`. Runs
from before preparation kept them leave `confidence` unset and `reason` empty.
Nothing is cut until someone accepts.

```python
prep = client.preparation.get(dataset_id)
for take in prep.cuts.takes if prep.cuts else []:
    if take.proposal:
        windows = [(w.start_seconds, w.end_seconds) for w in take.proposal.windows]
        print(take.episode, take.proposal.state, windows)
        for cut in take.proposal.cuts:
            print(f"  cut at {cut.start_seconds:.1f} s", cut.confidence, cut.reason)

# See first what accepting every open proposal of the newest run would do
plan = client.preparation.review_splits(dataset_id, "accept", validate_only=True)
for left in plan.left:
    print("left:", left.episode, left.reason)

client.preparation.review_splits(dataset_id, "accept", [take_a, take_b])
client.preparation.review_splits(dataset_id, "reject", [take_c])
```

Each of `cuts.takes` has its `proposal`. Its `state` is:

- `PROPOSED`: nobody decided yet. The take is one episode.
- `ACCEPTED` or `REJECTED`, with `decided_by` and `decide_time`.
- `SUPERSEDED`: a later run proposed a cut of the same take; that one stands.
- `APPLIED`: a split preparation published before it proposed splits. Head
  holds the pieces (`children`). `undo_refusal` is empty when the take can be
  restored, else it says why not
  ([Undo an old split](#undo-an-old-split)).

```python
review_splits(dataset, decision, episodes=None, *, run_id=None,
              validate_only=False, request_id=None)
```

`review_splits` decides the proposals of one preparation run.
`decision` is `"accept"` or `"reject"`, in any case. With no `episodes` it
decides every open proposal of the run; with no `run_id` the run is the newest
(`get(...).run_id`). `validate_only=True` reports what it would decide and
leave, and writes nothing. `request_id` is an idempotency key: a retry with the
same one and the same arguments answers as the first call did. The SDK makes
one per call when you pass none, except with `validate_only`. The reply lists
the proposals it decided in `reviewed`, as they stand now, and the takes it
left in `left`, each with its reason.

- **Accept** draws the split on the take's draft, as if a person drew it in
  the studio. Each window becomes a kept piece, snapped to the take's frames;
  the gaps and the stretches before the first and after the last window are
  dropped. The dataset does not change: head still holds the take. The pieces
  become episodes in the next version published from a Publish preview, like
  any drawn split. To change or discard it, edit the drawing in the studio or
  call `client.episodes.unsplit`.
- **Reject** closes the proposal and writes nothing else. The take stays as
  it was. A rejected proposal can still be accepted later.

The proposal records who decided and when (`decided_by`, `decide_time`). A
person or an API key decides, as for any drawing; the model and the platform
cannot. A later preparation run that cuts the same take again replaces its open
proposal. Checks read the takes whole, since head holds no proposed pieces.

Accept leaves a take as it is, and the call still succeeds, when:

| Reason in `left`                                    | Why                                                                                 |
| --------------------------------------------------- | ----------------------------------------------------------------------------------- |
| the take has a saved drawing; open it in the studio | A trim, dropped stretch, piece tags or split is saved on its draft                  |
| being edited by _name_                              | Another person has the take open in the studio                                      |
| the take changed since the run read it              | Its recording is not the one the run read (below)                                   |
| the take is no longer in the upload                 | A re-ingest removed it                                                              |
| preparation split this take already; undo it first  | An old split preparation published is still on head ([undo it](#undo-an-old-split)) |

Accept never replaces a saved drawing; the studio shows the proposal next to
it. A take whose plan would keep more than 512 pieces is not proposed: the run
lists it as skipped, with the reason. A proposal already decided, or replaced by
a later run's, is left too, and `left` says which ("the proposal is rejected
already", "a later run proposed another cut of this take").

"Changed" compares the take on the upload's head with the same take in the
version the run read: its frames, time span, video and source file. A re-ingest
or a re-cut changes them; a label edit does not. A window that ends past the
recording counts as changed too.

Preparation publishes no split. When it matches a Task, linking the takes to it
still makes one new version of the upload, as before; with no match it
publishes nothing.

## Undo an old split

Before preparation proposed splits, it published them: each split take's
pieces became episodes of the upload's next version. An undo restores such a
take. The upload gets one new version that holds the take and not its pieces,
however many takes the call restores. The cut becomes an open proposal again,
so a good cut is one accept away.

```python
plan = client.episodes.unsplit_many(dataset_id, preparation=True, validate_only=True)
print(len(plan.restored), "takes can be restored")
for left in plan.left:
    print("left:", left.episode, left.reason)

done = client.episodes.unsplit_many(dataset_id, preparation=True)
print(done.version)  # the upload's new head version
```

```python
unsplit_many(dataset, episodes=None, *, preparation=False,
             validate_only=False, request_id=None)
```

`unsplit_many` restores the takes named in `episodes`, or with
`preparation=True` every take whose preparation split is still on head. Pass
one or the other: both, or neither, raises `ValueError`. `validate_only=True`
reports what it would restore and leave, and writes nothing. `request_id`
works as for `review_splits`. The reply lists `restored` (each take, its
`pieces` now off head, its `proposal`, open again, and a `note`), `left` (each
take and its `reason`) and `version`, the upload's new head version. `version`
is empty with `validate_only` and when nothing was restored.
`client.episodes.unsplit(episode)` restores one take. Nothing undoes old splits
on its own.

An undo only restores a take whose pieces nobody edited. A piece counts as
edited when, after the split, a person, an API key or an operator did any of
these to it:

- kept, rejected, reset or restored it;
- changed a label or its Task link, reviewed its subtasks or assigned it a
  Task;
- raised, edited, converted, withdrawn, dismissed or reopened an issue on it;
- reverted an event on it.

Each of these is recorded, so an action later reset or reverted still counts.
What the model, rules or the platform wrote does not: the split itself,
preparation's Task link, check runs and the issues they found. Nor do replies,
views or being pinned in a version. The take is then left, and `left` names
the piece and the edit ("piece 18.2: relabelled by _name_, _time_").

A drawing saved on a piece's draft also leaves the take ("piece 18.2: a saved
drawing by _name_, _time_"), but only while it is saved: a draft discarded
before the undo leaves no record and does not count. A take or piece someone has open
in the studio is left as "being edited"; try again later. A split a person
published, before splits were drawn on drafts, is never restored: the take is
left, with the reason.

- **Versions that hold a piece keep it.** They train and export the same
  frames as before. The piece's page says its split was undone. To train on
  the whole take, publish a new version, or re-pin a saved dataset (it
  resolves from head).
- **The Task link.** Preparation linked its Task to the pieces. When the take
  has no link of its own and the model linked every piece to the same Task, the
  take gets it. A take with its own link keeps it. Otherwise the take comes back
  unlinked and its `note` says why: "restored without a Task link: its pieces
  were linked to different tasks", "…: only some of its pieces were linked to a
  task" or "…: not every piece was linked to its task by the model". `note` is
  empty when nothing else happened to the take.
- **Checks.** The heuristic checks run again on the restored takes, unless
  automatic heuristic checks are off. No VLM check starts and no credits are
  spent.
- **Repeats.** A take already restored is left as "already restored".

## In the CLI and the dashboard

The CLI has the same: `qualia dataset preparation` (`--wait` waits; its table
tells each Task apart), `qualia dataset confirm-task-names`,
[`qualia dataset splits`](https://docs.qualia.dev/cli/commands.md#qualia-dataset-splits) (short for
`splits list`), `splits accept|reject` and
[`qualia dataset unsplit -d <dataset> --preparation`](https://docs.qualia.dev/cli/commands.md#qualia-dataset-unsplit).

```bash
qualia dataset splits <DATASET_UUID>
qualia dataset splits accept <DATASET_UUID> --all --dry-run
qualia dataset splits reject <DATASET_UUID> <EPISODE_UUID>
qualia dataset unsplit -d <DATASET_UUID> --preparation --dry-run
```

`splits accept`, `splits reject` and `unsplit` print every take, done or left
with its reason, then the count; `unsplit` ends a restored take's line with its
`note` when it has one. They exit 0 when every take was done, 4 when any was
left, and 1 on an error.

In the dashboard, the Preparation card links to the cuts panel on the upload's
v0, with Accept, Reject and Undo split per take. The studio shows an open
proposal on the take's edit line, with Accept and Reject.
