# Derivations

A derivation reads one source row (an order, a delivery, a reservation), looks up
related rows, asks decision tables for parameters and matching rules, and
appends the result as one entry to an append-only record type. Every write
stores an immutable trace: the source values, lookups, table matches, the
releases used, the configuration snapshot and the result rows.

Typical use: every new order becomes stock movements, one row per warehouse
bucket, with the shelf chosen by a second table.

## Flow

1. Publish the source type, the append-only target type and the decision
   tables (see read_docs("rules")). Release every table with `rules.release`.
2. `derivations.create` with `space_id`, `key`, `name`, `source_type_id`,
   `target_type_id` and `config`. Errors list every invalid path in
   `details.issues`.
3. `derivations.preview` with `derivation_id` and `record_id`: the entry that
   would be written, the facts behind it and a `proposal_hash`. Nothing is
   written.
4. `derivations.run` with the same ids and `expected_proposal_hash` from the
   preview: appends the entry and stores the trace.
5. `derivations.traces.list` / `derivations.traces.get` to read what happened.

## Configuration

```json
{
  "lookups": [
    {"name": "customer", "relation": "customer", "required": true},
    {"name": "warehouse", "type": "warehouses",
     "match": {"field": "code", "value": "source.warehouse_code"}}
  ],
  "parameters": [
    {"name": "max_weight", "table": "weight_limits", "at": "source.ordered_on",
     "input": {"region": "source.region"}, "output": "max_weight"}
  ],
  "tables": [
    {"name": "rate", "table": "shipping_rates", "at": "source.ordered_on",
     "input": {"region": "source.region", "weight": "source.weight"}, "required": true},
    {"name": "split", "table": "stock_splits", "at": "source.ordered_on",
     "input": {"region": "source.region"}, "required": true},
    {"name": "place", "table": "shelf_locations", "for_each": "split",
     "at": "source.ordered_on", "input": {"bucket": "match.bucket"}, "required": true}
  ],
  "entry": {
    "key": "concat(\"order-\", source.order_no)",
    "effective_on": "source.ordered_on",
    "source": "concat(\"orders:\", source.id)",
    "trace_field": "trace",
    "rows": [
      {"for_each": "split",
       "values": {
         "name": "concat(source.order_no, \" \", match.bucket)",
         "moved_on": "source.ordered_on",
         "bucket": "match.bucket",
         "shelf": "match.place.location",
         "quantity": "round(source.weight * match.share, 2)"}},
      {"when": "source.weight > param.max_weight", "required": false,
       "values": {
         "name": "concat(\"Heavy parcel for \", lookup.customer.name)",
         "moved_on": "source.ordered_on",
         "shipping": "table.rate.first.price"}}
    ]
  }
}
```

- `lookups`: `relation` follows a record_relation field of the source and needs
  exactly one linked row; `type` + `match` finds exactly one active row whose
  `field` equals the value (text, number, date, boolean or single_select
  fields). More than one row fails with `lookup_ambiguous`; none fails with
  `lookup_missing` when `required` is true, otherwise the lookup is null.
- `many: true` (only with `relation`) reads every linked row, ordered by
  creation, up to 500; more fail with `lookup_too_many`. No row is an empty
  list; with `required: true` at least one row must be linked. Read it through
  `lookup.<name>.count`, `lookup.<name>.sum.<field>` or a `for_each`.
- `parameters`: one value from a decision table. Exactly one rule must match.
- `tables`: all matching rules of a decision table at the date `at`. `input`
  covers every input of the table. `for_each` evaluates the table once per
  match of an earlier table that has no `for_each` itself, or once per row of
  a `many` lookup (one level).
- `entry.key`, `entry.effective_on` (a date), `entry.source` (text, optional).
- `entry.trace_field`: a text field of the target that receives
  `adlass:trace:<trace id>` on every row. It is not part of the proposal hash.
- `entry.guards` (optional): `[{"when": <boolean expression>, "code": <machine
  key>, "message": <text>}]`, checked after lookups, parameters and tables and
  before the rows. A guard whose `when` is false or null stops the run with
  `derivation_guard_failed` and `details` `code`, `message` and `path`
  (`entry.guards[i]`); automatic runs keep it in the failed trace. Example:
  `{"when": "source.weight > 0", "code": "weight_missing", "message": "The
  order has no weight."}`.
- `entry.rows`: row templates. Without `for_each` a template makes at most one
  row; with `for_each` one row per match of that table or per row of that
  `many` lookup. `when` skips the row
  when false or null; with `required: true` a false condition fails the run
  with `derivation_row_required`. `values` names target fields; every template
  sets the title field, the effective date field and every required field. The
  platform sets `entry_key` itself.
- All types live in the derivation's Space. The target is append-only and
  differs from the source. Tables are decision tables.

### Linked rows

An order links its items through the record_relation field `items`; every item
becomes one movement, its account comes from a table per item, and a closing
row books the order total:

```json
{
  "lookups": [{"name": "items", "relation": "items", "many": true, "required": true}],
  "tables": [
    {"name": "account", "table": "item_accounts", "for_each": "items",
     "at": "source.ordered_on", "input": {"category": "match.category"},
     "required": true}
  ],
  "entry": {
    "key": "concat(\"order-\", source.order_no)",
    "effective_on": "source.ordered_on",
    "guards": [
      {"when": "lookup.items.sum.amount == source.total",
       "code": "items_incomplete", "message": "The items do not add up to the total."}
    ],
    "rows": [
      {"for_each": "items",
       "values": {"name": "match.title", "moved_on": "source.ordered_on",
                  "account": "match.account.code", "credit": "match.amount"}},
      {"values": {"name": "source.order_no", "moved_on": "source.ordered_on",
                  "account": "\"receivables\"", "debit": "source.total"}}
    ]
  }
}
```

Inside such a `for_each`, `match.<field>` reads the linked row (also
`match.id`, `match.title`) and `match.<table>.<output>` the single match of a
table with `for_each` on the same lookup.

The guard on `.sum` stops entries whose items are incomplete. When items and
total may differ by rounding, allow the gap in the guard
(`abs(source.total - lookup.items.sum.amount) < 1`) and book it as its own row
with `when`, since `balanced` has no tolerance:
`{"when": "source.total != lookup.items.sum.amount", "values": {...,
"account": "\"rounding\"", "credit": "source.total - lookup.items.sum.amount"}}`.

## Expressions

Every value in the configuration is an expression.

- Literals: `12`, `0.19`, `"text"`, `true`, `false`, `null`, dates as
  `d"2026-01-01"`.
- References: `source.<field>` (plus `source.id`, `source.title`; money as
  `source.<field>.amount` / `.currency`), `lookup.<name>.<field>`,
  `lookup.<many>.count`, `lookup.<many>.sum.<field>` (number fields, or the
  amounts of a money field in one currency; mixed currencies fail),
  `param.<name>`, `table.<name>.count`, `table.<name>.first.<output>` (only when
  exactly one rule matches; with no or several matches it is null, without an
  error), and inside `for_each`: `match.<output>`, `match.rule_key`,
  `match.<nested table>.<output>`, or `match.<field>` of a linked row.
- A `collect` table can match several rules: read them with a row template
  `for_each` and `match.<output>`, not with `table.<name>.first`. Check
  `table.<name>.count` when exactly one match is expected.
- Operators: `+ - * /`, `== != < <= > >=`, `and or not` (short-circuit).
- Functions: `round(x, n)` (half up), `abs`, `min`, `max`, `coalesce`,
  `concat`, `when(cond, a, b)`, `date`, `year`, `month`, `number`, `text`,
  `lower`, `upper`, `is_null`.
- Null: a missing reference is null; arithmetic with null is null; comparisons
  with null are false except `== null` / `!= null`. Division by zero fails.
- A number into a money field uses the field's default currency.

## Preview and run

`derivations.preview` defaults to `mode: released`: every decision table uses
its latest release; a table without release fails with `release_required`.
`mode: working` uses the current table rows to try changes before a release;
its proposal is marked `writable: false`.

`derivations.run` always uses releases. With `expected_proposal_hash` the run
fails with `proposal_stale` when anything changed since the preview.

Running the same source row again returns its current trace and entry
(`created: false`), also after a rerun. When the result differs from the
current one, or its entry was reversed, the run fails with `entry_conflict`;
use `derivations.rerun`. Entry keys must not end with `@` and a number: reruns
add that suffix.

## Rerun

`derivations.rerun` (`derivation_id`, `record_id`, `effective_on`) needs Space
administration rights. It reverses the
last entry of this source row on `effective_on` and appends the new result as
`<entry key>@<n>`, where `n` counts the earlier runs with an entry plus one.
The same `@<n>` is appended to every field of the target's
`kind_config.reversal.keys` (its unique text fields), so the new rows do not
collide with the original ones; values longer than 255 characters fail. All of
this runs in one transaction. An entry that is already reversed is not reversed
again. Runs and reruns of the same source row wait for each other. The new
trace points to the trace it supersedes.
Assistants need the person's approval.

After a lock (`records.locks.set`), reverse and rerun with an `effective_on`
after the lock date.

## Automatic runs

With `auto_run: true` every new source row starts a durable job under the user
who switched it on. `derivations.jobs.list` shows the jobs (`queued`,
`running`, `succeeded`, `failed`, `skipped`). A domain error (for example a
missing release) stores a `failed` trace with the error and the facts gathered
so far; the job is not retried. Database outages are retried. Jobs are skipped
when the derivation was archived or switched off, the user is inactive or the
Space is read-only.

`run_when` in the config limits automatic runs to rows that are ready, for
example after an approval: a boolean expression over `source.*` and
`lookup.*` (no `param`, `table` or `match`), such as
`"source.status == \"approved\""`. With `run_when`, a new row starts a job and
so does an update that changes a field named as `source.<field>` in
`run_when`, as long as the row has no entry of this derivation yet. Other
updates, such as linking rows to the source row, start nothing. The job reads
the current row and skips (`skipped`, no trace) when `run_when` is false or the
row got an entry in the meantime. Existing entries are never run again
automatically; use `derivations.rerun`. Without `run_when` only new rows start
jobs.

Rows written by a derivation never start other derivations automatically.
Rows of a reversal entry (`<entry key>#reverse`) in an append-only source type
start no jobs either. Bulk imports start no jobs: afterwards call
`derivations.run_pending` (`derivation_id`, `limit` up to 1000, default 100).
It queues a job for every row, oldest first, that has no entry of this
derivation and no `queued` or `running` job (rows of a reversal entry are left
out), and returns `queued`, `skipped` (rows another call queued at the same
time) and `has_more`; call it again while `has_more` is true. It needs
`auto_run` and also retries rows whose job failed or was skipped: rows without
any job come first, then the least recently tried ones. `has_more` stays true
only while rows without any job remain, so rows that keep failing never make
the loop endless. `derivations.jobs.list` shows which rows have a job.

## Trace

A trace holds `facts` (source values, lookups, a list of rows for `many`
lookups, parameter values, matches per table and per parent match or linked
row), `releases` (`type_key`, `release_id`, `number`,
`content_hash`), the `config` snapshot and `config_hash`, `engine_version`,
`result` (rows without the trace field) and `result_hash`, `entry_id`,
`supersedes_id` and `job_id`. Traces never change.

## Errors

- `derivation_config_invalid`: fix the paths in `details.issues`.
- `expression_error`: the expression at `details.path` does not parse or has
  the wrong type.
- `release_required`: release the tables in `details.tables`, or preview in
  working mode.
- `no_match` / `ambiguous_match`: the table at `details.path` has no rule or
  several rules for `details.input`; add or prioritise rules and release.
- `lookup_missing` / `lookup_ambiguous`: link or create exactly one row.
- `lookup_too_many`: the `many` lookup at `details.path` links more than
  `details.limit` rows.
- `derivation_row_required`: a required row template produced no row.
- `derivation_guard_failed`: a guard is false; `details.code` and
  `details.message` say which check failed.
- `proposal_stale`: preview again and pass the new `proposal_hash`.
- `entry_conflict`: another result exists under this key; use
  `derivations.rerun`.
- `entry_locked`: the entry date lies on or before the target's lock date.
- `entry_unbalanced`: the proposed rows break a `balanced` constraint of
  the target; `details.issues` lists the difference per group.
- `nothing_to_rerun`: run the derivation once first.
- `derivation_inactive`: the derivation is archived.
- `derivation_key_taken`: an active derivation with this key exists.
- `auto_run_required`: turn `auto_run` on before `derivations.run_pending`.
- Skipped jobs carry `error.code` `run_when_false` or `already_derived` when
  `run_when` stopped them.

Routine runs get derivations_preview and derivations_run for derivations whose
source, target and every type they read (lookups, tables, parameters) lie in
their record scope. derivations_run counts its rows toward the run's row cap;
a rehearsal only previews. derivations.run_pending and derivations.rerun stay
with people, because pending jobs run as the user who switched auto_run on.
