# Summaries

A summary turns the rows of an append-only record type into totals per period:
for example outgoing stock per month, or points earned per quarter. The
definition says which rows count and how; `summaries.compute` stores each
result as an immutable run with its values, evidence and a content hash, and a
person confirms the run once it is final.

Summaries only read append-only types, because their rows never change after
they are written. A confirmed run therefore stays reproducible: the same
definition over the same period and data gives the same `content_hash`.

## Flow

1. `records.types.describe` on the append-only type: note the field keys.
2. `summaries.create` with `space_id`, `record_type_id`, `key`, `name` and
   `config`. Errors name the invalid config path.
3. `summaries.compute` with `definition_id`, `period_start` and `period_end`
   (exclusive, at most 5 years). Every call stores a new run; nothing is
   overwritten.
4. `summaries.runs.list` (newest first, without lines) and `summaries.runs.get`
   (complete run) to read results.
5. `summaries.confirm` with `run_id` once a person agrees with the values.
   Assistants need the person's approval for this step.

## Configuration

```json
{
  "period_field": "moved_on",
  "bucket": "month",
  "group_by": ["warehouse"],
  "lines": [
    {
      "key": "outgoing",
      "label": "Outgoing units",
      "filter": {
        "conditions": [{"field": "direction", "op": "eq", "value": "out"}]
      },
      "measure": {"field": "quantity", "agg": "sum"},
      "sign": -1,
      "corrections": {"field": "is_correction", "mode": "separate"},
      "rounding": {"unit": 100, "mode": "half_up"},
      "requires": {
        "type": "stock_counts",
        "filter": {
          "conditions": [
            {"field": "year", "op": "eq", "value": "{bucket.year}"},
            {"field": "month", "op": "eq", "value": "{bucket.month}"}
          ]
        }
      }
    },
    {"key": "movements", "label": "Movements", "measure": {"agg": "count"}}
  ]
}
```

- `period_field`: a date field of the type. Rows count when
  `period_start <= value < period_end`; archived rows never count.
- `bucket`: `month`, `quarter`, `four_month` (January-April, May-August,
  September-December), `year` or `whole` (one bucket for the full period).
  Buckets follow the calendar and are cut at the period edges.
- `group_by`: up to two text, single select, date or number fields; each
  bucket then has one result per group value.
- `lines` (1 to 100), each with a unique `key` and a `label`:
  - `filter`: the same filter tree as `records.rows.query`; empty means all rows.
  - `measure`: `sum` of a number or money field, or `count` of rows. A sum
    may set `weight_field` (a number field); each row then adds
    `field * weight`, and an empty weight counts as `1`. Example: with
    `{"field": "amount", "agg": "sum", "weight_field": "share"}` a row with
    amount 200 and share 0.25 adds 50.
  - `sign`: `1` or `-1`, applied after the corrections.
  - `corrections`: a boolean field that marks correction rows. `net` subtracts
    the correction rows from the other rows; `separate` keeps both values apart
    (`base` and `corrections`).
  - `rounding`: rounds to a multiple of `unit` (half up), applied last.
  - `requires`: an evidence condition. The line looks for rows of another
    record type that match the filter; without a match the line is `pending`
    in that bucket. Its values are still computed and shown.
  - `cumulative`: `true` makes the line a balance at the end of each bucket
    (see below). Default `false`.

## Cumulative lines

A cumulative line counts every row with `value < bucket end`, without a lower
bound: stock on hand, a points balance, open items or an account balance at
the cut-off date. Filter, corrections, sign, `weight_field` and `count` work as
usual; rounding applies to the accumulated value. A group shows up in every
bucket in which its balance is not zero, also without movements in that
bucket; groups whose balance is zero are left out. `rows` counts all rows up
to the bucket end, and `rows_included` and `data_through` include the rows
before `period_start`. The 5-year limit applies only to the bucket grid, not
to the data.

Signed movements come from the data (a signed field, `weight_field`) or from
two lines with opposite `sign`. A trial balance per account uses three lines:

```json
[
  {"key": "debits", "label": "Debits", "measure": {"field": "debit"}},
  {"key": "credits", "label": "Credits", "measure": {"field": "credit"}},
  {"key": "closing", "label": "Closing balance", "measure": {"field": "balance"}, "cumulative": true}
]
```

The opening balance of a bucket is `closing - debits + credits`.

## Placeholders

String values in `requires.filter` may contain `{bucket.start}`,
`{bucket.end}` (dates, end exclusive), `{bucket.year}`, `{bucket.month}` (first
month of the bucket) and `{bucket.index}` (position of the bucket within its
year, starting at 1). `{bucket.month2}` and `{bucket.index2}` are the same
numbers as two-digit text with a leading zero (`05`), for example
`"{bucket.year}-{bucket.month2}"` gives `2026-05`. A value that is only a
placeholder keeps its type for number and date fields; inside text it is
replaced as text.

## Run contents

A run holds the period, bucket, a snapshot of the configuration with its hash,
the published schema version, `engine_version`, `rows_included`,
`data_through` (newest row creation time seen) and `snapshot_xmin`. Each line
has one result per bucket and group with:

- `base`, `corrections`, `raw` (value after corrections and sign), `rounded`
  and `corrections_rounded`, all as decimal strings
- `rows` (number of rows counted), `status` (`ok` or `pending`) and `evidence`
  (ids of the records that satisfied `requires`)

## Immutability and confirmation

Runs never change and cannot be deleted, also not directly in the database.
The single allowed change is `summaries.confirm`: status `computed` becomes
`confirmed` with time and person. To correct a result, append correction rows
to the source type and compute a new run. Changing a definition does not touch
existing runs. Archiving a definition keeps its runs readable and frees its key.

## Errors

- `summary_config_invalid`: the configuration does not fit; `details.issues`
  lists each path and problem.
- `summary_target_invalid`: the record type is not a published append-only type.
- `summary_key_taken`: an active summary with this key exists in the Space.
- `summary_archived`: the summary is archived and cannot be changed or computed.
- `summary_timeout`: the computation took too long; shorten the period or use
  a coarser bucket.
- `result_too_large`: a line yields more than 10,000 groups.
- `summary_run_confirmed`: the run is already confirmed.
- `validation_error`: `period_start` is not before `period_end`, or the period
  is longer than 5 years.
