Sinks and reading back

A sink says where and how a hook, a materialized view or a logger writes, and serving reads what it holds back as an ordinary source.

SINK('<url>' [KEY <expression> | TABLE '<name>' [KEY (<column>, …)]] [INDEXED ON <field> UNIQUE ON <field>]
     [WITH (MODE = …, SHAPE = …, FORMAT = …, RETENTION = …, WATERMARK_KEY = …, PASSWORD = SECRET(…))])
sql

A hot sink, a queue or a view's sink has one writer. A second hook or view naming it is refused at registration (UE/SINK-SHARED), and so is a hook or view naming a logger's sink. Loggers are the exception: several can share one cold sink, each writing under its own path ( Feature logging ). The check is on the sink feature, not on what it points at ( Limits ).

Modes

MODEKeepsWritten by
latestone value per key, the newest: for a hook, the one with the newest request_time; for a view, the last run'shooks and views: Redis, PostgreSQL, MySQL/MariaDB
appendone member or row per identity. On Redis, the event index: a sorted set per KEY, scored by INDEXED ON, one member per UNIQUE ON value. On a table, one row per KEY columns plus UNIQUE ONhooks: Redis (SHAPE = 'sorted_set'), PostgreSQL, MySQL/MariaDB. Loggers: files and object stores, every row
replacethe last run's rows, swapped whole at each runviews: PostgreSQL, MySQL/MariaDB, object stores and file://
  • Hot for hooks, cold for loggers. A hook writes the stores serving reads. Files, object stores and stdout:// are a logger's.
  • Whole values. A write replaces its key's whole value, or its member's or row's. A retried record writes again what its statement computes then, which differs when a source it reads changed: a replay never adds a row, and it does not restore the values computed before.
  • Keys. A table sink names its key columns, taken from the statement's inputs (a ROW input's fields) or its output. A Redis KEY is an expression over the same.
  • A hash tag in every Redis key. An event index writes two keys, the sorted set and <key>:ids, in one script. On Redis Cluster they must share a slot, so the registry requires a hash tag in the KEY of every Redis sink a hook or view writes: 'shop:pay:{' || MERCHANT_ID::VARCHAR || '}'. On a single Redis the braces do nothing.
  • The event index on Redis. Each member is the row in the sink's FORMAT (MessagePack in the tutorials), scored by its INDEXED ON time in seconds. <key>:ids maps each UNIQUE ON value to that score. UNIQUE ON makes a replayed record replace its member rather than add a second one. A member is unique within its key only.
  • An index in a table is an append table sink: one row per KEY columns plus the UNIQUE ON field, which are the table's primary key, trimmed by RETENTION on the INDEXED ON time. A history in PostgreSQL rather than Redis:
PAY_HISTORY := SINK('postgresql://hooks@db:5432/app' TABLE 'pay_history' KEY (merchant_id)
    INDEXED ON event_time UNIQUE ON payment_id
    WITH (MODE = 'append', RETENTION = INTERVAL '30 DAYS', PASSWORD = SECRET('env', 'PG_PASSWORD'))),
-- CREATE TABLE pay_history (merchant_id BIGINT NOT NULL, event_time TIMESTAMP(3), payment_id BIGINT NOT NULL,
--     amount NUMERIC(12, 2), request_time TIMESTAMP(6), compute_time TIMESTAMP(6), datakey TEXT,
--     "partition" INTEGER, "offset" BIGINT, drain BIGINT, PRIMARY KEY (merchant_id, payment_id));
sql

To read it, start from SHOW CREATE SINK PAY_HISTORY READER, which prints a point lookup, and turn it into a read over merchant_id and a range of event_time ( Long horizons ).

Which write lands

Writer and modeA write landsOn the same time or identity
hook, latestwhen its request_time is not older than the stored one. Redis compares in a script, a table in the upsertit replaces: the last write wins ( Which write lands )
hook, appendalways, replacing the member or row of the same identity wholethe last write wins, whatever its INDEXED ON value or its request_time
view, latest or replacewhen its run is newer than the run the sink published ( How a run lands )a run number is never reused
queue entryby its due time and the hook's POLICY ( WITH )one pending entry per reference
  • append has no fence. A replay of an event rewrites its member or row from what the statement computes then. A corrected payload under the same identity is overwritten by an older record replayed later ( Late, corrected and missing events ).
  • An identity is scoped to its key: the Redis key, or the table's KEY columns. An event that moves to another key, such as another merchant, gets a member there and leaves the old one.
  • A Kafka tombstone removes nothing. A record with no value is a decode error, not a removal.

Retention

RETENTION removes a row once its time is older than the store's clock minus the retention. The time is the INDEXED ON field for an append member or row, and request_time for any other row (for a view, its slot).

StoreHow rows expire
Redis valuewith PEXPIREAT
Redis indextrimmed inside each write to its key: expired members go with their <key>:ids entries. Both keys expire at the newest member's time plus the retention, so an idle key's index disappears on its own
Tablerows deleted by a periodic sweep of featuremeshd ( retention_sweep_every ), so a row can outlive its retention by up to one sweep period. A reader that needs an exact window filters on the time

A view's watermark never expires ( Materialized views ).

Properties

Clause or WITHSinksValuesDefault
KEY <expression>Redisthe key, with a {hash tag}required
TABLE '<name>' KEY (…)PostgreSQL, MySQL/MariaDBthe table, and its key columnsTABLE required; KEY required for latest
INDEXED ON … UNIQUE ON …hooks' append sinksthe time field and the identity fieldrequired for append, refused otherwise
MODERedis'append', 'latest''append'
PostgreSQL, MySQL/MariaDB'append', 'latest', 'replace' (views)'append'
object stores, files'append' (loggers), 'replace' (views)'append'
SHAPERedis'sorted_set' for append, 'string' for latestfollows MODE
FORMATRedis'json', 'msgpack'required
object stores, files'parquet', 'jsonl''parquet'
RETENTIONhot sinksa fixed INTERVAL in days, hours, minutes or seconds: INTERVAL '30 DAYS' is accepted, months and years are refusednone: rows stay
WATERMARK_KEYa view's Redis latest sinkthe key of the view's watermarkrequired there, refused elsewhere
PASSWORDhot sinks, queuesa SECRET(…)none
COMPRESSION, ROLL_SECONDS, ROLL_MBParquet and file sinks (loggers, views)see Feature logging

A sink takes its password as a source does: SINK('postgresql://fm@db:5432/fm' TABLE '…' WITH (PASSWORD = SECRET('env', 'PG_PASSWORD'))), for a table and for a queue. When featuremeshd reads it is in Credentials . Sinks and queues connect over TLS as the sources of their store do:

StoreWhen the URL says nothingOther settingsPrivate CA
PostgreSQLsslmode=verify-full: TLS, the certificate and name checked against the system's rootsrequire (TLS, certificate not checked), disable (plain text, for a local database)sslrootcert=/path/ca.crt
MySQL, MariaDBsslmode=required: TLS, the certificate and name checked against the system's rootspreferred (TLS without a certificate check when the server offers it, plain text when it does not: not for credentials over a network you do not trust), disabled (plain text)sslrootcert=/path/ca.pem
Redisplain text with redis://rediss://: TLS, the certificate checked against the system's rootsset in featuremeshd's environment ( Rotate credentials and certificates )

Queues

A queue is a bare hot sink: a TABLE without KEY columns, or a constant Redis KEY prefix, plus PASSWORD if it needs one. MODE, SHAPE, FORMAT, RETENTION, INDEXED ON, UNIQUE ON, KEY columns and WATERMARK_KEY are refused (UE/HOOK-QUEUE-OPTIONS).

MINUTE_QUEUE := SINK('postgresql://fm@postgres:5432/fm' TABLE 'minute_queue'
    WITH (PASSWORD = SECRET('env', 'PG_PASSWORD'))),
MINUTE_QUEUE := SINK('mysql://fm@mariadb:3306/fm' TABLE 'minute_queue'
    WITH (PASSWORD = SECRET('env', 'MYSQL_PASSWORD'))),
MINUTE_QUEUE := SINK('rediss://redis:6380' KEY 'minute_queue'
    WITH (PASSWORD = SECRET('env', 'REDIS_PASSWORD'))),
sql
  • A Redis prefix needs no hash tag. FeatureMesh wraps it in braces, so the queue's keys {minute_queue}:due, :entries, :meta and :lease share one slot of a cluster. A prefix that already holds braces is kept as written.
  • The queue's table is created for you. featuremeshd creates a missing queue table when it starts draining, if its credentials allow CREATE, because the engine owns the queue's format. SHOW CREATE HOOK prints the statements that create it, for you to run or adapt:

FeatureQL
SHOW CREATE HOOK FM.TUTORIALS.HOOK_REF.ROLLUP_MINUTE;
Result
OUTPUT VARCHAR
-- The queue of FM.TUTORIALS.HOOK_REF.ROLLUP_MINUTE, FM.TUTORIALS.HOOK_REF.MINUTE_QUEUE. CREATE TABLE IF NOT EXISTS minute_queue ( ref_hash BYTEA PRIMARY KEY, reference BYTEA, due_time BIGINT, token BYTEA, claim_time BIGINT, holder TEXT, lease_number BIGINT, identity TEXT ); CREATE INDEX IF NOT EXISTS minute_queue_due ON minute_queue (due_time);

  • What a queue holds. A table's rows hold the reference encoded, under ref_hash, and its due_time in epoch seconds. A Redis queue keeps {<prefix>}:due, a sorted set of hashes scored by due time, and {<prefix>}:entries, their references. Entries are not keyed by a readable reference. SHOW SERVING STATUS gives a queue's depth, its due entries and the oldest one's age ( Status ).

FeatureMesh creates nothing else you did not name. A sink's table is your schema, read by your readers, so it is never created for you.

The write layout

The rows a writer lands have its keys, its value's fields, then the layout's columns:

ColumnHolds
the keystable sinks: the KEY columns
the value's fieldsone per field of the statement's ROW output (a scalar: one, named as the feature); a view's columns
request_timethe call's REQUEST_TIME(): an event hook's record's Kafka timestamp, a scheduled hook's drain time, a hook ON a statement's trigger's; a view's slot
compute_timewhen the value was computed. NULL in a tombstone
datakeythe definition that wrote it: its name and a hash of its compiled version, FM.SHOP.ON_PAYMENT@78667480d51269c7
partition, offsethooks: the stream record behind the row, its trigger's for a hook ON a statement. NULL for a scheduled hook
drainhooks: a scheduled hook's drain number, shared by every reference of that drain. NULL otherwise
runviews: the run that wrote it

Readers name the fields, in any order. A row's identity is its key, not these columns: a topic has no column, every reference of a drain has the same drain, and a retried drain has a new one.

Tables

A table sink's table is yours to create before its writer runs. The registry does not check it: a missing column fails the write with the store's error, and the hook is STALLED until the table has it. Check the table against the columns SHOW CREATE SINK … READER prints. The columns are named, in any order:

Writer, MODEPrimary key, or unique keyColumns
hook, latestthe KEY columns (the upsert needs it)keys, value fields, request_time, compute_time, datakey, partition, offset, drain
hook, appendthe KEY columns and the UNIQUE ON fieldthe same
view, latestthe KEY columnsthe view's columns, request_time, compute_time, datakey, run
view, replacenone neededthe same
  • Nullable. Leave every column but the keys and request_time nullable. A tombstone sets the others to NULL, and the layout columns a writer does not fill are NULL.
  • Types. Times are TIMESTAMP(6) in PostgreSQL and DATETIME(6) in MySQL/MariaDB. datakey is text, partition an integer, and offset, drain and run big integers. The value's columns take the types the statement writes ( Keep money exact ).
  • Quoted. partition and offset are quoted, with double quotes in PostgreSQL and backticks in MySQL/MariaDB.
  • Privileges. Grant SELECT, INSERT, UPDATE and DELETE on the table, and on a view's watermark table.
  • A key column is the input's. A KEY column named like a field of the statement's output is refused at registration (SINK-KEY-AMBIGUOUS): the table would hold one of the two. Drop the field from the output, since the key comes from the input, or rename one of them.

For minute buckets whose amounts are DOUBLE:

-- PostgreSQL
CREATE TABLE per_minute (
    merchant_id  BIGINT NOT NULL,
    minute       TIMESTAMP(3) NOT NULL,
    n            BIGINT,
    total        DOUBLE PRECISION,
    request_time TIMESTAMP(6),
    compute_time TIMESTAMP(6),
    datakey      TEXT,
    "partition"  INTEGER,
    "offset"     BIGINT,
    drain        BIGINT,
    PRIMARY KEY (merchant_id, minute)
);
-- MySQL/MariaDB: the same columns, with
--     minute DATETIME(3), total DOUBLE, request_time DATETIME(6), compute_time DATETIME(6),
--     `partition` INT, `offset` BIGINT
sql

A view's table and its watermark table are in Materialized views .

Reading back

Hooks and views only write. A read is an ordinary feature over an ordinary source, declared against the layout above, and FeatureMesh never links it to the sink. SHOW CREATE SINK … READER prints that declaration for the sink as its writer is compiled now: paste it, rename, and drop the columns you do not need.

For the event index, read as a history : EXTERNAL_KV(KEY … FROM … AS ARRAY<ROW<…>> INDEXED ON event_time WITH (FORMAT = 'msgpack')), the layout's columns included, its clauses in that order:

FeatureQL
SHOW CREATE SINK FM.TUTORIALS.HOOK_REF.PAY_INDEX READER;
Result
OUTPUT VARCHAR
-- Reads FM.TUTORIALS.HOOK_REF.PAY_INDEX, written by FM.TUTORIALS.HOOK_REF.ON_PAYMENT (key columns, the value's fields, then request_time, compute_time, datakey, partition, offset, drain). CREATE OR REPLACE FEATURES IN FM.TUTORIALS.HOOK_REF AS PERSIST PAY_INDEX_KV := SOURCE_KV('redis://redis:6379'), PAY_INDEX_READ := EXTERNAL_KV(KEY ('pay:{' || FM.TUTORIALS.HOOK_REF.MERCHANT_ID::VARCHAR || '}') FROM PAY_INDEX_KV AS ARRAY(ROW(event_time TIMESTAMP(3), payment_id BIGINT, amount DOUBLE, request_time TIMESTAMP(6), compute_time TIMESTAMP(6), datakey VARCHAR, partition INTEGER, offset BIGINT, drain BIGINT)) INDEXED ON event_time WITH (FORMAT = 'msgpack'))[value];

For a table:

FeatureQL
SHOW CREATE SINK FM.TUTORIALS.HOOK_REF.PER_MINUTE READER;
Result
OUTPUT VARCHAR
-- Reads FM.TUTORIALS.HOOK_REF.PER_MINUTE, written by FM.TUTORIALS.HOOK_REF.ROLLUP_MINUTE (key columns, the value's fields, then request_time, compute_time, datakey, partition, offset, drain). -- A key whose call raised holds a tombstone, request_time and no compute_time: it reads as NULL. CREATE OR REPLACE FEATURES IN FM.TUTORIALS.HOOK_REF AS PERSIST PER_MINUTE_DB := SOURCE_DB('postgresql://fm@postgres:5432/fm' WITH (tables = ARRAY['per_minute'], password = SECRET('env', 'PG_PASSWORD'))), PER_MINUTE_MERCHANT_ID := INPUT(BIGINT), PER_MINUTE_MINUTE := INPUT(TIMESTAMP(3)), PER_MINUTE_STORED := EXTERNAL_COLUMNS("merchant_id" BIGINT BIND TO PER_MINUTE_MERCHANT_ID, "minute" TIMESTAMP(3) BIND TO PER_MINUTE_MINUTE, "n_doubled" BIGINT, "request_time" TIMESTAMP(6), "compute_time" TIMESTAMP(6), "datakey" VARCHAR, "partition" INTEGER, "offset" BIGINT, "drain" BIGINT FROM TABLE(PER_MINUTE_DB[per_minute])), PER_MINUTE_READ := IF(PER_MINUTE_STORED[compute_time] IS NULL, NULL, PER_MINUTE_STORED);

A Redis latest value is read as a ROW, without INDEXED ON and without [value], through the same tombstone check. A view's reader also checks the run ( Reading a view ).

What a reader sees, for a latest sink read as READ := IF(STORED[compute_time] IS NULL, NULL, STORED), and for an event index:

The store holdslatest: READlatest: STORED[source_status]Event index
a valuethe valueOKthe members, OK
nothing: never written, expired or deletedNULLMISS[], OK: an empty history is never MISS
a tombstone NULLOK, with request_time set and compute_time NULL
the store is down or slowthe call fails (SERVING-SOURCE-UNAVAILABLE, SERVING-SOURCE-TIMEOUT); a guarded read gives NULL and the call is PARTIALUNAVAILABLE, TIMEOUTthe same
  • The fallback is the reader's. An outage is never read as "no activity" unless the reader says so. By default it fails the call. Reading source_status guards the read, and the feature chooses ( Serving errors and fallbacks ). In an index, a key with no events and a key never written are both []. A reader that tells the cases apart:
SCORE_OR_REVIEW := CASE
    WHEN STORED[source_status] NOT IN ('OK', 'MISS') THEN 'REVIEW'   -- the store did not answer
    WHEN STORED[compute_time] IS NULL THEN 'NO_VALUE'                -- a miss, or a tombstone
    ELSE STORED[tier] END,
  • Freshness is the reader's rule. A hook has no watermark. How old a value may be, and which datakey it may come from, the reader decides over the value's request_time and datakey.

Related