Skip to main content

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.

In short

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 over lookup selects the active accounts, filtered by tenant_id or account_ids when you give them.
  • fan_out runs the job once per row (a pass), four at a time. Each pass reads its own row's columns; its refresh_token is decrypted by a Python function first.
  • client_secret comes 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​

  1. An input binds a lookup with lookup: {from: NAME, field: PATH}, in spec.config or spec.secrets.
  2. An explicit value wins: --set, --config, --secrets or STREAMWRIGHT_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.
  3. 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.
  4. With fan_out, each pass is a complete run in its own scope, with its own failed_job_policy and attempts. The run holds its leases for all its passes. One account's failure does not stop the others.

Binding an input​

KeyWhat it doesDefault
fromA lookup (of spec.lookups or fan_out), or a fan-out item (its as name)
fieldA 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_empty applies.
  • 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​

typeKeysNotes
databaseconnection (required), query (required), params, rows, secret_fields, transformsconnection 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.
commandcommand (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.
functionfunction (required, module:function), argumentsNeeds --allow-lookup-exec.
aws_secretsmanagersecret_id (required), region
filesconnection, path (required), days, hours, folders, timezone, path_pattern, for_each, modified_after, max_files, sql, paramsA file connection's listing, one row per file (below).
sqltables, query (required), params, rows, logOne query over other lookups' rows (below).

Every lookup also takes format, which says how its value is read:

formatReads the value as
auto (default)JSON when it is JSON (a JSON string holding JSON is unwrapped), else text
textText, never parsed
jsonJSON
json_stringJSON 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 typeKeys
functionfunction (module:function), arguments ({{ row.COLUMN }} is the row's column); needs --allow-lookup-exec
commandcommand, stdin (for example {{ row.encrypted_token }}), timeout; needs --allow-lookup-exec
builtinapply (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
ColumnHolds
pathThe file's location, as a read step's path takes it (an absolute path or a URL)
name, folderThe file name and its folder
path_idA short hash of path, for a state scope (scopes are at most 185 characters)
size, modifiedBytes, and the last change (UTC). Together they name a version of the file.
changed, createdLocal files only: the inode's last change, and the birth time where the system keeps one
day, hourWith a {day} or {hour} window, the window's value that matched
path_pattern's groupsText, or null when the pattern does not match
The for_each row's columnsThe file's own columns win a clash
  • Date windows. path takes a read's date windows ({day} with days, {hour} with hours, {folder} with folders), dated at the run's start in runtime.timezone. Only the window's folders are listed.
  • for_each lists once per row of another lookup, up to fan_out.concurrency at once. Use it when the account is part of the path. When it isn't, list once and join the accounts in a sql lookup.
  • modified_after filters 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. validate warns about a listing with neither a date window nor modified_after.
  • Names a read cannot take (a glob character, ?, %, #, a backslash or ') are left out, with a warning that counts them.
  • sql shapes the listing with one SELECT over the table files. params bind its :name parameters, as a SQL lookup's do: WHERE :ids IS NULL OR account_id IN :ids keeps every file when ids is not given.
  • One INFO line tells what was listed, path by path, and what sql kept: 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 database lookup 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.
  • params binds :name parameters, as in a database lookup. rows: one (default) expects one row; rows: many returns them all, for fan_out.
  • log logs a SELECT over the same tables, like a step's log: (message, level, max_rows, sql).
  • A fan_out.key may not be a secret_fields column 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.

KeyWhat it doesDefault
lookupsLookups run once per run, before any item
each.asRequired. The item's name: steps, connections, outputs and runtime settings read its columns as {{ <as>.COLUMN }}
each.overRequired. 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.keyThe row's column that names an itemThe first column
each.concurrencyItems at once (--fan-out-concurrency N sets the outermost level's)1
each.concurrency_perAt 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 itNone
each.on_failurecontinue: the other items still run; stop: no new item starts after one failed (--fan-out-on-failure, every level)continue
each.on_emptyNo item: fail or skip (a warning)fail
each.lookupsLookups run once per item of this level, before the level below
each.eachThe level below: per item, the items of its own over (below)None
  • Items in templates. {{ account.manager_id }} reads the pass's account row. A secret_fields or transforms column of the level's over is 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.lease may lock an outer level (scopes and locks).
  • The earlier shape still works: runtime.fan_out with 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 over reads the outer item: {{ account.* }} in its templates, tables: [account], or for_each. It runs once per account. validate warns 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_failure and on_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_fields column, 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, validate warns (driver-not-installed, an error with --strict), and run stops before any lookup, naming what to install. A connection that only lookups use needs no engine adapter. A PostgreSQL connection's sslmode and options apply to lookups too: set options: {connect_timeout: "15"} so an unreachable database fails the lookup quickly.
  • Validation checks what a binding names, that over is a rows: many lookup 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 serve never lets a caller set an input that has a lookup:: a caller's value would skip the lookup and could name any account.

See also​