> ## Documentation Index
> Fetch the complete documentation index at: https://docs.molpha.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Policies

> Combine several inputs into one value, decide when the data is not good enough, and sign a declared fallback instead of refusing.

A **policy** is an optional block of a [source](https://docs.molpha.io/concepts/sources.md). It turns each input into a **candidate** value, qualifies or disqualifies each candidate by its own **rules**, **combines** the qualifying candidates into one value, and decides whether the result is **conclusive**. When it is not, the policy can declare a **fallback**: a value the nodes sign under the same `sourceId` instead of refusing the round.

A policy changes nothing about the attestation. It is still `value`, `sourceId`, `registryVersion`, `signaturesRequired` and `timestamp`, signed once and verified unchanged on Solana, EVM and Starknet. Verifiers, tickets and feeds see an ordinary attestation.

For a step-by-step walkthrough, see [Write and test a policy](https://docs.molpha.io/guides/policies.md).

## Where it runs

Each node evaluates the whole policy on its own fetches, between decoding the inputs and running the transform:

```text theme={null}
fetch -> decode -> [ candidates -> rules -> combine -> inconclusiveIf ] -> transform -> assert -> output
                     \______________________ policy ______________________/
```

A source without a `policy` key evaluates exactly as before, and its `sourceId` does not change. The policy is part of the canonical source, so `sourceId` commits to the policy, to whether an INCONCLUSIVE result can ever be signed, and to what is signed.

## The policy block

```json theme={null}
"policy": {
  "candidates": {
    "venueA": {
      "role": "corroborating",
      "value": { "op": "rescale", "args": [{ "op": "num", "args": [{ "ref": "venueA.price" }], "mode": "dec" }], "scale": "2", "round": "halfEven" },
      "weight": null,
      "rules": [],
      "onError": "disqualify"
    },
    "venueB": { "...": "the same over venueB" },
    "venueC": { "...": "the same over venueC" }
  },
  "combine": { "op": "median", "minQualifying": "2", "maxSpreadBps": "100", "order": null },
  "independence": "distinctHosts",
  "inconclusiveIf": [],
  "inconclusive": { "fallback": { "const": "-1" } }
}
```

`policy` is a top-level key of the source. Omit it when unused; `"policy": null` is rejected. Inside the block every key is present and an absent optional is `null`, as everywhere else in a source. The SDK's `defineSource` fills the defaults for you; a node or gateway rejects a missing key.

| Key | Value | SDK default |
| - | - | - |
| `candidates` | 1 to 4 entries, each named after a declared input | none |
| `candidates.<in>.role` | `primary`, `corroborating` or `fallback` | `corroborating` |
| `candidates.<in>.value` | Expression yielding a decimal | The input's field, when it has exactly one |
| `candidates.<in>.weight` | Decimal of at least 0. Required for `weightedMedian`, `null` otherwise | `null` |
| `candidates.<in>.rules` | 0 to 8 boolean expressions; all must hold | `[]` |
| `candidates.<in>.onError` | `disqualify` or `refuse` | `disqualify` |
| `combine.op` | `single`, `median`, `weightedMedian`, `allEqual`, `majority`, `fallback`, `primaryPlusOne` | `single` with one candidate, `median` otherwise |
| `combine.minQualifying` | Minimum qualifying candidates, or `null` (by op) | The candidate count, where the op takes it |
| `combine.maxSpreadBps` | 0 to 10000, or `null` (by op) | `null` |
| `combine.order` | Every candidate name once, for `fallback`; `null` otherwise | Candidate names in byte order, for `fallback` |
| `independence` | `none`, `distinctHosts` or `distinctChains` | `distinctHosts` with 2+ candidates, `none` with one |
| `inconclusiveIf` | 0 to 8 boolean expressions | `[]` |
| `inconclusive.fallback` | `null`, or a fallback expression | `null` |

An input that is not a candidate is a **helper** input. It is fetched and decoded as usual, and `inconclusiveIf`, `transform` and `assert` can read its fields, but it is never qualified or combined.

### Combinators

`n` is the number of qualifying candidates. Sorting is ascending by value, ties broken by input name.

| `op` | Candidates | Takes | INCONCLUSIVE when | Result (`$agg`) |
| - | - | - | - | - |
| `single` | exactly 1 | | the candidate does not qualify (`0x01`) | the candidate's value |
| `median` | 2 to 4 | `minQualifying`, optional `maxSpreadBps` | `n < minQualifying` (`0x01`); spread too wide (`0x02`) | the lower median |
| `weightedMedian` | 2 to 4 | `minQualifying`, optional `maxSpreadBps`, `weight` on every candidate | `n < minQualifying` or zero total weight (`0x01`); spread too wide (`0x02`) | the weighted lower median |
| `allEqual` | 2 to 4 | `minQualifying` | `n < minQualifying` (`0x01`); values differ (`0x02`) | the common value |
| `majority` | 2 to 4 | `minQualifying` | `n < minQualifying` (`0x01`); no value held by more than half (`0x02`) | the majority value |
| `fallback` | 2 to 4 | `order` | no candidate qualifies (`0x01`) | the first qualifying candidate in `order` |
| `primaryPlusOne` | 2 to 4 | `maxSpreadBps`; exactly one `primary`, at least one `corroborating` | the primary does not qualify, or no corroborating value is within `maxSpreadBps` of it (`0x03`) | the primary's value |

The spread check for `median` and `weightedMedian` is `(max - min) * 10000 <= abs($agg) * maxSpreadBps`, computed exactly. All arithmetic is exact decimal. Evaluation reads no node clock and no randomness: time enters only through the round timestamp.

### Independence

Checked when the source is parsed, so a gateway and a node reject the same sources:

* `none`: no check.
* `distinctHosts`: no two `http` candidates share a URL host name. Chain candidates are not compared.
* `distinctChains`: every candidate is a chain input and no two read the same chain.

`distinctHosts` cannot see two host names that serve one upstream, such as a mirror or an aggregator. Independence of origin is declared, not proven.

### References

Policy expressions use the transform grammar plus `and`, `or`, `not` and `in`, and these references:

| Reference | Meaning | Readable in |
| - | - | - |
| `$value` | The candidate's value | that candidate's `rules` and `weight` |
| `$agg` | The combined value | `inconclusiveIf`, `transform`, `assert` |
| `$n` | The number of qualifying candidates | `inconclusiveIf`, `transform`, `assert`, the fallback |
| `$tsMs` | The round timestamp in milliseconds (`$ts` stays whole seconds) | wherever `$ts` is |
| `$reason` | The INCONCLUSIVE reason code | the fallback only |

A candidate's `value`, `rules` and `weight` read only that candidate's own input, so whether one input qualifies never depends on another. Comparisons between inputs belong in the combinator.

> [!TIP]
>
> In `inconclusiveIf`, `transform` and `assert`, read `$agg`, `$n` and helper inputs, not a candidate's fields. A candidate's input may have failed, and reading a failed input there refuses the round. The analysis warns about this (`readsCandidateField`).

## How nodes evaluate it

1. **Fetch and decode** every input concurrently. With a policy, one input's failure does not cancel the others.
2. **Helper inputs.** A helper input that failed refuses the round.
3. **Candidates**, in input-name order. A failed input or an expression error is handled by `onError`: `disqualify` drops the candidate, `refuse` refuses the round. The first rule that is `false` disqualifies the candidate. Otherwise it qualifies.
4. **Combine** the qualifying candidates into `$agg` and `$n`. A failed constraint makes the result INCONCLUSIVE.
5. **`inconclusiveIf`**, in order. The first entry `i` that holds makes the result INCONCLUSIVE with reason `0x10 + i`. An entry that errors refuses the round.
6. **Transform, assert, encode.** This is the CONCLUSIVE result.
7. **INCONCLUSIVE.** With a fallback, the node evaluates and encodes it (assertions do not run on it). Without one, it refuses.

Some failures are never a verdict on the data. They refuse the round for any input, candidate or not, and never lead to the fallback: the node's own fetch deadline, the node's own fetch limits (a per-host cap or an open circuit breaker), and an upstream that rejects the payment, provider credential or secret the request carried with HTTP 401, 402 or 403. A caller therefore cannot turn a round into the fallback by sending a bad payment.

## Outcomes

| What the policy concludes | Fallback declared | No fallback |
| - | - | - |
| A refusal (an `onError: refuse` candidate, a helper input, an error in `inconclusiveIf`, `transform`, `assert` or encoding) | refused | refused |
| A combinator constraint fails | **fallback** signed, reason `0x01` to `0x03` | refused at stage `policy inconclusive` |
| `inconclusiveIf` entry `i` holds | **fallback** signed, reason `0x10 + i` | refused at stage `policy inconclusive` |
| Otherwise | **conclusive**: the transform's result | **conclusive** |

INCONCLUSIVE is only ever what the policy's own rules conclude from data that was fetched. Errors are refusals, not verdicts.

### Reason codes

| Code | Meaning |
| - | - |
| `0x01` | Insufficient sources: fewer than `minQualifying` qualified (none, for `single` and `fallback`; zero total weight, for `weightedMedian`) |
| `0x02` | Source divergence: the spread, equality or majority constraint failed |
| `0x03` | Primary unconfirmed (`primaryPlusOne`) |
| `0x10` to `0x17` | `inconclusiveIf` entry 0 to 7 held |

## The fallback

The fallback is an expression over literals, `$reason` and `$n` only: a literal, `{"ref": "$reason"}`, `{"ref": "$n"}`, or an `if` over tests (`eq`, `ne`, `lt`, `lte`, `gt`, `gte`, `in`, `and`, `or`, `not`) of those. So a policy can sign one value for every INCONCLUSIVE result, or a different value per reason.

The set of values a fallback can produce is known without running it. Each of them must encode under the source's `output` (exactly, at its `decimals`), or the source is rejected. A node therefore never reaches an INCONCLUSIVE result it cannot sign.

### Fallback words

The 32-byte words a fallback can sign are its **fallback words**. They are what the outcome is read from. For example, a fallback of `-1` on an `int256` output with 2 decimals signs `-100` in two's complement:

```text theme={null}
0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff9c
```

The SDK computes them with `fallbackWords(source)`; the analysis lists them too.

### Keeping the fallback distinguishable

A consumer tells the fallback from a result by the value alone, so make the fallback a value no result can be:

* pair it with an assertion that excludes it, such as `-1` with `gte($out, 0)` on a price; or
* pick a value the transform cannot produce, such as `2` on a `uint256` verdict whose transform yields only `1` or `0`.

The analysis checks this and reports `fallback.reachable`, with the warning `fallbackReachable` when a result could encode to a fallback word. It warns and never rejects: mapping INCONCLUSIVE onto a result value can be deliberate.

> [!WARNING]
>
> Mind the rounding. An `int256` or `uint256` output rounds the result half-even to its `decimals`, so the assertion must exclude everything that rounds to the fallback word. At 8 decimals, `gt($out, -1)` does not exclude a fallback of `-1` (`-0.999999996` passes and encodes as `-1`); `gte($out, -0.99999999)` does.

## Reading the outcome

The outcome of a round is read from the **signed value**:

* a value among the source's fallback words is the **fallback**: the policy concluded INCONCLUSIVE;
* any other value is **conclusive**.

The gateway and the SDK both read it this way. A node also labels a fallback with `outcome: fallback` and its `reason`, but that label is not signed. The gateway uses it only to supply the reason code, and only when it agrees with the value; a label that disagrees is dropped and never costs a signed round. The `reason` you receive is therefore a hint, not something a verifier can check.

In the SDK, `readOutcome(result.payload, source)` returns `{ kind: "conclusive" | "fallback", value }`, or `null` when the attestation is not for that source. On-chain, compare the verified `value` with the fallback words. See [Consume it on-chain](https://docs.molpha.io/guides/policies.md#7-consume-it-on-chain).

What INCONCLUSIVE means to you (wait, expire, refund, void) is your contract's decision. If a round settles something, also guard against outcome shopping: accept only attestations whose `timestamp / 1000` falls in your resolution window, and only the first one you accept.

## Signing modes

**Exact mode** (`aggregation: null`). Every signer must produce the identical message. A node that disqualified a venue the others accepted produces a different message, and the round fails. A fallback is signed only when every signer reaches the same fallback word. Exact mode suits verdicts (`bool`, `bytes32`) and single-candidate policies. The analysis warns (`exactComposite`) on an exact-mode policy with more than one candidate.

**Tolerance mode.** Each node's signed round-1 observation carries its outcome: CONCLUSIVE with its value, or INCONCLUSIVE with its fallback word. Every node then applies one rule:

1. If at least `signaturesRequired` observations are CONCLUSIVE, the median of those is signed, as in ordinary [tolerance mode](https://docs.molpha.io/concepts/sources.md). Only CONCLUSIVE in-band nodes sign.
2. Otherwise, if at least `signaturesRequired` observations are INCONCLUSIVE with the same fallback word, that word is signed. Only those nodes sign.
3. Otherwise the round fails.

A fallback that reads `$reason` or `$n` can give nodes different words; rule 2 needs `signaturesRequired` of them on one word.

### One outcome per round

A node signs at most once per round. The gateway admits a source with a fallback only when `signaturesRequired` is **above** the registry's redundancy buffer, so the selected set (at most `signaturesRequired` plus the buffer) cannot hold two disjoint quorums, one for the result and one for the fallback. Both would be under the same `sourceId`, so a node that signed both would be caught by the existing equivocation rule.

On the current devnet deployment the redundancy buffer is 2 and the minimum quorum is 3, so every admissible quorum qualifies.

A fallback is never signed in a provider round (`requireProvider`): the gateway rejects a fallback source with `requireProvider`, and a provider round needs a policy with exactly one candidate.

## Over HTTP

A round of a policy source is requested like any other round, at the same price.

| Situation | Gateway answer |
| - | - |
| Conclusive | `200`; `data.outcome` is `conclusive` |
| Fallback signed | `200`; `data.outcome` is `fallback`, `data.reason` the reason code (for example `0x01`) when the label agreed |
| INCONCLUSIVE with no fallback | `503`, `{"error": "node round failed: policy inconclusive: reason 0x01 (insufficient sources)"}` |
| Other refusal | `503` with the stage the nodes stopped at, for example `evaluating policy` |
| Fallback with `signaturesRequired` at or below the redundancy buffer | `400`, field `signaturesRequired` |
| Fallback with `requireProvider` | `400`, field `requireProvider` |

A source without a policy has no `outcome` field.

> [!WARNING]
>
> The SDK treats every `503` as a busy gateway and retries, up to `maxRetries` (6 by default). A policy that refuses will usually refuse again, and every retry is a new round that spends quota or needs another payment. For a policy source without a fallback, set `maxRetries` low.

Two free endpoints evaluate a policy without signing or charging anything:

* `POST /v1/source/preview` fetches the inputs and evaluates the source the way a node would, twice, a second apart.
* `POST /v1/source/simulate` evaluates the source over inputs you supply (a response body, decoded fields, or a failure), with the nodes' own evaluator. Nothing is fetched.

Both return a `policy` object: each candidate's `qualified`, `rule` (the first false rule) or `error` (`fetch` or `eval`), `n`, `agg`, `outcome` (`conclusive` or `inconclusive`), `reason`, and `signed` (the fallback is the value). See [Preview and simulate](https://docs.molpha.io/guides/policies.md#3-preview-it-against-live-data).

## Receipts

For every round of a policy source, each node keeps a **receipt**: its own account of what it read and decided. The gateway fetches each node's receipt shortly after the round (libp2p protocol `/molpha/receipt/1.0.0`) and stores the receipts with the round in its archive.

| Field | Meaning |
| - | - |
| `roundId`, `sourceId`, `node`, `timestampMs` | Which round, and the node's registry index |
| `inputs[]` | Per input: `name`, `kind`, `ok`, `bodyHash`, `block`, `durationMs`, `error`, `httpStatus` |
| `policy` | `candidates[]` (`name`, `qualified`, `rule`, `error`, `value`), `n`, `agg`; absent when the node stopped before the policy ran |
| `outcome` | `conclusive`, `inconclusive` (the node computed the fallback) or `refused` |
| `reason` | The INCONCLUSIVE reason, also on a refusal for want of a fallback |
| `stage` | Where a refused node stopped, such as `fetching data` or `policy inconclusive` |
| `value` | The 32-byte word this node computed. In tolerance mode, the node's own reading, not the round's median |

An http input is identified by `bodyHash`, the keccak256 of the response body exactly as received; a chain input by the `block` it was pinned to. Two nodes that read the same bytes have the same hash, and anyone holding the body can check it. A receipt never carries a body, a header, a secret or an error message; an input's `error` is only its class (`fetch`, `decode` or `canceled`).

**What a receipt proves.** Nothing on chain. It is not signed: it explains a round, it does not attest one. Use it to see why a round ended as it did, which venue each node could not read, and which rule disqualified a candidate. The attestation's signature is the only proof.

**Where to read it.** The round archive at `https://indexer.molpha.io` serves a round, and its receipts, under its round ID:

```bash theme={null}
curl https://indexer.molpha.io/v1/rounds/<roundId>
```

`receipts` lists `{gateway, node, nodeAccount, receipt}`. A signed report of a policy round also has `result` (`outcome`, `reason`): that is the gateway's reading, not a signed field. The SDK returns the round ID as `result.roundId`.

Sources without a policy get no receipt, and neither do private (`{{secret.NAME}}`) or paid-source rounds, whose inputs belong to one consumer. Nodes keep receipts in memory for a short time (600 seconds by default), so a receipt the gateway did not collect in time is gone.

## Limits

| | |
| - | - |
| Candidates | 1 to 4 (a source has at most 4 inputs) |
| Rules per candidate | 8 |
| `inconclusiveIf` entries | 8 |
| Constants in one `in` | 16 |
| Expression nodes, all trees of the source | 128 with a policy (64 without) |
| Expression depth | 12 |

Limits are checked before anything is fetched, at the gateway and again at each node. Every node fetches every input, so a three-venue policy costs each node three fetches.

## Analysis

`analyzeSource` in the SDK (and the nodes' own analysis, which gives the same facts) describes a source without fetching or evaluating it: its inputs and their hosts or chains, the candidates and their roles, the combinator, the fallback words and whether a result can reach them, the expression size, fetches per node, the node capabilities it needs (`policy/1`, `fallback/1`, `round1/2`, `tsMs/1`) and warnings:

| Warning | Meaning |
| - | - |
| `fallbackReachable` | A conclusive result may encode to a fallback word |
| `fallbackTolerance` | A fallback in tolerance mode: on Solana, a signed fallback replaces the feed's last value |
| `exactComposite` | Exact mode with two or more candidates: signers rarely read byte-identical values from live venues |
| `independenceNone` | Two or more candidates with `independence: none` |
| `readsCandidateField` | `inconclusiveIf`, `transform` or `assert` reads a candidate's field |

The MCP server exposes it as `analyze_source`, and the simulation as `simulate_source`. See [MCP tools](https://docs.molpha.io/mcp/tools.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.