Rules
Rules are checks that run after extraction and normalisation, in-process, by Deskew. The model never sees them. A rule that fails adds a flag to the result; it never changes a value and never makes the model try again. Rules are the deterministic, auditable part of the pipeline.
"rules": [ { "id": "items_sum", "check": "abs(sum(line_items[].amount) - (subtotal ?? total)) <= 1", "message": "Line items do not add up", "severity": "error" }, { "id": "dates", "check": "discharge_date == null || discharge_date >= admission_date" }, { "id": "total_math", "check": "abs(subtotal - discount + tax - total) <= 1", "when": "subtotal != null" }, { "id": "recent", "check": "admission_date >= today() - days(365)", "severity": "warning", "message": "Bill is more than a year old" }]| Key | Rules |
|---|---|
id |
^[a-z][a-z0-9_]{0,63}$, unique within the extractor. Becomes flags[].rule |
check |
The expression. Must be truthy for the rule to pass. 1 to 1,000 characters |
when |
Optional guard. The rule only runs when this is true |
message |
Up to 300 characters, shown in the flag. Defaults to rule <id> failed |
severity |
error (default) or warning |
Rules are parsed when you save a draft or publish. A syntax error or a reference to a field that does not exist is reported as a problem at rules.<index>.check or rules.<index>.when and the definition is refused.
Grammar
Section titled “Grammar”expr := oror := and ("||" and)*and := not ("&&" not)*not := "!" not | cmpcmp := coalesce (("==" | "!=" | "<" | "<=" | ">" | ">=") coalesce)?coalesce := add ("??" add)*add := mul (("+" | "-") mul)*mul := unary (("*" | "/") unary)*unary := "-" unary | primaryprimary := number | string | null | true | false | function "(" args ")" | path | "(" expr ")" | "[" args "]"path := name ("." name | "[]" | "[" integer "]")*- Numbers are decimals:
1,0.5,1000. No separators or signs other than unary minus. - Strings use single or double quotes. Only
\',\"and\\are escapes; regex escapes such as\dpass through untouched, somatches(code, '^[A-Z]{2}-\d+$')reads as written. - Lists are
[a, b, c], used within()andmin()/max(). - Paths name your fields:
total,patient.name,line_items[0].amount,line_items[].amount.[]maps over every row and yields a list;[2]picks one row (0-based). A key after[]is applied to every element. - Comparison is non-associative:
a < b < cis a syntax error; writea < b && b < c.
| Operators | Meaning |
|---|---|
+ - * / |
Arithmetic on numbers. / by zero gives null. + on two strings concatenates. date - date gives the difference in days; date +/- days(n) shifts a date |
== != |
Equality. Compares null as a value: x == null is true or false, never null |
< <= > >= |
Ordering on numbers and dates. An ISO date string is coerced to a date when the other side is one |
&& || ! |
Boolean logic, three-valued (below) |
?? |
Null coalescing: subtotal ?? total is subtotal unless it is null |
Values from data are the normalised ones: dates are ISO strings, money is a number (or an object whose amount is used automatically), enums are the canonical value. Numeric strings are coerced in comparisons with a number.
Null semantics
Section titled “Null semantics”Not found is null, and null is “unknown”, not “false”.
- Arithmetic and ordering with a
nulloperand givenull:subtotal > 1isnullwhensubtotalis missing. ==and!=treatnullas a value:discharge_date == nullistrue.&&and||use three-valued logic:null && falseisfalse,null && trueisnull,null || trueistrue,null || falseisnull.!nullisnull.- Truthiness:
false,0,"",[]andnullare not truthy; everything else is. - A rule whose
checkevaluates tonullis skipped, not failed. It appears nowhere inflags. The same happens whenwhenis nottrue.
So the dates rule above is skipped on a bill with no discharge date, and items_sum is skipped when there are no amounts to sum against. Write a separate required field, or a rule with != null, when absence itself is the problem.
Functions
Section titled “Functions”| Function | Returns | Notes |
|---|---|---|
sum(list) |
number | Sum of the non-null numeric items. sum([]) is 0 |
count(list) |
number | Number of non-null items. count(null) is 0; count(x) of a scalar is 1 |
min(list), max(list) |
number | Of the numeric items, or null when none. Also min(a, b, c) with several arguments |
abs(x) |
number | Absolute value |
round(x, digits?) |
number | Round half to even; digits defaults to 0 |
len(x) |
number | Length of a string or a list (including null rows); null for anything else |
matches(text, regex) |
boolean | Regular expression search anywhere in the text. null when text is null or the pattern is invalid |
in(x, [list]) |
boolean | Membership. null when x is null |
today() |
date | Today in UTC |
days(n) |
duration | For today() - days(30) or invoice_date + days(45) |
lookup("list", value) |
boolean | Whether the value is on an uploaded lookup list, matched ignoring case and surrounding whitespace. null when the value is null or the list does not exist (the rule is skipped and the run carries a warning) |
lookup("list", value, "column") |
string | The named column of the matching row, else null. Guard with when to avoid null == "x" failing |
lookup("list", value, threshold) |
boolean | Close match: true when the most similar list key scores at least threshold (0 to 1, character similarity after normalisation), so Apollo Hospital, Jubilee Hills matches Apollo Hospitals Jubilee Hills at 0.85. An exact match always wins |
lookup("list", value, "column", threshold) |
string | The column of the closest row at or above threshold, else null |
The list and column names of lookup() must be quoted literals; lookup(panel, x) is a syntax error. A reference to a list that is not uploaded is a warning, not a validation error.
Severity
Section titled “Severity”severity |
On failure |
|---|---|
error |
Adds an error flag and sets extraction.status to flagged. With output.on_rule_error: "reject" the status is rejected instead and document.reason is "rule errors"; the data is still returned |
warning |
Adds a warning flag; the status stays ok |
Normalisation problems have fixed severities: unparseable, not_in_enum, missing_required and too_few_items are errors; pattern_mismatch, too_many_items and too_many_pages are warnings.
How failures appear
Section titled “How failures appear”Every failed rule is one entry in extraction.flags:
{ "rule": "items_sum", "severity": "error", "message": "Line items do not add up", "fields": ["line_items[].amount", "subtotal", "total"], "detail": "line_items[].amount=[2 items], subtotal=None, total=31000.0"}| Field | Meaning |
|---|---|
rule |
The rule id, or a built-in code: missing_required, unparseable, pattern_mismatch, not_in_enum, too_few_items, too_many_items, too_many_pages |
severity |
error or warning |
message |
Your message, or the generated one for built-ins |
fields |
Every field path the check read, sorted. For built-ins, the one field concerned |
detail |
Present on failed rules: the current values of up to six referenced fields, as path=value, lists shown as [n items]. Point a reviewer at this line |
The job object and the webhook payload carry only the count (extraction.flags); fetch the result for the entries.
Examples
Section titled “Examples”Sums. Line items add up to the subtotal, or to the total when there is no subtotal, within one unit of currency:
abs(sum(line_items[].amount) - (subtotal ?? total)) <= 1Total arithmetic, only when the pieces exist:
{ "id": "total_math", "check": "abs(subtotal - discount + tax - total) <= 1", "when": "subtotal != null" }Without the when, a missing discount would make the whole check null and the rule would be skipped anyway; the guard just says so explicitly. Use (discount ?? 0) when a missing value should count as zero.
Date order:
discharge_date == null || discharge_date >= admission_dateinvoice_date >= admission_dateLength of stay matches the room line:
discharge_date - admission_date == sum(line_items[].quantity)Identifier format (also possible with match on the field, which does not make the run flagged):
matches(gstin, '^[0-9]{2}[A-Z0-9]{13}$')Enum membership and conditional presence:
in(line_items[0].category, ['room', 'consultation'])paid == true || balance_due > 0Recency with today() and days():
{ "id": "recent", "check": "invoice_date >= today() - days(365)", "severity": "warning" }{ "id": "not_future", "check": "invoice_date <= today()" }Membership in an uploaded list (see Lookup lists):
{ "id": "on_panel", "check": "lookup(\"panel\", hospital.name)", "message": "Hospital is not on the panel" }{ "id": "tier_a", "check": "lookup(\"panel\", hospital.name, \"tier\") == \"A\"", "when": "lookup(\"panel\", hospital.name)", "severity": "warning" }Row counts and bounds:
count(line_items[].amount) == len(line_items)max(line_items[].amount) <= total