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

0.6.0 reconciled + 0.5.1 detail

Hooks

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

Contents · Source map · Evidence

The 0.6 edition note

The extension contract now includes policy supervision and before/after-action callbacks through adl.host interface 8. The host supplies declared policy views and operation context; an extension that claims supervision returns the decision. The ADL core does not hard-code the compliance plugin’s name as the language’s only possible supervisor.

A callback’s existence is not a coverage guarantee. The action must invoke it, the extension must be installed, and its mode must match the intended behavior. The operation table identifies the documented boundary. After-action permit recording follows successful completion and is outside the business transaction; callback order must not be mistaken for atomic commit.

Retained Lua/lifecycle hook observations remain separate from this native extension interface. This edition does not imply that every lifecycle hook, notification, dispatch, or direct storage write traverses the policy supervisor.

Retained reference detail

The numbered sections below are carried from 25-hooks.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.

25.1 Scope and the binding contract

A hook declaration names an action to invoke at a resource lifecycle point. The name is an action identifier, not a filename. An application, native plugin, or script host must register that action separately. Declaring it in ADL does not supply an implementation or demonstrate that it is bound.

This chapter owns the declaration and the generated resource operation’s side of the call. Lua registration, Lua return-value conversion, the kalos.* API, and sandboxing belong to the platform’s Lua-host chapter. A native action is a valid implementation of the same hook contract; the executable examples here use native bindings to isolate ADL behavior from a script host.

The account develops the v0.5.0 conversion (retired) with Draft 05 §13, §20 item 4, and §21.2 and the signed rulings. Observed results use revision 31e59154, a fresh matching Release build, and the verification record. Several inherited claims about ordering, returned fields, and unbound hooks do not match current generated actions.

25.2 Declaring lifecycle points

The complete lifecycle example declares:

hooks:
  beforeValidate: [example.beforeValidate]
  afterValidate: [example.afterValidate]
  beforeCreate: [example.beforeCreate]
  afterCreate: [example.afterCreate]
  beforeUpdate: [example.beforeUpdate]
  afterUpdate: [example.afterUpdate]
  beforeDelete: [example.beforeDelete]
  afterDelete: [example.afterDelete]

These eight names are the recognized resource hook points. Each value should be an ordered array of action-name strings. The parser retains order within a point, including duplicates. It gathers different points in its fixed lifecycle order, so the order of mapping keys does not schedule the lifecycle.

The native parser ignores a scalar handler value, numeric array members, unknown points such as beforeCreat, and a list-shaped hooks block. The checked strict parse gives no warning for these omissions. Empty arrays declare no handler. Two occurrences of the same action invoke it twice in the live create control; they are not deduplicated.

The independent modeller differs: it accepts a scalar action string, reports unknown hook points, and has checks for duplicate/non-string/empty action names. Use arrays and exact point spellings for portable authoring. A modeller error or a clean native parse alone does not establish runtime binding.

The hook model and parser define the native representation. Trait composition and derivation can also carry or alter hooks; ADL 13 and ADL 14 own those mechanisms. This chapter tests explicit resource declarations.

25.3 Ordering and operation coverage

25.3.1 The checked lifecycle

Generated operationHook calls observed in order
CreatebeforeValidate, afterValidate, beforeCreate, afterCreate
PATCHbeforeUpdate, afterUpdate
Named state transitionbeforeUpdate, afterUpdate
DeletebeforeDelete, afterDelete
RestorebeforeUpdate, afterUpdate
PUT replacementbeforeUpdate, afterUpdate
Enabled data importNone

PUT and restore coverage was added in #1554. Their before-hook runs after authorization and row lookup; rejection returns 422 without the record write or after-hook. PUT also completes field validation and state guards before invoking the hook. The after-hook runs only after a successful write and receives the resulting typed record. As with PATCH, a failing after-hook does not undo the write. PATCH, PUT and named transitions apply before-update return fields subject to caller permissions and validation (#1534). Restore still ignores returned fields: it only clears the deletion marker. The HTTP reproduction checks these paths on SQLite and PostgreSQL; the older chapter evidence predates this change.

Data import deliberately remains a trusted bulk-load operation, not repeated create calls. It checks field constraints and permissions but bypasses hooks, rules and state-machine workflows. Hook side effects and per-row calls would change that bulk-load contract. Enable features.dataImport only when this bypass is intended; use ordinary create operations when per-row lifecycle checks are required. No request flag opts PUT or restore out of their hooks.

The name afterValidate is misleading in the current create handler. It runs after initial access/field-write checks but before full field and record validation. The invalid-create control invokes both validation-named hooks and then returns VALIDATION_ERROR. Its error response cannot undo effects already performed by afterValidate.

beforeValidate runs before the create permission check. A denied viewer create still invokes that hook, then returns 403. Named transition hooks run after the transition’s guards; rules run after returned fields are merged. Hook order therefore must be understood in relation to the specific operation, not inferred solely from names.

Named afterCreate, afterUpdate and afterDelete callbacks wait for their owning request write to commit (#1373). In a kalos.atomic block, inner writes and savepoint commits do not deliver them; the outer atomic commit does, and rollback discards them (#1533). afterValidate remains a pre-write phase; it is deferred only when an enclosing atomic operation already owns the request. A same-connection read alone establishes row visibility, not durable commit.

25.3.1a What a beforeCreate hook’s reads can rely on

A beforeCreate hook often checks other rows: no overlapping booking, a seat limit, one active record per parent. Its reads run outside the write’s transaction, so on their own they say nothing about the moment of the insert: two concurrent creates could both read “no overlap” and both insert (#1529, Cal.com 22).

The runtime therefore serializes the creates of a resource that declares a beforeCreate hook, optimistically:

  1. Each attempt notes the resource’s write generation, then runs the hook without holding any lock.
  2. Just before its first write it enters the resource’s gate. If another create of the resource has committed since step 1, the hook’s reads are stale: the attempt is abandoned before writing and the whole create runs again, hooks included.
  3. Otherwise it writes, commits, advances the generation and leaves the gate before any after-hook runs.

So a hook’s reads of the resource’s own rows hold at the insert: among concurrent creates exactly one wins a contested slot, and the others get the hook’s own refusal. Consequences:

  • A beforeCreate hook may run more than once for one request under contention. It must not have effects that a second run would duplicate; put those in afterCreate.
  • After 50 stale attempts the create answers 409 WRITE_CONTENDED. A create that waits more than 10 s for the gate answers 503 WRITE_BUSY. Both are safe to retry.
  • The guarantee covers creates of that resource through the generated create action, within one kalosd process. It does not cover updates or transitions that move a row into the checked range, writes made directly through kalos.store, a create nested inside an enclosing transaction (it commits with its caller), or several kalosd processes sharing one PostgreSQL database.

25.3.2 Internal requests, dry runs, and bulk writes

Generated create invokes its hooks under both internal and seeder transport labels in these checks. Internal middleware bypass does not remove explicit hook calls made inside an action handler. The inherited assertion that seeding bypasses the hook chain does not describe these generated creates; other seeding utilities need their own evidence.

A PATCH with X-Kalos-Dry-Run: true invokes beforeUpdate but neither persists the update nor invokes afterUpdate. The called action may already have caused its own effects. A dry run is not a general suppression of application calls.

Standalone bulk create invokes the normal create path per item. A later invalid item rolls back the shared record state, but a per-item after-create hook may already have run: a database transaction alone does not own named hook delivery. Wrapping the bulk call in kalos.atomic supplies the outer request-write owner; that block defers the callbacks until commit and discards them on rollback.

These results follow the create, update, delete, transition, and bulk handlers.

25.4 Inputs, context, and returned fields

25.4.1 What the handler receives

The dispatcher constructs a new Request for each handler. Its action is exactly the declared string and its transport is internal. The current caller’s user ID, username, primary role, and additional roles are copied from the lifecycle payload. The triggering request’s client address is available as req.remote_addr. Headers are absent by default; each handler can declare the headers it needs (#1532):

hooks:
  beforeCreate:
    - handler: inspectComment
      headers: [User-Agent, Idempotency-Key]
    - existingHandler

The object form accepts handler and an optional headers array. Header names must be HTTP tokens and are normalized to lowercase in req.headers. The string form remains valid and receives no headers. Only the named handler sees its selected headers; lifecycle event payloads do not include wire metadata. Deferred after-hooks own these selected values until commit. Hooks never get raw request bytes. Scheduler and workflow calls have empty headers and client address, even when triggered inside a client request. The older chapter context control’s undeclared X-Example header therefore remains absent.

The Request also says what fired the hook (#1541). req.action is the handler’s own name, so one handler bound to several resources or operations reads req.hook instead:

-- req.hook for a named transition's beforeUpdate on Booking
{ point = "beforeUpdate", domain = "bookings", resource = "Booking",
  operation = "transition",
  transition = { name = "accept", from = "pending", to = "accepted" } }
KeyValue
pointThe declared point: beforeCreate, afterUpdate, …
domain, resourceThe domain and the resource as declared (Booking, not booking)
operationcreate (also for beforeValidate/afterValidate), update (PATCH and PUT), delete, transition or restore
transitionOnly when a named transition fired: its name, from and to states

req.hook is nil on every request that is not a lifecycle-hook call. C++ handlers read the same object from Request::hook.

Hook familyRequest.dataRequest.existing
Create before-hooksIncoming create fields, including prior returns within that same point’s chainNull
afterValidateIncoming fieldsNull
afterCreateResulting recordNull
PATCH beforeUpdatePartial request, including the IDTyped existing record
PUT beforeUpdateReplacement request and transition assignments, including the routing IDTyped existing record
Restore beforeUpdateStored primary-key fields plus deletedAt: null; other request fields are ignoredTyped deleted record
Transition beforeUpdateTransition requestTyped existing record
afterUpdateResulting recordNull; prior record remains only in the announcement payload
Delete before/afterOld row data; checked numeric values arrive as stringsNull

The delete dispatcher does not populate existing even though the generic before-hook helper supports it. Delete’s old record is in data. After-update announcements carry previous, but fire_after_hook does not forward that value into the newly constructed handler Request. These distinctions matter to code comparing old and new values.

Copied identity is attribution supplied by the originating operation. These checks use synthetic callers and do not verify authentication or every host claim. Internal transport is not an authority grant; kernel action metadata and explicit checks in the called handler still matter.

25.4.2 Ordered merges

For a successful before-hook response whose data is an object, the dispatcher merges top-level keys into the record passed to the next handler and accumulates the returned fields for the caller. Later values for the same key replace earlier ones. It is a shallow merge; non-object response data adds no fields.

The bound chain registers two before-create actions. The first returns note: first; the second reads that note and returns note: first second. The stored row contains first second. Its after-create action sees that row; returning note: ignored after leaves storage unchanged.

The operation calling the helper must apply the accumulated fields. Current behavior differs by point:

PointReturned field object applied to the eventual write?
beforeCreateYes
beforeValidateNo; its accumulated fields are discarded by create
beforeUpdate on PATCH, PUT and named transitionYes, after caller field checks and validation (#1534)
beforeUpdate on restoreNo; restore only clears the deletion marker
beforeDeleteNo
Every after-hookNo; results are ignored

A before-validate action cannot repair a missing required title through its return object in the checked create. A before-update action returning priority 8 replaces the PATCH-requested priority 3 in storage. PUT and named transitions apply the same returned-field contract. Returned values pass field and record validation; rules see the resulting record before it is written.

Update returns use the caller’s field-write permissions. They cannot change a primary key, immutable/internal/automatic field, governed owner, or the selected state-machine state. A matching primary-key or state echo is a no-op. Unknown returned fields are refused. This grants no independent hook identity or run-as authority (#1535). Password hashing, encryption and content preprocessing still apply before storage. Rejection leaves the record unchanged and skips after-hooks.

The original published evidence predates #1534. The executable cases and HTTP reproduction assert the updated behavior on PATCH, PUT and named transitions.

Before-create fields are applied after normal validation and rule evaluation. Returning priority -5 after a valid incoming priority 2 writes -5 despite the field’s min: 0. The generated state machine still assigns its initial state after that merge, unless the hook returned a state listed in stateMachine.startStates (ADL 22 §22.2.1, #1540). Validate the values an application hook produces; do not assume they pass through the same checks as incoming fields.

25.5 Failures and unbound hooks

25.5.1 Return handling

At the native boundary, the handler returns a Response. Lua nil/table/status/error forms are translated into that Response by the Lua host; this chapter does not execute that conversion.

A response code below 400 is treated as success. Object data contributes fields for a before-hook; other data is ignored. A code of 400 or greater rejects a before-hook, preserving its error code/message or supplying HOOK_REJECTED and a default message when empty. The rejection answers with the handler’s own status when it is 403, 404, 409 or 422, so a permission refusal can be a 403 and a conflict a 409; any other status answers 422 (ADL plugin 0.102.84, #1547; before that every rejection answered 422). An unbound gate’s 404 ACTION_NOT_FOUND is not a missing record and still answers 422 (§25.5.2).

After-hook responses, including failures, do not abort or replace the operation response. This includes afterValidate, contrary to the inherited hook table. The runtime invokes these handlers synchronously and ignores their results; “ignored result” does not imply queued or asynchronous execution.

With default-on features.transactions (ADL 0.102.91, #1373), named afterCreate, afterUpdate and afterDelete handlers wait until the request’s write scope succeeds. A late audit/history/derived failure rolls back the write and skips those handlers. Their bus announcements still reach internal derived subscribers inside the transaction. Before-hooks and afterValidate remain preflight calls; their own explicit nested writes are separate requests. See ADL 29 §29.7 for the transaction and explicit opt-out boundaries.

25.5.2 The missing-action mismatch

When a declared hook names an action that nothing registered, the kernel router answers 404 ACTION_NOT_FOUND. The lifecycle dispatcher treats that answer by hook kind:

Hook pointOperationRecorded
before-validate, before-create (and other before* points)Refused with 422 ACTION_NOT_FOUND; nothing is writtenYes
after-create (and other after* points)Succeeds; the declared effect does not happenYes

“Recorded” means the dispatcher logs one warning per event/handler pair and adds the pair to unbound_hooks(). A before-hook’s warning says the operation was refused; an after-hook’s says the effect did not happen.

The mismatch the heading names is in the dispatcher’s skip path. It was written to skip an unbound hook (#438) and tests for lowercase action_not_found, while the router emits uppercase. A before-hook therefore fails closed rather than being skipped, and this build keeps that: an unbound gate refuses writes until a handler is bound. Only a handler that itself returns lowercase action_not_found takes the skip path; the operation then proceeds, and the pair is recorded.

Until #1013 the uppercase answer was never recorded, so neither row of the table produced a warning, and unbound_hooks() stayed empty.

“Unbound hooks are silently skipped” therefore does not describe this build. Verify a binding with an actual operation, not from the presence of a hook declaration.

25.6 Announcements are separate from invocation

When handlers exist at a point, the lifecycle dispatcher first publishes an announcement containing _hook, _handlers, operation data, and caller fields. It then invokes each named action directly. Observing a bus message is not the same as implementing the named handler or returning a veto from it.

For this Entry example, the before-create announcement is dual-published as:

adl.hooksdemo.hooksdemo_v1.entry.before_create
adl.hooksdemo.Entry.beforeCreate

The first is canonical; the second is the compatibility spelling. Canonical resource/operation spelling differs from the legacy camel-case form. The payload’s channel identifies the canonical channel on either delivery. A wildcard subscriber sees two deliveries for one announcement, while each declared handler is invoked only once unless its name was repeated in the declaration.

Use ADL 3 for the bus contract and ADL 24 for history events. A hook-point announcement, a CRUD notification, and a history entry are separate signals with different payloads and coverage.

25.7 Hook bodies and package digests

The package example names normaliseEntry. Its illustrative Lua files contain two versions of a body. The runner independently hashes their actual bytes, supplies a path-to-SHA-256 manifest to the production parser, records the emitted canonical CBOR bytes, and independently recomputes their SHA-256 values.

ComparisonObserved digest relationship
Same declaration, changed body hash at the same manifest pathSource digest changes
Same declaration, changed supplied body hashResolved model digest remains the same
Same declaration with and without the manifestSource digest differs

The manifest is folded into the source tree under __files__. Hook names alone do not cause the parser to read local files. A caller invoking the parser without a manifest covers the declaration but not those external body bytes.

Source inspection of file bootstrap shows recursive collection of .lua files beneath the document directory and forwarding of their relative paths/hashes through __package_files. It scans Lua files beyond just the explicitly named hooks; the inspected path does not collect arbitrary seed-file extensions and catches directory traversal exceptions. This is narrower than a blanket guarantee that every shipped executable or seed file was discovered. The chapter’s direct manifest checks do not execute file bootstrap.

The digest proves the relationship between the supplied manifest, declaration, and canonical bytes. It does not bind a runtime action, execute the Lua body, validate its behavior, authenticate a publisher, or prove that the host loaded that same body. ADL 8 and ADL 9 own package and canonicalization contracts; the Lua host owns loading and execution.

25.8 Restoration and verification

The checked exporter and both registry reload paths preserve the hook names and per-point order for these fixtures. A source-free model reload does not recreate registered application actions or their bodies. Restoring configuration and restoring an executable binding are separate operations.

The dossier contains five complete YAML files, two illustrative Lua bodies, 41 native cases, 296 passing assertions, five independent modeller projections, and ten passing focused helper tests. Thirteen cases inspect parsing, restoration, and package digests; 28 sequences exercise generated actions in disposable SQLite stores.

The evidence report records method and limitations. The run does not load a Lua plugin, exercise a real authentication provider, prove external transaction isolation, or establish crash recovery. Actual action binding, handler order, return handling, context, and write outcomes are executed through the current kernel. No production source snapshots are copied.