# Software delivery: the release train

**What you will learn:** how a harness lets its [policy](../reference/glossary.md#policy)
look at a call's arguments (staging is cleared, production needs a person), stops a stage
of several agents early on the first bad verdict, and rolls back on its own when production
cannot be observed healthy. You will release one version and watch another roll back.

**Read first:** [Domains](index.md), for what every harness here is made of;
[Enterprise](enterprise.md), the previous domain page, for errands, joins and approvals;
[Workflows in depth](../concepts/workflows-in-depth.md) (joins), [Errands](../concepts/errands.md) and
[Run context](../concepts/run-context.md).

**Time:** about 25 minutes.

`sdlc/release_train` (module `gvn_domains.sdlc.release`) takes a release candidate to
production, or stops it safely: assess every change, deploy to staging, check health, ask a
person for the go/no-go, watch production, and roll back if production cannot be observed
healthy. It orchestrates and gates; it writes no code.

## 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 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 release train they look like this:

```mermaid
flowchart LR
    brief(["brief: the release"])
    approver(["a person: go or no-go"])
    subgraph harness ["release_train"]
        plan["<b>ReleaseRun</b> plan<br/>assess · stage · verify · gate · observe · roll back"]
        policy["policy and tools<br/>staging cleared, production needs a person"]
        plan -- "tool calls" --> policy
    end
    ports[("your ports<br/>Changes · Deployments")]
    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: the same tool is safe or dangerous depending on its
arguments, and the plan declares an undo (the rollback) that the verifier checks.

## The problem

Version 2.4.0 of the billing service bundles two merged changes. Someone must judge each
change's risk, try the release on staging, and decide go or no-go before production
changes. Staging is cheap to touch; production is not. And if production turns out broken,
the fix (putting the previous release back) must not wait for someone to wake up.

## The plan

A run is a `ReleaseRun` [workflow](../concepts/workflows.md). Its stages host agents where
judgement is needed and [errands](../concepts/errands.md) (small actors that make fixed
tool calls with no model) everywhere else:

- `assessing`: one assessor agent per change, all at once;
- `staging`: an errand deploys the version to staging;
- `verifying`: an errand checks staging's health;
- `gating`: an agent writes release notes and asks to `promote`, which needs a person;
- `observing`: an errand checks production's health;
- `rolling_back`: an errand rolls the service back;
- `released`, `rolled_back`, `held` or `failed`: the run is over.

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
    assessing : emits assess
    failed : emits failed
    gating : emits gate
    held : emits held
    idle : emits idle
    observing : emits observe
    released : emits released
    rolled_back : emits rolled_back
    rolling_back : emits roll_back
    staging : emits stage
    verifying : emits verify
    [*] --> idle
    assessing --> failed : assessment_failed
    assessing --> staging : low_risk
    assessing --> held : too_risky
    gating --> failed : gating_failed
    gating --> held : not_promoted
    gating --> failed : promote_failed
    gating --> observing : promoted
    idle --> assessing : started
    observing --> released : healthy
    observing --> rolling_back : unhealthy
    observing --> rolling_back : unobserved
    rolling_back --> failed : not_reverted
    rolling_back --> rolled_back : reverted
    staging --> failed : not_staged
    staging --> verifying : staged
    verifying --> gating : healthy
    verifying --> failed : unhealthy
    verifying --> failed : unobserved
    failed --> [*]
    held --> [*]
    released --> [*]
    rolled_back --> [*]
    note right of idle
        otherwise: stay
    end note
```

In the table, a stage with several children at once is a **fan-out**; its **join** decides
when it is over ([Joins](../concepts/workflows-in-depth.md#joins-when-is-a-fan-out-over));
a **judge** is a [Decision](../reference/glossary.md#decision) that reads what a stage's
child did and picks the stage's result
([Judges](../concepts/workflows-in-depth.md#judges-deciding-on-what-a-child-said)).

| Stage | Who | How it ends |
|---|---|---|
| `assessing` | one assessor agent per change, at once: `change_details`, `test_report`, `assess` | the `Worst` join over a risk classification: at once `assessment_failed` if an assessor failed, or `too_risky` if one assessed its change high or finished without assessing it (the others are stopped); `low_risk` once all assessed low or medium |
| `staging` | an [errand](../concepts/errands.md): `deploy` to staging, the release's version | `staged` or `not_staged` |
| `verifying` | an errand: `health` of staging | `healthy`; `unhealthy` or `unobserved` (the check did not run) fail the run |
| `gating` | an agent: `promote` (needs a person) | a judge on the `promote` attempts: `promoted` when one ran; `not_promoted` when a person denied it (or the policy forbade it), leaving production untouched; `promote_failed` when it was approved but failed, since it may have half changed production |
| `observing` | an errand: `health` of production | `healthy`; `unhealthy` or `unobserved` go to `rolling_back` |
| `rolling_back` | an errand: `rollback` of the release's service | `reverted` or `not_reverted` |

Only two jobs need a model: assessing a change, and writing the release notes at the gate.
Every step fully determined by the release is an errand, with no model to get it wrong.
Every branch is decided from what the tools did, never from what the model says.
`interrupted` and `resumed` (a person pausing and continuing the run, see
[Humans and interruption](../concepts/human-in-the-loop.md)) are passed on to the active
children.

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
   assessing     assess       assessment_failed -> failed, low_risk -> staging, too_risky -> held
*  failed        failed       -
   gating        gate         gating_failed -> failed, not_promoted -> held, promote_failed -> failed, promoted -> observing
*  held          held         -
>  idle          idle         started -> assessing
   observing     observe      healthy -> released, unhealthy -> rolling_back, unobserved -> rolling_back
*  released      released     -
*  rolled_back   rolled_back  -
   rolling_back  roll_back    not_reverted -> failed, reverted -> rolled_back
   staging       stage        not_staged -> failed, staged -> verifying
   verifying     verify       healthy -> gating, unhealthy -> failed, unobserved -> failed
otherwise: stay
```

The plan also declares that `rolling_back` [compensates](../guides/compensation.md) (undoes)
the promotion in `gating`, and that `rolled_back` is the "undone" end. The verifier proves, before
any run, that every way to `rolled_back` after the promotion leaves `rolling_back` on
`reverted`. A rollback that fails ends `failed`, not `rolled_back`:

```python
from gvn_domains.sdlc.release import ReleaseRun

print(ReleaseRun.plan().compensations())
```

```text
(Compensate('gating', by='rolling_back', done=['reverted']),)
```

## Walking through a run

The blocks below run in order, as one program, in the docs tests.

### 1. The outside world: two ports

The harness reaches the outside world only through these two ports; you implement them. A
method that changes something takes a `key`, an
[idempotency key](../reference/glossary.md#idempotency-key): a port that performs one change
per key turns a repeated request into a no-op.

| Port | Methods |
|---|---|
| `Changes` (read only) | `details(change)`, `test_report(change)` |
| `Deployments` | `deploy(environment, version, key)`, `promote(version, notes, key)`, `rollback(service, key)`: each performs one change per key; `health(environment)` |

The cluster below records each change it makes, under its key. Production is healthy unless
the version promoted is in `broken`:

```python
import typing

from gvn_domains.sdlc.release import Changes, Deployments


class Merged(Changes):
    async def details(self, change: str) -> dict[str, str]:
        return {"title": change, "summary": "A small fix."}

    async def test_report(self, change: str) -> dict[str, int]:
        return {"passed": 120, "failed": 0}


class Cluster(Deployments):
    def __init__(self, broken: tuple[str, ...] = ()) -> None:
        self.broken, self.production, self.changes = set(broken), None, {}

    async def deploy(self, environment: str, version: str, key: str) -> str:
        return self.changes.setdefault(key, f"{environment}:{version}")

    async def promote(self, version: str, notes: str, key: str) -> str:
        self.production = version
        return self.changes.setdefault(key, f"release:{version}")

    async def rollback(self, service: str, key: str) -> str:
        self.production = "previous"
        return self.changes.setdefault(key, f"rollback:{service}")

    async def health(self, environment: str) -> str:
        bad = environment == "production" and self.production in self.broken
        return "unhealthy" if bad else "healthy"
```

### 2. Building the harness

The catalog builds the harness by its path from your ports (see
[The catalog](index.md#the-catalog)). A run starts with the brief
`{"release": {"version": str, "changes": [str, ...], "service": str}}`.

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

cluster = Cluster(broken={"2.4.1"})
train = catalog().harness(path="sdlc/release_train", ports=Ports.of(Merged(), cluster))
release = {"version": "2.4.0", "changes": ["PR-12", "PR-15"], "service": "billing"}
for identity in train.toolbox().identities():
    print(identity)
```

```text
gvn_domains.sdlc.release.assess
gvn_domains.sdlc.release.change_details
gvn_domains.sdlc.release.deploy
gvn_domains.sdlc.release.health
gvn_domains.sdlc.release.promote
gvn_domains.sdlc.release.rollback
gvn_domains.sdlc.release.test_report
```

The toolbox lists each tool by its
[identity](../concepts/tools.md#two-names-the-short-name-and-the-identity): the module that
defines it, a dot and the short name the model sees. The module names the same tools with
constants built without their ports (`DEPLOY`, `PROMOTE`, `ROLLBACK`, `HEALTH`, and the
assessors' `ASSESSING_TOOLS`); the plan offers and declares them, the errands call them, and
the policy and evaluation match on them (see
[how a harness names its tools](index.md#how-a-harness-names-its-tools)).

### 3. What the model may do, and what needs a person

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 sees each call's arguments:

- reading changes, recording an assessment and checking health are cleared;
- `deploy` is cleared only when its `environment` is exactly `"staging"`, and otherwise
  needs approval, like `promote`: whatever is not provably staging is treated as production;
- `rollback` is cleared: it restores the release a person already approved, only the
  release's own service can be rolled back, and a broken production must not wait for
  someone to wake up;
- anything else is forbidden. Each call of a reply gets [its own verdict](../concepts/reference-agent.md#one-verdict-per-call), so a
  person is asked only about the calls that need one.

Ask it directly with a `Consultation`, the question a policy answers: the calls, the
identity of each call's tool (the policy matches by identity), the `origin` (the address of
the actor asking) and the [run context](../concepts/run-context.md), which here is the
release.

```python
from gvn.harness.messages import ToolCall
from gvn.harness.tools import Consultation, Tool
from gvn_domains.sdlc.release import DEPLOY, ROLLBACK


def verdict(tool: Tool, arguments: dict[str, typing.Any]) -> str:
    call = ToolCall(call_id="c1", name=tool.name(), arguments=arguments)
    consultation = Consultation(
        calls=[call], identities=[tool.identity()], origin="rel/staging.1", context=release
    )
    return train.policy().decide(consultation).name()


print(verdict(DEPLOY, {"environment": "staging", "version": "2.4.0"}))
print(verdict(DEPLOY, {"environment": "production", "version": "2.4.0"}))
print(verdict(DEPLOY, {"environment": "staging", "version": "2.5.0"}))
print(verdict(ROLLBACK, {"service": "auth"}))
```

```text
cleared
needs_approval
forbidden
forbidden
```

Staging is cleared, production goes to a person, another version and another service are
refused before anyone is asked.

### 4. A model for the assessors and the gatekeeper

No real model is used: the function below plays every agent. A fake model 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.

Each assessor reads its change and records a low risk. The gatekeeper asks to promote the
version with release notes. The module exports both instructions (`ASSESS`, `GATE`); each
agent's prompt names its change (`Change: PR-12`) or the version (`Version: 2.4.0`).

```python
from gvn.harness.messages import TOOL, Message
from gvn.harness.ports import Exchange, Reply
from gvn_domains.sdlc.release import ASSESS, GATE


def calling(*calls: tuple[str, dict[str, typing.Any]]) -> Reply:
    tool_calls = [
        ToolCall(call_id=f"c{number}", name=name, arguments=arguments)
        for number, (name, arguments) in enumerate(calls)
    ]
    return Reply(message=Message.assistant(text="", calls=tool_calls))


def field(exchange: Exchange, label: str) -> str:
    lines = exchange.messages()[0].text().splitlines()
    return next(line.removeprefix(f"{label}: ") for line in lines if line.startswith(label))


def release_model(exchange: Exchange) -> Reply:
    results = [r for m in exchange.messages() if m.role() == TOOL for r in m.results()]
    if exchange.instructions() == ASSESS:
        change = field(exchange, "Change")
        if not results:
            details = ("change_details", {"change": change})
            return calling(details, ("test_report", {"change": change}))
        if len(results) == 2:
            return calling(("assess", {"risk": "low", "note": "small, tests pass"}))
    if exchange.instructions() == GATE and not results:
        version = field(exchange, "Version")
        return calling(("promote", {"version": version, "notes": f"Release {version}."}))
    return Reply(message=Message.assistant(text="Done."))
```

### 5. Assessing, staging and the go/no-go

The [`Launcher`](index.md#the-launcher) runs the harness with four test fakes from
`gvn.testing.fakes` ([Testing your harness](../concepts/testing.md)): `FunctionModel`
answers with `release_model`, `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 (`rel-2.4.0/gating.1`: the first visit
of stage `gating`).

```python
import asyncio

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

launcher = Launcher(
    harness=train,
    model=FunctionModel(respond=release_model),
    journal=MemoryJournal(),
    output=RecordingOutput(),
    clock=ManualClock(),
)
waiting = asyncio.run(launcher.start(run_id="rel-2.4.0", brief={"release": release}))
go_no_go = waiting.pending()[0]
print(waiting.status(), go_no_go.origin())
```

```text
waiting rel-2.4.0/gating.1
```

What happened:

1. **Assessing.** A fan-out started one assessor per change. Its join is `Worst`: it ranks
   the verdicts and can end as soon as one is bad (one failure or one high risk stops the
   others at once). Both changes were assessed low, so the stage ended `low_risk`.
2. **Staging and verifying.** Two errands deployed 2.4.0 to staging (cleared: the
   environment is exactly `"staging"`) and checked its health.
3. **Gating.** The go/no-go **is** the production change: the gating agent calls
   `promote(version, notes)`, which needs a person's approval. The notes are part of the
   action, since they are published with the release, and the approver also sees the
   agent's explanation and the release itself.

### 6. Go: released

`approve` delivers a person's yes and drives the run on; `grade` checks the 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
released = asyncio.run(launcher.approve(run_id="rel-2.4.0", request=go_no_go))
print(released.outcome().state(), cluster.production)
print(asyncio.run(launcher.grade(run_id="rel-2.4.0")).passed())
```

```text
State('released') 2.4.0
True
```

After the promotion, the `observing` errand read production's health, found it healthy, and
the run ended `released`. Had the person said no, the stage would have ended `not_promoted`
and the release `held`, with production untouched.

### 7. A broken production rolls back on its own

Version 2.4.1 is broken in production in this cluster. The run goes through the same steps,
a person approves, and then production is observed unhealthy:

```python
patch = {**release, "version": "2.4.1"}
waiting = asyncio.run(launcher.start(run_id="rel-2.4.1", brief={"release": patch}))
request = waiting.pending()[0]
after = asyncio.run(launcher.approve(run_id="rel-2.4.1", request=request))
print(after.outcome().state(), cluster.production)
for key in sorted(cluster.changes):
    print(key)
```

```text
State('rolled_back') previous
deploy:staging:billing:2.4.0
deploy:staging:billing:2.4.1
promote:production:billing:2.4.0
promote:production:billing:2.4.1
rollback:production:billing:2.4.1
```

The `observing` errand saw `unhealthy`, so the run went to `rolling_back`, whose errand is
cleared by the policy: nobody was asked. Production that cannot be observed healthy is rolled
back, whether the check said `unhealthy` or did not run at all (`unobserved`).

Notice the keys the cluster received. They are not the tool calls' own keys but
`effect_key`: a key naming the change from the trusted release
(`"<tool>:<environment>:<service>:<version>"`). The next section explains why.

The evaluation: the run finishes `released`, `rolled_back` or `held`, nothing is rejected,
it takes at most 60 events, and no call that touches production succeeded without a person's
approval: `Gated([DEPLOY, PROMOTE], when=changes_production)`, a check on the recorded run
([checking a safety rule](../concepts/testing.md#checking-a-safety-rule-on-recorded-runs))
whose `when` function picks the calls it gates, so a `deploy` to staging is not gated and
one to production is.

## What is enforced before any effect

Every agent's and errand's [run context](../concepts/run-context.md) is the release
(`version`, `changes`, `service`), and each assessor is built for one change.

- The tools refuse a change outside the release, a `deploy` or `promote` of another
  version, and a `rollback` of another service. `assess` takes the change it assesses from
  its context.
- The policy forbids the same calls, so a person is never even asked to approve them, and
  forbids these tools in a run with no release in its context.
- `deploy`, `promote` and `rollback` pass the `Deployments` port a key naming the change
  from the trusted release (`effect_key`), and the port performs one change per key. The
  call's own key covers a crash, but a call the agent makes again after an interrupt is a
  new call with a new key; the release-derived key covers both.

## What this harness uses from gvn

This harness uses three parts of gvn (see the [domains overview](index.md#what-the-harnesses-use-from-gvn)): the model-free step (`Errand`), the
`Worst` join and `Gated([tool, ...], when=...)`. `Gated` with `when`
lets the evaluation gate by arguments, as the policy does: a `deploy` to staging is not
gated, one to production is.

## What the harness and its ports supply

- **Effect keys across interrupts.** The release-derived `effect_key` is what makes a
  production change happen once even when the gating agent is interrupted and asked again.
- **Health.** Staging and production are judged on the `health` port's `"healthy"` or
  `"unhealthy"`; anything richer belongs in that port.

The harness's own tests are in gvn's repository, in
`packages/gvn-domains/tests/test_dom_sdlc_release.py`.

## Recap

- A policy can read a call's arguments: the same tool is cleared on staging and needs a
  person on production.
- `Worst` ends a fan-out on the first bad verdict.
- The go/no-go is the production change itself, approved by a person.
- Rolling back is cleared, so a broken production is fixed without waiting.
- Effects that must happen once are keyed by what they are, from trusted data.

**Next:** [Data](data.md), where a backfill undoes its own changes when something goes wrong.
