Lookups and fan-out
A lookup fetches a value when the job runs, instead of you passing it up front: from a database, a command, a
Python function or AWS Secrets Manager. Fan-out (fan_out) is the work: it runs the whole job once per item, such
as an account, or each feed of each account. Together they let one job serve one account, several, or every account
of a tenant.
Both engines support this (kind: DuckDBJob and kind: SparkJob); a SparkJob runs its items one at a time.
spec is the interface: config is what a caller passes, secrets and lookups the credentials and where they come
from. fan_out is the work: its levels (each), their items (over) and the lookups each runs. Steps, connections,
outputs and the state read an item's columns as {{ account.COLUMN }}.
Example
spec:
config:
tenant_id: {type: string, required: false}
account_ids: {type: list, items: string, required: false}
secrets:
client_secret: {type: string, lookup: {from: app_secrets, field: credentials.clientSecret}} # once per run
lookups:
app_secrets:
type: command # an argument list, never a shell
command: [secrets-cli, read, ads/app]
format: auto # auto | text | json | json_string
fan_out:
each:
as: account # steps read {{ account.COLUMN }}
over: # the items: a lookup, inline or by name
type: database # database | command | function | aws_secretsmanager | files | sql
connection: creds_db # a postgres, mysql, duckdb or sqlite connection of the job
query: |
SELECT account_id, manager_id, refresh_token_enc FROM accounts
WHERE status = 'active' AND (CAST(:tenant_id AS text) IS NULL OR tenant_id = :tenant_id)
AND (CAST(:account_ids AS text) IS NULL OR account_id IN :account_ids)
params: {tenant_id: "{{ config.tenant_id }}", account_ids: "{{ config.account_ids }}"}
rows: many
secret_fields: [refresh_token_enc]
transforms: # per row, when its pass starts: function | command (stdin) | builtin
refresh_token: {type: function, function: "acme.crypto:decrypt",
arguments: {ciphertext: "{{ row.refresh_token_enc }}"}}
key: account_id
concurrency: 4
connections:
ads:
provider: google_ads
login_customer_id: "{{ account.manager_id }}"
refresh_token: "{{ account.refresh_token }}" # a transforms column: a secret, masked and never kept
client_secret: "{{ secrets.client_secret }}"
runtime:
state:
sqlite: state.db
scope: "account:{{ account.account_id }}" # each account keeps its own state
What it does:
- The inline
overlookup selects the active accounts, filtered bytenant_idoraccount_idswhen you give them. fan_outruns the job once per row (a pass), four at a time. Each pass reads its own row's columns; itsrefresh_tokenis decrypted by a Python function first.client_secretcomes from a command, once per run, and is shared by every pass.- Each pass keeps its own state, because the scope names the account.
Run it for one account, several, or a whole tenant:
sw run job.yaml --set account_ids=a1 --allow-lookup-exec # the query's filter
sw run job.yaml --set account.account_id=a1,a2 --allow-lookup-exec # pick listed accounts
sw run job.yaml --set tenant_id=t1 --allow-lookup-exec --summary # every active account of a tenant
sw spark run job.yaml --set tenant_id=t1 --allow-lookup-exec # Spark (forwarded to the driver)
sw state list --url sqlite:///state.db --scope account:a1 # one account's batches
How it works
- An input binds a lookup with
lookup: {from: NAME, field: PATH}, inspec.configorspec.secrets. - An explicit value wins:
--set,--config,--secretsorSTREAMWRIGHT_SECRET_*. A lookup that nothing needs never runs. A value for an item's column, or for an input bound to an item, picks items instead. - Lookups run before anything connects. A lookup that reads a fan-out item runs once per item (per account, or per pass); the others run once per run.
- With
fan_out, each pass is a complete run in its own scope, with its ownfailed_job_policyand attempts. The run holds its leases for all its passes. One account's failure does not stop the others.
Binding an input
| Key | What it does | Default |
|---|---|---|
from | A lookup (of spec.lookups or fan_out), or a fan-out item (its as name) | |
field | A dot path or column in the value: credentials.clientId, items[0].id. It also reads into text that holds JSON. | The whole value |
Pick items
A value given for an item's column (<as>.COLUMN), or for an input bound to a fan-out item, picks the items whose
column has it. Each pass still reads its own item.
sw run job.yaml --set account.account_id=a1 --allow-lookup-exec # account a1 only
sw run job.yaml --set account.account_id=a1,a3 --allow-lookup-exec # a1 and a3 (or a list in --config)
sw run job.yaml --set feed.id=f7 --allow-lookup-exec # one feed, at an inner level
- The value is checked as the input's type and constraints; the run logs how many items it picked.
- No item picked: the level's
on_emptyapplies. - One value cannot be given for an input that differs per item in another way: one bound to a lookup that runs per item, a secret bound to an item, or a list. The run stops and says so, before any lookup.
Lookup types
type | Keys | Notes |
|---|---|---|
database | connection (required), query (required), params, rows, secret_fields, transforms | connection is a postgres, mysql, duckdb or sqlite connection of the job. rows: one (default) expects exactly one row; rows: many returns a list, for fan_out. |
command | command (required), stdin, timeout (default 30s) | command is an argument list, never a shell. Pass sensitive values on stdin, not in the arguments. Needs --allow-lookup-exec. |
function | function (required, module:function), arguments | Needs --allow-lookup-exec. |
aws_secretsmanager | secret_id (required), region | |
files | connection, path (required), days, hours, folders, timezone, path_pattern, for_each, modified_after, max_files, sql, params | A file connection's listing, one row per file (below). |
sql | tables, query (required), params, rows, log | One query over other lookups' rows (below). |
Every lookup also takes format, which says how its value is read:
format | Reads the value as |
|---|---|
auto (default) | JSON when it is JSON (a JSON string holding JSON is unwrapped), else text |
text | Text, never parsed |
json | JSON |
json_string | JSON serialized inside a JSON string |
Query parameters
:name parameters are bound from params. After IN, a list expands to (?, ?, ...) and a missing one becomes
(NULL); elsewhere a missing one is NULL. Cast it where the database must know its type, for example
CAST(:ids AS text) IS NULL on PostgreSQL.
Transforms
Transforms compute a value from each row of a database lookup, for example to decrypt or decode it. They run when the row is used (when its pass starts), and their input and output are masked.
Transform type | Keys |
|---|---|
function | function (module:function), arguments ({{ row.COLUMN }} is the row's column); needs --allow-lookup-exec |
command | command, stdin (for example {{ row.encrypted_token }}), timeout; needs --allow-lookup-exec |
builtin | apply (base64, base64url, hex or json) and value (for example {{ row.b64_secret }}) |
Templates
A lookup's templates read {{ config.* }}, {{ secrets.* }} and the fan-out items' {{ <as>.COLUMN }} (each level's).
Transforms, and a files lookup's path with for_each, also read {{ row.COLUMN }}.
Files lookup
A files lookup lists the files under path of a files, s3, gcs or azure_blob connection: one row per
file, before any pass starts. It lists through the connector's own reader, with the connection's roots and
credentials.
feeds:
type: files
connection: nas
for_each: accounts # one listing per account
path: "{{ row.account_id }}/conversions/*.csv"
path_pattern: "/(?P<feed>[^/]+)\\.csv$" # named groups become columns
modified_after: 30d # or an ISO time
| Column | Holds |
|---|---|
path | The file's location, as a read step's path takes it (an absolute path or a URL) |
name, folder | The file name and its folder |
path_id | A short hash of path, for a state scope (scopes are at most 185 characters) |
size, modified | Bytes, and the last change (UTC). Together they name a version of the file. |
changed, created | Local files only: the inode's last change, and the birth time where the system keeps one |
day, hour | With a {day} or {hour} window, the window's value that matched |
path_pattern's groups | Text, or null when the pattern does not match |
The for_each row's columns | The file's own columns win a clash |
- Date windows.
pathtakes a read's date windows ({day}withdays,{hour}withhours,{folder}withfolders), dated at the run's start inruntime.timezone. Only the window's folders are listed. for_eachlists once per row of another lookup, up tofan_out.concurrencyat once. Use it when the account is part of the path. When it isn't, list once and join the accounts in asqllookup.modified_afterfilters after listing: a store still lists every key under the path's fixed prefix.max_files(default 10000) caps each listing. More files fail the lookup rather than cut the list.validatewarns about a listing with neither a date window normodified_after.- Names a read cannot take (a glob character,
?,%,#, a backslash or') are left out, with a warning that counts them. sqlshapes the listing with one SELECT over the tablefiles.paramsbind its:nameparameters, as a SQL lookup's do:WHERE :ids IS NULL OR account_id IN :idskeeps every file whenidsis not given.- One INFO line tells what was listed, path by path, and what
sqlkept:lookup feeds: 21 file(s): 20261130/conv_* 21, 20261201/conv_* 0; 7 row(s) after its sql. A lookup that runs once per run logs as the run, not as the account whose pass needed it first.
SQL lookup
A sql lookup runs one query over other lookups' rows, each a table named after its lookup. It runs in an in-memory
DuckDB that holds only those rows: no files and no network.
processed:
type: database
connection: app_db
rows: many
query: SELECT path, size FROM processed_feeds
work:
type: sql
rows: many
tables: [feeds, processed]
query: |
SELECT f.* FROM feeds f
ANTI JOIN processed p ON p.path = f.path AND p.size = f.size
ORDER BY f.modified
log:
sql: SELECT f.path FROM feeds f SEMI JOIN processed p USING (path, size)
message: "feed {path} skipped: already processed"
- Empty tables keep their columns. A
databaselookup with no rows is still a table, so the join works on the first day. Its column types come from the values, else VARCHAR: cast in joins where it matters. paramsbinds:nameparameters, as in a database lookup.rows: one(default) expects one row;rows: manyreturns them all, forfan_out.loglogs a SELECT over the same tables, like a step'slog:(message,level,max_rows,sql).- A
fan_out.keymay not be asecret_fieldscolumn of any table the query reads.
Fan-out: the work
fan_out holds the work: the lookups it runs once per run, then a level of items (each), each with the lookups it
runs per item and, optionally, the level below.
| Key | What it does | Default |
|---|---|---|
lookups | Lookups run once per run, before any item | |
each.as | Required. The item's name: steps, connections, outputs and runtime settings read its columns as {{ <as>.COLUMN }} | |
each.over | Required. Its items: a rows: many, files or sql lookup, inline or by name, or a list input of spec.config. Log lines name an inline one <as>_items (account_items) | |
each.key | The row's column that names an item | The first column |
each.concurrency | Items at once (--fan-out-concurrency N sets the outermost level's) | 1 |
each.concurrency_per | At most N items at once per value of an item's column, e.g. {manager_id: 1}. An item whose value is NULL is not limited by it | None |
each.on_failure | continue: the other items still run; stop: no new item starts after one failed (--fan-out-on-failure, every level) | continue |
each.on_empty | No item: fail or skip (a warning) | fail |
each.lookups | Lookups run once per item of this level, before the level below | |
each.each | The level below: per item, the items of its own over (below) | None |
- Items in templates.
{{ account.manager_id }}reads the pass's account row. Asecret_fieldsortransformscolumn of the level'soveris a secret: masked, and never pinned in a batch (a retry looks it up again). Other columns are pinned with the batch, so a retry runs with them. They read as text; for a typed value (a number in a setting), bind an input:{type: integer, lookup: {from: account, field: id}}. - Lookups read items too (
{{ account.* }},tables: [account],for_each), and run once per item of the deepest level they read. - The scope names the innermost item, so each pass keeps its own history;
runtime.state.leasemay lock an outer level (scopes and locks). - The earlier shape still works:
runtime.fan_outwith inputs bound to the items. A run reads both alike; a job uses one or the other.
Accounts under one manager account often share its API quota. Run many accounts at once, but one per manager, and let their calls share one rate limit:
fan_out:
each: {as: account, over: accounts, concurrency: 8, concurrency_per: {manager_id: 1}}
connections:
ads:
provider: google_ads
policy:
rate_limit: {requests: 10, per: 1s, shared_by: "{{ account.manager_id }}"}
With shared_by, every pass, step and output that calls through ads with the same value shares one limit, in this
run. Without it, each step and output has its own.
Each account can have its own time zone: runtime.timezone: "{{ account.timezone }}" sets the pass's today, date
windows and file names.
Nested fan-out
Feeds per account, two accounts at a time, five feeds of each at once:
fan_out:
lookups:
work: {type: files, connection: drop, path: "feeds/{day:%Y%m%d}/*.tsv", days: {last: 2}, rows: many}
each:
as: account
over: accounts
key: account_id
concurrency: 2 # accounts at once
lookups:
customer: {type: database, connection: ads_db, query: "SELECT currency FROM customers WHERE id = :id",
params: {id: "{{ account.account_id }}"}}
each:
as: feed
over: # once per account: its new files
type: sql
rows: many
tables: [work, account, customer]
query: |
SELECT w.path, w.modified, c.currency FROM work w, account a, customer c
WHERE w.account_id = a.account_id ORDER BY w.modified
key: path
concurrency: 5 # feeds of an account at once
on_empty: skip # an account without a new feed is skipped
steps:
- name: rows
read: tsv
path: "{{ feed.path }}"
runtime:
state:
scope: "account:{{ account.account_id }}:feed:{{ feed.path }}"
lease: "account:{{ account.account_id }}" # one run per account at a time
job_key: "{{ feed.modified }}" # a feed version runs once
failed_job_policy: retry
- A pass is one innermost item (a feed), a complete run in its own scope. The next account starts when an account has finished all its feeds.
- An inner
overreads the outer item:{{ account.* }}in its templates,tables: [account], orfor_each. It runs once per account.validatewarns when it reads none (every account would get the same feeds). - Data flows down through the items. A level's lookups feed the next level's
over; the innermost row carries what the pass needs (here the feed's currency). Steps read items, not lookups. - Failures stay in their item. A feed that fails fails its account, not the others. An account whose feeds lookup
fails fails alone, with that error. Each level has its own
on_failureandon_empty. - Up to three levels (manager, account, feed).
The run exits 0 when every item succeeds, 1 when one failed, and 75 when another run held a lease it needed
(busy: run it again later; the items it did not start are busy too). Each failed pass or account logs an ERROR line,
a busy one or one that did not run a WARNING. --summary lists passes (item, status, job ids, outputs, error); an account's entry holds its feeds' in its
own passes. The run history keeps what failed in each run.
Good to know
- Allow code to run. Command and function lookups and transforms need
--allow-lookup-exec; without it the run exits 2. - Secrets stay masked. Every value bound to a secret, every
secret_fieldscolumn, and every transform's input and output is masked in logs, errors, summaries and state. A retry looks the credentials up again. - Database drivers. A database lookup opens its connection with a Python DB-API driver (PostgreSQL:
psycopg, MySQL:pymysql), separate from the connector's engine adapter. When the driver is missing,validatewarns (driver-not-installed, an error with--strict), andrunstops before any lookup, naming what to install. A connection that only lookups use needs no engine adapter. A PostgreSQL connection'ssslmodeandoptionsapply to lookups too: setoptions: {connect_timeout: "15"}so an unreachable database fails the lookup quickly. - Validation checks what a binding names, that
overis arows: manylookup or a list input, that the scope names the item, and that the state store reads no item (one store serves the run). - State actions (
sw state ... --url URL) read the state database alone: they run no lookups. - Serving.
streamwright servenever lets a caller set an input that has alookup:: a caller's value would skip the lookup and could name any account.
See also
- DuckDB jobs: scopes, locks and failed batches.
- Accounts & secrets.