# OIP-0018: Trigger definitions and evaluations

| Field | Value |
|---|---|
| Status | DRAFT |
| Affects | §4.2 (TriggerDefinition, TriggerEvaluation row), new §15; new schemas `trigger-definition` and `trigger-evaluation` |
| Requires | OIP-0006 (origin vocabulary), OIP-0008 (signature envelope). Answers OIP-0005 open question 1. The shared definitions (`SignatureEnvelope` with its `Digest` and `ProtocolRole`) are copied verbatim, so the patches apply to the current tree on their own |
| Protocol version | obsp/0.1 (additive) |

## Problem

OIP-0005 lets an alert notice reference "the trigger definition it evaluated" only by URI and digest. Nothing says what
a trigger definition contains, so two operators cannot agree on what a notice proved, a consumer cannot check it, and
parametric or anticipatory-action schemes, which pay or act on a declared condition, have no protocol object to point
at. Nor is there a record of an evaluation: which observations were used, which were left out and why, and whether the
result was "not met" or "not enough evidence to say".

## Change

### Normative text (new §15 "Trigger definitions and evaluations")

The full text is in `patches/spec.patch`; in short:

| Id | Requirement |
|---|---|
| TRG-1 | A definition states subject (observed property or product type, never both), basis (`observed`, `forecast`), condition, window, minimum evidence, spatial scope, quality requirement, admitted origins, version and owner role; it is signed; a change is a new version that names the one it supersedes |
| TRG-2 | Conditions: threshold (max, min, mean, sum, last), nearest-rank percentile, rate of change (scaled to `perSeconds`), compound `all`/`any` of 2 to 16 conditions, at most four deep; UCUM units, never converted implicitly |
| TRG-3 | Admission rules in a fixed order: PROPERTY, WINDOW (start exclusive, end inclusive, by result time), SCOPE, VALUE, UNIT, QUALITY (every flag `GOOD`, at least one), TIME (trusted), ORIGIN; every considered input is recorded and each excluded one carries the first rule it failed |
| TRG-4 | An observed basis never admits `SIMULATED`; a forecast basis admits `MODEL_DERIVED` or `SIMULATED`; the evaluation repeats the basis; a forecast result is never presented as an observation |
| TRG-5 | `MET`, `NOT_MET`, `INSUFFICIENT_EVIDENCE`; too few admitted inputs is `INSUFFICIENT_EVIDENCE`, never `NOT_MET`; compounds use three-valued (strong Kleene) logic |
| TRG-6 | The evaluation references the definition by UNI, version and digest (sha256 over RFC 8785 without `signature`), carries the window, inputs by digest, exclusions, computed values per condition, result and evaluator, and is signed |
| TRG-7 | Deterministic and reproducible, whatever the input order; computed values rounded half to even to six places before comparison; a verifier that gets a different result rejects the evaluation |
| TRG-8 | A notice, payout decision or anticipatory action rests on a `MET` evaluation of the definition it names; `INSUFFICIENT_EVIDENCE` is never treated as `MET` or `NOT_MET` |
| TRG-9 | A correction of an input makes the evaluator evaluate again; the new evaluation supersedes the old one and names the correction notice |

With OIP-0005: `alert-notice.trigger.uri` is the definition's `triggerUni` and `trigger.digest` its digest; ALRT-1
then also names the evaluation (an `evaluationUni` member is proposed for OIP-0005's `trigger` object on acceptance of
both). ALRT-2's "every flag GOOD and trusted time" is TRG-3's admission rule, applied by the evaluator.

### Contracts (schemaVersion `3.1.0`)

`trigger-definition`: `triggerUni`, `version` (integer), `title`, `owner` (`role`, `participantUni`), `basis`, `subject`
(`observedProperty` or `productType`, optional `unit`), `condition` (`$defs.Condition`: `Threshold`, `Percentile`,
`RateOfChange`, `Compound`, told apart by `kind`; a leaf may name its own `observedProperty` inside a compound),
`window.durationSeconds`, `minimumEvidence`, `spatialScope` (`bbox`, `geocodes`, `featureOfInterestUnis`,
`systemUnis`; an input in any of them is in scope), `qualityRequirement` (`acceptedFlags` const `["GOOD"]`,
`requireTrustedTime` const `true`), `originsAllowed` (the OIP-0006 origins; basis rules in `allOf`), `issuedAt`,
optional `validFrom`, `validTo`, `supersedes`, `references`, required `signature`, `extensions`.

`trigger-evaluation`: `evaluationUni`, `evaluatedAt`, `definition` (`triggerUni`, `version`, `digest`), `basis`,
`window` (`start`, `end`), `inputs` (`recordUni`, optional `recordVersion`, `digest`), `excluded` (`recordUni`,
`digest`, `reason`), `computed` (`path` as a JSON pointer into the definition, `kind`, `result`, `admitted`, `value`,
`unit`), `result`, `evaluator`, optional `supersedes` (`evaluationUni`, `digest`, `reason` `INPUT_CORRECTED`,
`LATE_INPUT` or `DEFINITION_SUPERSEDED`; `correctionRef` required for `INPUT_CORRECTED`), required `signature`.

The repository writes enum values in upper case, so the results are `MET`, `NOT_MET` and `INSUFFICIENT_EVIDENCE`
(met, not-met, insufficient-evidence in the work package text); `basis` keeps the lower-case words it was asked for.

### Reference evaluator and vectors

`sdk/python/src/obsp/triggers.py` (non-normative): `evaluate(definition, inputs, evaluatedAt)`, `reproduce`,
`definition_digest`, `normalise_record` (an observation record as an input: numeric `result` or `result.value`, the
quality entries, trusted time through a time-quality record in hand, the `origin` member of OIP-0006) and four suite
invariants: `trigger-definition-consistent` (nesting depth, units against the subject, supersedes an earlier version
of the same trigger, validity interval), `trigger-evaluation-links-definition` (definition in the set with that UNI,
version, digest and basis), `trigger-evaluation-reproducible` (a fresh run gives the recorded definition reference,
basis, window, inputs, exclusions, computed values and result; superseded evaluations are skipped) and
`trigger-evaluation-supersedes` (TRG-9 links to the old evaluation and the correction notice).

`conformance/vectors/triggers/`: `met`, `not-met`, `insufficient-evidence`, `origin-excluded`, `quality-excluded`
(QUALITY and TIME), `window-scope-unit-excluded` (WINDOW, SCOPE, UNIT, VALUE), `rate-of-change`, `compound`
(nested any/all, one branch INSUFFICIENT_EVIDENCE, MET overall), `compound-all-not-met`, `forecast-basis` (product type,
PROPERTY exclusion). Each vector holds the definition, the inputs, the evaluation time and the expected output.

## Compatibility

Additive: two new objects, no existing schema or document changes. Records written before OIP-0006 have no `origin`;
the evaluator never admits them (ORIGIN), which the example sets show.

## Tests

| Requirement | Case | Kind |
|---|---|---|
| TRG-1 to TRG-7, TRG-9 | CT-GRID-095 | the four invariants on `trigger-definition`, `trigger-evaluation` (and the set's observation, time-quality and correction records) |
| TRG-4 to TRG-9 | CT-CONSUMER-095 | `trigger-evaluation-links-definition`, `-reproducible`, `-supersedes` on the consumer's set |

The example evaluation in both sets is honest about the set's only observation record: it has no unit, so it is
excluded (UNIT) and the result is `INSUFFICIENT_EVIDENCE`. `sdk/python/tests/test_triggers.py` (17 tests) runs every
vector, checks input-order independence, the window boundary, three-valued logic and the digest rule, and breaks each
invariant (tampered result, missing input, digest and basis mismatch, unit mismatch, supersession after a correction).

Positive fixtures: `trigger-definition.threshold.valid`, `.compound.valid`, `.compound-forecast.valid`;
`trigger-evaluation.met.valid`, `.insufficient.valid`. Negative, one rule each: `trigger-definition.simulated-on-observed-basis`,
`.forecast-without-model-origin`, `.quality-not-good-only`, `.untrusted-time-allowed`, `.compound-single-condition`,
`.unknown-operator`, `.missing-signature`, `.no-spatial-scope`, `.percentile-zero`, `.zero-window`,
`.property-and-product`; `trigger-evaluation.unknown-result`, `.definition-without-digest`, `.excluded-without-reason`,
`.missing-signature`, `.corrected-without-notice`.

## Relation rows proposed on acceptance (not in the patches)

```yaml
  - { id: EXT-UCUM, standard: 'Unified Code for Units of Measure (UCUM)', kind: aligns-with, schemas: [trigger-definition, trigger-evaluation] }
```

and `EXT-RFC8785` gains `trigger-definition` and `trigger-evaluation` (the definition digest). Then run
`python3 tools/build_edges.py`. `registers/functions.yaml`: `exchange` objects gain `trigger-definition` and
`trigger-evaluation`; that line is also edited by OIP-0001 and OIP-0005, so it is left to acceptance.

## Open questions

1. Coverage placement: both cases cite `correct`, because the §5.10 index rows are changed by OIP-0001, OIP-0005 and
   OIP-0009 to OIP-0011 and a case under `exchange` would stop those patches applying. On acceptance they move to
   `exchange` (keeping `correct` for TRG-9). A manual consumer case for TRG-8 (the decision, not only the evidence)
   joins with the OBSP-CONSUMER attestations that OIP-0001 and OIP-0005 also edit.
2. Rounding to six decimal places suits the units in the vectors; should the precision be a definition field?
3. Percentile reference: `reference` records where a percentile value comes from (a climatology) but is not read. Should
   a definition be able to carry the reference distribution itself?
4. Spatial scope uses bounding boxes, geocodes, features and systems; polygons would need a geometry library in every
   evaluator. Wanted?
5. Section number: §15 assumes OIP-0016's §14; renumber if this proposal is accepted first.
6. Last call: revision (30 days) or new capability (90 days)?
