# A polled function pays only for what changed

> osy lint's cost-polled-function-pays-for-what-did-not-change judges a function machines call on a timer — marked [Polled], run by a timer under an hour, or an API-key endpoint whose answer says when to call again — on what every call pays when nothing changed: a read the same for every caller, a read per row, a write on every path, everybody's housekeeping, a runas. Each finding names its shape and the fix; answering "nothing changed" first is the main one.

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

## Summary        {#summary}

A function a machine calls every few seconds is paid for at every call, whether or not anything changed. Its cost
should grow with **what changed since the last call**, not with the data. Every other cost rule judges one function and
one call; this one knows how often the call comes.

Measured on a large app in production: one poll its worker machines made was 58 % of the app's statements in a month — 78 a call over
100,036 calls — and an idle poll changed nothing. It passed every per-call rule.

The poll below reads the rules every host shares and writes the host's heartbeat at every call:

```osy title="before: every poll reads and writes, whatever changed" test app=function-polled-cost-before
entity Host {
  [MaxLength(40)] string Name = "";
  DateTime? SeenAt;
  security { allow read, update when IsAuthenticated; }
}
entity Job {
  Host? Host;
  bool Open;
  security { allow read when IsAuthenticated; }
}
entity Rule {
  [MaxLength(40)] string Kind = "";
  int Limit;
  security { allow read when IsAuthenticated; }
}
class WorkAnswer { public long Version; public bool Unchanged; public int Rules; public int Jobs; }

[Polled(EverySeconds = 5)]
WorkAnswer PollForWork(Host host, long known) {
  host.SeenAt = DateTime.UtcNow;
  var rules = Rule.Where(r => r.Limit > 0).Take(200).ToList();
  var mine = Job.Where(j => j.Host == host && j.Open).Take(20).ToList();
  return new WorkAnswer { Rules = rules.Count, Jobs = mine.Count };
}
```

`osy lint` says, for each shape, where it is and what to do:

```text
model/hosts.osy:21  SHOULD  cost-polled-function-pays-for-what-did-not-change
  'PollForWork' is polled (`[Polled(EverySeconds = 5)]`: about 17,280 calls a day for each caller). Every call makes
  one read whose answer depends neither on the caller nor on what changed since its last call — the same for every
  caller until somebody writes: Rule (PollForWork, line 21). An idle call changes nothing, and pays this every time.
  → Answer "nothing changed" first: keep a change counter the writers bump (or have the caller send back the version
    it holds), return `unchanged` when it has not moved, and read the rest only when it has.
model/hosts.osy:20  SHOULD  cost-polled-function-pays-for-what-did-not-change
  … Every call that returns writes, whatever changed: Host.SeenAt (PollForWork, line 20). …
  → Compare before writing, and write a heartbeat or a sample at most once a minute.
```

After: one counter row the writers bump. The host sends back the version it holds; while it has not moved, the poll
reads one row and answers `Unchanged`, and the heartbeat is written at most once a minute:

```osy title="after: an idle poll reads the counter and answers unchanged" test app=function-polled-cost-after
entity Host {
  [MaxLength(40)] string Name = "";
  DateTime? SeenAt;
  security { allow read, update when IsAuthenticated; }
}
entity Job {
  Host? Host;
  bool Open;
  security { allow read, create when IsAuthenticated; }
}
entity Rule {
  [MaxLength(40)] string Kind = "";
  int Limit;
  security { allow read when IsAuthenticated; }
}
entity WorkClock {
  long Version;
  security { allow read, create, update when IsAuthenticated; }
}
class WorkAnswer { public long Version; public bool Unchanged; public int Rules; public int Jobs; }

// Every writer of what a poll answers bumps the counter in the commit it already makes.
void OfferJob(Host host) {
  new Job { Host = host, Open = true };
  var clock = WorkClock.FirstOrDefault();
  if (clock == null) { new WorkClock { Version = 1 }; } else { clock.Version = clock.Version + 1; }
}

[Polled(EverySeconds = 5)]
WorkAnswer PollForWork(Host host, long known) {
  var clock = WorkClock.FirstOrDefault();
  var version = clock == null ? 0 : clock.Version;
  if (version == known) {
    if (host.SeenAt == null || host.SeenAt < DateTime.UtcNow.AddMinutes(-1)) { host.SeenAt = DateTime.UtcNow; }
    return new WorkAnswer { Version = version, Unchanged = true };
  }
  var rules = Rule.Where(r => r.Limit > 0).Take(200).ToList();
  var mine = Job.Where(j => j.Host == host && j.Open).Take(20).ToList();
  return new WorkAnswer { Version = version, Rules = rules.Count, Jobs = mine.Count };
}
```

## Signature      {#signature}

```osy syntax
[Polled(EverySeconds = <n>)]
<Answer> <Name>(<the caller>, <what it holds>) {
  <read the counter>;
  if (<counter> == <what it holds>) { return <unchanged>; }   // the since-gate: every idle call stops here
  <the full answer, only when something moved>
}
```

## Description    {#description}

### Which functions it judges   {#polled}

Only a function something calls on a timer. A function nobody polls is never judged, whatever it does. It is polled when:

- it carries [[function-polled|`[Polled(EverySeconds = N)]`]] — SHOULD, and the finding says how many calls a day that is
  for each caller;
- a workflow reminder's `ThenEvery`, or a schedule rule whose schedule makes a row a workflow tracks, runs it more often
  than once an hour with a literal cadence ([Schedule (recurring work)](https://osysharp.com/reference/scheduling/schedule/)) — SHOULD;
- it is an `Endpoint` of a `RestApi` whose `Auth` takes an API key and nothing else, or an MCP `Tool`, and its answer is
  a class with a member named `PollSeconds`, `LeaseSeconds` or `NextPollAt` — CONSIDER, because it is inferred, under
  its own rule `cost-machine-door-pays-for-what-did-not-change` (same shapes, same fixes). Add `[Polled]` to make it
  exact; it is then reported once, under the SHOULD rule.

### What every call pays   {#shapes}

Through everything the function calls:

| shape | what it is | the fix |
|---|---|---|
| a read the same for every caller | a query that names nothing from outside itself — no parameter, no local the caller shapes, no function's answer. A time bound (`DateTime.UtcNow`, or a local made of it) is the same for every caller and does not count as naming one | a change counter the writers bump, or a version the caller sends back, and `unchanged` while it has not moved |
| a read per row | a query, or a call that reads, inside a `foreach` over rows | one read for all the rows before the loop (`Where(p => keys.Contains(p.Key))`) |
| a write on every path | on the function's straight line — not inside an `if`, a loop or a `try`, and before any `return` a branch can take — a row created, the clock stored, a counter bumped, a set-based write | compare before writing; a heartbeat at most once a minute |
| housekeeping for everybody | a call to an `Ensure…`, `Sweep…` or `Keep…` function that writes; a write to rows a query found without naming the caller, or naming it only to say "not mine" (`t.Host != host`) | a schedule that does it once for everybody, every minute |
| a `runas` | each one builds a security context for its actor — measured at 7 to 8 statements | `runas` only around the writes that need it, on the path that makes them |

**An assignment of a value is not a write on every path.** The unit of work drops a write of the value a row already
holds, so `host.Name = name` costs nothing when the name did not change. Only a value that always differs counts: the
clock, a fresh id, a field moved by a step.

### The since-gate ends what every call pays   {#gate}

The first statement on the function's straight line that is an `if` naming one of its parameters and returning from
its branch is the **since-gate**. Only what comes before it runs at every call; what comes after runs only when
something moved, and is not judged. The reads the gate's condition makes — the counter, and the locals made of it — are
the gate's own price and are not findings. So the "after" above is clean.

### A timer is judged on less   {#timers}

A function a timer runs has no caller, and doing everybody's work is its job — it is the fix the housekeeping shape
names. So it is judged on reads per row and writes on every path only, and the row the timer is about (the schedule's
occurrence, the reminder's tracked item) is its own to write.

### Hold the number   {#test}

The finding's last line asks for a test: call the polled function with nothing changed and hold what it costs with
[`Cost.Span`](https://osysharp.com/reference/testing/cost-spans/), so the next change that adds a read to the idle path fails a test instead of
showing up on next month's bill.

## Examples       {#examples}

Work for everybody moved off the caller's path: the poll touches only the caller's own rows, and a sweep, run by a
schedule every minute, gives up the jobs of hosts that went quiet:

```osy title="the caller's own rows on its path; everybody's on a sweep" test app=function-polled-cost-sweep
entity Host {
  [MaxLength(40)] string Name = "";
  DateTime? SeenAt;
  security { allow read, update when IsAuthenticated; }
}
entity Job {
  Host? Host;
  bool Open;
  security { allow read, update when IsAuthenticated; }
}
class WorkAnswer { public int Jobs; }

[Polled(EverySeconds = 5)]
WorkAnswer PollForWork(Host host) {
  var mine = Job.Where(j => j.Host == host && j.Open).Take(20).ToList();
  return new WorkAnswer { Jobs = mine.Count };
}

// Run once a minute for everybody — by a schedule whose workflow calls it — not at every host's poll.
void GiveUpQuietHosts() {
  var quietSince = DateTime.UtcNow.AddMinutes(-20);
  foreach (var j in Job.Where(j => j.Open && j.Host != null && j.Host.SeenAt < quietSince).Take(100).ToList()) {
    j.Open = false;
  }
}
```

## See also       {#see-also}

- [[Polled] — a function machines call on a timer](https://osysharp.com/reference/function/polled/) — `[Polled(EverySeconds = N)]`
- [Cost.Mark() and Cost.StatementsSince(mark)](https://osysharp.com/reference/testing/cost/) — `Cost.Mark` and the counts a test can hold
- [Cost.Span(name, mark): a named part of a test, in the report and held to a budget](https://osysharp.com/reference/testing/cost-spans/) — `Cost.Span`: name a part of a test and hold its budget
- [Schedule (recurring work)](https://osysharp.com/reference/scheduling/schedule/) — recurring work, once for everybody
