Hooks and views in Python
The Python library runs hooks and materialized views inside your own process, on the engine of embedded serving . A hook or a view run in Python writes the same values as featuremeshd, under the same fences and run numbers.
The library runs them; your process drives them. Two things featuremeshd does on its own become your code's:
- The stream. Your own Kafka consumer polls the records, hands each batch to the library, then commits the batch's offsets.
- The clock. Your own loop, cron job or scheduler task asks the library to drain the due queues and run the due views. When you ask decides each drain's time (its
REQUEST_TIME()), which entries have passed theirEXPIREand are dropped, and which slot a view runs.
Register and load
The definitions are the ones featuremeshd runs: streams, sinks, hooks and materialized views, in FeatureQL ( Hooks , Materialized views ). Register them in the local registry, then load them into the engine:
import featuremesh
from featuremesh import RegistryDeployment, ServingClient, ServingDeployment
featuremesh.set_default("registry", RegistryDeployment.LOCAL)
featuremesh.set_default("serving", ServingDeployment.EMBEDDED)
featuremesh.set_default("local.db_path", "registry.db")
client = ServingClient()
for path in ("event_hook.fql", "scheduled_hook.fql"): # the two CREATE FEATURES of Hooks
client.translate(open(path).read())
client.query("RECOMPILE SERVING;")
for row in client.hooks_status("FM.TUTORIALS.HOOK_REF.%"):
print(row["feature"], row["status"]) FM.TUTORIALS.HOOK_REF.ON_PAYMENT RUNNING
FM.TUTORIALS.HOOK_REF.ROLLUP_MINUTE RUNNING The two files hold the two CREATE FEATURES of Hooks : ON_PAYMENT, an event hook writing each merchant's payments to a Redis index, and ROLLUP_MINUTE, a scheduled hook with one entry per merchant and minute in a PostgreSQL queue. translate() registers each, and RECOMPILE SERVING loads them ( The local registry ). One call takes one statement: several statements in one text must be wrapped in START TRANSACTION; … COMMIT;.
A sink's PASSWORD = SECRET('env', …) is read by the library, from your process's environment, when it connects. The stream's connection properties are not read: the library never connects to Kafka ( The stream ).
Hand in a batch
run_event_hook(hook, records) runs an event hook over the records your consumer polled, as one batch:
report = client.run_event_hook("FM.TUTORIALS.HOOK_REF.ON_PAYMENT", [
{"value": {"payment_id": 1, "merchant_id": 7, "amount": 12.5, "event_time": "2026-11-26T10:00:01"},
"partition": 0, "offset": 10},
{"value": {"payment_id": 2, "merchant_id": 7, "amount": 0.0, "event_time": "2026-11-26T10:00:02"},
"partition": 0, "offset": 11},
{"value": b"not json", "partition": 0, "offset": 12},
])
print(report) {'hook': 'FM.TUTORIALS.HOOK_REF.ON_PAYMENT', 'records': 3, 'calls': 1, 'skipped': 1, 'writes': 1, 'deletions': 0, 'trimmed': 0, 'scheduled': 1, 'deduplicated': 0, 'data_errors': 1, 'errors': [{'hook': 'FM.TUTORIALS.HOOK_REF.ON_PAYMENT', 'row': 2, 'code': 'HOOK-RECORD-DECODE', 'message': 'the record does not decode into its declared fields: expected ident at line 1 column 2', 'partition': 0, 'offset': 12}]} The first record is written to the index and queues an entry for ROLLUP_MINUTE. The hook's WHERE p[amount] > 0 skips the second. The third does not decode: it is a data error, counted and sampled in errors, and the batch goes on.
The records are confluent_kafka.Message objects, or dicts with the same fields:
| Field | Takes | When missing |
|---|---|---|
value | bytes, text, or a dict (written as JSON). A value that is not a JSON object, None included, is a decode error | a decode error |
key | text | NULL |
timestamp | epoch milliseconds, Kafka's (type, ms) pair, or a datetime (naive is UTC). Not available or negative means now | now |
partition | an integer | 0 |
offset | an integer | -1 |
headers | (name, value) pairs | none |
Before it returns, the library:
- decodes each value as the stream's
FORMATsays, and fills the record's reserved fields (record_key,record_time,record_partition,record_offset,record_headers, Reserved fields ); - runs the hook's statement once per record;
- writes the hook's sinks;
- runs the hooks
ONits statement withoutAT, and writes theirs; - queues the entries of the hooks
ONit withAT; - fires the statements' loggers.
Commit after it returns. Commit, per partition, the offset after the batch's last record, once run_event_hook has returned. Hooks run at least once: a crash before the commit hands the same records in again ( At least once ). A loop that consumes, retries and commits is in Feed hooks from your own pipeline .
A data error never raises. A record that does not decode, or a call that raises, is counted and skipped, with the same effects as in featuremeshd ( Failures in a batch ). Read data_errors and errors in each report.
A store that does not answer raises. A source, sink or queue that fails makes run_event_hook raise RuntimeError at once, after the loggers have their rows. The batch is not written whole: commit nothing, and hand the same records in again or stop. Retrying is yours ( Retries ).
Drains and views
Three methods do what featuremeshd's clock does:
run_due_hooks()drains every scheduled hook's due entries once, under the queue's lease, as featuremeshd's drainer does: in batches of up to 1,000 entries, until none is due. A drain that stops short reportserror, and its entries wait for the next call.run_due_materialized_views()runs each view whose latest due slot, from itsSCHEDULEandTIME_ZONE, has not run yet in this process. Missed slots are skipped, as in featuremeshd. A failed or busy slot is run again by the next call. A view withoutSCHEDULEnever runs here.recompute_materialized_view(view)isRECOMPUTE MATERIALIZED VIEW, whichclient.query()refuses here (UE/MATERIALIZED-VIEW-RECOMPUTE-SERVING-ONLY): it runs the view's latest due slot now, inline, with a new run number, and makes one attempt. A view withoutSCHEDULEruns at a slot of the time it is asked, in whole seconds.
After the batch above, ROLLUP_MINUTE's entry for merchant 7 and minute 10:00 falls due at 10:01:10. Once it has passed, the next tick drains it, runs MINUTE_PS and writes PER_MINUTE:
for drained in client.run_due_hooks():
print(drained) {'hook': 'FM.TUTORIALS.HOOK_REF.ROLLUP_MINUTE', 'error': None, 'drains': 1, 'fired': 1, 'expired': 0, 'deleted': 1, 'dropped': 0, 'data_errors': 0, 'busy': False, 'errors': []} How often you call is your drain period: a hook's EVERY applies to featuremeshd only ( The clock ).
Methods
| Method | Returns | Raises RuntimeError |
|---|---|---|
run_event_hook(hook, records) | the batch's report: hook, records, calls, skipped (by WHERE), writes, deletions, trimmed, scheduled, deduplicated, data_errors (the counts include the hooks ON its statement), and errors, up to five dicts hook, row (the record's position in the batch), code, message, partition, offset | when a source, sink or queue fails, the batch not written whole; for a hook not served, or not ON a stream |
run_due_hooks() | one dict per scheduled hook: hook and error (None, or why its drain stopped short; a hook ON its statement that failed leaves the entries for the next call); after a drain also drains, fired, expired, deleted, dropped, data_errors, busy (another holder has the lease) and errors | never for a drain |
run_due_materialized_views() | one dict per view with a due slot not run yet in this process: view, slot (UTC text), run (0 when nothing ran), attempts, rows, deleted, data_errors, stale (sinks a newer run had published), busy (the holder, or None), error | never for a run |
recompute_materialized_view(view) | the same dict, for the slot it ran | for a view not served. A run that fails, or finds another holder, has error or busy |
hooks_status(pattern) | the SHOW SERVING STATUS rows of this process's hooks and views, as dicts: feature, kind, status, since, message, and details, the message's JSON ( A hook's details ) |
- Every method raises
NotImplementedErroron a client that is not embedded: featuremeshd runs hooks and views itself. It raisesRuntimeErroronce the client is closed. - One client, two threads. A consumer thread and a tick thread can share one
ServingClient: the engine runs each call outside Python's global lock.
What the library writes
Your code never writes a sink or a queue: the library does, with featuremeshd's rules ( Which write lands ). A latest value lands only over an older or equal one, and a view's run publishes only if no newer run has. Loggers on the statements hand their rows to your log_handler, as for serving calls ( Logging from Python ).
- The batch, then your commit. Within
run_event_hook, the library writes the index and the sinks, and queues the scheduled hooks' entries. Your consumer commits after. Nothing spans Kafka and the stores: a crash between the two hands the batch in again over sinks already written, which take the same values again. - A drain writes its sinks and its queue updates in one transaction only when they share a PostgreSQL or MySQL database ( Failures in a drain ).
- A view's lease and run number are kept in the local registry file. Two processes sharing one registry file never both publish a slot. A run's number starts above the run its sinks already published, so a deleted or restored registry file never locks a view out of its own sinks.
Reading what a hook or view wrote is an ordinary feature over the store, served by the same client ( Reading back ).
Related
- Differences from featuremeshd : the stream, the clock, retries, and running one hook in one place.
- Feed hooks from your own pipeline : a production consumer loop.
- Hooks and Materialized views : the definitions.