# Reading a run — from app code and from a test

> App code and tests read a workflow run THROUGH THE ROW IT TRACKS: `<Wf>.For(item).Flow` (did it start, has it finished), `.Audit` (what happened), `Workflow.Work<T>()` (what is open, and when it breaches), `Workflow.Current` (the run this code is in). `WorkflowRun` itself is the engine's table and no principal may read it, so `WorkflowRun.Count(…)` in a test or a page answers 0 rows however many runs exist. `For(item)` on a row with no run OF THAT WORKFLOW raises `NotFoundException` — another workflow's run on the same row is never used in its place.

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

## Summary        {#summary}
A run is read **through the row it tracks**, never by querying the engine's tables. The closed set:

| you want to know | read |
|---|---|
| did a run of `Wf` start on this row; has it finished | `Wf.For(item).Flow` — `StartedAt`, `IsFinished`, `FinishedAt` |
| what happened to it, in order | `Wf.For(item).Audit` — one entry per move, deposit, breach |
| what is open on it, who holds it, when it breaches | `Workflow.Work<T>()` / `Workflow.WorkByItem<T>()` |
| which run THIS code is running in | `Workflow.Current` |
| every run as it starts, moves or ends | `[On] void F(WorkflowRunStarted e)` (and `…Moved`, `…Ended`) |

## Signature      {#signature}
```osy syntax
Wf.For(item).Flow          // FlowMetrics — StartedAt, IsFinished, FinishedAt, Lead, Touch, Wait
Wf.For(item).Audit         // List<WorkflowAuditEntry> — Kind, Slot, Actor, Message, At, From, To
Workflow.Work<T>()         // one row per open slot — Item, WorkflowName, SlotAlias, Status, Assignee, BreachesAt
Workflow.Current           // WorkflowRunInfo? — null outside a run
```

## Description    {#description}
### Why does `WorkflowRun.Count(…)` answer 0?   {#why-zero}
`WorkflowRun` (and `Slot`) are the engine's bookkeeping, declared `[Authority(Owned)]` with no read rule: **no
principal may read them** — not anonymous, not a `[runas(…)]` person, not an owner. A query of them from a test
body, a page, an `[Action]` or an API answers no rows, however many runs exist; it is not an error, so the test
fails on its assertion with nothing pointing at the cause. Ask the row instead, with the table above.

A `[Test]` body that queries `WorkflowRun` or `Slot` is warned at compile time (`TEST_READS_THE_ENGINES_RUN_TABLE`),
and the warning points here.

### Has this row got a run of `Wf`?   {#has-a-run}
`Wf.For(item)` reaches the run **of `Wf`** bound to the row. When the row has none — `Wf` never started on it, or
its finished run was reaped by [`app.Workflow.Retention`](https://osysharp.com/reference/config/workflow/) — every read and every raise through it
raises **`NotFoundException`**. That holds when the row carries a run of ANOTHER workflow: an item tracked by two
workflows reaches each one's run by naming it, and a raise through the workflow that has no run there is refused
rather than delivered to the other one.

### Which run, when the row has several of `Wf`?   {#which-run}
A row can carry more than one run of the same workflow — an old finished run beside a later one, or a second revision's
start. `Wf.For(item)` (and every raise through `Wf`) reaches **the item's live run**: a run that has not ended (running or
waiting), and among several the one **most recently started**. With none live it reaches the most recently started run
that was not cancelled, and only if every run was cancelled, the most recently started of those. The answer never
depends on the order the database returns rows in.

## Examples       {#examples}
```osy title="a test asserts which runs a row has, by asking the row" run app=workflow-reading-runs
app Desk {
  use Osysharp.Workflow;
  model "model/**/*.osy";
}

using Osysharp.Workflow;

enum Review { Open, Closed }
enum Billing { Due, Paid }

entity Invoice {
  [Required, MaxLength(40)] string Number;
  Review Review = Review.Open;
  Billing Billing;
  security { allow read, create, update when IsAuthenticated || IsAnonymous; }
}

/// Started by hand: most invoices never have one.
workflow InvoiceReview {
  Tracks = Invoice.Review; Autostart = false; Initial = Open;
  event Close();
  state Open { on Close { goto Closed; } }
  terminal success Closed { }
}

/// Every invoice has one.
workflow InvoiceBilling {
  Tracks = Invoice.Billing; Autostart = true; Initial = Due;
  event Pay();
  state Due { on Pay { goto Paid; } }
  terminal success Paid { }
}

[Test]
void the_row_says_which_runs_it_has() {
  var inv = new Invoice { Number = "INV-1" };
  Workflow.Settle(inv);

  Assert.False(InvoiceBilling.For(inv).Flow.IsFinished);                 // a billing run started…
  Assert.Throws<NotFoundException>(() => InvoiceReview.For(inv).Audit);  // …and no review run did

  InvoiceBilling.RaisePay(inv);
  Assert.True(InvoiceBilling.For(inv).Flow.IsFinished);
  Assert.True(InvoiceBilling.For(inv).Audit.Count > 0);
}

[Test]
void a_raise_through_a_workflow_with_no_run_reaches_nothing() {
  var inv = new Invoice { Number = "INV-2" };
  Workflow.Settle(inv);
  Assert.Throws<NotFoundException>(() => InvoiceReview.RaiseClose(inv));
  Assert.Equal(Billing.Due, Invoice.Single(i => i.Number == "INV-2").Billing);   // the billing run did not take it
}
```

## See also       {#see-also}
- [Flow metrics — how long an item took, and how much was waiting](https://osysharp.com/reference/workflow/flow-metrics/) — `For(item).Flow`: when a run started and finished, and how long it took
- [For(entity).Audit](https://osysharp.com/reference/workflow/audit/) — `For(item).Audit`, and a row whose run was reaped
- [Workflow.Work&lt;T&gt; (everything outstanding) and its SLA numbers](https://osysharp.com/reference/workflow/work/) — the open slots of every run, with their deadlines
- [Workflow.Current (which run is this code in?)](https://osysharp.com/reference/workflow/run-facts/) — `Workflow.Current`, inside a run
- [WorkflowRunStarted, WorkflowRunMoved, WorkflowRunEnded — hear a run start, move and end](https://osysharp.com/reference/workflow/run-events/) — hearing every run start, move and end
