# Collect and samples

Some services only tell you what's happening now. Parcel lists the deliveries on the way and a short list of recent ones, then forgets them, so a page that reads it can't say how long deliveries took last quarter. History fixes that: a page keeps the rows it chooses from each answer, on this Mac, and other pages you allow read them later, with a period row like any other page.

- **One page collects.** A source with `collect` keeps chosen fields of chosen items, as rows in a named history (a dataset), each time it fetches.
- **Other pages read.** A source with `{ "dataset": "name" }` answers with the rows kept, filtered to the page's period, and cards use the usual [rules](https://legatobar.com/docs/mapping.md#mapping) on them.
- **Or samples over time.** With `sample`, a page keeps one row per item per interval, such as each monitor's state every 5 minutes, and a page for each item reads its own with `key`. See [Samples](https://legatobar.com/docs/history-collect.md#samples).
- **Nothing leaves the Mac.** The rows are in Legato's folder on this Mac, they don't sync between Macs, and **Settings → History** shows, exports and deletes them.
- **Rows can also come from outside,** from an agent or a script, with `legato rows add` or the MCP tool `add_rows`.

## When you don't need it

Many services keep their own history and answer for a range of dates. Ask them for the period showing, with `{period.start}` and `{period.end}` in the request (see [Periods](https://legatobar.com/docs/periods.md#periods)), and the page works from the first fetch, with nothing kept on the Mac:

- **Tesla, through Tessie:** the charges request takes `from` and `to`, so a charging page asks for the period's sessions.
- **Lunch Money:** `balance_history` gives monthly balances for a range of months. History is only worth it for daily points.
- **GitHub:** a repository's pull requests carry `created_at` and `merged_at`, so open-to-merge times come from the list itself.
- **Pi-hole:** its long-term database answers for a range of days, 91 by default. Keep a history only to look further back than that.

Use History for services that forget: Parcel's deliveries, readings a service only reports as they are now, or rows an agent supplies. For a single number over time on one sparkline, a [history rule](https://legatobar.com/docs/mapping-sparklines.md#sparkline-readings) is simpler: it shows the newest configured readings (up to 60) for that card, with no `collect` and no readers. Its readings are listed in [Settings → History](https://legatobar.com/docs/history-coverage.md#settings-history) too.

## Collect on the page that fetches

Add `collect` to the source whose answer has the items. This is the Packages page's Parcel source; the complete page is in the [Parcel example](https://legatobar.com/docs/history-parcel.md#a-complete-example-parcel).

```json
"parcel": {
  "url": "https://api.parcel.app", "secret": "parcel", "auth": { "type": "header", "name": "api-key" },
  "every": "30m",
  "requests": { "active": "/external/deliveries/?filter_mode=active",
                "recent": "/external/deliveries/?filter_mode=recent" },
  "collect": {
    "dataset": "parcel-deliveries",
    "each": ["active.deliveries", "recent.deliveries"],
    "key": "{carrier_code}:{tracking_number}",
    "fields": ["carrier_code", "tracking_number", "description", "status_code",
               "events[].date", "events[].event", "events[].location"],
    "remove_after": { "events[].event": { "markers": ["Received By:", "Delivered:"],
                                          "keep_exact": ["Signature Not Req", "Signature Required"] } },
    "date": { "date": { "first": "date", "of": "events", "where": { "path": "event", "contains": "Delivered" },
                        "sort": { "by": "date", "order": "desc", "as": "date" } } },
    "keep": { "for": "400d" },
    "readers": ["delivery-times"]
  }
}
```

Each time the source answers, Legato takes the items at `each`, keeps only `fields` of each, removes text after the `remove_after` markers, works out the row's `date`, and stores the row under its `key`. A row whose key comes again replaces the one kept. The cards on the page use the answer as they always do: collecting changes nothing they show and adds no request. A source with `collect` that no card uses is fetched all the same, on its `every`. A fetch that fails keeps nothing, including an answer the source's [`fail`](https://legatobar.com/docs/source-polling.md#when-the-answer-reports-an-error) turns down; adding `fail` to a source that collects keeps its history as it is.

**Records and measurements are kept differently.** A record history keeps the latest complete record for each key; it does not append a new version on every poll. A delivery uses its tracking identifier, so a later answer updates that delivery. For measurements over time, each monitor's state or each host's load, add `sample` and History keeps one row per item per interval, timed by Legato's own clock: see [Samples](https://legatobar.com/docs/history-collect.md#samples).

A sparkline's `history` rule is simpler: one number per card over time, with its own `every` and `keep` settings. Its readings are kept in the same database and listed in Settings → History by page, where you can export or delete them, but they aren't a dataset: there's no `collect`, no key and no readers. See [Sparkline readings](https://legatobar.com/docs/mapping-sparklines.md#sparkline-readings).


| `collect` field | Required? | Meaning |
| --- | --- | --- |
| `dataset` | yes | The history's name, which readers use: 1–64 lowercase letters, digits and `-`, starting with a letter or digit, like `parcel-deliveries`. |
| `each` | yes | A [path](https://legatobar.com/docs/mapping.md#mapping) to the list of items to keep, or a list of 2 to 4 paths read in order. When a key comes up more than once in one answer, the item where it first appears is kept. |
| `key` | yes | A template of the item's own fields that names it, the same next time: `{carrier_code}:{tracking_number}`. Up to 256 characters, with at least one `{…}`. Each field it uses must be text; an item whose key is missing, blank, longer than 256 characters or made from a number isn't kept, and is counted as rejected. |
| `fields` | yes | The only fields kept of each item: 1 to 64 different paths. Write `[]` after a list for every item of it: `events[].date`. Everything else in the answer is left out before anything is stored. |
| `keep` | yes | `{ "for": "400d", "clock": … }`: how long a row is kept, `1d` to `9999d`, and what its age counts from. See [How long rows are kept](https://legatobar.com/docs/history-dates.md#how-long-rows-are-kept). |
| `remove_after` | no | For 1 to 16 kept fields, text removed after a marker before the row is stored. See [Removing text](https://legatobar.com/docs/history-collect.md#removing-text). |
| `date` | no | A [rule](https://legatobar.com/docs/mapping.md#mapping), read on the row as it's kept, giving the row's date. See [Dates](https://legatobar.com/docs/history-dates.md#dates). |
| `time_zone` | no | The zone the service's times without one are in, like `America/Los_Angeles`. Needs `date`. |
| `date_range` | no | `{ "from", "to" }`: the dates kept as dates. Needs `date`. |
| `readers` | no | Up to 32 ids of other pages that may read the history. See [Readers](https://legatobar.com/docs/history-accounts.md#readers-and-grants). |
| `accepts_rows` | no | `true` lets `legato rows add` and `add_rows` add rows. `false` by default. |
| `account` | no | A template from the answer saying whose data it is, like `{account.id}`. When its value changes, a new history starts. See [Accounts](https://legatobar.com/docs/history-accounts.md#accounts-and-histories). |

- **Keep complete records.** A row is replaced whole, so an item must carry everything you want kept each time. Parcel sends every event of a delivery each time, which suits it. A service that sends only the newest events of a record would replace the older ones.
- **Keep only what a reader needs.** `fields` is the promise of what's stored: a page with `fields` of three names keeps three names, whatever else the service sends.
- **One source per history.** A page can collect several histories from different sources, but two sources on one page can't collect the same `dataset`.
- **What can collect:** an `http` source, or a source of `collect` alone that only [receives rows](https://legatobar.com/docs/history-rows.md#rows-from-outside-legato). Not a `calendar`, `reminders` or `dataset` source.
- **What can't:** a source that uses `{period.…}` or `{compare.…}`, since one history can't change with the period row; and any source on a page with [params](https://legatobar.com/docs/detail-pages.md#one-page-for-every-item), or `{param.…}` anywhere in `collect`. Collect on the page that lists every item, and let the page with params read the history.

Legato checks `collect` with the rest of the page, whether or not a card uses the source. A mistake stops the page loading, with a message after the file's name (`packages.json: sources.parcel.collect: …`) such as:

| Message | Cause |
| --- | --- |
| `sources.parcel.collect: key is a template of the item's fields, like {carrier_code}:{tracking_number}, of up to 256 characters` | `key` has no `{…}`, or is too long |
| `sources.parcel.collect: fields lists 1 to 64 different fields to keep` | `fields` is empty, too long, or names a field twice |
| `sources.parcel.collect: keep is { "for": days like 400d, "clock": date, last_seen or date_or_last_seen }` | `keep` is missing or wrong |
| `sources.parcel.collect: time_zone reads the date rule's times, so it needs a date` | `time_zone` without `date` |
| `sources.parcel.collect: date_range bounds the date rule's dates, so it needs a date` | `date_range` without `date` |
| `sources.parcel.collect: collect has no setting "readres" (it takes accepts_rows, account, dataset, date, date_range, each, fields, keep, key, readers, remove_after, time_zone)` | A misspelled setting |
| `sources.archive and sources.parcel both collect parcel-deliveries; a page keeps a dataset from one source` | Two sources, one history (named in alphabetical order) |
| `sources.parcel: a source that collects can't use {period.…}` | A collecting source follows the period row (`{period.…}` or `{compare.…}`) |
| `sources.parcel: a page with params can't collect; collect on the page that lists every item, and read its dataset here` | `collect` on a page with `params` |
| `sources.daily: only an http source can collect` | `collect` on a calendar or reminders source |
| `sources.daily: a source that only receives rows has collect and nothing else` | A source with no `url` that has more than `collect` |
| `sources.daily: with no url to fetch, collect needs "accepts_rows": true` | A source of `collect` alone without `accepts_rows` |

### Removing text

Carriers put names in delivery events: "Delivered. Received By: Pat Example". `remove_after` keeps the first marker in the field and replaces everything after it with ` [removed]`, before the row is stored:

```json
"remove_after": { "events[].event": { "markers": ["Received By:", "Delivered:"],
                                      "keep_exact": ["Signature Not Req", "Signature Required"] } }
```

| Kept as | From |
| --- | --- |
| Delivered. Received By: [removed] | Delivered. Received By: Pat Example |
| Delivered: [removed] | Delivered: P.EXAMPLE |
| Delivered: Signature Not Req | Delivered: Signature Not Req |
| Delivered, Front Door/Porch | Delivered, Front Door/Porch (no marker) |

- A marker is literal text, and case matters. 1 to 16 markers, each 1–64 characters, for each of up to 16 fields.
- When several markers are in the text, the one that comes first is kept.
- `keep_exact` lists up to 32 phrases (1–64 characters each) that may follow a marker and stay, matched whole once the spaces around them are trimmed. "Delivered: Signature Not Req, P. Example" becomes "Delivered: [removed]".
- Nothing after the marker, or only spaces, leaves the text as it is.
- It applies to text fields only, and it runs on rows added from outside too.

This removes text at a marker you name. It isn't anonymization: a name the service puts somewhere else stays, so read a few answers in **Preview Source…** before choosing the markers.

## Samples

Some services only say how things are now: a monitor is up and answered in 41 ms, a host is at 12% CPU, a container is running. With `sample`, the page that lists them keeps one row per item per interval, so a page for each item can show its last day, or its last quarter, from what the overview fetched.

```json
"kuma": {
  "url": "https://status.example.com/metrics", "every": "1m",
  "collect": {
    "dataset": "kuma-samples", "each": "monitors", "key": "{monitor_id}",
    "sample": { "every": "5m" },
    "fields": { "state": { "path": "monitor_status", "values": { "1": "ok", "0": "critical", "3": "off" }, "default": "unknown" },
                "ms": "monitor_response_time" },
    "readers": ["uptime-monitor"]
  }
}
```

- **One row per item per interval.** `sample.every` is the interval: minutes that divide an hour, `1m` to `1h` (`1m`, `2m`, `3m`, `4m`, `5m`, `6m`, `10m`, `12m`, `15m`, `20m`, `30m`, `60m` or `1h`), `5m` by default. It's apart from the source's own `every`, and can't be shorter than it: with a `5m` source and `1m` samples, four intervals in five would be empty.
- **Timed by Legato's clock.** Intervals start on the clock: at 14:06 with `5m`, the sample is the 14:05 one. A later answer in the same interval replaces that interval's row, whole, so each holds the last answer in it. A one-minute outage between two answers in the same interval isn't kept; sample more often to catch shorter ones.
- **`fields` are rules.** An object of 1 to 16 names (lowercase letters, digits and `_`) and the [rules](https://legatobar.com/docs/mapping.md#mapping) that fill them from the item; a list of such names keeps those fields as they are. What's stored is each rule's result: text of up to 256 characters, a number, or true or false. Anything else, or nothing, leaves the name out of that sample. A sample is at most 512 bytes of JSON.
- **What a sample's rules can't use:** `{param.…}`, `{period.…}`, `{ "answer": … }`, `lookup`, `match` or `in_list`. A kept value has to mean the same thing later, whichever link opened the page, whatever period shows and whatever Settings → Lists holds.
- **Kept a year.** `keep` is optional: a sample is kept 365 days unless `"keep": { "for": "90d" }` says otherwise. Its age is its own time, so there's no `clock`.
- **Not with** `remove_after`, `date`, `time_zone`, `date_range` or `accepts_rows`: a sample's time is Legato's, its values are rule results, and nothing adds samples from outside.
- `key`, `each`, `account` and `readers` are as for records. An item whose key is missing, blank or a number isn't kept, and is counted as rejected. A service that numbers its items, as Proxmox numbers guests, gets a text id in `derive`: give the list a field `"id": { "template": "{vmid|raw}" }`, collect from that list, and key by `{id}`.

### Reading one item

A page for every item reads its own samples with `key`, which its link fills:

```json
"sources": { "samples": { "dataset": "kuma-samples", "key": "{param.id}" } }
```

- **`key` is compared as text on both sides.** Kept keys are always text, and `key` is the text the link filled in, so `"7"` reads the item kept as `7`, and `"07"` doesn't. It works on a record history too, for that one row.
- **Without a period row, the last 24 hours.** More exactly, the last 24 hours of intervals with the one in progress last: at 14:06 with `5m`, from 14:10 yesterday to 14:10 today. "Now" is the end of the interval in progress, at most one interval ahead of the clock. The page reads again at each interval's end, even when nothing new has been kept, so a quiet hour shows as one.
- **With a [period](https://legatobar.com/docs/periods.md#periods), the period's.** From the start of its first day to midnight after its last, in the Mac's time zone, up to the interval in progress when it includes today. A [strip](https://legatobar.com/docs/card-time.md#strip) follows the period row; it isn't one of the cards that always read the default choice.
- **Without `key`,** a read takes every item's samples, up to 100,000 of them; more says "This period holds more samples than a page reads at once; read one item with key". Thirty items over 24 hours are 8,640.
- `row` is for records: a sample is small already.

The answer:

```json
{ "kept": {
    "rows": [ { "key": "git", "at": "2026-11-08T14:05:00Z", "row": { "state": "ok", "ms": 41 } } ],
    "selected_count": 288, "total_count": 105120, "undated_count": 0,
    "span": { "from": "2026-11-07T14:10:00Z", "until": "2026-11-08T14:10:00Z" },
    "sample": { "every": "5m", "seconds": 300 },
    "epoch": { … }, "coverage": { "recording_since": …, "last_success": …, "interruptions": [ … ] } } }
```

| Field | Meaning |
| --- | --- |
| `rows` | The samples in the span, oldest first: each with its item's `key`, `at` (the start of its interval, ISO 8601 in UTC) and `row` (its fields). |
| `selected_count`, `total_count` | How many `rows` has, and how many the item (or, without `key`, the history) keeps in all. |
| `span` | The span read, `from` and `until`, for [`by_time`](https://legatobar.com/docs/mapping-expiry.md#slices-of-time). |
| `sample` | The interval, as written and in seconds. |
| `epoch`, `coverage` | As for records. An interval with no sample is a time nothing was kept: the Mac asleep, the service not answering. |

The strip and a response-time sparkline on one item's page:

```json
{ "id": "history", "type": "strip", "label": "Last 24 hours", "start_label": "24 hours ago", "end_label": "Now", "segments": [],
  "source": { "ref": "samples", "map": {
    "segments": { "each": "kept.rows", "by_time": { "at": "at", "span": "kept.span" },
                  "fields": { "state": { "worst": "row.state", "of": "rows" }, "label": { "template": "{from|time}" } } } } } },
{ "id": "ms", "type": "sparkline", "label": "Response time", "unit": "ms", "points": [],
  "source": { "ref": "samples", "map": {
    "points": { "each": "kept.rows", "by_time": { "at": "at", "span": "kept.span" }, "value": { "path": "row.ms", "round": 0 } } } } }
```

`by_time` cuts the span into 144 slices unless `buckets` says, and `worst` gives each slice its worst state; see [Slices of time](https://legatobar.com/docs/mapping-expiry.md#slices-of-time).

### What changes, and what pauses

- **A rule changing** keeps old samples as they were measured, and new ones follow the new rule. A change of `sample.every` starts at the next interval; old samples keep their spacing.
- **A name taken out of `fields`** leaves every read, export and `rows list` at once, then is removed from the samples on disk in the background, a batch at a time, which carries on after Legato restarts. Collecting doesn't wait. A name put back shows new values only; old ones stay gone.
- **A changed key** pauses with "Paused: the page now keys its samples differently", and the choice is **Start new history**: a sample keeps its fields' results, not the item, so there's nothing to re-key from.
- **A history keeps its kind.** A page that collects a history of records as samples, or one of samples as records, keeps nothing and Settings says so. Delete the history to start one of the other kind, collect under another name, or change the page back.
- A changed secret, a new `account` and a missing page behave as for records.

### Limits for samples

Samples have their own limits, apart from records', so a history of samples never stops Parcel's deliveries from being kept:

| | Limit |
| --- | --- |
| One sample | 512 bytes of JSON |
| One answer | 2,000 items |
| One history of samples | 10,000 items, and 200 MB |
| Every history of samples together | 400 MB |
| A read without `key` | 100,000 samples |

- **At a limit, a history makes room in itself:** its oldest day of samples goes, across all its items, then the next, until it fits, counted as pruned for space. It never takes room from another history, and never the interval being written. Only when a history has nothing older to give does its batch wait, and Settings says History storage is full, as for records.
- A new item past 10,000 isn't kept and is counted as rejected; it never pushes another out.
- Thirty items every 5 minutes for a year are about 3.15 million samples: about 80 MB of row data, and more on disk with the database's indexes.

