Hooks

A hook runs a prepared statement you already serve, unchanged, when a stream record arrives, when another hook runs that statement, or when a queued entry falls due.

HOOK(RUN <prepared statement> ON <trigger> [AS <alias>] [WHERE <condition>] [AT <due time>]
     USING <values> [TO <sink> [, <sink> …]] [QUEUE <sink>]
     [WITH (START = …, POLICY = …, EVERY = …, EXPIRE = …)])
sql

A hook is a feature, declared in CREATE FEATURES like any other. It shares its clauses with LOGGER . Streams, sinks and hooks reach featuremeshd at RECOMPILE SERVING or at its next sync ( Recompile before serving ).

Three kinds

Event hookHook on a statementScheduled hook
Declared asHOOK(… ON <stream record>)HOOK(… ON <statement>), without ATHOOK(… ON <statement> AT …)
Fired byeach record of a Kafka topiceach successful call of its statement by another hook, once that hook's batch is writtenan entry of its queue falling due. Entries are queued by the hook runs of the statement it is ON
Callsone per recordone per triggering callone per due reference
Writesthe event index, latest values, the queues of the hooks on its statementthe samelatest values, the queues of the hooks on its statement
REQUEST_TIME()the record's Kafka timestamp, not a time field of its payload such as event_timethe trigger's own REQUEST_TIME(): down a chain from an event hook, the record's Kafka timestampthe drain's time T, on the queue store's clock in whole seconds: the due time or later, by the drain period, a backlog or retries
State of its own, besides what it writesnone: its offsets are in Kafkanoneits queue, in a store

REQUEST_TIME() is also the request_time of every value the call writes. A scheduled hook's value is as of its drain, not its due time, so a later drain reads more of the index. A bucket's own minute or hour is in its key. A materialized view is not a hook: it is a scheduled query.

An event hook, ON a stream's record, writing an event index:

FeatureQL
CREATE OR REPLACE FEATURES IN FM.TUTORIALS.HOOK_REF AS
PERSIST
    stream := SOURCE_STREAM('kafka://broker:9092' WITH (FORMAT = 'json')),
    payments := EXTERNAL_COLUMNS(
        payment_id BIGINT,
        merchant_id BIGINT,
        amount DOUBLE,
        event_time TIMESTAMP(3)
        FROM TABLE(stream[payments])
    ),
    payment_id := INPUT(BIGINT),
    merchant_id := INPUT(BIGINT),
    amount := INPUT(DOUBLE),
    event_time := INPUT(TIMESTAMP(3)),
    pay_row := ROW(
        event_time AS event_time,
        payment_id AS payment_id,
        amount AS amount
    ),
    minute_ref := ROW(
        merchant_id AS merchant_id,
        DATE_TRUNC(event_time, 'minute') AS minute
    ),
    minute_close := (DATE_TRUNC(event_time, 'minute') + INTERVAL '70 SECOND')::TIMESTAMP(0),
    pay_ps := PREPARED_STATEMENT(
        pay_row
        USING (payment_id, merchant_id, amount, event_time)
        CAPTURE (minute_ref, minute_close)
    ),
    pay_index := SINK(
        'redis://redis:6379'
        KEY 'pay:{' || merchant_id::VARCHAR || '}'
        INDEXED ON event_time UNIQUE ON payment_id
        WITH (
            FORMAT = 'msgpack',
            MODE = 'append',
            SHAPE = 'sorted_set',
            RETENTION = INTERVAL '1 DAY'
        )
    ),
    on_payment := HOOK(
        RUN pay_ps
        ON payments AS p
        WHERE p[amount] > 0
        USING (p[payment_id], p[merchant_id], p[amount], p[event_time])
        TO pay_index
        WITH (
            START = 'earliest'
        )
    )
;
Result
feature_name VARCHARstatus VARCHARmessage VARCHAR
FM.TUTORIALS.HOOK_REF.AMOUNTCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_REF.EVENT_TIMECREATEDFeature created as not exists
FM.TUTORIALS.HOOK_REF.MERCHANT_IDCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_REF.MINUTE_CLOSECREATEDFeature created as not exists
FM.TUTORIALS.HOOK_REF.MINUTE_REFCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_REF.ON_PAYMENTCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_REF.PAYMENTSCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_REF.PAYMENT_IDCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_REF.PAY_INDEXCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_REF.PAY_PSCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_REF.PAY_ROWCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_REF.STREAMCREATEDFeature created as not exists

A scheduled hook ON the event hook's statement. Its reference MINUTE_REF is a row, (merchant_id, minute), so the queue holds one entry per merchant and minute. The statement it runs, MINUTE_PS, takes that row as its input, so each run is a lookup on one merchant:

FeatureQL
CREATE OR REPLACE FEATURES IN FM.TUTORIALS.HOOK_REF AS
PERSIST
    mm := INPUT(ROW<merchant_id BIGINT, minute TIMESTAMP(3)>),
    n_doubled := mm[merchant_id] * 2,
    minute_ps := PREPARED_STATEMENT(n_doubled USING mm),
    per_minute := SINK(
        'postgresql://fm@postgres:5432/fm'
        TABLE 'per_minute' KEY (MERCHANT_ID, MINUTE)
        WITH (
            MODE = 'latest',
            PASSWORD = SECRET('env', 'PG_PASSWORD')
        )
    ),
    minute_queue := SINK(
        'postgresql://fm@postgres:5432/fm'
        TABLE 'minute_queue'
        WITH (
            PASSWORD = SECRET('env', 'PG_PASSWORD')
        )
    ),
    rollup_minute := HOOK(
        RUN minute_ps
        ON pay_ps
        AT minute_close
        USING (minute_ref)
        TO per_minute
        QUEUE minute_queue
        WITH (
            POLICY = 'earliest',
            EVERY = INTERVAL '10 SECOND',
            EXPIRE = INTERVAL '23 HOUR'
        )
    )
;
Result
feature_name VARCHARstatus VARCHARmessage VARCHAR
FM.TUTORIALS.HOOK_REF.MINUTE_PSCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_REF.MINUTE_QUEUECREATEDFeature created as not exists
FM.TUTORIALS.HOOK_REF.MMCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_REF.N_DOUBLEDCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_REF.PER_MINUTECREATEDFeature created as not exists
FM.TUTORIALS.HOOK_REF.ROLLUP_MINUTECREATEDFeature created as not exists

Clauses

ClauseTakesNotes
RUNa PREPARED_STATEMENTThe statement reads its sources like any serving call. Its output goes TO the sinks, and its loggers log the hook's calls
ONa stream's record, or a prepared statementA record is EXTERNAL_COLUMNS(… FROM TABLE(STREAM[topic])) and needs AS. A statement's call row (its inputs, output and captures) is read by feature name
ASan aliasA record only: ON PAYMENTS AS p, then p[field]
WHEREa boolean over the trigger's rowNULL does not fire
ATa TIMESTAMP(0) over the trigger's rowQueues the run: the USING values are the reference, AT its due time. A statement trigger only: AT schedules a run after the writes of the statement the hook is ON, and a stream's record has none (UE/HOOK-AT-ON-STREAM). Run a statement on the stream, and schedule ON it
USINGthe call's inputs, by positionThe statement's own USING, binders removed, each input replaced by a value: (a, b), c for two input tables. One input table of three inputs takes one group of three values
TOhot sinks: the stores serving reads, Redis, PostgreSQL and MySQL/MariaDBMay be empty when the statement's loggers or hooks are the point. A hot sink has one writer: a second hook or view writing it is refused (UE/SINK-SHARED), as is a logger's sink ( Sinks )
QUEUEa bare sink: a table, or a constant Redis key prefix ( Queues )Where a scheduled hook keeps its queue. Required with AT, refused without

USING, WHERE and AT read the trigger's row and nothing else: no source, no other feature, no REQUEST_TIME() or NOW(). A value several hooks need is a feature of the triggering statement, listed in its CAPTURE (…). A capture is computed in the same call, from the same reads, and is not returned to the caller ( CAPTURE ).

AT takes whole seconds, cast visibly: DATE_TRUNC(…, 'second')::TIMESTAMP(0). Another type is refused (UE/HOOK-AT-NOT-SECONDS). A cast to TIMESTAMP(0) rounds to the nearest second, half up: 10:00:59.5 gives 10:01:00. DATE_TRUNC truncates first, which is what a bucket boundary needs.

WITH

PropertyForTakesDefault
STARTan event hookWhere its consumer starts on a partition that has no committed offset yet: 'earliest', 'latest', or an interval back from now (INTERVAL '1 HOUR'). It applies to the partitions the hook finds when it first subscribes. A partition added to the topic later is read from its beginning, whatever START says. Under 'latest', the index holds no record produced before the hook first got the partition'latest'
POLICYa scheduled hookWhich due time an entry keeps when it is queued again before it runs. 'earliest' keeps the earlier one, so a bucket's close does not move. 'latest' keeps the later one, a debounce: a burst pushes the run back, and it runs once after the burst. Under 'latest', a due time far in the future (an event stamped a year ahead) pins its entry there: guard the due time where it is computed'earliest'
EVERYa scheduled hookHow often its queue is drained, at least one secondthe configuration's drain_every, 5 seconds
EXPIREa scheduled hookHow long after its due time an entry may still run. An older entry is dropped, counted, and not runrequired (UE/HOOK-AT-WITHOUT-EXPIRE)

Changing EXPIRE, EVERY or POLICY with CREATE OR REPLACE keeps the queued entries. A change of the QUEUE, of the USING text or of the reference's types moves the queue, and drops its entries ( Queues and drains ).

Queues and drains

A scheduled hook's queue keeps one pending entry per reference, such as a merchant and a minute. Every call of the statement it is ON queues its reference, due at AT, so a minute's payments for one merchant fold into one entry.

  • Queued again before it runs, an entry is folded by POLICY.
  • Queued again after it ran, or while it runs, the reference gets a new entry, which runs again. Under 'earliest' it runs at the next drain, already past due. Under 'latest' it runs at its new due time.
  • A late event queues its reference again with the same due time, already past, so it runs at the next drain if it is still within EXPIRE. That run computes the whole reference again.

The queue lives in the store its QUEUE names and survives restarts. Any featuremeshd running the hook can drain it, one at a time, under a lease ( Leases ).

Every EVERY, the drainer runs the due entries in batches, until nothing is due. A batch's size is a setting of featuremeshd ( drain_batch_max ). The next drain starts one EVERY after the previous one ended. Without lag, an entry runs at its due time plus the wait for the next drain. Consumer lag, a backlog, a store failure or a lease handover add to that, without bound.

A drain reads its time T on the queue store's clock, in whole seconds, and takes the entries due at or before T. Each entry is checked against EXPIRE then:

At the drainThe entry
due ≤ T ≤ due + EXPIREruns
T > due + EXPIREis dropped, unrun, and counted in entries_expired

Everything before the drain counts against EXPIRE: the consumer's lag, the drain period, a backlog, a drain retried after a failure. Each attempt reads a new T, so the same limit covers an outage and a late event. How a drain fails, entry by entry, is in Failures in a drain .

A recompile that names another QUEUE, or changes the hook's USING text or its reference's types, moves the queue. The old entries are dropped and counted: entries_dropped in SHOW SERVING STATUS, DROPPED rows in SHOW SERVING WRITES, and five references sampled in featuremeshd's log. No migration keeps them, and a bucket not written yet stays missing until another event schedules that same reference ( Move a queue ).

Chains

A hook ON a statement fires after every hook run of that statement: an event hook's statement can schedule a minute rollup, whose statement schedules an hour rollup. Hooks on one statement run in no defined order. A cycle is refused (UE/HOOK-CYCLE). Serving calls fire no hook ( Limits ).

Create a hook and every hook ON its statement in one CREATE FEATURES. An event hook loaded before the scheduled hook on its statement indexes records without queueing their references, and those buckets are not scheduled until another event of the same bucket arrives.

Checked at registration

USING follows the statement's own grammar:

FeatureQL
CREATE OR REPLACE FEATURE FM.TUTORIALS.HOOK_REF.BAD AS HOOK(RUN FM.TUTORIALS.HOOK_REF.PAY_PS ON FM.TUTORIALS.HOOK_REF.PAYMENTS AS p USING (p[payment_id], p[merchant_id]), p[amount], p[event_time]);
Result
ERROR UE/HOOK-USING-SHAPE FM.TUTORIALS.HOOK_REF.BAD: USING is (_, _), _, _; FM.TUTORIALS.HOOK_REF.PAY_PS takes (_, _, _, _) (its USING, binders removed, one value per input).

A hook writes hot sinks only. Files, object stores and stdout:// are a logger's:

FeatureQL
CREATE OR REPLACE FEATURE FM.TUTORIALS.HOOK_REF.BAD AS HOOK(RUN FM.TUTORIALS.HOOK_REF.PAY_PS ON FM.TUTORIALS.HOOK_REF.PAYMENTS AS p USING (p[payment_id], p[merchant_id], p[amount], p[event_time]) TO SINK('file:///tmp/fm_hook_ref'));
Result
ERROR UE/HOOK-SINK-COLD FM.TUTORIALS.HOOK_REF.BAD: a hook writes hot sinks only (redis://, postgresql://, mysql://), read back by serving; file:// is a logger's.

A sink has one writer:

FeatureQL
CREATE OR REPLACE FEATURE FM.TUTORIALS.HOOK_REF.BAD AS HOOK(RUN FM.TUTORIALS.HOOK_REF.MINUTE_PS ON FM.TUTORIALS.HOOK_REF.PAY_PS AT FM.TUTORIALS.HOOK_REF.MINUTE_CLOSE USING (FM.TUTORIALS.HOOK_REF.MINUTE_REF) TO FM.TUTORIALS.HOOK_REF.PER_MINUTE QUEUE SINK('postgresql://fm@postgres:5432/fm' TABLE 'other_queue' WITH (PASSWORD = SECRET('env', 'PG_PASSWORD'))) WITH (EXPIRE = INTERVAL '1 HOUR'));
Result
ERROR UE/SINK-SHARED FM.TUTORIALS.HOOK_REF.BAD: FM.TUTORIALS.HOOK_REF.PER_MINUTE is written by FM.TUTORIALS.HOOK_REF.ROLLUP_MINUTE already; a sink has one writer.

AT needs a statement trigger:

FeatureQL
CREATE OR REPLACE FEATURE FM.TUTORIALS.HOOK_REF.BAD AS HOOK(RUN FM.TUTORIALS.HOOK_REF.MINUTE_PS ON FM.TUTORIALS.HOOK_REF.PAYMENTS AS p AT p[event_time] USING (p[merchant_id]) QUEUE FM.TUTORIALS.HOOK_REF.MINUTE_QUEUE WITH (EXPIRE = INTERVAL '1 HOUR'));
Result
ERROR UE/HOOK-AT-ON-STREAM FM.TUTORIALS.HOOK_REF.BAD: AT schedules a run after the writes of the statement the hook is ON; a hook ON a stream's record has none to come after.

EXPIRE has no default:

FeatureQL
CREATE OR REPLACE FEATURE FM.TUTORIALS.HOOK_REF.BAD AS HOOK(RUN FM.TUTORIALS.HOOK_REF.MINUTE_PS ON FM.TUTORIALS.HOOK_REF.PAY_PS AT FM.TUTORIALS.HOOK_REF.MINUTE_CLOSE USING (FM.TUTORIALS.HOOK_REF.MINUTE_REF) QUEUE SINK('postgresql://fm@postgres:5432/fm' TABLE 'bad_queue'));
Result
ERROR UE/HOOK-AT-WITHOUT-EXPIRE FM.TUTORIALS.HOOK_REF.BAD: a scheduled hook says how late an entry may still run, WITH (EXPIRE = INTERVAL ...): at most the index's RETENTION minus the window the run reads.

REQUEST_SEED() is refused in a hook's statement (UE/HOOK-REQUEST-SEED): a retried record would draw another value.

Related