# Visits — every time a run entered a state, and how it left

> A run's history, one row per time it entered a state: when it entered and left, the time the state's clock counted, what that clock expected, whether it ran out, and how and where the run left. Recorded by the engine in the same commit as every move.

<!-- id: workflow-visits · area: workflow · stability: stable · html: https://osysharp.com/reference/workflow/visits/ -->

## Summary        {#summary}
Each time a run enters a state, the engine records a **visit**. When the run leaves, the visit is closed. Two reads
return them:

```osy syntax
List<StateVisit> all = Review.For(doc).Visits;   // oldest first, the open one last
StateVisit? now      = Review.For(doc).Visit;    // the visit the run is in; null once it has ended
```

Inside the run, `Workflow.Current.Visit` is the visit whose state's handler is running ([below](#current)).

The visit is written in the commit of the move that caused it, so a read never sees a move without its visit.

## Signature      {#signature}
```osy syntax
<Workflow>.For(entity).Visits   // List<StateVisit>, in the order the run made them
<Workflow>.For(entity).Visit    // StateVisit?, the open visit
Workflow.Current.Visit          // StateVisit?, inside a run: the visit of the state whose handler is running
```

**`StateVisit`** has these fields:

| field | type | |
|---|---|---|
| `State` | `string` | the state's name |
| `Visit` | `int` | which entry to this state it was in this run: 1, 2, 3… |
| `EnteredAt` | `DateTime` | when the run entered the state |
| `LeftAt` | `DateTime?` | when it left; null while the visit is open |
| `Wall` | `TimeSpan` | `LeftAt` (or now) minus `EnteredAt` |
| `Accrued` | `TimeSpan` | the time the state's clock counted (see [below](#accrued)) |
| `Expected` | `TimeSpan?` | the state's `Expire` budget, if it has one |
| `ExpiredAt` | `DateTime?` | when that clock ran out, if it did |
| `WasLate` | `bool` | `ExpiredAt != null` |
| `Outcome` | `VisitOutcome` | how the visit ended |
| `To` | `string?` | where the run went, by state name |

**`VisitOutcome`** — `Open` (the run is still there), `Moved` (a `goto` or a timer route took it on), `Cancelled`
(stopped where it stood), `Failed` (given up), `Migrated` (a new version moved it to a state with another name).

## Description    {#description}

### One visit per entry   {#per-entry}
- Entering a state opens a visit.
- Leaving it closes the visit, with `To` naming the next state.
- A `goto` to the state the run is already in closes the visit and opens the next one. The second visit has
  `Visit == 2`, so rework is counted.
- A terminal state never has a visit, because the run ends when it arrives. The move into it closes the last visit as
  `Moved`, with `To` set to the terminal's name.
- A run stopped with no cancel terminal closes its open visit as `Cancelled`. A run given up closes it as `Failed`.
- A new version that maps the run to a state with a **different name** closes the visit as `Migrated` and opens one
  under the new name. A state that keeps its name keeps its visit open. A migration that sends the run to a terminal
  closes the visit as `Migrated`, with `To` naming the terminal, and opens none there.

Visits are keyed by state **name**, as the audit trail is, so a run's history reads the same after it moves to a new
version.

### `Accrued` is the clock's count   {#accrued}
In a state with an SLA `Expire`, `Accrued` is the time that clock counted: service hours on the run's `ServiceHours`
calendar. A ticket that enters on Monday at 16:00 and leaves on Tuesday at 10:00, on a 09–17 calendar, has `Wall` of
18 hours and `Accrued` of 2 hours.

In a state with no clock, or a wall-time one (`Expire { Within = …; Accrues = false; }`), `Accrued` equals `Wall`.

These visits record wall time: an open visit (until it closes), a visit closed because the run was given up or by a
migration, and a visit the engine writes from the audit trail (the deploy backfill, and the catch-up after a deploy,
[below](#backfill)). No run context counts the clock's time for them.

A stop counts the clock's time, as a move does.

### `Workflow.Current.Visit` inside the run   {#current}
Code running in a state's handler reads the visit the run is in with `Workflow.Current.Visit`: the state, its entry
number (`Visit`), when it began, what its `Expire` clock expects and whether it ran out. The read costs no query, and
it sees the visit the move being made has just opened. Outside a run, `Workflow.Current` is null.

```osy syntax
on Expire {
  var visit = Workflow.Current!.Visit!;
  Escalate(this.Item, visit.State, visit.Visit, visit.EnteredAt, visit.Expected);
}
```

It is null when no visit of the handler's state is open: a run from before visits, until the next deploy writes them.

### `ExpiredAt` is when it ran out   {#expired}
When a state's `Expire` clock runs out, the visit records the instant it was **due**, not the later moment a sweep got
to it. `WasLate` is true from then on, whether or not the timer's route moved the run.

### `.Flow` and `.TimeInStates` read these   {#flow}
[`Flow` and `TimeInStates`](https://osysharp.com/reference/workflow/flow-metrics/) are computed from the visits. `TimeInStates` sums each state's
visits and counts them, so a self-`goto` counts as a second visit there too.

### Runs from before visits   {#backfill}
The first deploy of an app after visits arrived writes the visits of its existing runs from their audit trails. It runs
in the deploy's transaction, before the new version serves. A move to the state the run was already in counted as no
move in that trail, so a backfilled run shows such a self-`goto` as one longer visit.

While a deploy is under way, a run on the previous version can still move or end without writing a visit. The engine
catches up from the audit trail:

- A run that moves on: its next move finds that the run entered a state after its open visit began. Each missed move
  is given its own visit, at its own time, so the state the visit was open in gets only its own time.
- A run that ended: the next deploy closes its open visit. The run's last state is closed at the run's end, and a run
  that ended by moving into a terminal has its last visit closed by that move.

### Who can read them   {#security}
`Visits` and `Visit` answer only for an item the caller may read. The item is read again as the caller. For an item the
caller cannot read, both throw the same `NotFoundException`, with the same words, as for a row that has no run. A
stranger cannot tell a hidden item with a history from an item that has none. Every other history read of a run does
the same ([[workflow-reading-runs#unreadable]]).

The visit table is the engine's own. No app code reads or writes it directly.

### Retention   {#retention}
Visits are part of their run. They are deleted with it under `app.Workflow.Retention`. While the run is live, a visit it
**left** longer ago than the retention window is deleted, as its old audit rows are. The open visit is never deleted.

## Examples       {#examples}

A document that goes back to its author until it is accepted. The function says how many rounds it took and how long the
current one has lasted:

```osy title="rounds of review, from the visits" test app=workflow-visits
using Osysharp.Workflow;

enum DocState { Drafting, InReview, Accepted }

entity Doc {
  [Required, MaxLength(200)] string Title;
  DocState State;
  security { allow read, create, update when IsAuthenticated || IsAnonymous; }
}

workflow Review {
  Tracks    = Doc.State;
  Autostart = true;
  Initial   = Drafting;

  event Submit();
  event Return();
  event Accept();

  state Drafting {
    subscribe Submit() as Sent;
    on Sent { goto InReview; }
  }

  state InReview {
    subscribe Return() as Back;
    subscribe Accept() as Done;
    on Back { goto Drafting; }
    on Done { goto Accepted; }
  }

  terminal success Accepted { }
}

string Rounds(Doc d) {
  var reviews = Review.For(d).Visits.Count(v => v.State == "InReview");
  var now = Review.For(d).Visit;
  return now == null
    ? $"accepted after {reviews} review(s)"
    : $"review round {reviews}, in {now.State} for {now.Wall}";
}
```

## See also       {#see-also}
- [Flow metrics — how long an item took, and how much was waiting](https://osysharp.com/reference/workflow/flow-metrics/) — lead, touch and wait, summed from these visits
- [For(entity).Audit](https://osysharp.com/reference/workflow/audit/) — the full trail of everything that happened to a run
- [Reading a run — from app code and from a test](https://osysharp.com/reference/workflow/reading-runs/) — every read `For(item)` has
- [ServiceHours (SLA-accrual windows)](https://osysharp.com/reference/workflow/service-hours/) — the calendar an SLA clock counts in
