# Data: pipeline backfill

**What you will learn:** how a harness performs a **saga**, which pairs reversible effects
with declared steps to undo them. You will see stages that run tool calls without any model,
a stage that works on every partition at once and retries only what failed, a person's "no" at the last step
undoing every change, and gvn's verifier (the checker that refuses an incomplete machine
before it runs) proving that every way to an undone end passes through the undo.

**Read first:** [Domains](index.md), for what every harness here is made of;
[Software delivery](sdlc.md), the previous example. On concepts:
[Errands](../concepts/errands.md) (stages without a model),
[Workflows](../concepts/workflows.md) and
[Workflows in depth](../concepts/workflows-in-depth.md) (fan-outs, joins and loops), and
[Run context](../concepts/run-context.md).

**Time:** about 25 minutes.

`data/pipeline_backfill` (module `gvn_domains.data.backfill`) rewrites a dataset's bad
daily partitions. It can restore them from their snapshots if the rewrite fails. The run
ends `needs_operator` if restoring or discarding staged data fails.

## Where this harness fits

Every harness in `gvn-domains` is made of the same parts (see
[What a domain harness is made of](index.md#what-a-domain-harness-is-made-of)): a **plan**,
which is a [workflow](../reference/glossary.md#workflow) whose states are stages; tools and
a [policy](../reference/glossary.md#policy) that check every call before it has an effect;
[**ports**](../reference/glossary.md#port), small abstract classes for the outside world
that you implement; a **brief**, the data a run starts with; and the
[`Launcher`](index.md#the-launcher), which runs the harness on a
[Governor](../reference/glossary.md#governor). For the backfill they look like this:

```mermaid
flowchart LR
    brief(["brief: dataset, date range, incident"])
    approver(["a person who approves publishing"])
    subgraph harness ["pipeline_backfill"]
        plan["<b>BackfillRun</b> plan<br/>diagnose · plan · forward steps · undo steps"]
        policy["policy and tools<br/>check every call"]
        plan -- "tool calls" --> policy
    end
    ports[("your ports<br/>Warehouse · Lineage")]
    launcher["<b>Launcher</b>"]
    brief --> launcher
    launcher -- "drives" --> plan
    policy -- "cleared calls" --> ports
    launcher -- "asks" --> approver
    approver -- "approve or deny" --> launcher
```

What sets this harness apart: after the first two stages no model acts at all, and every
change it makes has an undo that the plan declares and the verifier checks.

## The problem

A data pipeline wrote bad data for a date range, and the dataset's daily partitions must be
rewritten. Rewriting means several steps against the warehouse (snapshot, stage, swap,
validate, publish), any of which can fail part way, and the last of which, publishing to
downstream consumers, cannot be undone. Whatever happens, each partition must end either
fully rewritten or fully restored, never half and half.

A run starts with the brief `{"dataset": str, "start": "YYYY-MM-DD", "end": "YYYY-MM-DD",
"incident": str}`, at most 92 partitions (`MAX_PARTITIONS`).

## The plan

A run is a `BackfillRun` [workflow](../concepts/workflows.md). Only the first two stages use
a model:

- `diagnosing` and `planning`: agents find the fault and propose which partitions to
  rewrite with which transform;
- `snapshotting`, `staging`, `swapping`, `validating`, `publishing`: the forward steps,
  each an [`Errand`](../concepts/errands.md): tool calls fixed by code from the plan,
  vetted by the policy and performed by the toolbox, with no model at all;
- `restoring` and `discarding`: the undo steps;
- `published`, `rolled_back`, `aborted`, `needs_operator` or `failed`: the ends.

Here is the plan as gvn draws it from the code (a docs test checks that it still matches).
Each box is a state, `emits` names the work it asks for, and each arrow is labelled with the
input that moves the run along it; `otherwise: stay` means any input not drawn leaves the
run where it is:

```mermaid
stateDiagram-v2
    aborted : emits aborted
    diagnosing : emits diagnose
    discarding : emits discard
    failed : emits failed
    idle : emits idle
    needs_operator : emits needs_operator
    planning : emits plan
    published : emits published
    publishing : emits publish
    restoring : emits restore
    rolled_back : emits rolled_back
    snapshotting : emits snapshot
    staging : emits stage
    swapping : emits swap
    validating : emits validate
    [*] --> idle
    diagnosing --> planning : diagnosed
    diagnosing --> failed : undiagnosed
    discarding --> needs_operator : discard_failed
    discarding --> aborted : discarded_aborted
    discarding --> rolled_back : discarded_rolled_back
    idle --> diagnosing : started
    planning --> snapshotting : planned
    planning --> failed : unplanned
    publishing --> restoring : not_published
    publishing --> published : published_ok
    restoring --> needs_operator : restore_exhausted
    restoring --> discarding : restored
    snapshotting --> aborted : snapshot_failed
    snapshotting --> staging : snapshotted
    staging --> swapping : staged
    staging --> discarding : staging_exhausted
    swapping --> restoring : swap_failed
    swapping --> validating : swapped
    validating --> restoring : invalid
    validating --> publishing : valid
    aborted --> [*]
    failed --> [*]
    needs_operator --> [*]
    published --> [*]
    rolled_back --> [*]
    note right of idle
        otherwise: stay
    end note
```

The table below uses a few workflow words. A **judge** is a
[Decision](../reference/glossary.md#decision) that reads what a stage's child did and picks
the stage's result. A [`ForEach`](../guides/items-and-retries.md) stage starts one child per
item (here, per partition) at once; `Retry` starts a failed item again, a bounded number of
times; and its **join**, here `AllOf`, decides when the stage is over: when every item's
final attempt succeeded, or not
([Joins](../concepts/workflows-in-depth.md#joins-when-is-a-fan-out-over)).

| Stage | Who | How it ends |
|---|---|---|
| `diagnosing` | an agent: `partition_stats`, `upstream_runs`, `record_diagnosis` | `diagnosed` or `undiagnosed` |
| `planning` | an agent: `list_transforms`, `propose_backfill` | `planned` from its successful proposal, or `unplanned` |
| `snapshotting` | one errand: `snapshot_partition` for every planned partition | `snapshotted`, or `snapshot_failed` (nothing visible changed: `aborted`) |
| `staging` | a [`ForEach`](../guides/items-and-retries.md) over the planned partitions, one errand each: `stage_partition`; an errand that does not end `done` is tried again, at most 3 attempts (`Retry`) | an `AllOf` join over each partition's final attempt: `staged`, or `staging_exhausted` |
| `swapping` | one errand: `swap_partition` each | `swapped`, or `swap_failed` to `restoring` |
| `validating` | one errand: `validate_partition` each, row counts against lineage | `valid`, or `invalid` to `restoring` |
| `publishing` | one errand: `publish_backfill`, which needs a person | `published_ok`, or `not_published` to `restoring` |
| `restoring` | a `ForEach` over every partition whose swap was attempted, one errand each: `restore_partition`, at most 3 attempts | `restored`, or `restore_exhausted` (`needs_operator`) |
| `discarding` | one errand: `discard_staged` each | back to `rolled_back` or `aborted`, or `discard_failed` (`needs_operator`) |

The same plan as a table, also rendered from the code: `>` marks the initial state, `*` the
final states, and each row lists the state's output and its transitions.

```text
   state           output          transitions
*  aborted         aborted         -
   diagnosing      diagnose        diagnosed -> planning, undiagnosed -> failed
   discarding      discard         discard_failed -> needs_operator, discarded_aborted -> aborted, discarded_rolled_back -> rolled_back
*  failed          failed          -
>  idle            idle            started -> diagnosing
*  needs_operator  needs_operator  -
   planning        plan            planned -> snapshotting, unplanned -> failed
*  published       published       -
   publishing      publish         not_published -> restoring, published_ok -> published
   restoring       restore         restore_exhausted -> needs_operator, restored -> discarding
*  rolled_back     rolled_back     -
   snapshotting    snapshot        snapshot_failed -> aborted, snapshotted -> staging
   staging         stage           staged -> swapping, staging_exhausted -> discarding
   swapping        swap            swap_failed -> restoring, swapped -> validating
   validating      validate        invalid -> restoring, valid -> publishing
otherwise: stay
```

## The saga

`EFFECTS`, a table in the module, declares for every tool that changes the world what kind
of effect it is and what undoes it, and the plan follows that table. Its keys and undo steps
are the module's tool constants (`SWAP_PARTITION`, `RESTORE_PARTITION`, ...), built without
their ports: they name the tools, as the plan, the policy and the evaluation do (see
[how a harness names its tools](index.md#how-a-harness-names-its-tools)). It is looked up by
the tool and matched by identity, so `EFFECTS[tool]` answers for the tool the harness's
toolbox builds over its ports too; `OWNER` (the stage that owns each code-made call) works the
same way, and `READS`, `RECORDS` and `IRREVERSIBLE` are toolboxes (`tool in IRREVERSIBLE`).
Printed by short name:

```python
from gvn_domains.data.backfill import EFFECTS

for tool, (kind, undo) in EFFECTS.items():
    print(f"{tool.name():<20} {kind:<13} {undo.name() if undo else ''}".rstrip())
```

```text
snapshot_partition   private
stage_partition      undone_by     discard_staged
swap_partition       undone_by     restore_partition
restore_partition    compensation
discard_staged       compensation
publish_backfill     irreversible
```

A snapshot is private (it writes the run's own slot; no reader sees a change), staging is
undone by discarding, a swap by restoring from the snapshot, the two undo steps are
compensations themselves, and publishing is irreversible, so the policy makes a person
approve it.

Every path that leaves after `swapping` started and does not end `published` goes through
`restoring`, which restores **every** partition whose swap was attempted, failed ones
included (a failed swap may have half applied). Every path that leaves after staging goes
through `discarding`. So when a run ends, each planned partition is either fully new
(`published`) or fully restored (`rolled_back`, `aborted`). `needs_operator` is the one end
where that could not be proven, and it says so.

The plan says this to the verifier, not only in prose. It declares two
[compensations](../guides/compensation.md) (a stage that undoes an earlier stage's effect), `staging` undone by `discarding` and `swapping`
undone by `restoring`, and the final states that mean "undone":

```python
from gvn_domains.data.backfill import BackfillRun

plan = BackfillRun.plan()
for pair in plan.compensations():
    print(pair)
print(sorted(state.name() for state in plan.undone()))
```

```text
Compensate('staging', by='discarding', done=['discarded_aborted', 'discarded_rolled_back'])
Compensate('swapping', by='restoring', done=['restored'])
['aborted', 'rolled_back']
```

The plan would not build otherwise: every way the machine can walk into `rolled_back` or
`aborted` leaves `restoring` on `restored` after a swap and `discarding` on a discarded symbol
after staging, restoring first. What the verifier cannot see is data: that `restoring`
restores the right partitions. That is what the `Compensated` check on recorded runs is for
(a check of the harness's evaluation; see [step 6](#6-a-person-approves-and-grading-both-runs)).

## Walking through a run

The steps below follow two runs in the order they happen: one a person declines at the last
step, one a person approves. Each block runs, in order, in the docs tests.

### 1. The outside world: two ports

The harness reaches the warehouse and the pipeline's history only through these two ports;
you implement them. Every effect takes a `key`, an
[idempotency key](../reference/glossary.md#idempotency-key): the same string each time the
same call is delivered, so a port that acts once per key makes a repeat harmless.

| Port | Methods |
|---|---|
| `Warehouse` | `counts(dataset, partitions)`; `snapshot`, `stage`, `swap`, `restore`, `discard` (each on one partition) and `publish(dataset, partitions, run_id, key)`; every effect acts once per key |
| `Lineage` (read only) | `runs(dataset, start, end)`, `transforms(dataset)`, `expected_rows(dataset, partition)` |

This in-memory warehouse holds each partition as a row count and records every effect it
applies. `_once` makes each effect act once per key, as the port requires: a call
re-issued after a crash carries the same key and gets the first answer back.

```python
import typing
from collections.abc import Callable, Iterable

from gvn_domains.data.backfill import Lineage, Warehouse


class Tables(Warehouse):
    """Daily partitions as row counts. Every effect acts once per key."""

    def __init__(self, partitions: list[str], bad_rows: int) -> None:
        self.live = {partition: bad_rows for partition in partitions}
        self.effects = []
        self._snapshots, self._staged, self._done = {}, {}, {}

    def _once(self, key: str, effect: str, act: Callable[[], typing.Any]) -> typing.Any:
        if key not in self._done:
            self._done[key] = act()
            self.effects.append(effect)
        return self._done[key]

    async def counts(self, dataset: str, partitions: Iterable[str]) -> dict[str, int]:
        return {partition: self.live[partition] for partition in partitions}

    async def snapshot(self, dataset: str, partition: str, run_id: str, key: str) -> int:
        slot = (run_id, partition)
        return self._once(key, "snapshot", lambda: self._snapshots.setdefault(slot, self.live[partition]))

    async def stage(self, dataset: str, partition: str, transform: str, run_id: str, key: str) -> int:
        return self._once(key, "stage", lambda: self._staged.setdefault((run_id, partition), 100))
```

The class continues (a subclass of the same name, so each block stays short): the swap
makes the staged copy live, and restore and discard are the undo steps.

```python
class Tables(Tables):
    async def swap(self, dataset: str, partition: str, run_id: str, key: str) -> int:
        def act() -> int:
            self.live[partition] = self._staged.pop((run_id, partition))
            return self.live[partition]

        return self._once(key, "swap", act)

    async def restore(self, dataset: str, partition: str, run_id: str, key: str) -> int:
        def act() -> int:
            self.live[partition] = self._snapshots[(run_id, partition)]
            return self.live[partition]

        return self._once(key, "restore", act)

    async def discard(self, dataset: str, partition: str, run_id: str, key: str) -> bool:
        return self._once(key, "discard", lambda: self._staged.pop((run_id, partition), None) is not None)

    async def publish(self, dataset: str, partitions: Iterable[str], run_id: str, key: str) -> str:
        return self._once(key, "publish", lambda: f"P-{run_id}")


class Pipeline(Lineage):
    async def runs(self, dataset: str, start: str, end: str) -> list[dict[str, str]]:
        return [{"partition": start, "job": "ingest", "version": "v1"}]

    async def transforms(self, dataset: str) -> list[str]:
        return ["v1", "v2"]

    async def expected_rows(self, dataset: str, partition: str) -> int:
        return 100
```

### 2. Building the harness

The catalog builds the harness by its path from your ports (see
[The catalog](index.md#the-catalog)). Two partitions hold 90 rows each where the source
says 100:

```python
from gvn_domains.catalog import Ports
from gvn_domains.directory import catalog

DAYS = ["2026-03-01", "2026-03-02"]
tables = Tables(partitions=DAYS, bad_rows=90)
ports = Ports(mapping={Warehouse: tables, Lineage: Pipeline()})
backfill = catalog().harness(path="data/pipeline_backfill", ports=ports)
```

Here the ports are filed by naming each port class. `Ports.of(...)`, used on the other
pages, would file each object under the nearest abstract class it inherits from, which for
this two-step `Tables` is the first, still abstract, `Tables`, not `Warehouse`. Asking for
`Warehouse` would still find it, because `get` falls back to the one held object that is an
instance of the class asked for.

### 3. What the model may do: diagnose and plan

No real model is used: the function below plays both agents. A fake model, `FunctionModel`,
calls it with the **exchange**, everything the model would be shown (instructions and
messages so far), and it returns a `Reply`, the model's answer; a `ToolCall` in it asks for
a tool, and a message with role `TOOL` carries results back.

The model plays two agents. The diagnoser reads the partition statistics and records a
diagnosis; the planner proposes the two partitions and transform `v2`. `DIAGNOSE` and `PLAN`
are the two agents' instructions, exported by the module:

```python
from gvn.harness.messages import TOOL, Message, ToolCall
from gvn.harness.ports import Exchange, Reply
from gvn.testing.fakes import FunctionModel
from gvn_domains.data.backfill import DIAGNOSE, PLAN


def call(name: str, **arguments: typing.Any) -> Reply:
    tool_call = ToolCall(call_id="c1", name=name, arguments=arguments)
    return Reply(message=Message.assistant(text="", calls=[tool_call]))


def backfill_model(exchange: Exchange) -> Reply:
    tool_results = [message for message in exchange.messages() if message.role() == TOOL]
    if exchange.instructions() == DIAGNOSE:
        if not tool_results:
            return call("partition_stats")
        if len(tool_results) == 1:
            return call("record_diagnosis", fault="10 rows short a day", cause="ingest v1")
    if exchange.instructions() == PLAN and not tool_results:
        return call("propose_backfill", partitions=DAYS, transform="v2")
    return Reply(message=Message.assistant(text="Done."))


model = FunctionModel(respond=backfill_model)
```

None of these tools takes a dataset or a run: those come from the
[run context](../concepts/run-context.md), and `propose_backfill` may only name partitions
inside the brief's date range.

### 4. The forward steps, without a model

Start the run. The [`Launcher`](index.md#the-launcher) takes the harness, the model and
three more test fakes from `gvn.testing.fakes`
([Testing your harness](../concepts/testing.md)): `MemoryJournal` keeps the journal in
memory, `RecordingOutput` keeps what would be shown, and `ManualClock` moves only when
moved. `start` drives the run until it finishes or must wait; `pending()` lists the
requests it waits on, and `origin()` names the actor that asked (`bf-1/publishing.1`: the
first visit of stage `publishing`). After planning, every stage is an errand built by code
from the plan. The run goes as far as it can before a person must decide:

```python
import asyncio

from gvn.testing.fakes import ManualClock, MemoryJournal, RecordingOutput
from gvn_domains.launcher import Launcher

launcher = Launcher(
    harness=backfill,
    model=model,
    journal=MemoryJournal(),
    output=RecordingOutput(),
    clock=ManualClock(),
)
brief = {"dataset": "sales.orders", "start": "2026-03-01", "end": "2026-03-02", "incident": "INC-9"}
waiting = asyncio.run(launcher.start(run_id="bf-1", brief=brief))
request = waiting.pending()[0]
print(waiting.status(), request.origin())
print(tables.effects)
print(tables.live)
```

```text
waiting bf-1/publishing.1
['snapshot', 'snapshot', 'stage', 'stage', 'swap', 'swap']
{'2026-03-01': 100, '2026-03-02': 100}
```

Both partitions were snapshotted, staged (a fan-out, one errand per partition), swapped and
validated against lineage. The data is live, but not yet published: the `publishing` errand
asked for `publish_backfill`, which needs a person.

An [errand](../concepts/errands.md) is a small actor of its own. It uses the agent's
request kinds (asking the policy, asking a person, running tools), so the policy vets
each call of the batch and a person approves the calls that need it. Its calls are fixed by
code, so each `FixedCall` names its tool as an object, and the errand records the tool's
[identity](../concepts/tools.md#two-names-the-short-name-and-the-identity) beside the call.
You can build one by hand and see its first request:

```python
from gvn.harness.errand import Errand
from gvn.harness.events import Event

from gvn.harness.tools import FixedCall
from gvn_domains.data.backfill import SWAP_PARTITION

swap_call = FixedCall("c0", SWAP_PARTITION, {"partition": "2026-03-01"})
errand = Errand(
    name="bf-17/swapping.1",
    calls=[swap_call],
    context={"dataset": "sales.orders", "run": "bf-17"},
)
(first_request,) = errand.handle(Event("started")).requests()
print(first_request.request_id(), first_request.kind().name())
```

```text
bf-17/swapping.1/consult_policy consult_policy
```

### 5. A person declines: the saga undoes everything

The person says no (`deny`, the opposite of `approve`). The run cannot publish, so it
compensates:

```python
declined = asyncio.run(launcher.deny(run_id="bf-1", request=request))
print(declined.outcome().state())
print(tables.effects[6:])
print(tables.live)
```

```text
State('rolled_back')
['restore', 'restore', 'discard', 'discard']
{'2026-03-01': 90, '2026-03-02': 90}
```

`publishing` ended `not_published`, so the run went through `restoring` (every attempted
swap restored from its snapshot) and `discarding`, and ended `rolled_back`: both partitions
hold their original 90 rows again.

`staging` and `restoring` show wide fan-out with partial failure: one child per partition,
and a partition whose errand failed is tried again at once, as a new child with new keys,
while the others carry on; the join waits for each partition's final attempt. Which
partitions are rewritten, retried and restored is computed from the workflow's Memo (its
record of every finished stage visit, see
[Workflows in depth](../concepts/workflows-in-depth.md#the-memo-in-full)), so it is in the
journal and visible to replay.

### 6. A person approves, and grading both runs

A second run over the same warehouse, approved this time. `grade` checks each finished run
against the harness's evaluation, its statement of what a good run looks like
([Replay and evaluation](../guides/replay-and-evaluation.md#step-6-evaluations-and-scorecards)):

```python
tables.effects.clear()
waiting = asyncio.run(launcher.start(run_id="bf-2", brief=brief))
approved = asyncio.run(launcher.approve(run_id="bf-2", request=waiting.pending()[0]))
print(approved.outcome().state(), tables.effects[-1])
print(tables.live)
for run in ("bf-1", "bf-2"):
    print(run, asyncio.run(launcher.grade(run_id=run)).passed())
```

```text
State('published') publish
{'2026-03-01': 100, '2026-03-02': 100}
bf-1 True
bf-2 True
```

The evaluation: the run finishes `published`, `rolled_back` or `aborted`; nothing is
rejected; `publish_backfill` never succeeds before a person approved it
(`Gated(IRREVERSIBLE)`, the tools `EFFECTS` marks irreversible; a check
on the recorded run; see
[checking a safety rule](../concepts/testing.md#checking-a-safety-rule-on-recorded-runs));
a run that swapped and did not publish restored every attempted swap (`Compensated`); and at
most a number of events that grows with the width of the brief's range (a computed
`Within`). `Gated` sees the errand's `publish_backfill` call, because it reads the requests
every actor makes. A rolled-back run is a good run: it did what it must when it could not
publish.

## Policy

The policy gives every call one of three verdicts: `cleared` (it runs), `needs_approval` (a
person is asked first) or `forbidden` (it never runs). It clears reads, the diagnosis,
proposals and the reversible effects;
`publish_backfill` needs a person's approval; anything else, and any call the scope rules
below refuse, is forbidden.

## What is enforced before any effect

Every child's [run context](../concepts/run-context.md) is the brief plus `"run"` (which
keys the run's snapshot and staging slots). Errands also get the plan; a per-partition errand
gets a plan narrowed to its own partition, so its context names nothing else it could
touch. One rule set, `permitted(tool, origin, context, arguments=None)`, is used by the policy
and again by every tool:

- `propose_backfill` may only name partitions inside the brief's date range;
- a partition effect needs the partition in the range **and** in the plan, and the call
  must come from the stage that owns that tool in the module's `OWNER` table
  (`SWAP_PARTITION` only from `swapping`, `RESTORE_PARTITION` only from `restoring`, and so
  on), read from the caller's name;
- `publish_backfill` only from `publishing`, in a context with a plan;
- no tool takes a dataset, a date range or a run: those come from the context.

## What this harness uses from gvn

The backfill is the package's example of compensation and of wide fan-out with partial
failure. Every stage but planning is the model-free stage, `Errand`. The fan-out over
partitions is `ForEach` with `Retry`, and the saga rule is a declared `Compensate` that the
verifier proves. Its evaluation uses a `Gated` that sees every actor and a computed `Within`.
The [domains overview](index.md#what-the-harnesses-use-from-gvn) lists these parts of gvn across all the harnesses.

## What the harness computes itself

- **Which partitions to undo.** The verifier proves that every undone end passes through
  `restoring` and `discarding`; that they restore and discard the right partitions is data,
  computed from the Memo and checked on recorded runs by `Compensated`.
- **Keys across retries.** A retry is a new child, so its calls have new keys; the
  warehouse's slots, keyed by run and partition, are what make a repeated stage or restore
  harmless.

Its own tests are in `packages/gvn-domains/tests/test_dom_data_*.py`.

## Recap

- `EFFECTS` declares each effect's undo; the plan declares the same pairs with `Compensate`,
  and the verifier proves every undone end passes through `restoring` and `discarding`.
- `staging` and `restoring` are `ForEach` stages: one errand per partition, retried a
  bounded number of times.
- After planning, no model acts: errands built from the plan make every call, through the
  same policy and approval as an agent's.
- A declined publication ends `rolled_back` with every partition restored; only
  `needs_operator` admits that this could not be proven.
- Scope (partitions, stage, dataset, run) is checked by one rule set, in the policy and
  again in every tool.

**Next:** [Education](education.md), where a harness holds a conversation with a learner.
