ADL 20 · Part III — Expressions, authority, and behavior

0.5.1 baseline + 0.6 edition note

Validation

ADL 0.6.0 reference · Review draft 1 · November 14, 2026.

Contents · Source map · Evidence

The 0.6 edition note

This chapter retains the detailed language contract and its source-specific observations. Its chapter number and numbered sections remain stable. The 0.6 additions do not by themselves change this subject’s defaults or supply fresh execution evidence for it.

Reverification should cover validation order, effective update values, and structured error detail. Use the original examples and evidence links below to recover the earlier test context. The new edition’s source map records this chapter as inherited detail; the current draft does not claim those historical tests were rerun.

Retained reference detail

The numbered sections below are carried from 20-validation.md. Their original baseline and evidence remain attached to the source. Statements about “current” or “checked” behavior in this retained text refer to those original observations unless the edition note explicitly updates them. This is a consolidated draft, not a claim of complete re-verification.

20.1 Scope of this chapter

Validation rejects values or combinations that a resource does not accept. Two declaration layers work together on ordinary create and partial-update paths:

  • Field constraints and validators check individual submitted values.
  • Cross-field rules in the resource’s validation mapping check the proposed record, including values retained from an existing row.

ADL 10 owns field types and built-in constraints; ADL 11 owns enum membership. ADL 18 owns expression syntax, functions, targets, and scope rules. This chapter owns validation placement, context, scheduling, and failure identifiers. ADL 31 owns the general error envelope.

The converted chapter (v0.5.0, retired) and legacy declaration tables (v0.3.1, retired) are inherited sources. The legacy correction record (v0.3.1, retired) left merged-update context, operation gating, malformed custom regexes, and assembled field-keyed responses unexecuted. This draft checks those paths.

Two inherited blanket statements need correction. Validation runs inside generated create/update actions even when their request transport is internal or seeder. Also, some field declarations produce database constraints: unique is enforced by a unique index/constraint, and the checked initial DDL includes NOT NULL for required ordinary fields. Cross-field AEL rules and custom validators are application checks; they are not SQL CHECK constraints.

Source review uses dd129a19. Execution uses separately identified existing Linux Release artifacts from ../kalos-clone-a, with compatible archived c8cd9d7c headers. Only the documentation adapter was compiled. Evidence records source and executable identities.

20.2 Cross-field rules

Place named rules under validation alongside object, computed, and permissions in a resource. The following is a fragment from booking.yaml:

validation:
  dateOrder:
    rule: endDate == null || endDate > startDate
    message: End date must be after start date
  capacity:
    rule: seats <= capacity
    message: Seats exceed capacity
KeyShapeRequirement or default
Rule nameMapping keyIdentifies the rule (and keys the response detail unless field or fields is set)
ruleAEL expression stringRequired; the inherited contract requires true
messageStringRequired by the inherited declaration table
whenalways, create, or updatealways
fieldStringOptional field name to key the 422 error detail under (params.rule preserves the rule name)
fieldsArray of stringsOptional list of field names to key the 422 error detail under

Name a rule for its constraint. A rule name is not required to be an object field name. Setting field: title (or fields: [startDate, endDate]) directs the rule failure to the named field key(s) in data while recording "params": {"rule": "<ruleName>"} on each detail (#1551). Reusing a field name without field also directs its rule failure to that field’s response key. The current serializer then keeps only one error for that key (§20.5); use distinct names if both must be visible.

20.2.1 Admission and evaluation are separate

The native parser accepts a string shorthand such as dateOrder: "endDate > startDate" and synthesizes a message. It also admits an object rule with no message, retaining an empty string; the evaluator then supplies Validation rule 'name' failed. These are observed permissive forms. Use the complete mapping form to retain the inherited requirements and agreement with the modeller.

Missing, empty, or nonstring rule values are silently omitted. A nonmapping validation block is ignored. Unknown or nonstring when values become always rather than causing admission failure. A misspelled when: delete therefore runs on create and update; it does not create delete validation.

Current load-time AEL checking rejects the legacy three-argument aggregate with AEL_AGGREGATE_ARITY and malformed quoted targets with AEL_ADDRESS_INVALID. Ordinary syntax errors and unknown functions can still be admitted and fail on the first matching write as expression_error. Custom field expressions have a separate admission path (§20.4).

The runtime uses AEL’s truth test. The checked 1 and 'ok' expressions pass; false, 0, null, '', and [] fail as validation_rule. This permissiveness does not amend the inherited requirement to write a Boolean condition. Prefer expressions whose result is explicitly true or false.

Named validation rules can also participate in protected derivation contracts. ADL 14 owns protection and override authority; this chapter does not create a second set of inheritance rules.

20.2.2 The record and operation it sees

BindingOrdinary resource-rule context
Bare field nameLookup against $this
$thisProposed record; submitted data on create, existing row overlaid with submitted values on update
$recordThe same proposed record, retained when a target predicate changes $this
$oldPre-update record; null on create
$op"create" or "update"

The resource validator expects its caller to construct the merged record. Its direct helper does not merge the existing argument itself. Generated PATCH/update performs that merge before calling it. Supplying only a patch fragment directly to the helper is not an equivalent consumer test.

The checked Booking starts with:

{"id": 1, "startDate": "2026-01-01", "endDate": "2026-12-31", "seats": 2, "capacity": 5}

Updating only startDate to "2027-01-01" fails dateOrder because the retained end date is earlier. Updating only seats to 6 fails capacity. Both rejected updates leave the stored row unchanged. Updating only capacity to 8 succeeds and retains two seats.

Built-in and custom field validators on PATCH inspect submitted fields. Cross-field rules inspect the merged record. Thus omitting an optional field can skip its field validator while a rule still reads its existing value.

These contexts do not bind the request’s user identity. The checked $user.id != null fails; hasRole('admin') is refused in Validation scope. Permissions belong to ADL 21, not to a validation rule that assumes permission-context bindings.

20.2.3 Gate old-record comparisons explicitly

Use when: update for a rule that must not run on create. Dereferencing $old does not automatically skip evaluation. The complete contexts.yaml checks create and update bindings and uses this fragment:

updateContext:
  rule: $op == 'update' && value >= toNumber($old.value) && $record.value == value
  message: Value must not decrease
  when: update

Creating value 2 succeeds. A note-only PATCH succeeds, decreasing the value to 1 fails, and increasing it to 3 succeeds. toNumber makes the intended numeric comparison explicit; AEL conversions remain owned by ADL 18.

Separate false-rule controls confirm that when: update allows create but blocks update, while when: create blocks create and is skipped on update. There is no delete or put value in this scheduling vocabulary.

20.3 Rules that query other resources

Resource rules can use the Validation-scope query(target, filter) and exists(target, filter) functions. The consuming host supplies their query handler and domain context when the parser marks a rule as using targets.

The complete queries.yaml declares a Page and a Request. Its Request rule is this fragment:

slugFree:
  rule: "!exists('Page', {slug: $record.slug})"
  message: This slug is already used by a Page

With a Page whose slug is used, a Request for used fails and one for free succeeds. The handler queries the target’s physical table using the supplied filter. A nonexistent target or a failed SQL query becomes expression_error; it is not an empty successful lookup.

20.3.1 Target forms and the outer record

Draft 05 §14 and the Phase-15 target work also enable resource-target count, field aggregates, findOne, findMany, and lookup in this host. Their grammar and scope distinctions are in ADL 18 §18.7.

For example, this checked expression fragment rejects the same occupied slug:

count('adl.checks.checks.Page', slug == $record.slug) == 0

Inside the predicate, slug and $this.slug belong to each Page row. $record.slug still belongs to the Request being validated. Comparing slug == $this.slug would compare the target row to itself.

The parser now discovers target use through AEL analysis, including a spaced exists ( call and quoted target aggregates. The old substring-only query detection description is incomplete. By contrast, a standalone direct ResourceValidator call with no supplied handler reports an expression error for an otherwise valid query.

Custom field validators do not receive this resource query handler (§20.4). An expression’s permitted scope does not guarantee that every host supplies the services it needs.

20.3.2 Query semantics and limits

The reviewed handler builds equality filters joined by AND, using bound values. This filter object is not the generated list API’s operator grammar. Target predicates can run after fetching rows; consult ADL 18 for that difference and for row-value conversions.

The handler selects at most 1,000 rows. Target-wide counts and predicate searches over larger sets do not establish completeness. ADL 18 contains the executed cap controls; this chapter preserves the current SQL source and executes smaller local target examples.

These reads also differ from a generated GET/list:

  • A checked caller denied Page GET still reaches a rule that reads that Page and rejects its occupied slug. The query handler does not dispatch the target’s normal read-permission action.
  • A soft-deleted Page still makes the checked exists rule fail. The raw handler does not add the list action’s soft-delete predicate.

These observations define the current validation consumer boundary. They do not grant a caller general read permission. Cross-domain addressing, import grants, and target authority remain owned by ADL 7, ADL 8, and ADL 12. This chapter’s request checks use local targets, not a new cross-domain authorization proof.

A query rule performs a read while the write request is in progress. !exists(...) is not a concurrency-safe uniqueness constraint: two writers can both observe absence. Use unique or a suitable database unique index when the invariant is representable there. ADL 15 owns compound unique indexes. No cross-resource locking guarantee is added here.

20.4 Custom field validators

Place a validators array on an object field. Each entry is a mapping with type, an optional message, and its type-specific settings.

typeSettingsChecked behavior
domainallowedDomains: array of stringsCompare an email’s suffix after the last @ with an allowed domain, ignoring case
formatpattern: regex stringMatch the entire string using ECMAScript regex syntax
customrule: AEL expression stringTest a condition using $value and $field

The following is a field fragment from custom.yaml:

even:
  type: integer
  validators:
  - type: custom
    rule: $field == 'even' && $value % 2 == 0
    message: Use an even number

The custom evaluator binds $value to the submitted field value and $field to its name. It does not bind $this to that value, despite an older source comment saying otherwise. The checked $this == $value fails for a non-null string. It also supplies no merged record, identity, or query handler. Put a condition requiring another field or resource in resource validation.

A domain validator is an allow-list check, not a complete email parser. Use type: email for the built-in shape check. The example accepts u@EXAMPLE.COM and rejects u@other.com. Domain and format validators skip nonstring values; strict built-in validation can still reject the type.

Custom AEL runs for a present null. The even-number expression then reports expression_error rather than silently skipping. If null is permitted, write that branch explicitly, for example $value == null || $value % 2 == 0.

20.4.1 Regex and malformed-validator boundaries

DeclarationMatching behaviorMalformed pattern
Field patternSubstring searchChecked [ is ignored as no constraint
Custom type: formatWhole-string matchChecked [ fails as invalid_pattern

Thus [A-Z]{2} as a built-in pattern accepts xABx. The custom format [A-Z]{2}-[0-9]{4} rejects xAB-1234x. Anchor a built-in pattern if the whole value must match. The inherited statement that malformed custom regexes fail is correct; it must not be extended to built-in pattern.

Admission does not enforce all custom-validator shapes. Unknown types, empty custom rules, empty format patterns, and nonobject entries can produce no check. An empty allowedDomains list rejects string inputs. A nonempty malformed custom expression is admitted and later reports expression_error. Consequently, “a validator that cannot run never passes” is too broad.

There is no computed-field lightweight fallback here. AEL errors remain validation errors rather than being retried by ADL 19’s evaluator.

20.4.2 Messages

A custom entry’s message replaces its ordinary domain, format, or false-rule message. It does not replace the diagnostic for an invalid regex or an AEL evaluation error. A resource rule’s message likewise describes false conditions; expression errors include the failing rule name and AEL message.

Field messages overrides selected built-in constraints by declaration key, not by the returned error code. The checked example uses:

title:
  type: string
  minLength: 5
  messages:
    minLength: Use five or more characters

A short title returns too_short with that text. Other implemented override keys include required, type, maxLength, min, max, and pattern. This is not a promise that every built-in code consults messages. Localization ownership remains with ADL 46; a standalone localized-message helper is not proof of locale selection on each write path.

20.5 What each failure returns

BoundaryStatus and top-level codeDetails
Built-in field check422 VALIDATION_ERRORField name with required, invalid_type, too_short, too_large, or another constraint code
Custom domain / format / condition422 VALIDATION_ERRORField name with domain_not_allowed, format_mismatch, or custom_validation
Malformed custom regex422 VALIDATION_ERRORField name with invalid_pattern
False resource rule422 VALIDATION_ERRORRule name with validation_rule
Unevaluatable rule or custom expression422 VALIDATION_ERRORRule/field name with expression_error
Immutable input on PATCH400 IMMUTABLE_FIELDChecked even when the submitted value equals the stored value
Database unique violation on create409 DUPLICATESeparate from malformed-input validation
Required field omitted on PUT422 PUT_INCOMPLETEArray of missing field names
Built-in import validation422 IMPORT_VALIDATION_ERRORRow-indexed errors; separate from ordinary create details

For an ordinary validation failure, the action returns error code VALIDATION_ERROR and message Validation failed. Its data is a mapping where each failing key maps to {"code", "message"} plus an optional "params" object carrying the structured constraint parameters (min, max, pattern, enum, domains, expected/actual, or rule; #1551). The checked invalid date PATCH contains this details fragment:

{
  "dateOrder": {
    "code": "validation_rule",
    "message": "End date must be after start date",
    "params": {
      "rule": "dateOrder"
    }
  }
}

The adapter records the action Response directly. It does not claim an HTTP serialization test. Consult ADL 31 for the complete transport envelope.

20.5.1 Collection does not mean every error survives serialization

Create/update accumulate built-in, custom, and cross-field errors before returning from that validation block. However, ValidationResult::to_json assigns details[error.field] repeatedly. The last error for a key replaces earlier ones.

A checked field named value fails minimum length, custom format, and a resource rule also named value. The direct result holds three errors; the actual create response exposes only the resource-rule error. Distinct failing fields remain distinct keys. The inherited “all errors at once” claim must be qualified accordingly.

Other checks can also return before the validation block: permission refusal, immutable PATCH input, missing records, or a lifecycle-hook veto. Do not promise a complete form-wide diagnostic set after every rejected request.

20.6 Ordering and operation coverage

20.6.1 What the calculation precedes

String transforms (trim, lowercase, uppercase; ADL 10 §10.4) are applied to the submitted values first, on create, PATCH and PUT. Validation, hooks and rules all see the transformed values. A field with type: email, trim: true accepts " pad@example.com " and stores pad@example.com. A field with uppercase: true, pattern: ^[A-Z]+$ accepts abc and stores ABC. A rule value == 'READY' accepts a submitted ready under uppercase: true. Input that no transform can repair, such as " not an email ", is still refused (#1484).

On create, a cross-field rule sees a field the request left out as its default:, because that is the value the row is stored with. A rule value == 'READY' passes when the field is omitted under default: READY, and a rule units <= 4 refuses an omitted field under default: 9 exactly as it refuses an explicit 9. An explicit null stays null to the rule: the store keeps it, and the default is not applied. Numeric and boolean defaults reach the rule as numbers and booleans (#1853).

This covers the rules under validation:. Field validators still run only on submitted fields, lifecycle hooks receive the request as sent, and the domain rules: of ADL 22 are unchanged. Built-in required checking has its own default exemption. Owner injection and seeded aggregation identities are special handling too, so this is not yet a general “final row” contract. ADL 19 owns computed evaluation timing.

The legacy required/nullable matrix is not fully enforced by the built-in helper. A checked required: true, nullable: true field rejects null as required; an optional nullable: false field passes null at that helper. ADL 10 separates authoring requirements, helper behavior, and storage.

“Before any statement is issued” is inaccurate: update first fetches the existing record, and resource-query validators issue reads. The checked ordinary failures precede the target row’s INSERT/UPDATE. This evidence does not establish that hooks or every surrounding subsystem are free of effects. The reviewed create source even calls afterValidate before the actual validation block; ADL 25 owns lifecycle ordering rather than treating that hook name as an execution guarantee.

20.6.2 Follow the consuming operation

OperationExecuted validation boundary
CreateBuilt-in, custom, and matching resource rules
PATCH/updateBuilt-in/custom checks on submitted fields; matching rules on merged record
Create/update with internal or seeder transportThe same validation block still runs
bulk.createDispatches each item through create; checked failing item rolls back the batch
PUTRequired-presence and built-in checks; checked custom and cross-field rules are omitted
Import with features.dataImport: trueRequired/shape and built-in row checks; checked custom and cross-field rules are omitted
Direct SQLNo ADL validation; database constraints still apply

The bulk example submits one valid Booking and one whose seats exceed capacity. It returns VALIDATION_ERROR with _bulk_index: 1 and leaves no Booking rows.

The PUT control uses a UUID key so the key is represented as a string. It accepts six seats against capacity five and an end date earlier than the start date, then rejects a separate noninteger seats value. A separate integer-key control reaches a caught action exception when PUT expects id to be a string and returns 500 INTERNAL_ERROR. That key-conversion failure is not evidence that the resource rule ran.

Import accepts the same cross-field-invalid Booking but rejects a noninteger seats value with a row-indexed invalid_type error. A custom even-number validator is also bypassed: PUT and import both persist 3.

The immutable control distinguishes operations: PATCH rejects a resubmitted immutable field, while PUT silently retains the old value. A direct SQL duplicate still fails the database unique constraint. These observations do not establish parity between all write routes.

20.6.3 Loose mode is selective

features.validationMode: loose skips the ordinary built-in validator on create/update, but does not disable custom field or cross-field rules. The checked loose Booking accepts startDate: bad-date when the date-order rule is made irrelevant by a null end date, yet still rejects excess seats. The loose custom example accepts a too-short title but rejects an odd number.

Use ADL 29 for feature configuration and ADL 26 for CRUD ownership. This chapter does not infer state-transition, rule-action, or custom-action coverage from these paths. ADL 22 owns transition validation and ADL 23 owns rule-maintained writes.

20.7 Generated output and restoration

Generated resource schemas retain ordinary constraints such as the checked title’s minLength. They do not encode the custom even-number validator as a schema constraint. Resource cross-field rules are not a substitute for JSON Schema properties. A client schema check is therefore incomplete evidence for server acceptance.

The typed export retains the named resource rules but omits field validators. Field messages survives. Registry restoration is more nuanced:

  • Reopening with faithful resolved raw_source preserves the checked rules, validators, and messages.
  • Clearing both stored source texts in the disposable registry forces the legacy JSON projection path. It retains ordinary resource rules and messages, but drops custom validators. Field/rule order can also change.

These are three source-backed and three forced-fallback model comparisons. They do not simulate a full host restart or prove that every service resumes correctly. Preserve faithful source when evaluating restoration behavior; a typed export is not a lossless authoring round trip. ADL 17 owns definition changes and activation.

20.8 Complete example and verification

The complete checked booking.yaml is:

adl: "0.5.0"
domain:
  name: checks
  version: "1.0.0"
  resources:
    Booking:
      object:
        id:
          type: integer
          primaryKey: true
        startDate:
          type: date
          required: true
        endDate:
          type: date
        seats:
          type: integer
          required: true
          min: 1
        capacity:
          type: integer
          required: true
          min: 1
        note:
          type: string
      permissions:
        create:
        - '*'
        read:
        - '*'
        update:
        - '*'
        delete:
        - '*'
      validation:
        dateOrder:
          rule: endDate == null || endDate > startDate
          message: End date must be after start date
        capacity:
          rule: seats <= capacity
          message: Seats exceed capacity

All six fixture files use adl: "0.5.0" for inherited standalone grammar; the domain version is a separate string. The broad permissions isolate validation behavior and are not an authorization template.

Four complete examples pass both native CLI and modeller checking: Booking, custom validators, context bindings, and local resource queries. invalid-target.yaml is deliberately rejected by both. syntax-error.yaml is admitted by the native parser and rejected by the modeller; its native create fails with expression_error.

The modeller also diagnoses shorthand/nonmapping rules, missing expressions, invalid when values, and ordinary expression syntax that native admission can tolerate. One nonstring expression causes a captured Python TypeError. The comparison uses its independent declaration builder, not a simulated native request path.

From the clone-b repository root, with the compiler dependencies, Python, PyYAML, and modeller environment:

python3 docs/adl-v0.5.1-vol-1-adl/examples/20-validation/verify.py --build-root ../kalos-clone-a/build

The runner verifies the existing ADL library hash, compiles its documentation adapter using compatible archived headers, and creates fresh temporary stores. It does not rebuild production libraries or rewrite the committed evidence.

The verification record contains 87 native cases and 302 assertions: 27 declaration cases, 35 direct validation cases, and 25 disposable-store sequences. It also records 27 independent modeller projections, twelve CLI/modeller commands, six registry model comparisons, and 64 passing focused tests.

The direct helper cases inspect built-in, custom, and rule errors separately; the store cases establish the actual response and persistence consequences. An action’s sticky database error text can outlive the operation that set it, so the evidence checks response status, read-failure state, and stored rows rather than treating every nonempty error string as a failure.

No HTTP transport, external authentication, PostgreSQL execution, full host restart, or concurrency guarantee is claimed. These limits and the source provenance remain in the evidence record.

End of Chapter 20.