# Cost.Span(name, mark): a named part of a test, in the report and held to a budget

> Name what a part of a test spent — a tab opened, a click, a commit — and it leaves the test: printed under its result, carried on its cost event, written to osy test --cost-report with its five heaviest lines. Give it a budget and osy test holds it once the test has run: the test fails, naming every span over its budget and by how much.

<!-- id: testing-cost-spans · area: testing · stability: preview · html: https://osysharp.com/reference/testing/cost-spans/ -->

## Summary        {#summary}
`Cost.Mark()` starts a measurement; `Cost.Span` ends it with a NAME, so the number leaves the test — under its result,
in `osy test --json`, and in the report `osy test --cost-report` writes. Give it numbers and it is a budget `osy test`
holds:

```osy syntax
var mark = Cost.Mark();
Ui.Click("Plan");
Assert.Visible("Next up");
Cost.Span("Plan tab", mark, 255);       // at most 255 statements — checked when the test has run
```

## Signature      {#signature}
```osy syntax
int Cost.Span(string name, string mark)                                 // named, no budget
int Cost.Span(string name, string mark, int statements)                 // …at most this many SQL statements
int Cost.Span(string name, string mark, int statements, int rowsRead)   // …and at most this many rows read
int Cost.Span(string name, string mark, …, settledMs: int)              // …and the page settled within this many ms
int Cost.Span(string name, string mark, …, steps: int)                  // …and the server ran at most this many steps
```

```console
osy test --cost-report cost.json     # the run as usual, and its costs written to cost.json
```

## Description    {#description}
**A span is a mark with a name.** It counts what the test spent from `mark` to the line it is on — SQL statements,
round trips, rows read, rows written — the same counter as [Cost.Mark() and Cost.StatementsSince(mark)](https://osysharp.com/reference/testing/cost/), and like every `Cost.*` reading it first
waits for an open page to settle. It answers its statements, so `Assert.AtMost(255, Cost.Span("Plan tab", mark))` still
stops a test on the spot when that is what you want.

**A budget is held by the runner, after the test.** Unlike an `Assert.AtMost`, a span over its budget does not stop the
test: every later span is still measured. When the test body has finished, `osy test` fails the test, naming each span
over its budget, by how much, and where its statements came from:

```console
  ✗ plan_tab_stays_cheap (840ms · 312 statements · 4410 rows read · 3 written)
      ▸ Plan tab: 275 statements · 3990 rows read · 0 written   (budget 255 statements — over by 20)
    span 'Plan tab' is over its budget by 20 statements: 275 statements (budget 255).
      where its statements came from, most first:
        120 × tests/plan.test.osy:14 › model/plan.osy:40 · … · SELECT … FROM "data"."DelegateReason" …
```

The failure points at the line that named the first span over. A test that already failed keeps its own message; its
spans are still in the report, marked `over`.

**A budget is a count, with no slack.** Statements, rows and steps are the same on a laptop, a loaded CI runner and
production, so a budget is the ceiling you mean — write that number. The report carries each span's number beside its
budget, so a budget with room to spare can be tightened.

**The same reads of the same fixture count the same on every run.** A read asked twice in one unit of work, by the same
reader with nothing written in between, is answered by the first, so the second costs no statement. A read over a set
of ids is one statement whatever order the ids come in: an include, `ids.Contains(x.Id)`, a list in a filter. A
`runas` block changes the reader. On entering and leaving it, every read is sent again, even one the test made before
the block, so each block pays for its own reads. Two `runas (Ann)` blocks with the same reads cost the same.

**Rows you hold across a `runas` are not read again one by one.** This holds for a declared actor's block and for a
test's. The rows the code around the block already holds are kept from the block, because they were read under the
caller's rules. When the block ends, every row it did not read or write is the caller's again as it was, so using it
costs nothing. A row the block did read or write is read again the first time the caller uses it. It is read together
with the other rows of its type that were read with it, so a list of 12 costs one statement, not 12:

```osy title="a list of 12 read with its type, one statement" syntax
var keys = ModelKey.Take(n).ToList();
var pace = PaceAccountsOf(now);           // runas (KeyUseKeeping) { … } inside: reads its own rows
foreach (var k in keys) { total += k.Limit; }   // 0 statements at any n; 1 if the block wrote the keys
```

**A warm span is exact while the test's clock stands still.** Answers the platform keeps between requests (who the caller
is, the caller's own policy answers, the app's settings) are read again 30 seconds after they were read. That limit is how
long a change made outside the platform can go unseen. On a running app it is measured on the machine's clock. In a test
it is measured on the test's clock, pinned or not, including answers the platform reads for the page on its own account
(the app's ending notice): time passes for them only when the test moves its clock. So a warm visit costs the same however
long the machine takes to reach it, and a `TestClock.Advance` past 30 seconds (after `TestClock.Set`) is what makes the
next visit read those answers again. When each test starts, before its body runs, the
platform reads the ending notice again if the test's clock says it is too old, so the first page a test opens costs what
its later visits cost, however long the tests before it took. A write to anything an answer read still retires it at once, as on a running app.
A rule that reads the clock itself (`allow read when Pass.Any(p => p.Until > DateTime.UtcNow)`) is different: its answer
can change as time passes, so on a test whose clock runs it is decided again as the clock moves (at most 30 seconds apart).
Pin the clock (`TestClock.Set`) where a page with such a rule has its span held to a budget.

**A name is the span's key in its test.** Two windows need two names (`"Plan tab"`, `"Plan tab (second visit)"`); the
same name taken from a different mark is refused with that sentence, because the report would otherwise give one
number for two things.

**A budget on the page's time: `settledMs:`.** In a test that drives a page, every span also carries the
milliseconds from its mark to the moment the page settled: its last request or draw, the same time as
[[testing-cost#description|`Cost.SettledMsSince`]]. Not the moment the reading was taken, which is later by the quiet
moment every reading waits. `settledMs:` holds it like the counts, by name, beside them or alone:

```osy title="a page held to its statements and to the time it takes to settle" syntax
Cost.Span("Plan page", mark, 255, settledMs: 900);   // at most 255 statements, settled within 900 ms
Cost.Span("Plan page (time)", mark, settledMs: 900);  // time only
```

Over it, the test fails once it has run, with the span's time and its budget: `span 'Plan page' is over its budget by
140 ms settled: the page settled 1040 ms after the mark (budget 900 ms)`. Time is not a count. It varies with the
machine, so set the budget with room for a loaded one, and use the statement budget for the exact line. Refused on a
test that drives no page.

**A budget on the server's work: `steps:`.** Every span also carries the steps the app's server code ran from its mark
([[testing-cost#description|`Cost.StepsSince`]]): roughly one per statement or expression, in the test's own code and in
every request its pages made. Where `settledMs:` says how long a step took, `steps:` says how much work the server did
for it, and that does not change with how busy the machine is. The same work, run idle and again with every core of the
machine busy, took 1.3 to 6 times as long and ran the same number of steps. Hold it by name, beside the counts or alone:

```osy title="a tab held to the server's work, on any machine" syntax
Cost.Span("Plan tab", mark, 255, steps: 4000);   // at most 255 statements and 4000 steps
Cost.Span("Plan tab (work)", mark, steps: 4000); // steps only
```

Over it, the test fails once it has run: `span 'Plan tab' is over its budget by 120 steps: 4120 steps (budget 4000)`.
A loop that runs once per row, or a function called more often than it was, shows up here even when it sends no
statement. Use `steps:` where you would have written a time budget for the server's part of a step, and keep
`settledMs:` for what the browser waits for. Refused on a test that does not run inside `osy test`'s unit of work.

**Where the statements came from: the five heaviest lines.** When the run keeps lines — `--cost-report` and `--cost`
both do — each span carries its five heaviest (line, what the platform was doing, statement) rows: a clock policy asked
once per rule, or a read per row, is the first line of the list. A plain `osy test` does not keep lines, and a span
over budget then says to re-run with `--cost`.

**`osy test --cost-report <PATH>`** writes one JSON document when the run ends: every test in the order it ran, with
its name, verdict, totals and spans. It is the same data the `cost` event of `osy test --json` carries (`spans` beside
`lines`), joined to each test's name and verdict so a CI step can keep it as an artifact or read it without joining
events:

```json
{
  "tests": [
    { "id": "tests/plan.test.osy::FullPlan::plan_tab_stays_cheap", "name": "plan_tab_stays_cheap", "verdict": "failed",
      "statements": 312, "roundTrips": 280, "rowsRead": 4410, "rowsWritten": 3,
      "spans": [
        { "name": "Plan tab", "statements": 275, "roundTrips": 250, "rowsRead": 3990, "rowsWritten": 0, "settledMs": 840,
          "steps": 3870, "budget": { "statements": 255, "rowsRead": null, "settledMs": 900, "steps": null }, "over": true,
          "top": [ { "source": "tests/plan.test.osy:14 › model/plan.osy:40", "cause": "…",
                     "shape": "SELECT … FROM \"data\".\"DelegateReason\" …", "statements": 120 } ] } ] } ]
}
```

`budget` is null for a span with none; `top` is null when the run kept no lines; `settledMs` is null on a test that
drives no page; `steps` is null where no unit of work counts them. The console prints each span on one
line under its test.

**Spans or `[PageBudget]`?** A [[PageBudget]: what a page's first paint and live re-run may cost, held by osy test](https://osysharp.com/reference/testing/page-budgets/) budget holds a page's first paint with no test to write. Its
test names that first paint (and a live re-run) as spans too, so every budgeted page is in the report. A span holds what
a page budget cannot reach: a tab, a click, a step of a longer journey, a commit — anything between two lines of a test.

**Name a held number.** `Assert.AtMost(255, Cost.StatementsSince(mark))` holds the same count as a span, but the count
has no name. When it goes over, the test fails with two numbers and nothing else: no lines the statements came from, no
line under the result, no row in `--cost-report`. `osy lint` reports this as `testing-cost-asserted-unnamed` (SHOULD)
for `Cost.StatementsSince`, `Cost.RowsReadSince` and `Cost.StepsSince`, the readings a span holds to a budget. Name it with a budget, or keep
the stop on the spot by asserting what the span answers:

```osy title="a held cost reading, unnamed and named" test app=testing-cost-spans-named
[Test]
void Plan_stays_cheap() {
  var visit = Cost.Mark();
  Assert.AtMost(255, Cost.StatementsSince(visit));        // reported: the number has no name
  Cost.Span("Plan tab", visit, 255);                      // a budget the runner holds after the test
  Assert.AtMost(255, Cost.Span("Plan tab, held now", visit));   // stops on the spot, and is in the report
}
```

The literal is not the problem: a budget is a number you write. A reading with no span form, such as
`Cost.RoundTripsSince` or `Cost.BytesSentSince`, is not reported.

**Is a span flat in the data?** [[Growth(Small, Large)]: a test run at two sizes, each span held flat between them](https://osysharp.com/reference/testing/growth/) runs a test at two sizes (`[Growth(Small = 10, Large = 40)]` on a
test taking `int n`) and fails a span whose statements grow from one to the other — a read per row.

## Examples       {#examples}
```osy title="a shelf of parcels" test app=testing-cost-spans
entity Parcel {
  [Required, MaxLength(40)] string Label;
  int Weight;
  security { allow read, create when IsAnonymous || IsAuthenticated; }
}

void Receive(string label, int weight) {
  new Parcel { Label = label, Weight = weight };
  UnitOfWork.Commit();
}
```

```osy title="receiving and reading back, each a named span with a budget" run app=testing-cost-spans
[Test]
void Receiving_and_reading_parcels_stays_cheap() {
  Receive("warm-up", 1);                          // the first one pays what only the first pays

  var receiving = Cost.Mark();
  for (var i = 0; i < 3; i++) { Receive($"north-{i}", i); }
  Cost.Span("receive three", receiving, 40);      // at most 40 statements

  var reading = Cost.Mark();
  var all = Parcel.Where(p => p.Weight >= 0).ToList();
  Cost.Span("read them back", reading, 5, 10);    // at most 5 statements and 10 rows read
  Assert.Equal(4, all.Count);
}
```

A page journey, the way a product reviews its pages' cost: each step a span, the whole run written to a report a
workflow step keeps.

```osy title="a page journey, step by step" syntax
[Test(FullPlan)]
[runas(Planner)]
void plan_pages_stay_cheap() {
  Ui.Visit("/plan");                              // warm: the first visit pays what only the first pays
  var open = Cost.Mark();
  Ui.Visit("/plan");
  Assert.Visible("Next up");
  Cost.Span("Plan: first paint", open, 255, 4000);

  var tab = Cost.Mark();
  Ui.Click("Done");
  Assert.Visible("Finished");
  Cost.Span("Plan: Done tab", tab, 40);
}
```

```console
$ osy test --filter plan_pages_stay_cheap --cost-report out/cost.json
```

## See also       {#see-also}
- [Cost.Mark() and Cost.StatementsSince(mark)](https://osysharp.com/reference/testing/cost/) — `Cost.Mark()` and the readings a span is made of
- [[PageBudget]: what a page's first paint and live re-run may cost, held by osy test](https://osysharp.com/reference/testing/page-budgets/) — `[PageBudget]`: a page's first paint held with no test to write
- [[Growth(Small, Large)]: a test run at two sizes, each span held flat between them](https://osysharp.com/reference/testing/growth/) — `[Growth]`: the same spans compared at two sizes
- [Running tests](https://osysharp.com/reference/testing/running-tests/) — what `osy test` prints for each test
