Quickstart: CDC and batch pipelines in Airflow with Docker Compose
One docker compose up starts Airflow with rivet and this provider, two demo source databases, a bucket and a
warehouse. Four pipelines are ready to run:
| Pipeline | Source | Mode | Lands in ClickHouse |
|---|---|---|---|
rivet_mysql_cdc | MySQL shop | CDC (binlog): inserts, updates, deletes | mysql_cdc.customers, mysql_cdc.orders |
rivet_mysql_batch | MySQL shop | batch, incremental on updated_at | mysql_batch.* |
rivet_postgres_cdc | PostgreSQL shop | CDC (logical slot) | postgres_cdc.* |
rivet_postgres_batch | PostgreSQL shop | batch, incremental on updated_at | postgres_batch.* |
Everything runs on your machine: no cloud account is needed. The same files then take your own database: the command builder writes the commands for it.
The files are in quickstart/:
| File | What it is |
|---|---|
airflow-2.10/docker-compose.yaml | Airflow 2.10.5 (webserver, scheduler; LocalExecutor) and the demo services |
airflow-3.3/docker-compose.yaml | Airflow 3.3.2 (api-server, scheduler, dag-processor; LocalExecutor) and the same demo services |
Dockerfile | the official Airflow image plus rivet-cli and airflow-provider-rivet, pinned under Airflow’s constraints |
.env.example | AIRFLOW_UID and the host ports |
dags/rivet_quickstart.py | one DAG per pipeline, built from the pipeline’s config |
dags/rivet/<pipeline>.yaml | the four rivet configs, as rivet init writes them |
demo/*.sql | the demo tables (1,000 customers, 5,000 orders), grants, and the changes for a second run |
Both compose files are proven the same way: from an empty stack, the first run of every DAG lands every table, and
after the demo changes the second run lands them too. Each table in ClickHouse was compared with its source, row
count and sums of key, amount and text columns, on Airflow 2.10.5 and 3.3.2 with rivet-cli 0.32.2 and this
provider 0.2.0.
What runs where
MySQL / PostgreSQL ──► rivet (an Airflow task) ──► MinIO bucket (Parquet) ──► rivet load ──► ClickHouse
│
└── state: cursors, run journal, load ledger ──► rivet-state (PostgreSQL)
| Service | Image | Reach it at |
|---|---|---|
| Airflow UI | rivet-quickstart:<version> (built from Dockerfile) | http://localhost:8080, airflow / airflow |
mysql | mysql:8.4, binlog in ROW format with full metadata | docker compose exec mysql mysql -uroot -proot_demo shop |
source-postgres | postgres:16, wal_level=logical | docker compose exec source-postgres psql -U postgres -d shop |
minio | MinIO (S3 API) | console http://localhost:9001, rivet / rivet_minio_demo |
clickhouse | clickhouse/clickhouse-server:24.8 | http://localhost:8123/play, user loader, password rivet_clickhouse_demo |
rivet-state | postgres:16, one database per pipeline | inside the compose network only |
Every port is bound to 127.0.0.1. Every password is a demo value: change them before the stack holds anything real.
1. Start
Needs Docker with Compose v2 and about 6 GB of memory for Docker. The commands are for bash.
git clone --depth 1 https://github.com/rivet-lab/airflow-provider-rivet.git
cd airflow-provider-rivet/quickstart/airflow-3.3 # or airflow-2.10
cp ../.env.example .env # on Linux: set AIRFLOW_UID to the output of `id -u`
docker compose up -d --build --wait
The first start builds the image (the Airflow base image and a pip install), then every service reports healthy.
A port already in use: change it in .env (AIRFLOW_PORT, MINIO_CONSOLE_PORT, CLICKHOUSE_PORT).
2. Run the pipelines
Open http://localhost:8080 and switch on the four rivet_* DAGs, or:
for d in mysql_cdc mysql_batch postgres_cdc postgres_batch; do
docker compose exec -T airflow-scheduler airflow dags unpause rivet_$d
done
docker compose exec -T airflow-scheduler airflow dags list # is_paused: False for all four
A DAG unpaused before the scheduler has read its file is not unpaused: Airflow 2.10 prints
No paused DAGs were found, and Airflow 3.3 prints the DAG as it was. The dags list line is the evidence; repeat
the unpause until it shows False.
Unpausing starts the latest interval at once; the schedule is every 10 minutes. The first run of each DAG reads the whole tables (a CDC stream anchors its position first and then reads the tables, so no change falls between the two). In ClickHouse:
docker compose exec -T clickhouse clickhouse-client --user loader --password rivet_clickhouse_demo \
-q "SELECT count() FROM mysql_cdc.orders WHERE NOT __is_deleted" # 5000
<table> in ClickHouse is a view: one row per key, the latest version. A CDC table keeps a deleted key with
__is_deleted = 1, so live rows are WHERE NOT __is_deleted. The change log itself is <table>__changes.
3. Change the sources and run again
docker compose exec -T mysql mysql -uroot -proot_demo shop < ../demo/changes-mysql.sql
docker compose exec -T source-postgres psql -U postgres -d shop < ../demo/changes-postgres.sql
for d in mysql_cdc mysql_batch postgres_cdc postgres_batch; do
docker compose exec -T airflow-scheduler airflow dags trigger rivet_$d
done
The changes: 20 new customers, 30 orders moved to shipped, 5 orders deleted. After the runs:
| CDC pipelines | batch pipelines | |
|---|---|---|
| new customers | 1020 rows | 1020 rows |
| shipped orders | updated | updated |
| deleted orders | gone (4995 live rows) | still there (5000 rows) |
A batch pipeline reads the rows whose updated_at moved; a deleted row has none. To see deletes, use CDC.
4. Your own database
The command builder takes your database’s name, host, tables and mode, and writes every command below with those values. Without it, the steps are:
- Grants on your database:
SELECTon the tables; for MySQL CDC alsoREPLICATION SLAVEandREPLICATION CLIENTand the binlog settings above; for PostgreSQL CDC theREPLICATIONattribute andwal_level = logical(rivet’s CDC guide). - A Connection for the source, e.g.
airflow connections add rivet_billing --conn-type postgres .... The host must resolve from the containers: a database on your machine ishost.docker.internal. - The pipeline’s own state database, bucket, ClickHouse database and
state_dir:createdbinrivet-state, the Connectionrivet_state_<pipeline>,mc mbinminio,CREATE DATABASEinclickhouse,mkdir /opt/airflow/rivet-state/<pipeline>. - The config, generated inside the Airflow container from the live database by
rivet init, with the state in the pipeline’s own database, and--mode cdcor--mode incremental. - One line in
PIPELINESindags/rivet_quickstart.py(a config withmode: cdcexports becomes a CDC DAG with a group per stream, asinitwrites one stream per table outside PostgreSQLpublicand on SQL Server, Oracle and MongoDB; see DAG builders):"billing_batch": {"source": "rivet_billing"},. Optional keysstorageandwarehousename the Connections of your own S3 bucket and ClickHouse instead of the stack’s. - Unpause its DAG as in step 2.
Why each pipeline has its own of everything: rivet init gives every batch export the prefix exports/<table>/, so
two pipelines in one bucket would write into each other’s folders; two sources with the same table names would be one
table in one ClickHouse database; and a pipeline’s cursors and checkpoint belong to that pipeline only.
A batch config: rivet init writes a query: for each table and pk: auto in load:. For a query: export
rivet run records no key, so pk: auto works only while the key init recorded is in the state the DAG uses
(rivet#679). The demo configs and the builder’s commands declare
pk: [id]; for your tables, name their key. Without it a load stops with RIVET_LOAD_PRIMARY_KEY_MISSING.
Airflow 2.10 and 3.3
The two compose files differ only where Airflow does:
| 2.10 | 3.3 | |
|---|---|---|
| UI and API | airflow-webserver | airflow-apiserver, plus airflow-dag-processor |
| Auth | Airflow’s own | FAB auth manager, the same airflow user |
| Tasks talk to | the metadata database | the api-server (AIRFLOW__CORE__EXECUTION_API_SERVER_URL, a JWT secret) |
The demo services, the Connections, the DAG file and the configs are the same files.
From quickstart to production
- Passwords and keys: every demo password is in the compose file. Put real ones in a secrets backend or in
Connections (
airflow connections add), and setFERNET_KEYin.envso Airflow encrypts them. - TLS: the demo connects without TLS inside one compose network (
--tls disable,sslmode=disable). A database across a network takes--tls verify-fullinrivet init. - CeleryExecutor: run the commands in
airflow-workerinstead ofairflow-scheduler;./rivet-statemust be the same directory on every worker (State). - Back up the
rivet-statevolume and./rivet-state: a CDC checkpoint is a file there, and a lost one means a new baseline. - ClickHouse loading is a preview in rivet (known limits).
Stop and clean up
docker compose down -v # removes the containers and every volume: databases, bucket, warehouse, state
rm -rf logs rivet-state # the task logs and rivet's files on the host
Add your own database
The quickstart runs four pipelines on demo databases. This page writes the commands that add your own MySQL or PostgreSQL database as one more pipeline in the same stack: CDC or batch, into the stack’s MinIO and ClickHouse or into your own S3 bucket and ClickHouse.
Command builder. Fill in the form below and every command on this page is rewritten with your values, ready to
copy. On GitHub the form is not rendered: replace the {{…}} placeholders by hand.
1. The stack
git clone --depth 1 https://github.com/rivet-lab/airflow-provider-rivet.git
cd airflow-provider-rivet/quickstart/{{FOLDER}}
cp ../.env.example .env # on Linux: set AIRFLOW_UID to the output of `id -u`
docker compose up -d --build --wait # then http://localhost:8080, airflow / airflow
DC="docker compose" # the commands below run `$DC exec …` in this folder, in bash
Skip this if the stack from the quickstart is up: run the commands below in its folder.
2. Your database: grants
Run on your database, as an administrator. The containers must reach its host: a database on your own machine is
host.docker.internal.
{{GRANTS}}
3. The source Connection
The password is read from the terminal, never typed into a command line:
{{CONN}}
4. The pipeline’s state, bucket and warehouse
Each pipeline has its own state database, bucket, ClickHouse database and state directory: its cursors and CDC checkpoint belong to it alone, and two sources with the same table names never share a folder or a table.
{{STATE}}
{{BUCKET}}
{{WAREHOUSE}}
5. The config, generated from the live database
rivet init runs inside the Airflow container, reads your tables and writes dags/rivet/{{P}}.yaml, with its key
recorded in the pipeline’s own state:
{{INIT}}
Review the file before the first run: rivet init guesses partitions and modes from the tables (see
rivet’s config reference).
6. The DAG
Add this line to PIPELINES in dags/rivet_quickstart.py:
{{DAG_LINE}}
A config with a mode: cdc export becomes a CDC DAG (one stream, then a load per table); any other becomes a batch
DAG (an extract and a load per table). Then:
{{UNPAUSE}}
A DAG unpaused before the scheduler has read its file stays paused: Airflow 2.10 prints No paused DAGs were found,
Airflow 3.3 prints the DAG as it was. Repeat until dags list shows it False.
7. Check the warehouse
After the first run of {{DAG}}:
{{CHECK}}
Each count should be the source table’s row count. <table> in ClickHouse is a view with one row per key, the
latest version; a CDC table keeps a deleted key with __is_deleted = 1.
Notes
- Batch and the key. A batch config reads each table through a
query:, and for aquery:exportrivet runrecords no key, so the builder writespk: [<key>]into the config instead of leavingpk: auto(rivet#679). - Your own bucket or ClickHouse gets its own Connection, named in the pipeline’s
PIPELINESline (storage,warehouse). The demo pipelines keep the stack’s MinIO and ClickHouse. - CeleryExecutor: pick
airflow-workeras the service that runs tasks. - ClickHouse loading is a preview: known limits.
- What the builder’s commands were proven with: every command for a PostgreSQL CDC pipeline on Airflow 3.3.2 and for
a MySQL batch pipeline with its own ClickHouse Connection on Airflow 2.10.5 was run as generated against the
quickstart stack, and the ClickHouse tables were compared with the source. The
s3(AWS) bucket branch was not run.
Operators
The operators, the XCom value every task returns, and the block each task writes to its log.
Operators
Every operator takes the same parameters (plus Airflow’s own: task_id, retries, …).
Templated ones accept Jinja; env and env_from_connections are not templated, so their
values are never stored as rendered fields. No operator builds argv: one module,
invocation.py, builds it and runs the process; reading.py reads rivet’s outputs into units and classifies.
| Parameter | Default | Templated | What it is |
|---|---|---|---|
config | required | yes | path of the rivet YAML config on the worker |
export | None | yes | the export to run; required by RivetApplyOperator and RivetCdcRunOperator; RivetRunOperator without it runs the whole config |
table | None | yes | one table of the export, for load and compact |
state_dir | None | yes | an existing absolute directory on the worker for SQLite state, the config copy, sealed plans, locks and stderr files; never created by a task; required for SQLite state and CDC checkpoints (see State) |
plan_file | None | yes | the layout file RivetPlanOperator rewrites and build_batch_dag reads waves from |
rivet_bin | "rivet" | no | the binary: a name looked up on the worker’s PATH, else the one rivet-cli installed; or an absolute path. A binary that is missing or does not answer its probes is refused before any run (RIVET_AIRFLOW_BINARY_MISSING) |
env | None | no | extra variables for the rivet process; computed by your DAG file, so no secret literals |
env_from_connections | None | no | {ENV_NAME: conn_id}: a database URL built from an Airflow Connection inside the task (see Connections and secrets); the value may also be {"conn_id": …, "database": …, "odbc_ini": …, "dsn": …}: another database on the same server, and the odbc.ini data source dsn (default the id; MySQL, PostgreSQL, SQL Server and Oracle drivers) when no Connection has the id |
env_from_variables | None | no | {ENV_NAME: variable key}: each environment variable takes the value of an Airflow Variable, read when the task runs (a Variable no backend defines is refused: RIVET_AIRFLOW_VARIABLE_MISSING). It is merged like env and is what ${ENV_NAME} in the config resolves to; a name may not be in env too. See Connections and secrets |
env_passthrough | () | no | worker variables (names or MY_* patterns) passed on; nothing outside the allow-list is inherited otherwise |
cloud_credentials | () | no | "gcp", "aws", "azure": pass the worker’s credential variables of that kind |
connections | () | no | storage and warehouse Connection ids (see “Storage and warehouse connections”) |
deployment | "auto" | no | local (a host that keeps its disk) or pod (ephemeral); auto reads KUBERNETES_SERVICE_HOST |
extra_args | None | yes | arguments appended to rivet’s argv, e.g. ["--reconcile"] on a run task; -p / --param (["-p", "day=2026-10-20"]) only on the run, CDC run and plan tasks, because only rivet run, plan and check take it: the load, compact and apply tasks refuse it before rivet starts (RIVET_AIRFLOW_PARAM_NOT_ACCEPTED), and a ${name} in their config is read from env |
lock_wait | 600 | no | seconds a task waits for another task holding a lock it needs before it ends retryable (RIVET_AIRFLOW_EXPORT_BUSY); the wait is per lock, so a run of the whole config, which takes one lock per export, can wait up to its number of exports times this value; the same wait applies to the lock on the query-file records of a state directory (see State) |
rivet_notifications | False | no | True keeps rivet’s own notifications: on: --no-notify is not passed and nothing is warned (see Slack) |
crashed_retries | 1 | no | retries of a crash (a signal, exit 129-255) on their own budget, beside Airflow’s retries (see Retries) |
stderr_dir | None | yes | where rivet’s stdout/stderr files go; default <state_dir>/logs, else the temp directory |
stream_stderr | False | no | also copy rivet’s stderr lines into the task log as they come |
log_keep | 10 | no | stderr/stdout files kept per task; None keeps all |
cwd | None | yes | the rivet process’s working directory (default: the original config’s directory); it does not move a relative local destination.path, which lands under state_dir |
single_host | False | no | declares that every task of this deployment runs on one host; needed for SQLite state under an executor that may use several (Celery, Kubernetes), which is refused otherwise (RIVET_AIRFLOW_STATE_SQLITE_MULTI_HOST, see State) |
| Operator | Runs | Notes |
|---|---|---|
RivetApplyOperator | rivet plan -e X --format json -o <artifact> then rivet apply <artifact> | a retry replays the same sealed artifact while it is unexpired, and rivet answers a replay of a plan it already applied (“Retries”); a clear plans again |
RivetRunOperator | rivet run [-e X] --summary-output <file> | the fallback when sealed apply is not wanted; also runs a whole config |
RivetCdcRunOperator | rivet run -e X --summary-output <file> for a mode: cdc export | one bounded drain; succeeds on max_events, reports it, never loops |
RivetLoadOperator | rivet load -e X [--table T] | per export, per table when table is given |
RivetCompactOperator | rivet compact -e X [--table T] | rivet’s result says per table whether it merged or skipped (skip_reason); a task whose every unit rivet skipped is an Airflow skip |
RivetInitOperator | rivet init then rivet check of what it wrote | writes config once and never replaces it; the task build_source_dags adds while a source has no config (see DAG builders). It takes config, state_dir, rivet_bin and the environment parameters (env, env_from_connections, env_passthrough, cloud_credentials, connections), plus mode, source_env and init_args; the parameters of a rivet run (lock_wait, extra_args, crashed_retries, …) are not its own, and build_source_dags gives them to the run tasks only |
RivetPlanOperator | rivet plan --format json | rewrites the plan layout file atomically, only when the output is a layout build_batch_dag can read (waves with exports; one planned export, which rivet prints as a bare object with no campaign, is one wave from its export_recommendation); the file keeps its mode |
from airflow_provider_rivet.operators import RivetApplyOperator
orders = RivetApplyOperator(
task_id="orders",
config="/opt/pipelines/postgres.yaml",
export="orders",
state_dir="/var/lib/rivet/postgres",
env_from_connections={"RIVET_PG_URL": "rivet_postgres"},
)
Every task returns (and, on failure, pushes before raising) one XCom value under return_value:
{ "command": "apply", "decision": "success",
"units": [ { "export": "orders", "table": null, "target": null, "buffer": null,
"status": "success", "run_id": "orders_...",
"rows": 2500, "files": 1, "stop_reason": null, "error": null } ],
"error": null, "degraded": [],
"exit_status": 0, "signal": null, "stderr_path": "/var/lib/rivet/postgres/logs/...",
"skip_reason": null, "state_marker": "1d86...", "rivet_version": "0.32.2 (5ee08c0a)" }
A unit has exactly the shape of tests/fixtures/scheduler/xcom_unit*.json; a package test
compares the two, so the package and the Rust contract cannot drift. target and buffer are the
warehouse objects a load or compact unit wrote and read, as rivet’s result names them (null for a
run or apply unit, and null when the binary’s result has no names: the config’s guess is never
put in XCom). What the warehouse did (rows inserted, updated and deleted, parts, jobs, bytes) is
not part of the XCom unit: it is in the task log and in the rivet.unit record’s digest.
Reading the task log
Each task writes one block when it ends: a headline with the outcome first, one line per rivet
step, and indented note lines. A successful apply with SQLite state:
rivet apply users → OK: 30 rows, 1 file in 4.1 s (run users_20261016T092509.120_4242)
plan sealed, strategy incremental in 0.8 s
apply done in 2.9 s
note SQLite state is single-host — see https://github.com/rivet-lab/airflow-provider-rivet/blob/main/docs/state.md#local-worker-setup-guide
A failed one (a retry whose sealed plan another run has overtaken):
rivet apply users → REFUSED [RIVET_PLAN_ARTIFACT_STALE], final
plan replayed the sealed plan of an earlier try
apply exit 5 in 0.6 s
export users: failed [RIVET_PLAN_ARTIFACT_STALE] refusal
stderr <state_dir>/logs/<dag_id>/<task_id>-<hash>/<run_id>__try2.apply.stderr.log
note SQLite state is single-host — see https://github.com/rivet-lab/airflow-provider-rivet/blob/main/docs/state.md#local-worker-setup-guide
A task of one step that took the task’s time (a load, a compact, a run) has no step line: the
headline says it. The step line stays when the step failed or the task spent a second or more
outside it (a lock wait). rivet_version is the
whole rivet --version line after rivet, so a branch build is told apart from the release.
A load or compact task names the warehouse object it wrote after the arrow, as rivet’s result names
it: a load the table of a full export, else its __changes log
(rivet load cdc table orders → my-project.demo_cdc.orders__changes: OK: 50 rows in 12.0 s); a
compact the buffer it merged and the base (….orders__changes into ….orders). A command whose
result names no table (it failed before one) gets the name from the config’s load: block, marked (from config).
With rivet >= 0.32.2 a load or compact also says what the warehouse did, from rivet’s per-table digest (ADR-0039 D3): the headline sums the rows, the warehouse jobs and the bytes billed, and one line per table gives a compact’s inserted / updated / deleted rows and the base’s rows after, a load’s Parquet parts and source runs, the job ids (the first three) and the bytes billed. A value rivet did not return (bytes on ClickHouse and Snowflake, job ids on Snowflake) is left out, never shown as 0:
rivet compact cdc table orders → p.orders__changes into p.orders: OK: 1200 rows, 1 job, 50.0 MiB billed in 3.4 s, after 30.0 s waiting for the lock of export `cdc` (run …)
table cdc.orders → p.orders__changes into p.orders: compacted, 1200 rows, 200 inserted, 950 updated, 50 deleted, base 10150 rows, job rivet_compact_orders_1, 50.0 MiB billed (run …)
A task that waited for the export’s lock says so when it takes it (took the lock of export `cdc` after 30.0 s), and its headline gives the time after the wait apart from the wait. A run of a whole
config takes one lock per export: its headline sums the waits (after 2.4 s waiting for 2 locks (a, b)), and a
BUSY one names the lock that timed out, not the first it waited for. A skipped unit says why in its line and
in the headline (SKIPPED: nothing to do (nothing_to_compact)), also for run, apply and cdc_run; two
skipped tables with different reasons give them joined with ; .
- The headline’s outcome is
OK,SKIPPED(nothing to do: rivet’sskip_reason, or an earlier try already applied the plan),REFUSED(classrefusal, or a preflight refusal before rivet started),FAILED(with its class),CRASHED(a signal or a 129-255 exit),STOPPED(Airflow stopped the task) orBUSY(the export’s lock stayed held, or rivet’s own lease of the export or table was held by another rivet:RIVET_STATE_LOCK_TIMEOUT,RIVET_STATE_RUN_IN_PROGRESS,RIVET_LOAD_TABLE_BUSY; retried). A final failure saysfinaland is an ERROR line; one Airflow retries saysretryable, Airflow retries it (try N of M)and is a WARNING line. The registryactionfollows when rivet printed one, then rivet’s own error text after a colon:FAILED [RIVET_LOAD_WAREHOUSE_REJECTED] generic, final (run 65ed): table 'orders': BigQuery job rivet_orders_0 failed: Not found: Table p:d.orders__changes was not found in location US. A failed table’s or export’s line carries its own text when it differs from the headline’s. The text is the one rivet printed, on one line: Airflow’s secrets masker reads it first, then its lines (cut at\nonly) are joined with|, control characters are shown as\u{1b}-style escapes, and it is cut at 300 characters (…). The same text ends the exception message ([code] class: action (export): text); XCom still carries none of it. notelines are INFO, except what you must act on: anotifications:block rivet will send from, a crash-retry ledger that cannot be used (WARNING).- No INFO or WARNING line of a successful task holds
errororexception, the words Airflow colours red by default ([logging] color_log_error_keywords), unless an export or table name holds one. - rivet’s stderr text is never in the block: a failed task prints the file’s path. argv and the
structured records are at DEBUG (
[logging] logging_level = DEBUG); XCom carries the outcome, units, error object, degradations and paths.
DAG builders
build_batch_dag, build_cdc_dag and build_config_dag build whole DAGs from the operators.
DAG builders
Batch: build_batch_dag
from airflow_provider_rivet.dags import build_batch_dag
dag = build_batch_dag(
"rivet_postgres",
config="/opt/pipelines/postgres.yaml",
state_dir="/var/lib/rivet/postgres",
plan_file="/opt/pipelines/postgres.plan.json", # or exports=["users", "orders"]
compact_exports=["orders"],
operator_kwargs={"env_from_connections": {"RIVET_PG_URL": "rivet_postgres"}},
)
plan ──> apply: [a] [b] ─> wave_2_done ─> [big] ─> after_big ─> [huge]
│ │ │ │ │
└─> (every │ │ │ │
apply) [a] [b] load: [big] [huge]
load: │
compact: [big] every task ─> watcher
- Three TaskGroups,
apply,load,compact. They are the picture; dependencies run per table:apply.X >> load.X >> compact.X, allall_success. A failedapply.aleavesapply.b,load.band every later wave runnable; it blocksload.aandcompact.a. - Waves come from the plan file, as in the recipe, and each wave is ordered the way
rivet apply’s cost gate orders it: every heavy export alone, one after another, then the cheap exports of the wave together; wave N+1 starts after wave N. Ordering goes through tasks that do nothing,apply.wave_<n>_doneandapply.after_<export>, withtrigger_rule="all_done": the next export waits for the earlier one to finish, not to succeed. - Every rivet task is
trigger_rule="all_success"whateverdefault_argssays; atrigger_ruleinoperator_kwargsis refused, and so ismax_active_tis_per_dag(it is 1 on every rivet task, see limits).default_argsyou pass are merged over the builders’ (retries=2,retry_delay5 minutes), so adding a callback keeps the retries. exports,compact_exportsandtablesare lists; a bare string is refused. A name that is not an ASCII task id (daily orders,orders:v2,заказы) gets a task id with each character outside[A-Za-z0-9_.-]replaced by_and an 8-character hash of the name (apply.daily_orders_<hash>); rivet still receives the real name.planis a direct upstream of everyapplytask: a failed plan refresh blocks the whole run (upstream_failed), because a run that could not plan has nothing it should extract.- A run with a failed task is a failed run. Airflow colours a run by its leaf tasks, and an
ordering task that succeeds after a failure would otherwise leave the run green. Every DAG the
builders make ends in one task,
watcher(trigger_rule="one_failed", no retries), downstream of every other task: it is skipped when nothing failed and fails when anything did (the watcher pattern of Airflow’s documentation).
| What fails | Its own table | Other tables | Run |
|---|---|---|---|
plan | every apply, load, compact: upstream_failed; nothing reaches rivet | the same | failed |
apply.X | load.X, compact.X: upstream_failed | run; the next of a heavy chain and the next wave still start | failed |
load.X | compact.X: upstream_failed | run | failed |
compact.X | run | failed | |
| nothing | success (watcher skipped) |
plan_fileis read at parse time (no database access); without one, passexports=[...].- With
plan_file, aplantask rewrites that file fromrivet planat the start of every run;refresh_plan=Falsedrops the task and keeps the file as it is. extract="run"usesrivet run -e Xinstead of plan + apply.- Compact tasks are created only for the exports named in
compact_exports. Whether a table compacts depends on the load mode,load.layoutand the warehouse, which only rivet resolves (fullnever compacts; see ADR-0039 D3 for the skip reasons). A named export that rivet skips shows as an Airflow skip with itsskip_reasonin XCom; an export left out ofcompact_exportshas no compact task to show it. load=Falsedrops the load group (a config with noload:block).
CDC: build_cdc_dag
from airflow_provider_rivet.dags import build_cdc_dag
dag = build_cdc_dag(
"rivet_orders_cdc",
config="/opt/pipelines/cdc.yaml",
export="app_cdc",
tables=["orders", "users"],
state_dir="/var/lib/rivet/cdc",
)
runis ONE task for the stream.load.Tandcompact.Tare separate tasks per table.tablesare written as the config names them:dbo.ordersis loaded and compacted as the warehouse tabledbo_orders(the schema’s dot folded to_, as rivet names it).run >> load.T >> compact.T, allall_success: nothing is loaded or compacted after a drain that did not succeed (a refusal such as a log gap means the files of this cycle are not the stream), and a failedload.Tblockscompact.Tbut not another table. The parts of an earlier cycle whose load failed are loaded by the next run whose drain succeeds: the load consumes what rivet’s ledger says is unloaded. A load that finds nothing to do is a success (never an Airflow skip: a skip would propagate tocompact.T).- The same
watchertask ends the DAG: a failedrun,load.Torcompact.Tfails the run. - On
stop_reason: max_eventsthe run task succeeds, puts it in XCom and logs anotelinestopped at max_events (...)(recordrivet.cdc.max_events). It does not loop. load=Falsedrops the load and compact tasks (the stream’s files are the product);compact=Falsekeepsload.Tand dropscompact.T. Usecompact=Falseon Snowflake and ClickHouse, where there is nothing to compact (see “Storage and warehouse connections”).operator_kwargsgo to every task, as in the batch builder.
From a config: build_config_dag
build_config_dag builds the DAG of one rivet config the way build_source_dags builds a source’s DAG from its
config, with no Connection or init step of its own; the quickstart builds each pipeline through it. A config that cannot be built into a DAG at all is refused with RIVET_AIRFLOW_CONFIG_UNBUILDABLE, naming the exception.
from airflow_provider_rivet.dags import build_config_dag
dag = build_config_dag(
"rivet_erp_cdc",
config="/opt/pipelines/erp.yaml",
state_dir="/var/lib/rivet/erp",
operator_kwargs={"env_from_connections": {"RIVET_SOURCE_URL": "erp", "RIVET_STATE_URL": "rivet_state_erp"}},
)
modeis"cdc"or"batch"; left out, it is"cdc"when the config has amode: cdcexport. A CDC DAG of a config with nomode: cdcexport, a batch DAG of one with any (or with amode: ${VAR}that may resolve tocdc), and a config with no export are refused, coded (RIVET_AIRFLOW_CONFIG_NO_CDC_EXPORT,RIVET_AIRFLOW_CONFIG_HAS_CDC_EXPORT,RIVET_AIRFLOW_CONFIG_NO_EXPORT), as is a${...}inload.targetorload.layoutthat may decide whether an export compacts (RIVET_AIRFLOW_CONFIG_UNRESOLVED), and a stream namedwatcherbeside other streams (RIVET_AIRFLOW_CONFIG_RESERVED_EXPORT_NAME). As inbuild_source_dags, a refused or unreadable config is a DAG of one task,config, that fails naming the refusal; it never ends the DAG file, so a loop over several configs (the quickstart’s) still builds the others. Amodeother than these is aValueError.- Load tasks are built when the config has a
load:section; a compact task follows a table’s load only where rivet resolves it to a base and a buffer (a compacting warehouse withlayout: base_buffer, or a stream withbackfill:). ClickHouse and Snowflake get none. Task ids name the warehouse table:dbo.ordersisload.dbo_orders. - One CDC stream is built as
build_cdc_dagbuilds it:run,load.T,compact.Tat the top. Several streams (rivet initwrites one per table on SQL Server, Oracle, MongoDB and PostgreSQL outsidepublic) are aTaskGroupeach, named after the export (dbo_orders.run,dbo_orders.load.dbo_orders); they have no edges between them and run side by side, each under its own export’s lock, and the onewatcherends the DAG. build_cdc_dagnames a table’s tasks asbuild_config_dagdoes:dbo.ordersisload.dbo_orders(until this release it wasload.dbo.orders); rivet is still given the captured name.- Adding a second stream renames the first stream’s task ids (
runbecomes<export>.run): Airflow keeps the old ids’ history under the old names, and the new ids start with none.
One DAG per database: build_source_dags
Name the databases; each gets a DAG, created paused, that writes its own config the first time it runs. The operator’s work is to unpause it.
from datetime import datetime
from airflow_provider_rivet.dags import build_source_dags
globals().update(
build_source_dags(
["shop", "billing"], # Airflow Connection ids, else data sources of odbc.ini
mode="cdc", # or "batch"
config_dir="/opt/airflow/dags/rivet",
state_root="/opt/airflow/rivet-state",
state_connection="rivet_state", # a PostgreSQL server; each source gets the database rivet_state_<name>
init_args=[
"--tls",
"verify-full",
"--gcs-bucket",
"my-bucket",
"--bigquery-project",
"my-project",
"--bigquery-dataset",
"{name}",
],
operator_kwargs={"cloud_credentials": ["gcp"]},
schedule="0 */2 * * *",
start_date=datetime(2026, 1, 1),
catchup=False,
)
)
For each name <name>:
| DAG | rivet_<name>_cdc / rivet_<name>_batch, paused at creation (is_paused_upon_creation) |
| source | the Airflow Connection source_connection (default {name}; rivet_{name} for the layout of the cron recipe); without one, the data source [<name>] of odbc_ini (default /etc/odbc.ini; None turns it off). The task log says when odbc.ini was used, and the password of the data source is masked in it. The file is read as unixODBC reads it (the name in any case, the first section and the first value win, ; and # comments); a file that is missing or unreadable on the worker is refused with that cause, not as a missing data source. odbc.ini: MySQL, PostgreSQL, SQL Server (Server = host,port, a SQL login) and Oracle (ServerName = host:port/service) drivers; MongoDB only through a Connection |
| config | <config_dir>/<name>.yaml |
| state | the database rivet_state_<name> on the server of state_connection, and the folder <state_root>/<name> |
Before the config exists, the DAG has one task, init. When it runs:
- it creates
rivet_state_<name>if missing (the state Connection’s user needsCREATEDB) and<state_root>/<name>(state_rootmust exist: a missing one is a volume that is not mounted, and is refused); - runs
rivet init --source-env RIVET_SOURCE_URL [--mode cdc] -o <state_root>/<name>/.init/<name>.yaml <init_args>,{name}ininit_argsreplaced (--source,--source-env,--source-file,-o/--outputand, in a CDC DAG,--modeare the operator’s: refused in any spelling,--output=xand-oXtoo;--mode cdcin a batch DAG is refused, a value that readscdcis not).initnames the stream’sserver_id, slot, checkpoint and bucket prefix after the file name, so two sources never share them; - runs
rivet checkon it; - refuses a config that writes to a bucket prefix or a warehouse dataset another config in
config_dirwrites to (give each source its own, e.g.--bigquery-dataset {name}); - writes
<config_dir>/<name>.yaml, never over an existing file, and logs each export and its tables.
A failed step writes no config and is not retried: read the log, fix the cause, and clear the task in the latest run
only (an init cleared in several runs at once fails in each run that starts after the first one wrote the config,
since the DAG has no init task then). The bucket and the
warehouse dataset are not created: they must exist.
Once the config exists, the next parse builds the same DAG from it: for cdc, each mode: cdc export of the
config as a stream (run, then a load per table when the config has a load: block and a compaction of each table
whose layout rivet resolves to a base and a buffer); for batch, every export through build_batch_dag, with a load
when it has load: and a compaction of each export whose layout rivet resolves the same way. The layout is read as
rivet resolves it (ADR-0034 D7), from the config alone: BigQuery (the one warehouse that compacts), a load that
accumulates (incremental, cdc; never full, and an export without mode: is full), and layout: base_buffer
written at load:, over it at the export’s load:, over it at the captured table’s load.tables.<t>; with no layout
written, a stream with cdc.backfill is a base and a buffer, anything else a change log with no compaction.
rivet init --mode cdc writes one stream over all tables on MySQL and PostgreSQL’s public, which keeps the
build_cdc_dag shape (run, load.T, compact.T), and one stream per table on SQL Server, Oracle, MongoDB and other
PostgreSQL schemas: each stream is then a group named after its export (dbo_orders.run, dbo_orders.load.dbo_orders: a load takes the warehouse name, the schema’s dot folded to _),
the streams running side by side. A batch DAG takes init’s suggested mode per table (full for a small one), or the one init_args names
(--mode incremental). One name is one config and one state database: a source in both a CDC and a batch DAG needs
two names, or a config_dir and state_root per mode, and a batch DAG over a config that has a mode: cdc export is
refused (below). Oracle CDC signs in as a common user (c##…) that LogMiner
lets mine, with --schema naming the tables’ owner. init_args are one list for every name of a call: sources that need other flags
(--tls require for SQL Server, --schema) go in a call of their own. So
unpausing runs init at once, and the stream starts at the next scheduled run (or trigger one).
- The config folder must be one the scheduler (Airflow 3: the dag-processor) and every worker read, as the DAGs
folder. If
initkeeps running, the file it wrote is not where the scheduler reads. - Edit the config like any other: the DAG follows it at the next parse. Delete it to have
initwrite it again. - A config the builder cannot build a DAG from (not YAML, a wrong shape, no
mode: cdcexport for a CDC DAG, amode: cdcexport under a batch DAG, no export at all) never ends the DAG file: that source’s DAG keeps its id and has one task,config, which fails without retry naming the cause (RIVET_AIRFLOW_CONFIG_UNREADABLEwith the line and column of a YAML error,..._NO_CDC_EXPORT,..._HAS_CDC_EXPORT,..._NO_EXPORT,..._UNBUILDABLE) and the remedy; the other sources of the call are built as they are. Fix the config (or delete it forinit) and the next parse builds the real DAG. A wrong argument of the call itself (a bad name,operator_kwargs, a DAG setting) is still an import error, as it is the same for every source. - An export whose id in the
applygroup is the id of an ordering point of a plan (after_<heavy export>,wave_<n>_done) keeps its id; the ordering point gets_barrierappended. - A config moved from cron (
docs/cron-to-airflow-cdc.md) works as it is: the source goes to the variable itsurl_envnames. operator_kwargsgo to every task,initincluded;env_from_connections,env_from_variables,configandstate_dirare the builder’s.env_from_variables({ENV_NAME: "<variable key>"},{name}replaced in the key) fills an environment variable from an Airflow Variable per source, read when each task runs and never at parse. For a config withurl_secret: ${RIVET_SOURCE_URL_SECRET}:env_from_variables={"RIVET_SOURCE_URL_SECRET": "rivet_{name}_url_secret"}, one Variablerivet_<name>_url_secretper source. A missing Variable fails that source’s tasks withRIVET_AIRFLOW_VARIABLE_MISSING, before rivet starts, and no other source. The walk-through, the IAM grant and the comparison with Airflow’s Secret Manager backend are in Connections and secrets.- The DAG file reads only files: no database is reached while the scheduler parses it.
Connections and secrets
What reaches the rivet process, and how Airflow Connections become what rivet reads.
Secrets
-
rivet is configured through environment variables and nothing else, and the subprocess gets a minimal environment, not the worker’s. It is built from three things:
- The worker’s variables on one allow-list (
ENV_ALLOWLISTininvocation.py):PATH,HOME,USER,LOGNAME,TZ,LANG,LC_*,TMPDIR,SSL_CERT_FILE,SSL_CERT_DIR,HTTP_PROXY,HTTPS_PROXY,NO_PROXY,ALL_PROXY,http_proxy,https_proxy,no_proxy,all_proxy,KUBERNETES_SERVICE_HOST,KUBERNETES_SERVICE_PORT. Nothing else is inherited: notAIRFLOW__*, notAIRFLOW_CONN_*, not aRIVET_*variable set on the worker.env_passthrough=["RIVET_STATE_URL", "MY_*"]extends the list with names or shell-style patterns.cloud_credentials=["gcp", "aws", "azure"]addsGOOGLE_APPLICATION_CREDENTIALSandGOOGLE_CLOUD_PROJECT,AWS_*,AZURE_*for a destination or warehouse that authenticates from the environment. A storage Connection (connections=, below) that supplies a credential of one of these kinds replaces the worker’s variables of that kind, whichever way they were passed: the worker’sAWS_SESSION_TOKENnever rides beside a Connection’s static keys, nor its account key beside a Connection’s SAS token. A Connection that supplies no credential (an AWS one with only a region, a GCP one with only a project) leaves the worker’s identity in place. env={NAME: value}. It is not templated and not stored in the metadata database, but it is whatever your DAG file computes: do not write a secret literal there.env_from_connections={ENV_NAME: conn_id}, which builds a URL from an Airflow Connection’s fields insideexecute, credentials percent-encoded, and so the database name for PostgreSQL, MySQL and MongoDB. For SQL Server and Oracle the database is written as it is, because rivet reads that URL path without decoding it; a name holding@,?or#(and/on Oracle) is refused (RIVET_AIRFLOW_CONNECTION_UNSUPPORTED) as rivet would cut it there. An IPv6 host of a SQL Server connection with no port gets:1433, which rivet needs to split host from port. The scheme comes from{ENV_NAME: (conn_id, "postgresql")}, else the connection extrarivet_scheme, else the connection type (postgres,mysql,mssql,mongo,oracle); a type that names no rivet scheme, such asgeneric, is refused before rivet starts (RIVET_AIRFLOW_CONNECTION_SCHEME). A password without a login is kept, an IPv6 literal is bracketed with its zone encoded (fe80::1%eth0becomes[fe80::1%25eth0]), any other host is kept as written (db:5432with an empty port field), an Oracle connection’s extraservice_nameis used as the path. The standard extras that have a URL form become query parameters: PostgreSQLsslmode,application_name,connect_timeout; MongoDBsrv(themongodb+srvscheme, which takes no port),authSource,authMechanism,replicaSet,tls/ssl,allow_insecure,directConnection,readPreference,appName. An extra that changes how the hook authenticates and has no URL form (PostgreSQLiam,redshift; MySQLunix_socket) is refused (RIVET_AIRFLOW_CONNECTION_UNSUPPORTED). Other extras are client-library settings and are not read. The extrarivet_paramsis appended as written and wins over a mapped extra of the same name. Aconn_idno backend defines, here or inconnections=[...], is refused before rivet starts (RIVET_AIRFLOW_CONNECTION_MISSING), not retried.connections=[conn_id, ...]: storage and warehouse Connections, see below.
argv carries the config path, export names and flags.
- The worker’s variables on one allow-list (
-
XCom carries code, class, exit_code, retryable, action, kind, counts,
stop_reason, the degradations and file paths. It never carries the errormessage: redaction covers credentials only, and error text can embed source cell values. -
The task log gets a readable block (see “Reading the task log”): outcome, codes, class, action, counts, run id, step exit statuses, paths, and, on a failure, rivet’s error text on the headline and on a failed unit’s line, and in the exception. That text is rivet’s, not the package’s: Airflow’s secrets masker reads it first, it is cut to one line of at most 300 characters, and its control characters are shown as escapes. It can still hold a source value (a cell that failed to convert), which is why it is in the task log and the exception and never in XCom. Names the DAG gives (export, table) are the only other text in it the package did not write. The one-line JSON records,
rivet.start(argv),rivet.step,rivet.unit(one per unit),rivet.result,rivet.warning,rivet.crashed,rivet.cdc.max_events,rivet.refused, …, are written at DEBUG, under the same rules. -
rivet’s raw stdout and stderr go to files and never to the task log or to the worker process’s own stderr (which Airflow 3, and Airflow 2 with
run_as_user, copy into the task log). The files are<base>/<dag_id>/<task_id>-<hash>/<run_id>__try<N>.<step>.stderr.log(and.stdout.log), mode0600in0700directories; XCom and a failed task’sstderrlog line name the path (and therivet.startrecord at DEBUG).<base>isstderr_dirwhen given, else<state_dir>/logs, else, on a worker with no state directory,<temp dir>/rivet-airflow-<uid>/logs(recorded asstderr_temp; a pod loses the files with its disk, and what a failure was is still in the error object). -
Retention. When a task ends, the files of its newest
log_keeptries (default 10, counted per task across runs) are kept and the older ones are removed.log_keep=Nonekeeps everything. Only the task’s own folder is looked at; a file of an older layout is never removed (see “Upgrading a state directory” in State). Underairflow/<dag_id>/, a sealed plan artifact that has expired and was last written over 24 h ago is removed (with theplans/<run_id>/folder it leaves empty, when the folder itself was untouched for 24 h before the pass: the folder of a run in progress, even an empty one, is never removed by a sibling task’s cleanup), and so is a crashed ledger untouched for 24 h (a crash of that series more than 24 h after its last one starts a fresh budget). A ledger that is not the ledger’s JSON is left for a person to delete. -
stream_stderr=Truecopies stderr into the task log when each step ends. It is the one way raw stderr reaches the task log, and it is for debugging: it puts possibly data-bearing text into a store with wider access than the worker.
Storage and warehouse connections
connections=["gcp_rivet", "sf_rivet"] (on every operator, or in a builder’s operator_kwargs)
turns each Airflow Connection into what rivet reads, inside execute: variables, and key files
written mode 0600 into a private folder that is removed when the task ends, whatever its
outcome. The kind comes from the connection type, or from the extra rivet_kind; one task
takes at most one Connection of each kind (RIVET_AIRFLOW_CONNECTION_KIND_TWICE), and a type
that is none of them is refused before rivet starts (RIVET_AIRFLOW_CONNECTION_KIND).
| Kind (connection type) | Read from the Connection | rivet gets | The config names it |
|---|---|---|---|
gcp (google_cloud_platform) | extra keyfile_dict (written to a file) or key_path; project | GOOGLE_APPLICATION_CREDENTIALS, GOOGLE_CLOUD_PROJECT | nothing: GCS and BigQuery read it |
aws (aws) | login, password; extras aws_session_token, region_name, endpoint_url. A role (role_arn, assume_role_*), a profile_name, or keys in extras (also under session_kwargs) are refused, RIVET_AIRFLOW_CONNECTION_UNSUPPORTED: rivet signs with static or session keys only | AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN, AWS_REGION, AWS_ENDPOINT_URL | access_key_env: AWS_ACCESS_KEY_ID, secret_key_env: AWS_SECRET_ACCESS_KEY (+ session_token_env) |
azure (wasb) | login (account), password (key); extra sas_token | AZURE_STORAGE_ACCOUNT, AZURE_STORAGE_KEY, AZURE_STORAGE_SAS_TOKEN | account_name: ${AZURE_STORAGE_ACCOUNT} (rivet reads no account variable of its own), and account_key_env: AZURE_STORAGE_KEY or sas_token_env: AZURE_STORAGE_SAS_TOKEN |
snowflake (snowflake) | extras account, region, role, warehouse, database, private_key_content (PEM, or base64 of PEM as Airflow’s SnowflakeHook takes it; written to a file) or private_key_file; with a key the password is the key’s passphrase, else the login password | a snow connection named as load.connection in a private SNOWFLAKE_HOME; RIVET_SNOWFLAKE_KEY; PRIVATE_KEY_PASSPHRASE for an encrypted key | load.connection |
clickhouse (clickhouse, or any type with rivet_kind: clickhouse) | host (required, RIVET_AIRFLOW_CONNECTION_INCOMPLETE without one), port, login, password; extra secure or protocol | RIVET_CLICKHOUSE_URL, RIVET_CLICKHOUSE_USER, RIVET_CLICKHOUSE_PASSWORD, and the password also under the config’s own password_env (rivet init writes CLICKHOUSE_PASSWORD) | url: ${RIVET_CLICKHOUSE_URL}, user: ${RIVET_CLICKHOUSE_USER}, password_env: RIVET_CLICKHOUSE_PASSWORD (or any name) |
The config keeps what is not a secret (bucket, project, dataset, database, schema); the
Connection holds who may write there. The Snowflake loader runs the snow CLI, which must be on
the worker (pip install snowflake-cli into its own environment). On BigQuery rivet compact
merges the buffer into the base table; on Snowflake and ClickHouse the current state is a view
over <table>__changes and there is nothing to merge. rivet 0.32.2 reports that table as skipped in its result
(compact [<table>]: skipped — this warehouse keeps a change log behind a view and never compacts),
so a compact task whose every table is skipped ends as an Airflow skip, not green. For these warehouses
build the CDC DAG with compact=False and leave such exports out of compact_exports.
Source credentials from Google Secret Manager
A config can name its source’s URL or password by a Secret Manager secret instead of a Connection, an environment variable or a file. rivet reads the secret when it starts; the value is never written to the plan, the state or the log.
source:
type: postgres
url_secret: projects/my-project/secrets/shop-url # the whole URL, latest version
source:
type: mysql
host: db.internal
user: rivet
database: shop
password_secret: projects/my-project/secrets/shop-mysql-pw/versions/3 # a pinned version
url_secrettakes the place ofurl,url_envorurl_file: exactly one of them.password_secrettakes the place ofpasswordorpassword_env: at most one. A reference isprojects/<project>/secrets/<secret>(the latest version) or.../versions/<n>; any other shape isRIVET_CONFIG_SOURCE_CONNECTION_INVALID.- The credential is the one the GCS and BigQuery legs use: the key
GOOGLE_APPLICATION_CREDENTIALSnames, or gcloud application-default credentials. It needsroles/secretmanager.secretAccessoron each secret, not on the project. A secret rivet cannot read stops the run withRIVET_CONFIG_GCP_SECRET_UNREADABLE, naming the secret: HTTP 403 is the missing role, 404 a wrong project, name or version. That is an environment failure, so it is not retried as a bad config. - The worker passes the key to rivet the way it passes it to those legs. Either a GCP Connection with a key
(
connections=["gcp_rivet"], which writesGOOGLE_APPLICATION_CREDENTIALSfor the task) orcloud_credentials=["gcp"](the worker’s ownGOOGLE_APPLICATION_CREDENTIALSpassed through). A worker whose identity Google’s default chain finds without a file (a GKE workload identity, a VM’s service account) needs neither. - A config with
url_secret, or withpassword_secretand nourl_env(its host, user and database written in the config), reads no source Connection: a DAG built from it (below) needs only the state Connection. Apassword_secretwithurl_envstill reads the Connection for the URL. - rivet version. Secret sources need rivet 0.33.0 or newer.
An older rivet is refused before it starts with
RIVET_AIRFLOW_BINARY_TOO_OLD, naming the version needed.
rivet init writes url_env:. To source a config from a secret, write the file yourself, or change the written
url_env: <NAME> line to url_secret: ... before the DAG parses it. Then the DAG for the source reads the secret:
from datetime import datetime
from airflow_provider_rivet.dags import build_source_dags
# shop.yaml in config_dir names the secret (url_secret) and the exports; the DAG reads that file at parse time.
globals().update(
build_source_dags(
["shop"],
mode="batch",
config_dir="/opt/airflow/dags/rivet",
state_root="/opt/airflow/rivet-state",
state_connection="rivet_state",
# the worker's GOOGLE_APPLICATION_CREDENTIALS for the secret, as the GCS and BigQuery legs get it
operator_kwargs={"cloud_credentials": ["gcp"]},
schedule="0 */2 * * *",
start_date=datetime(2026, 1, 1),
catchup=False,
)
)
One Variable per source: the secret name at task run time
The secret’s name differs by deployment, and a DAG file must not read it at parse. So the name lives in an Airflow Variable per source, and the task puts it in rivet’s environment when it runs:
- The Variable
rivet_<name>_url_secretholds the reference,projects/<project>/secrets/<secret>(not a secret itself):airflow variables set rivet_shop_url_secret projects/my-project/secrets/shop-url, or the environment variableAIRFLOW_VAR_rivet_shop_url_secreton the worker. - The DAG says which variable fills which environment variable:
env_from_variables={"RIVET_SOURCE_URL_SECRET": "rivet_{name}_url_secret"}.{name}is the source’s name, so each source has its own Variable. - The config names the environment variable:
url_secret: ${RIVET_SOURCE_URL_SECRET}. rivet interpolates${...}from its environment, so it reads the secret the Variable named. - A Variable no backend defines fails only that source’s tasks, before rivet starts, with
RIVET_AIRFLOW_VARIABLE_MISSINGnaming the Variable, the environment variable it fills and the command that sets it. A retry cannot create it, so the task is not retried. The other sources of the DAG file are not affected.
from datetime import datetime
from airflow_provider_rivet.dags import build_source_dags
# shop.yaml and billing.yaml in config_dir each say `url_secret: ${RIVET_SOURCE_URL_SECRET}`
globals().update(
build_source_dags(
["shop", "billing"],
mode="batch",
config_dir="/opt/airflow/dags/rivet",
state_root="/opt/airflow/rivet-state",
state_connection="rivet_state",
env_from_variables={"RIVET_SOURCE_URL_SECRET": "rivet_{name}_url_secret"},
operator_kwargs={"cloud_credentials": ["gcp"]},
schedule="0 */2 * * *",
start_date=datetime(2026, 1, 1),
catchup=False,
)
)
Here the Variables are rivet_shop_url_secret and rivet_billing_url_secret, one secret each. The same mapping works on
the operators directly (env_from_variables= on any rivet task); operator_kwargs may not set it, since the builder
sets it per source.
- IAM is per secret. The credential rivet runs as (the key
GOOGLE_APPLICATION_CREDENTIALSnames, or the worker’s default identity) needsroles/secretmanager.secretAccessoron each secret it reads, not on the project:gcloud secrets add-iam-policy-binding shop-url --project my-project --member serviceAccount:$GSA --role roles/secretmanager.secretAccessor. A source whose binding is missing stops withRIVET_CONFIG_GCP_SECRET_UNREADABLE(HTTP 403) on its own. - Getting the config.
rivet initcannot read a secret: it writesurl_env:. A source in secret mode has its config one of two ways. Write<config_dir>/<name>.yamlby hand withurl_secret: ${RIVET_SOURCE_URL_SECRET}, before the DAG is unpaused. Or let theinittask write it once through the source’s Connection, then change the writtenurl_env: RIVET_SOURCE_URLline tourl_secret: ${RIVET_SOURCE_URL_SECRET}. The next parse builds the DAG from the edited file, and the source Connection is then not read. Theinittask reads the Variables too: a source whose Variable is missing is refused there as well.
Secret Manager by reference or by Airflow’s backend. Airflow’s CloudSecretManagerBackend reads a Connection (or a
Variable) from Secret Manager when a task asks for it: the secret’s value reaches the Airflow worker process, and rivet
gets it through the environment that process builds. url_secret and password_secret keep the value out of Airflow.
Only the reference passes through Airflow, as a Variable whose value is a name, so the metadata database and the task
log hold a resource name and never the password. rivet fetches the value itself when it starts, with its own
credential. Recommendation: for a source database, use url_secret or password_secret, with the per-source Variable
above, and the secret’s IAM granted per secret. Keep the backend for the Connections Airflow hands to rivet (the storage,
warehouse and state Connections), and for rivet versions older than the one that reads the secret keys.
Connections and secrets: recommended setup
Where the Connections of a rivet DAG live decides who else can read them. Safest first:
- Keyless GCP: the worker’s own identity. On GKE the worker pod runs as a Kubernetes service
account bound to a Google service account (Workload Identity); on Cloud Composer it is the
environment’s service account. No key file exists anywhere. The GCP Connection holds only
project; a Connection that supplies no credential leaves the worker’s identity in place, and rivet finds it through Google’s default chain (GCS: an ADC file, else the metadata server). rivet’s BigQuery loader has no metadata-server path of its own: with no ADC file it runsgcloud auth application-default print-access-token, so a Workload Identity worker that loads BigQuery needs thegcloudCLI on itsPATH. The live gate proves this leg with a credential file mounted read-only where the default chain looks; it has no Workload Identity to test. - Google Secret Manager as Airflow’s secrets backend for what has to be a secret: the Snowflake key, the ClickHouse password, source database passwords. Airflow reads a Connection from Secret Manager when a task asks for it; it is never in the metadata database, a compose file or the container’s environment. The worker’s identity is granted access to the connection secrets only, not to the project’s other secrets.
- Connections in the metadata database, with a Fernet key set (
[core] fernet_key). Without one Airflow stores every password in clear and logsempty cryptography key. AIRFLOW_CONN_*environment variables: the worst place. They are readable throughdocker inspect,/proc/<pid>/environof every Airflow process, compose files and deployment manifests. Use them for a throwaway stand only (the live gate’s default leg).
GCP, keyless. The Connection (it holds no secret, so it may live anywhere):
airflow connections add gcp_rivet --conn-json '{"conn_type": "google_cloud_platform", "extra": {"project": "my-project"}}'
The grants, for a worker running as rivet-worker@my-project.iam.gserviceaccount.com (these are the
usual roles; the gate runs as a project owner and does not measure the minimum):
GSA=rivet-worker@my-project.iam.gserviceaccount.com
gcloud iam service-accounts add-iam-policy-binding "$GSA" --role roles/iam.workloadIdentityUser \
--member "serviceAccount:my-project.svc.id.goog[airflow/airflow-worker]" # GKE: namespace/KSA
gcloud storage buckets add-iam-policy-binding gs://my-bucket --member "serviceAccount:$GSA" --role roles/storage.objectAdmin
gcloud projects add-iam-policy-binding my-project --member "serviceAccount:$GSA" --role roles/bigquery.jobUser
bq add-iam-policy-binding --member "serviceAccount:$GSA" --role roles/bigquery.dataEditor my-project:raw
Secrets, from Google Secret Manager. Airflow’s configuration (airflow.cfg, or the same as
AIRFLOW__SECRETS__BACKEND / AIRFLOW__SECRETS__BACKEND_KWARGS, which hold no secret):
[secrets]
backend = airflow.providers.google.cloud.secrets.secret_manager.CloudSecretManagerBackend
backend_kwargs = {"connections_prefix": "airflow-connections", "sep": "-", "variables_prefix": null, "config_prefix": null, "project_id": "my-project"}
A conn_id sf_rivet is then the secret airflow-connections-sf_rivet, holding the Connection in
Airflow’s JSON form. Make each secret from a file or stdin, never from a command-line argument:
# Snowflake: the key file goes in whole (private_key_content), the login is the key's user
jq -n --rawfile key rsa_key.p8 '{conn_type: "snowflake", login: "RIVET_LOADER",
extra: {account: "xy12345", role: "LOADER", warehouse: "LOAD_WH", database: "RAW", private_key_content: $key}}' |
gcloud secrets create airflow-connections-sf_rivet --data-file=-
# ClickHouse and a source database: the password is read from the terminal, not typed into argv
read -rs PW
jq -n --rawfile pw /dev/stdin '{conn_type: "clickhouse", host: "ch.internal", port: 8443, login: "loader",
password: $pw, extra: {secure: true}}' < <(printf %s "$PW") | gcloud secrets create airflow-connections-ch_rivet --data-file=-
jq -n --rawfile pw /dev/stdin '{conn_type: "postgres", host: "db.internal", port: 5432, login: "rivet_reader",
password: $pw, schema: "app", extra: {sslmode: "verify-full"}}' < <(printf %s "$PW") |
gcloud secrets create airflow-connections-pg_app --data-file=-
(printf %s is a shell builtin: the password is in no process’s argv, and it gets no trailing newline.) The worker’s identity reads these secrets only, through an IAM
condition on the secret name (it needs the project NUMBER):
gcloud projects add-iam-policy-binding my-project --member "serviceAccount:$GSA" \
--role roles/secretmanager.secretAccessor \
--condition='title=airflow-connections,expression=resource.name.startsWith("projects/123456789012/secrets/airflow-connections-")'
The DAG names the same conn_ids whatever backend serves them:
connections=["gcp_rivet", "sf_rivet"], env_from_connections={"PG_URL": "pg_app"}.
What the operator does with a secret. Inside execute, each try makes a private folder
(tempfile.mkdtemp, mode 0700, in the worker’s temp directory); a key a Connection carries
(keyfile_dict, private_key_content) and the Snowflake config.toml are written into it with
mode 0600, and the folder is removed in a finally when the try ends, whatever its outcome. A
worker killed with SIGKILL runs no finally, and the folder stays in its temp directory. A
password (ClickHouse, a database URL) is passed in the environment of the rivet process only, not
of the worker: the same user and root can read it in /proc/<pid>/environ while rivet runs.
State
Where rivet’s state lives under Airflow, and how to set up a worker for it.
State, by deployment
| Worker | State | What the operator does |
|---|---|---|
Ephemeral pod (KUBERNETES_SERVICE_HOST in the environment, or deployment="pod") | PostgreSQL, required | refuses SQLite (RIVET_AIRFLOW_STATE_SQLITE_ON_POD); refuses every CDC export (RIVET_AIRFLOW_CDC_ON_POD: the checkpoint is a file and would live on the pod’s disk) until rivet stores it in the state database; runs the config in place; keeps rivet’s stderr in a private file on the pod’s disk (stderr_temp), never in the task log |
Local or long-lived worker (deployment="local" overrides the detection for a long-lived Kubernetes worker with a persistent volume) | SQLite in a declared directory, or PostgreSQL | requires state_dir for SQLite state and for CDC; checks it; refuses state or a checkpoint left beside the original config; refuses SQLite state when Airflow’s executor may run tasks on several hosts (Celery, Kubernetes, Edge, …: RIVET_AIRFLOW_STATE_SQLITE_MULTI_HOST) unless the task says single_host=True; warns once per task that SQLite is single-host |
A state_dir that is not given where the state needs one is refused with RIVET_AIRFLOW_STATE_DIR_REQUIRED; one that cannot be created or written is refused with RIVET_AIRFLOW_STATE_DIR_NOT_WRITABLE. Creating a PostgreSQL state database needs psycopg2 on the worker, and a worker without it is refused with RIVET_AIRFLOW_STATE_DATABASE.
state_dir is an operator parameter, not an Airflow Variable. The builders pass one value to
every task they create, so “the same path for every task” holds by construction, it is visible
in the rendered fields, and reading it needs no metadata-database access on the worker.
PostgreSQL state is RIVET_STATE_URL=postgresql://... in the task’s environment:
env_from_connections={"RIVET_STATE_URL": "rivet_state"}, or set it on the worker and name it in
env_passthrough=["RIVET_STATE_URL"] (a worker variable is not inherited unless it is named).
A RIVET_STATE_URL set on the worker and not passed on is refused. If the worker’s
RIVET_STATE_URL names a state rivet would open, by rivet’s own rule (it starts with
postgres:// or postgresql://, or it is a sqlite:<path> file), and the task’s environment has
no entry for it (not in env_passthrough, env or env_from_connections), the task fails before
rivet starts with RIVET_AIRFLOW_STATE_ENV_NOT_PASSED and is not retried: rivet would otherwise run
green on an empty SQLite state in state_dir while the real state sits in the database or file the
worker names (an incremental export reads from the start again, a CDC stream re-anchors). An empty
or blank value, or one with any other scheme, selects no state here and is not refused. The
message names the variable and never its value. Fix it one of two ways: inherit the worker’s
value with env_passthrough=["RIVET_STATE_URL"], or give the task its own value with
env_from_connections={"RIVET_STATE_URL": "<conn_id>"} (or env). If the worker’s variable is
not meant for this pipeline, unset it on the worker, or declare env={"RIVET_STATE_URL": ""} on
the task: a declared value, also an empty one, is the task’s own decision and rivet then keeps
SQLite state in state_dir.
A sqlite:<path> state a task passes on is honoured. rivet opens the file the URL names: an
absolute path as written (sqlite:/data/rivet/state.db, sqlite:///data/...), a relative one
against the directory of the config it runs, which is state_dir (the copy). The checks for state
left beside the original config look for that file instead of state_dir/.rivet_state.db, the
single-host warning and the multi-host refusal name it, and a pod refuses it like any SQLite state.
The file still lives on this worker’s disk: it is single-host state.
Local worker setup guide
-
Create the state directory yourself, once, on storage that outlives the worker process. A host path or a named volume, never a container’s own filesystem. One directory per pipeline (per source database), for example
/var/lib/rivet/<pipeline>. The operator never creates it: a directory that silently appears empty is exactly the failure this guide exists to prevent, so a missing one is refused (RIVET_AIRFLOW_STATE_DIR_MISSING). -
Every task of every DAG that touches the pipeline must see the SAME absolute path. With Docker, mount the same host path at the same container path in every worker. Pass that path as
state_dir(the builders do it for all their tasks). -
What is in it.
.rivet_state.db: rivet’s state, under its default name.<config name>.<hash>.yaml(and<config name>.<hash>--<export>.yaml): the operator’s copy of your config, byte for byte.<hash>is the first 8 hex digits of the SHA-256 of the original’s absolute path, so two configs with one file name never share a copy. rivet resolves the config’s relative paths (its SQLite state, acdc.checkpoint, aquery_file, a localdestination.path) against the config’s directory, so running the copy puts all of them here (see 5). Edit your original; the copy is rewritten on every task. The operator does not setRIVET_STATE_URL=sqlite:itself: the copy already keeps the state here on every rivet it runs. Asqlite:value the task passes on moves the state to the file it names (see above); leave it unset for tasks unless the state must live elsewhere.- every relative
query_fileof the config, copied to the same relative path (see 5), and.rivet_airflow_query_files.json, which records the config directory each one came from, as the DAG gave it (thedags/repoof a git-sync link, not therev-<sha>it points to today), so a new revision of the same config is the same owner. The copy and the record are made under one lock (airflow/locks/state/query-files.lock), so two tasks of two config directories that share this state directory never both pass the check. - a relative
cdc.checkpoint, which resolves beside the copied config, that is, here. airflow/<dag_id>/: sealed plan artifacts (plans/<run_id>/<export>__<task_id>__s<max_tries>__<inputs>-<hash>.json), the crashed ledger, scratch files;airflow/locks/run/<export>.lock(run, apply, cdc_run),airflow/locks/<export>.lock(load and compact of a whole export) andairflow/locks/table/<export>__<table>-<hash>.lock(load and compact of one table) (Overlap).logs/<dag_id>/<task_id>-<hash>/: rivet’s stdout and stderr, one file per step and try.- How a name becomes a path. A DAG id, task id, run id or export name that is one lower-case
word of
a-z 0-9 _ . -(at most 80 characters, not starting with.or-) is used as it is. Any other name (other characters such as:+or non-ASCII letters, upper case, a mapped task’stask_id[index]) is written as its readable form (each run of other characters replaced by_) followed by-and 12 hex digits of the SHA-256 of the exact name: run idscheduled__2026-10-06T00:00:00+00:00becomesscheduled__2026-10-06T00_00_00_00_00-b07b0ae9e551. Two different names therefore never share a directory, a sealed plan, a log file or a ledger, also on a file system that ignores case. A task’s log folder always carries the hash, also for a plain task id, so it is never a folder an older layout wrote to. - One sealed plan per task, try series, config and export. The artifact’s name is made from the
export, the task id (with the map index), the try series (
s<max_tries>; Airflow movesmax_trieswhen a task is cleared) and<inputs>: a digest of the config’s absolute path, the config’s bytes and the export’squery_file. Two tasks of one DAG run never share a plan, also when they run two configs that both have an export of one name; a retry of the same task replays its own plan; a clear starts a new series and plans again, so a clear after a successful apply never replays a cursor snapshot that apply already moved past (rivet would refuse itRIVET_PLAN_ARTIFACT_STALE); a config or query file edited between two tries is planned again under a new name. - A retry replays its own plan only while the resolved config path and the config’s bytes are unchanged. A config reached through a symlink that is re-pointed between two tries (a new git-sync revision of the DAG folder) is planned again, also when the bytes are the same, and leaves one more config copy and plan artifact in the state directory.
- The plan digest does not cover the environment. Changing the source between two
tries of one task instance (another URL in
env, an edited Connection) replays the plan made for the old source against the new one. Clear the task in a new DAG run, or delete its artifact, after such a change. - The artifact records the export and the config it was planned from (
export_name,config_path).applyrefuses a plan object in which either is missing or is not the task’s own (RIVET_AIRFLOW_PLAN_ARTIFACT_FOREIGN), expired or not, and leaves the file as it is, so the retry is refused for the same reason until a person deletes it (or, once it has expired and is 24 h old, the pruning below removes it). The config is compared as a file, not as text: another case, Unicode form or symlink of the same file is the task’s own, and a recorded path that no longer exists is not. A file at that path that is not a JSON object (empty, cut short) is planned over. - Upgrading a state directory written by an earlier build of this package: files of an
older layout are left alone. They are never read, never pruned and never deleted, so
remove
logs/<dag_id>/<task_id>/folders without a-<hash>suffix andairflow/<dag_id>/plans/<run_id>/<export>.jsonfiles by hand when you no longer need them. A run in flight during the upgrade plans again, and its crashed budget starts empty (at most one extra crash retry). .rivet_airflow_marker: a random id written by the first task that used the directory; an empty one is refused (RIVET_AIRFLOW_STATE_DIR_MARKER_EMPTY) until a person deletes it.
The copies and every file under
airflow/andlogs/are created with mode0600, in directories of mode0700(an existingairflow/orlogs/directory is tightened). Moving an existing pipeline under Airflow: if.rivet_state.dbor a relativecdc.checkpointfile already sits beside your original config and not here, the task is refused before rivet starts (RIVET_AIRFLOW_STATE_BESIDE_CONFIG,RIVET_AIRFLOW_CHECKPOINT_BESIDE_CONFIG): the copy would not see it, and rivet would start from an empty state or re-anchor the stream. Stop the runs, move the file into the state directory (the state database with its-waland-shmfiles; the checkpoint to the same relative path), and run again. Using the config’s own directory asstate_dirneeds no copy and no move. Afterrivet init -o X: init records the source’s primary keys in a.rivet_state.dbbesideX, which the task then refuses the same way: move it (with-waland-shm) intostate_dir, or runinitwithRIVET_STATE_URLset to the PostgreSQL state the tasks use. rivet 0.32.2 addsRIVET_STATE_URL=sqlite:<path>, so init can write into<state_dir>/.rivet_state.db, the file the tasks use (README Quickstart). -
What breaks when a task sees a different or an empty directory. rivet creates a new, empty state there and treats every export as a first run: an incremental export re-reads from the start, a CDC stream re-anchors and the changes between the lost position and the new anchor are gone, with no error. What the operator can check without rivet’s state identity: the directory exists, is absolute and writable, and its marker equals the marker of each direct upstream rivet task of the same DAG run (taken from their XCom); on SQLite state a difference is refused with
RIVET_AIRFLOW_STATE_DIR_DIFFERS. On PostgreSQL state it is not: no task reads what another left in the directory, and several hosts, each with its own directory at one path, are the deployment that state is for (an extract on one host and its load on the other, measured by the live gate’s multi-host leg). It cannot see a directory that was emptied between two DAG runs, or two hosts that each have their own copy. -
Relative paths in the config. The copy changes the directory rivet takes as the config’s, and nothing else:
Key rivet resolves it against Under this package query_filethe config’s directory; an absolute path, ..and a symlink out of it are refused by rivetstays as written; the file is copied to the same relative path in the state directory before every task. Refused before rivet starts ( RIVET_AIRFLOW_QUERY_FILE) when it is absolute, has.., leaves the directory through a symlink, is missing for the task’s export, or when a config from ANOTHER directory already put a file at that relative path in this state directory (the refusal names the directory and the remedy for an owner that is an earlier revision of this config, or is gone: delete.rivet_airflow_query_files.jsonin the state directory and the next task claims the path)cdc.checkpointthe config’s directory resolves in the state directory, a subdirectory included (rivet 0.32.2’s init -o <stem>.yamlwrites./cdc/<stem>_<export>.ckpt); a file left beside the original is refused, see 3. The<checkpoint>.ownerrecord rivet 0.32.2 keeps beside it (which config owns the checkpoint) is neither checked nor touched by the operator: move it with the checkpoint or leave it, rivet re-claims a checkpoint whose recorded owner no longer names ita local destination.path(orprefix)the config’s directory the state directory: init’s ./output/orders/lands in<state_dir>/output/orders/(from rivet 0.32.2 a CDC scaffold written with-o <stem>.yamlsays./output/<stem>/orders_cdc/, which lands in<state_dir>/output/<stem>/orders_cdc/);cwddoes not move it. Write an absolute path to put the files elsewherethe other paths rivet opens as written, such as tls.ca_filethe process’s working directory unchanged: the working directory defaults to the directory of your ORIGINAL config; set cwdto change itThe preflight reads the config as rivet does: every ${name}is taken from a-p/--paraminextra_args(a run, CDC run or plan task only:rivet load,compactandapplyhave no -p, and those tasks refuse it withRIVET_AIRFLOW_PARAM_NOT_ACCEPTED), then from thetask’s environment, and spliced into the text before the YAML is parsed, with YAML 1.2 scalars ( 017andname: 2024stay the text written). Amodeno variable resolves is treated ascdcby the guards; an export name or acdc.checkpointno variable resolves is refused (RIVET_AIRFLOW_CONFIG_UNRESOLVED), as rivetrefuses the config. -
Single host. SQLite state and the lock files are visible to one host only. Two workers on two hosts need PostgreSQL state and a destination both reach (an object store). Measured with two Celery workers on two hosts, each with its own state_dir at one path (the live gate’s
--workers 2):- On PostgreSQL state with a GCS destination, extracts of one DAG run on both hosts, each
export moving host every run, and the CDC stream moving host, deliver every row once
and never move the stored cursor back. A retry of
RivetApplyOperatoron the other host finds no sealed plan there and plans again from the stored cursor: the delta is extracted once (the killed try on the first host wrote nothing and kept its artifact, pruned after 24 h). Not measured, by the same construction: a plan an earlier try on the first host already applied is not answeredalready_appliedon the other host but planned again, which for an incremental export reads only the rows past the moved cursor. - SQLite state: each host has its own
.rivet_state.db. An export that runs on the other host reads from the start, exit 0: the whole table again, and on the way back the rows the other host already took (990 of 1000 rows written twice). So SQLite state under an executor that may use several hosts is refused before rivet starts (RIVET_AIRFLOW_STATE_SQLITE_MULTI_HOST); a deployment with one Celery worker sayssingle_host=True. - A local destination (
rivet init’s default./output/, which lands in the state_dir): the files are split between the hosts; the first run on the other host writes there without complaint, and a later run on a host whose manifest is behind the stored cursor is refusedRIVET_STATE_CURSOR_PAST_MANIFESTby rivet. - The lock files guard one host (by construction, not measured): a zombie try on one host and its retry on another are kept apart only by rivet’s own run lease (Overlap).
- A ledger file would count crashes per host, so on PostgreSQL state the operator keeps none:
a crash is retried only within the first
crashed_retriestries (Retries).
- On PostgreSQL state with a GCS destination, extracts of one DAG run on both hosts, each
export moving host every run, and the CDC stream moving host, deliver every row once
and never move the stored cursor back. A retry of
-
Moving to PostgreSQL state. Stop the DAGs; create a database; set
RIVET_STATE_URLto itspostgresql://URL for every task (the worker’s environment, orenv_from_connections). This package does not copy the SQLite state into PostgreSQL: the new state starts empty, so plan the switch as a first run of every export (a full export simply runs again; an incremental export has no cursor to resume from). Keepstate_dirfor CDC: a checkpoint is a file on every state backend today, and it stays where it is.
Retries
How rivet’s exit and error object become an Airflow success, retry or stop.
Retries
| What rivet did | Object | Airflow |
|---|---|---|
| exit 0, no failed unit in the summary | none | success |
| exit 0, a failed unit in the summary | the worst failed unit’s (exit_zero_failed_unit) | by that object: retryable is retried, anything else is not |
a printed object that is malformed (no retryable, "retryable": "true", an unknown class, an exit_class that is not the exit status) | built from the exit status by the rows below (result_malformed) | by the built object; never an unhandled exception |
exit 2, error line printed with retryable: true (today: exit_class: 2) | retryable | AirflowException: retried under the task’s retries |
| exit 1, 3, 4, 5, 6 | generic, data_integrity, schema_drift, refusal, internal | AirflowFailException: no retry |
| exit 2, no error line (argument error) | built: generic, exit_code 1 | AirflowFailException: no retry |
| exit 101 (panic) | built: internal, exit_code 6 | AirflowFailException: no retry |
| killed by a signal, or exit 129-255 | built: crashed, exit_code null | retried under its OWN budget, crashed_retries (default 1), then AirflowFailException; with no Airflow try left (retries=0, or the last try) it is final at once: AirflowFailException, crashed_retry false, headline final: no try left |
exit 1 with a printed line saying class: "crashed" (a killed child, future binary) | crashed | the same crashed budget |
| any other status | built: generic | AirflowFailException: no retry |
| the package’s own preflight refused | preflight_refusal: RIVET_AIRFLOW_* in XCom | AirflowFailException: no retry |
code RIVET_STATE_RUN_IN_PROGRESS or RIVET_LOAD_TABLE_BUSY (rivet >= 0.32.2, kind busy, exit 2 both) (another rivet holds the export’s run lease or the table’s load lease; rivet’s remedy is “wait, then repeat”) | refusal, retryable: true whatever the line says | AirflowException: retried under retries; the headline says BUSY |
code RIVET_STATE_LOCK_TIMEOUT (rivet >= 0.32.2, kind busy, exit 2: rivet waited --lock-wait seconds for a lease another rivet process holds and gave up; the same end as RIVET_AIRFLOW_EXPORT_BUSY, inside rivet) | retryable, retryable: true whatever the line says | AirflowException: retried under retries; the headline says BUSY, the exception names the export |
code RIVET_LOAD_BLOCK_MISSING (rivet >= 0.32.2, kind usage, exit 1: load or compact on a config with no load: block) | generic | AirflowFailException: no retry; add the block |
code RIVET_SOURCE_CDC_CHECKPOINT_SHARED (rivet >= 0.32.2, exit 5: another config’s export owns the checkpoint, <checkpoint>.owner) | refusal | AirflowFailException: no retry; give the export its own cdc.checkpoint |
code RIVET_INIT_CDC_NAME_TAKEN (rivet >= 0.32.2, exit 5; rivet init only, which no operator runs) | refusal | AirflowFailException: no retry |
the export’s lock stayed held for lock_wait seconds (Overlap) | busy: RIVET_AIRFLOW_EXPORT_BUSY in XCom; rivet is not started | AirflowException: retried under retries |
The exception text is [code] class: action (export): text, where text is rivet’s own error text, redacted by
Airflow’s secrets masker, on one line and cut at 300 characters (Reading the task log);
the XCom error object never carries it.
The crashed budget across tries. Airflow clears a task instance’s XCom at the start of every
try, so the count cannot live there. On a local worker with SQLite state the operator keeps a small ledger file,
<state_dir>/airflow/<dag_id>/crashed/<run_id>__<task_id>-<hash>.json, holding [try, max_tries] for
every try that ended in a crash. A crash is retried when fewer than crashed_retries earlier
crashes carry the task instance’s current max_tries. Airflow moves max_tries when a task is
cleared, so a manual clear gets a fresh budget; changing retries in the DAG file in the middle
of a series does not move it, so it cannot reset the budget.
Every way the ledger can fail grants NO crash retry (crashed_ledger in degraded, the reason
in a WARNING note line and in the rivet.crashed record under ledger_problem): a directory that cannot be created or
written, and a file that is not the ledger’s JSON, which is left as it is until a person deletes
it. On a worker with no state directory (a pod) there is no file: a crash is retried only within
the first crashed_retries tries of the task instance, so neither a crash after a transient
failure nor a crash after a manual clear is retried.
The same holds on PostgreSQL state, where tries may run on different hosts and a ledger on one
host’s disk would grant the budget again on the next (crashed_ledger in degraded).
Limit: the crashed budget can only shorten Airflow’s own budget, never extend it. With
retries=0 Airflow retries nothing, a crash included. The builders default to retries=2.
The operators never run rivet state reset-chunks before a retry: a crashed checkpointed run is
resumed by the next process.
A retry of an apply that already succeeded. The task process can die after rivet apply exited
0 and before Airflow recorded the success (OOM of the task runner, a pod evicted, a zombie). The
retry is a try of the same series, so it replays the same sealed plan, and rivet (the minimum, 0.32.2)
answers it: a point-in-time plan (mode: full) it already applied is not extracted again,
the summary names the run that applied it (status: already_applied, answered_by_run), and the
task logs SKIPPED: an earlier try already applied this plan (record
rivet.apply.already_applied) and ends success with that run’s run_id, rows and files. An
incremental plan whose own apply moved the cursor is not refused RIVET_PLAN_ARTIFACT_STALE: the replay reads from the moved cursor
and finds only rows that arrived since, so nothing is extracted twice. A cursor another process
moved is still refused STALE. An apply that failed or was killed is replayed and runs as before.
Slack alerts: setup guide
A failed rivet task posts one message to a Slack channel: a one-line title,
dag_id.task_id — <error type>, with the run id and a link to the task log under it. The error
text goes into that message’s thread as a code block: rivet’s error line for the failed step, or,
when the task failed outside rivet, the exception’s message. The channel stays a list of titles.
It is Airflow’s on_failure_callback (slack_failure_callback from this package) sending through
the Slack provider. rivet itself sends nothing: do not configure notifications: in a rivet
config run under Airflow, or every failure is sent twice.
Two ways to connect, both set up below:
| Bot token (recommended) | Incoming webhook (fallback) | |
|---|---|---|
| Channel message | title + run id + task-log link | title + run id + task-log link + error text |
| Error text | a reply in the thread, a code block | in the same message |
| Airflow Connection type | slack (“Slack API”) | slackwebhook (“Slack Incoming Webhook”) |
| Password field holds | the bot token, xoxb-… | the whole URL, https://hooks.slack.com/services/… |
| DAG names | the conn_id and the channel id: slack_failure_callback("slack_rivet", channel="C…") | the conn_id: slack_failure_callback("slack_rivet_webhook") |
A webhook cannot thread: Slack answers it with ok, not with the message id a reply needs.
In short
A failed rivet task posts one title to a Slack channel, dag_id.task_id — <error type> (the
rivet code and final or retryable, else the exception’s class), with the run id and a
task-log link; its error text (rivet’s error line for the failed step, else the exception’s
message, through Airflow’s secrets masker) is a code block in the thread. A bot token
(slack Connection, scope chat:write, channel= the channel id) threads; an incoming webhook
(slackwebhook Connection, no channel) posts title and error text as one message.
from airflow_provider_rivet.callbacks import slack_failure_callback
from airflow_provider_rivet.dags import build_batch_dag
dag = build_batch_dag(
"rivet_postgres",
config="/opt/rivet/configs/postgres.yaml",
state_dir="/opt/rivet/state",
exports=["users", "orders"],
default_args={"retries": 2, "on_failure_callback": slack_failure_callback("slack_rivet", channel="C0123ABCDEF")},
)
The watcher task carries no failure callback: the builders set its on_failure_callback to
none, so a failed run sends one message per failed task and nothing for the watcher (which has no
rivet result to show). Unlike XCom and the task log (Secrets), the thread carries rivet’s error
text, which can hold source values. format_title and format_error_text are the formatters on their own, to send
through another channel. The thread (or the webhook message) carries each failed unit’s remedy as an action: line
before rivet’s error line. format_title never carries text: a channel is a list of titles.
Mutual exclusion: under Airflow, rivet’s own notifications are off and alerting is Airflow’s.
The operators pass --no-notify to every rivet process. To keep rivet’s own notifications instead (a config
whose notifications: you want), pass rivet_notifications=True: the operator does not pass --no-notify.
1. Install the Slack provider
On every worker, and wherever the scheduler or DAG processor parses DAGs:
pip install "airflow-provider-rivet[slack]"
or apache-airflow-providers-slack with Airflow’s constraints file. The official Airflow images
already ship it.
2. Create the Slack app
https://api.slack.com/apps → Create New App → From scratch → a name (it is the sender’s
name in the channel, e.g. rivet-airflow) and your workspace → Create App.
Bot token (recommended)
- Features → OAuth & Permissions → Scopes → Bot Token Scopes → Add an OAuth Scope:
chat:write. It is the only scope the callback uses. - Top of the same page: Install to Workspace → Allow. After adding a scope to an installed
app, click Reinstall to Workspace: until then the token keeps its old scopes, and Slack
answers
missing_scope(see Troubleshooting). - Copy the Bot User OAuth Token,
xoxb-…(step 3 below says where to put it). - In the channel:
/invite @rivet-airflow(your app’s name). A bot posts only where it is a member; a private channel works the same way. - The channel id: click the channel’s name → About (or Channel details) → at the bottom,
Channel ID: C…→ copy. The callback needs the id, not the name: the token has nochannels:readscope, so the bot cannot look a name up, and a name fails withchannel_not_found.
Incoming webhook (fallback, no thread)
Features → Incoming Webhooks → Activate Incoming Webhooks: On → Add New Webhook to Workspace → pick the channel → Allow. Copy the Webhook URL. A webhook posts to that one channel only.
3. Store the secret
The token, and the webhook URL, are credentials: whoever has one posts into your channels.
Store them like a password: never in a DAG file, a repository, a ticket, a chat, or a command
line (argv is visible to every user of the host in ps, and lands in shell history).
Getting it from the browser into a file without pasting it into a terminal or a chat: copy it in Slack, then on a Mac
mkdir -p ~/.config/rivet
(umask 077; pbpaste > ~/.config/rivet/slack_bot_token)
wc -c < ~/.config/rivet/slack_bot_token # a bot token is about 55-60 bytes; nothing is printed
(on Linux xclip -o -selection clipboard or wl-paste instead of pbpaste). The file is mode
0600 from the start. The steps below read it and never print it.
Where the Connection lives decides who else can read it. The reasoning, and the same choice for the database and warehouse Connections, is in Connections and secrets: recommended setup.
Recommended: a secrets backend (Google Secret Manager, AWS Secrets Manager, Vault). With
Airflow’s Secret Manager backend configured as in that section (connections_prefix: airflow-connections, sep: -), the conn_id slack_rivet is the secret
airflow-connections-slack_rivet:
jq -Rs '{conn_type: "slack", password: rtrimstr("\n")}' < ~/.config/rivet/slack_bot_token |
gcloud secrets create airflow-connections-slack_rivet --data-file=-
For a webhook: conn_type: "slackwebhook", the URL file instead of the token file.
Acceptable: the metadata database, with a Fernet key set ([core] fernet_key). Check that
there is one; this prints a length, not the key:
airflow config get-value core fernet_key | wc -c # more than 1
Without a key Airflow stores the token in clear text. Then either the UI (Admin →
Connections → +: Connection Id slack_rivet, Connection Type Slack API, the token in
Slack API Token; for a webhook Slack Incoming Webhook, the URL in Webhook URL or
Password), or a file only you can read:
(umask 077; jq -Rs '{slack_rivet: {conn_type: "slack", password: rtrimstr("\n")}}' \
< ~/.config/rivet/slack_bot_token > /tmp/slack_rivet.json)
airflow connections import /tmp/slack_rivet.json && rm /tmp/slack_rivet.json
Not airflow connections add --conn-password <token>: that puts the token in argv. In a
container, copy the JSON file in and run the import there.
Never in production: AIRFLOW_CONN_SLACK_RIVET in the environment, or the token in DAG code.
An environment variable is readable through docker inspect, /proc/<pid>/environ of every
Airflow process, compose files and deployment manifests.
The callback resolves the Connection on the worker, in the process of the task that failed, so the backend must be configured for the workers. On Airflow 3 a worker asks its own configured backends first and then the API server, which reads the metadata database and the API server’s backends.
4. Wire the callback
Put it in the DAG’s default_args; the builders merge it over their retries=2:
from airflow_provider_rivet.callbacks import slack_failure_callback
from airflow_provider_rivet.dags import build_batch_dag
dag = build_batch_dag(
"rivet_postgres",
config="/opt/rivet/configs/postgres.yaml",
state_dir="/opt/rivet/state",
exports=["users", "orders"],
default_args={"retries": 2, "on_failure_callback": slack_failure_callback("slack_rivet", channel="C0123ABCDEF")},
)
For a webhook, leave channel out: slack_failure_callback("slack_rivet_webhook"). Other keyword
arguments go to the Slack hook (timeout=, proxy=). An operator you build yourself takes the
same callback:
from airflow_provider_rivet.callbacks import slack_failure_callback
from airflow_provider_rivet.operators import RivetRunOperator
run = RivetRunOperator(
task_id="run_users",
config="/opt/rivet/configs/postgres.yaml",
export="users",
state_dir="/opt/rivet/state",
on_failure_callback=slack_failure_callback("slack_rivet", channel="C0123ABCDEF"),
)
The builders’ watcher task carries no failure callback, so a failed run sends one message per
failed task and nothing for the watcher.
Airflow 2.10 and 3.x behave the same for this callback: it runs in the failed task’s own process on the worker, after the task has failed for good, with the exception in its context. The differences are where the link points and what the log line looks like:
- The task-log link uses
[webserver] base_urlon Airflow 2 and[api] base_urlon Airflow 3. Unset, it points athttp://localhost:8080: set it to the address your users open. - An error in the callback is logged as
Error in callback at index 0: notifyon Airflow 2 andFailed to run task callbackon Airflow 3.
5. What arrives
Airflow calls on_failure_callback only when a task has failed for good: its last try failed,
or it failed in a way Airflow does not retry. A try that Airflow will retry sends nothing. So
every message is about a task that is failed now; the title says what kind of failure it is.
The error type is the rivet code with final or retryable (retryable only when Airflow runs another try); with several failed exports, the
code of the error that decided the task (the one the exception carries) and +N more; when the task died without a rivet result, the exception’s class
(AirflowTaskTimeout, …).
Final (a refusal, or a stop before rivet started): running it again changes nothing; fix what the code names. An export the config does not have:
:x: rivet_slack_test.apply.no_such_export — RIVET_AIRFLOW_EXPORT_UNKNOWN (final) run
manual__2026-10-16T10:57:40+00:00· task log
In its thread, one code block with the exception’s message (the task stopped before rivet ran):
[RIVET_AIRFLOW_EXPORT_UNKNOWN] config /opt/rivet/configs/postgres_batch.yaml has no export `no_such_export`
Retryable: the cause may go away by itself, and the retries ran out. Once it is fixed (here: the database is back), clear the task:
:x: rivet_slack_test.apply.users — RIVET_PLAN_SOURCE_UNREADABLE (retryable) run
manual__2026-10-16T10:57:40+00:00· task log
In its thread, rivet’s own error line for the step that failed (read from the end of that step’s stderr file on the worker):
[RIVET_PLAN_SOURCE_UNREADABLE] plan 'users': the source could not be read, so no plan was written (`rivet apply` would fail on it): nothing is listening on 127.0.0.1:1 — check the port in `url:` and that the server is up (driver: error connecting to server: Connection refused (os error 111))
The thread holds no Python traceback and no other stderr line: they are in the task log and in the stderr file, which the task log names.
What the thread can hold. Unlike XCom and the task log (Secrets), the thread
carries rivet’s error text, and that text can hold source values (a cell that failed to
convert). The callback passes it through Airflow’s secrets masker: every Connection password and
masked value the task saw becomes *** (rivet already removes credentials from its own error
text). A value from the data is not a secret Airflow knows: send alerts to a channel whose
members may read the source data. A short password is masked wherever its characters appear,
also inside words. The text is cut at 3,500 characters (3,000 through a webhook), ending in
… truncated, full log: <task log link>.
6. Test it with a DAG that fails on purpose
examples/rivet_slack_alerts.py defines two DAGs with no schedule that read no database and
write no file: rivet_slack_test_refused (an export the config does not have: final) and
rivet_slack_test_transient (a source on a port nobody listens on: a retryable code, final here). Both have
retries=0, so the alert comes on the first try and says final.
- Copy
examples/rivet_slack_alerts.pyandexamples/configs/into the DAGs folder (the DAG readsconfigs/postgres_batch.yamlnext to itself). - On the workers and the scheduler:
RIVET_EXAMPLE_STATE_DIR(an existing directory),RIVET_SLACK_CHANNEL(the channel id; leave it unset for a webhook) andRIVET_SLACK_CONN_IDif the conn_id is notslack_rivet. None of them is a secret. - Trigger both:
airflow dags unpause rivet_slack_test_refused && airflow dags trigger rivet_slack_test_refused
airflow dags unpause rivet_slack_test_transient && airflow dags trigger rivet_slack_test_transient
Within seconds each run fails, and the channel gets two titles,
rivet_slack_test_refused.apply.no_such_export — RIVET_AIRFLOW_EXPORT_UNKNOWN (final) and
rivet_slack_test_transient.apply.users — RIVET_PLAN_SOURCE_UNREADABLE (final), each with a
thread reply holding its error text (section 5). The failed task’s log says what was sent, after the failure:
Slack alert for rivet_slack_test_refused.apply.no_such_export posted to channel C0123ABCDEF (ts 1760612345.000100) through connection `slack_rivet`, its error text in the thread
(through a webhook:
Slack alert for ... sent through connection `slack_rivet_webhook`: HTTP 200 ok). Pause or
delete the two test DAGs when done.
7. Troubleshooting
Slack’s refusal is raised in the callback and Airflow logs it with the error name (step 4 says
which line). If neither that nor the Slack alert for ... line is in the failed task’s log, the
callback never ran: check that on_failure_callback reached the task (default_args of that
DAG, the DAG file the worker parsed).
| Slack says | Meaning | Fix |
|---|---|---|
not_in_channel | the bot is not a member of the channel | /invite @<app> in the channel |
channel_not_found | a channel name instead of its id, a typo, or a private channel the bot is not in | the C… id from About; invite the bot |
missing_scope (needed: chat:write) | the token lacks the scope | add it under Bot Token Scopes, then Reinstall to Workspace |
invalid_auth, not_authed, token_revoked, account_inactive | the Connection’s token is wrong, empty, or revoked (an app removed or reinstalled elsewhere) | copy the current Bot User OAuth Token into the Connection again |
The conn_id `...` isn't defined | no backend the worker reads has that Connection | step 3, for the workers |
webhook 404 no_service | the webhook was removed, or the app uninstalled | a new webhook URL (step 2) |
webhook 403 invalid_token / action_prohibited | the webhook belongs to a revoked app, or an admin restricted posting | a new webhook URL; ask the workspace admin |
webhook 404 channel_not_found / 410 channel_is_archived | the webhook’s channel was deleted or archived | a new webhook for a live channel |
| a timeout, a proxy or DNS error | the worker cannot reach slack.com / hooks.slack.com | open egress to them, or pass proxy= |
Recipe: a MySQL CDC stream from cron to Airflow
How to move a rivet MySQL CDC stream that cron runs today (a config, its .rivet_state.db and its checkpoint file
in one folder) to an Airflow DAG with PostgreSQL state, one stream per source database. The stream continues from
the binlog position cron stopped at: no new baseline, and only the changes made after cron stopped are loaded.
Proven on Airflow 2.10.2 with CeleryExecutor and one worker (the official docker-compose file), rivet-cli 0.32.2
and airflow-provider-rivet 0.2.0 from PyPI, with configs and states written by rivet 0.32.1 and 0.30.0 (state schema
v31). The steps below were run as written on synthetic data, including the way back and a second source. Values read
back from BigQuery with bq matched the source, and no change arrived twice.
The layout, per source
Every source database is its own stream with its own names. For a source shop:
| What | Name | Example |
|---|---|---|
Airflow Connection to MySQL (type mysql) | rivet_<src> | rivet_shop |
| rivet state database | rivet_state_<src> | rivet_state_shop |
Airflow Connection to it (type postgres) | rivet_state_<src> | rivet_state_shop |
| rivet config | dags/rivet/<src>.yaml | dags/rivet/shop.yaml |
state_dir | /opt/airflow/rivet-state/<src> | /opt/airflow/rivet-state/shop |
| BigQuery dataset | one per source | shop |
| DAG | rivet_<src>_cdc | rivet_shop_cdc |
Why each one is separate:
- The checkpoint file is one server’s binlog position for one stream. rivet 0.32.2 writes
<file>.ckpt.ownerbeside it and refuses a second config on it (RIVET_SOURCE_CDC_CHECKPOINT_SHARED). - The state database:
rivet state copywrites only into an empty database, so each cron.rivet_state.dbneeds its own. server_idis the stream’s MySQL replica id; two streams on one MySQL server with oneserver_idknock each other off.- The bucket prefix: two configs in one prefix mix their files.
- The warehouse dataset:
ordersof two sources would be one table, and the second source’s load is refused (RIVET_LOAD_TARGET_NOT_RIVETS).
Before you start
- A PostgreSQL for the state, apart from Airflow’s metadata database, e.g. a
postgres:16service with its own volume in the compose file and no published port. Create one database per source in it. - The state directory,
./rivet-stateon the host, bind-mounted at/opt/airflow/rivet-statein every Airflow service and owned by the Airflow user. The CDC checkpoint lives here, not in PostgreSQL: if this directory is lost, the stream loses its position. Back it up together with the state database’s volume. rivet-cliandairflow-provider-rivetin the image (see Install). Check withdocker compose exec airflow-worker rivet --version.- Google credentials. The operator passes nothing from the worker’s environment to rivet except a short
allow-list (Connections and secrets). A key file named by
GOOGLE_APPLICATION_CREDENTIALSin the compose environment reaches rivet only withcloud_credentials=["gcp"]on the tasks. - MySQL:
binlog_format=ROW,binlog_row_image=FULL,binlog_row_metadata=FULL(otherwiseRIVET_SOURCE_CDC_PREREQUISITE), and the grantsREPLICATION SLAVE,REPLICATION CLIENT,SELECT.
The commands below run in the compose project folder, in bash. The compose file passes RIVET_STATE_USER and
RIVET_STATE_PASSWORD from .env into the Airflow services’ environment (steps 4 and 6 use them inside the worker):
DC="docker compose --env-file .env"
name=shop
env_value() { grep "^$1=" .env | cut -d= -f2-; }
AIRFLOW_UID=$(env_value AIRFLOW_UID) # the compose file's value, not the shell's
1. Connections and the state database
$DC exec -T rivet-state createdb -U "$(env_value RIVET_STATE_USER)" "rivet_state_$name"
read -rs MYSQL_PASSWORD && export MYSQL_PASSWORD # typed, not on any command line
$DC exec -T -e MYSQL_PASSWORD airflow-worker bash -c "airflow connections add rivet_$name \
--conn-type mysql --conn-host db1.internal --conn-port 3306 --conn-schema $name \
--conn-login rivet --conn-password \"\$MYSQL_PASSWORD\""
$DC exec -T airflow-worker bash -c "airflow connections add rivet_state_$name \
--conn-type postgres --conn-host rivet-state --conn-port 5432 --conn-schema rivet_state_$name \
--conn-login \"\$RIVET_STATE_USER\" --conn-password \"\$RIVET_STATE_PASSWORD\" \
--conn-extra '{\"rivet_params\": \"sslmode=disable\"}'"
mkdir -p "rivet-state/$name" && sudo chown -R "${AIRFLOW_UID}:0" "rivet-state/$name"
- Spell the MySQL host exactly as the cron config does. rivet keys its state by export name and source
host:port/database:127.0.0.1and the server’s DNS name are two sources. A CDC stream still continues, because its position is in the checkpoint file. An incremental export, however, finds no cursor and silently re-reads its table in full: exit 0, duplicate rows at the destination (rivet#690). sslmode=disableis for a state server reached only over the compose network. rivet refuses a state URL to another host that names nosslmode(RIVET_STATE_URL_TLS_REQUIRED).- A Connection with the same id in a secrets backend wins over these: Airflow asks the backend first.
--conn-schemais the MySQL database; here it has the source’s name.
2. Stop cron, and find its folder and config
Comment out the rivet line in the crontab and wait until pgrep -x rivet prints nothing. If cron and Airflow both
ran the stream, each would read the binlog from the same position and every change would arrive twice.
The commented line names the two things the next steps need: the folder cron runs rivet in and the config it passes. Set them in the shell you run the rest of the steps in:
crontab -l | grep rivet
# e.g. # 0 */2 * * * cd /srv/elt/shop && rivet run -c cdc.yaml
CRON_DIR=/srv/elt/shop # the folder after `cd`
CONFIG=cdc.yaml # the file after `-c` / `--config`
ls -la "$CRON_DIR" # $CONFIG, .rivet_state.db and the checkpoint's folder (cdc/)
grep -nE 'url_env|url:|^[[:space:]]+checkpoint:|server_id:' "$CRON_DIR/$CONFIG"
With no cd and a full path after -c, CRON_DIR is that file’s folder and CONFIG its name. If the line runs a
script, the script holds both. No .rivet_state.db beside the config means the state lives elsewhere
(RIVET_STATE_URL in cron’s environment): this recipe does not cover that case.
Check the host now. If the config says url_env: <VAR>, the MySQL address is not in the config but in cron’s
environment: find <VAR> in the crontab line or the script it runs, and read its host:port/database. Compare it with
the Connection from step 1 (this prints no password):
$DC exec -T airflow-worker python -c "from airflow.hooks.base import BaseHook; c = BaseHook.get_connection('rivet_$name'); print(f'{c.host}:{c.port or 3306}/{c.schema}')" | tail -n 1
If the spelling differs, edit the Connection, not the cron config (step 1 explains why it matters).
3. Copy the cron folder
mkdir -p rivet-state/migration-src
cp -a "$CRON_DIR" "rivet-state/migration-src/$name"
sudo chown -R "${AIRFLOW_UID}:0" rivet-state/migration-src
Work on the copy. rivet 0.32.2 run on the original folder (even rivet check) upgrades its SQLite schema in place and
keeps the old file as .rivet_state.db.v31…. The untouched original is the way back.
4. Move the state, the checkpoint and the config
cfg=/opt/airflow/rivet-state/migration-src/$name/$CONFIG
$DC exec -T airflow-worker bash -c "RIVET_STATE_URL=\"postgresql://\$RIVET_STATE_USER:\$RIVET_STATE_PASSWORD@rivet-state:5432/rivet_state_$name?sslmode=disable\" \
rivet state copy -c $cfg"
This reads the .rivet_state.db beside the config and copies every table into the empty database in one transaction,
checking each table’s row count. The SQLite file is only read. It prints copied N table(s), M row(s) ….
RIVET_STATE_USER/_PASSWORD must be in the worker’s environment for this line.
The checkpoint goes into state_dir at the config’s own relative cdc.checkpoint path. The operator runs rivet on
a copy of the config in state_dir, so a relative path resolves there:
grep -nE '^[[:space:]]+checkpoint:' "rivet-state/migration-src/$name/$CONFIG" # e.g. checkpoint: ./cdc/cdc.ckpt
mkdir -p "rivet-state/$name/cdc"
cp -a "rivet-state/migration-src/$name/cdc/cdc.ckpt" "rivet-state/$name/cdc/" # the file name the grep printed
sudo chown -R "${AIRFLOW_UID}:0" "rivet-state/$name"
An absolute checkpoint: (a path on the cron machine) does not exist in the container. Make it relative in the copy.
The config goes to dags/rivet/$name.yaml, unchanged except the source variable, which the DAG maps from the
Connection:
mkdir -p dags/rivet
sed -E 's/^([[:space:]]*)url_env:.*/\1url_env: RIVET_MYSQL_URL/' "rivet-state/migration-src/$name/$CONFIG" > "dags/rivet/$name.yaml"
Never put the config inside rivet-state/, and keep no cdc/ beside it in dags/rivet/: the checkpoint lives only
in state_dir.
5. The DAG
examples/rivet_cdc_per_source.py builds one DAG per source. It reads the
mode: cdc export’s name and tables from dags/rivet/<src>.yaml and wires state_dir, the two Connections and
cloud_credentials=["gcp"] by the layout above. Copy it into dags/, then list the sources (RIVET_EXAMPLE_SOURCES,
or edit SOURCES) and set the schedule to cron’s. The scheduler and the worker read RIVET_EXAMPLE_SOURCES when
they parse the file: after changing it in .env, run $DC up -d so they see it.
List only the sources that already have dags/rivet/<src>.yaml, each once. The source name is the key every other
name hangs on (Connections, state database, state_dir), so a missing config is fixed by moving or generating it,
never by renaming another source’s file. The example refuses both mistakes at parse, and list-import-errors below
shows why: no config for <src> … or sources listed twice: <src>. A source cron never ran joins the list after its
config is generated (below).
A new DAG file is picked up by the scheduler within dag_dir_list_interval (5 minutes by default). airflow dags list and airflow tasks list parse the files themselves and show the DAG earlier, so they are no evidence that the
scheduler has it. Check the tasks, then unpause, and repeat the unpause until it prints rivet_<src>_cdc | False.
Before that it prints No paused DAGs were found and does nothing:
$DC exec -T airflow-scheduler airflow tasks list "rivet_${name}_cdc" # run, load.*, compact.*, watcher
$DC exec -T airflow-scheduler airflow dags unpause "rivet_${name}_cdc" # until: rivet_<src>_cdc | False
$DC exec -T airflow-scheduler airflow dags list-import-errors # then: No data found
6. The first run
Unpause one DAG at a time (step 5). Unpausing starts the latest interval at once, so do not also press Trigger.
When it has finished:
-
The tasks are green and
watcheris skipped. That is normal: it runs nothing and fails the run only when another task failed. Therunlog line readsrivet run cdc → OK: <n> rows, <k> files …, counting the change rows since cron stopped. An UPDATE that moves a row to another partition of itsload:table is written as a delete and an insert, so it counts as two rows. -
No new baseline. In rivet’s run journal, the runs that started after cron stopped are of the CDC export, with no
…__snapshot_…run. Cron’s own baseline, which is older, may still be in the list:$DC exec -T airflow-worker bash -c "RIVET_STATE_URL=\"postgresql://\$RIVET_STATE_USER:\$RIVET_STATE_PASSWORD@rivet-state:5432/rivet_state_$name?sslmode=disable\" \ rivet state runs -c /opt/airflow/dags/rivet/$name.yaml --last 5"With
cleanup_source: true(whatrivet initwrites) the bucket’ssnapshot/files are gone after a load, so the bucket is no evidence. -
BigQuery holds the changes made after cron stopped: a changed row has its new value, and a deleted row has
__is_deleted = true. -
A run with no new changes reports
OK: 0 rows, 0 files, andload.*/compact.*areSKIPPED: nothing to do.
When every stream has passed its first run, delete rivet-state/migration-src/.
When the checkpoint is in the wrong place
Both cases were measured, and in both nothing is written:
| Where the checkpoint is | What happens | What to do |
|---|---|---|
Beside the config (dags/rivet/cdc/) and not in state_dir | the task stops before rivet starts: RIVET_AIRFLOW_CHECKPOINT_BESIDE_CONFIG, naming where to move it | move it into state_dir |
| Missing or empty | RIVET_SOURCE_CDC_CHECKPOINT_INVALID: the state knows the stream ran before | put the file back and run again; do not re-baseline as the message offers |
A source cron never ran
Run step 1 with name=<src> (its state database, both Connections, its state_dir). Then generate its config
inside the worker, with the state in the source’s own database (so that init records its keys where the DAG’s runs
read them) and a BigQuery dataset of its own:
read -rs RIVET_MYSQL_URL && export RIVET_MYSQL_URL # mysql://user:password@db1.internal:3306/<database>
$DC exec -T -e RIVET_MYSQL_URL airflow-worker bash -c "cd /opt/airflow/dags/rivet && \
RIVET_STATE_URL=\"postgresql://\$RIVET_STATE_USER:\$RIVET_STATE_PASSWORD@rivet-state:5432/rivet_state_$name?sslmode=disable\" \
rivet init --source-env RIVET_MYSQL_URL --mode cdc --include orders customers --tls disable \
--gcs-bucket <bucket> --bigquery-project <project> --bigquery-dataset $name -o $name.yaml"
--tls disable writes tls: { mode: disable } in source:, for a MySQL reached without TLS; drop it for one with TLS.
init names everything after the -o file: the checkpoint ./cdc/<src>_cdc.ckpt, the stream’s prefix <src>/cdc/
and the server_id, so two sources on one server do not collide. Review the load: block, then add the source to the
DAG’s sources (step 5). Its first run reads the baseline: every captured table in full from the source, so unpause
it in a quiet hour on a busy server.
The way back
- Before the first DAG run: pause the DAG and uncomment the crontab line. cron continues from its original folder, which these steps did not touch.
- After it: the binlog position has moved on in
rivet-state/<src>/cdc/, and the cron folder’s checkpoint is behind. Do not just re-enable cron: it would read again from where it stopped, and the changes Airflow already loaded would arrive a second time. Pause the DAG, then copy the current checkpoint over the cron folder’s (rivet-state/<src>/cdc/<file>.ckpt→<cron folder>/cdc/<file>.ckpt) before re-enabling cron. A CDC stream on its old SQLite state with the current checkpoint was measured to continue with no gap and no duplicate. An incremental export, by contrast, re-reads from the SQLite cursor everything exported since the copy; the load deduplicates it by key. - rivet 0.32.1 or earlier on cron: once another database on the same MySQL server holds a table with a name the
stream captures (for example after “A source cron never ran” adds one), every cron run stops with
RIVET_SOURCE_CDC_TABLE_UNRESOLVED. rivet 0.32.2 reads only the connection’s database. Upgrade cron’s rivet to 0.32.2 before re-enabling it (it upgrades the folder’s SQLite in place and keeps the old file), or qualify the tables (shop.orders) in the cron config.
Capabilities
What the package does today when the rivet it runs (0.32.2 or newer) lacks a member of the scheduler contract.
Works today / needs a newer rivet
ADR-0039 describes several things no released binary emits yet. The package reads what rivet’s
output holds and takes a recorded fallback for the rest: every task’s XCom carries
degraded: [<key>, ...]; the task log names each key in words, and the rivet.result record at
DEBUG carries the list. Nothing is guessed without a key.
How it detects. An output member (class, failures[], stop_reason) is detected by its
presence in the output itself. The version is used for one thing only: the minimum-version refusal
(rivet 0.32.2; every flag the package passes exists on every subcommand it passes it to there, so
no flag is probed).
“Needs” names the ADR-0039 section; none of it is in a released rivet at this package’s date.
| Key | Missing in rivet 0.32.2 | What the package does today | Needs (ADR-0039) |
|---|---|---|---|
per_unit_error | failures[] and per_export[].error | when several units of one process failed, each carries the process-level object | D2/D3, rivet >= unreleased |
stop_reason | CDC stop_reason and tables[] | stop_reason is null: a max_events stop cannot be told from caught_up | D4, rivet >= unreleased |
Five more keys record something the worker or one output lacks, not the binary’s version:
| Key | What is missing | What the package does |
|---|---|---|
stderr_temp | a state directory or stderr_dir on the worker | writes rivet’s stdout and stderr to a private per-user directory under the temp directory (see Secrets); a pod loses them with its disk |
crashed_ledger | a readable and writable crashed-budget ledger | without a state directory: a crash is retried only within the first crashed_retries tries of the task instance; with a ledger that cannot be read or written: no crash retry at all |
result_malformed | an error object or a result entry with the contract’s keys and types; also a stderr line that starts with { and is not JSON, or a last stderr line longer than the 1 MiB read, or a summary file of an exit-0 process that is not a JSON object | a malformed error object is ignored and the task is classified by the exit-code table; a value of the wrong type is null; a status outside the contract’s words counts as failed |
result_missing | the --summary-output file of a process that exited 0 | rivet could not write it (it only warns); the units are built as if the binary had no summary flag: one unit per requested export or table, status from the exit |
exit_zero_failed_unit | a non-zero exit when the summary reports a failed unit | the task fails, classified by the worst failed unit (data_integrity > internal > refusal > schema_drift > retryable > generic, ADR-0039 D2) |
Not detectable, so not recorded per task:
- A child process killed by a signal is not reported as
crashedby today’s binary: the parent exits 1 (or 2, by a text match) and the task follows that exit. A kill of the rivet process the operator started is seen directly and iscrashedtoday. - There is no
RIVET_STATE_FOREIGNrefusal yet. The package’s own marker check (below) is the only guard against a wrong state directory. - rivet does not yet warn about a relative
cdc.checkpointunder PostgreSQL state.
The list lives in one place in the code, airflow_provider_rivet/capabilities.py
(DEGRADATIONS), and a test fails when a key has no row in this table.
Overlap and known limits
How runs of one export are kept apart, and what the package cannot see.
Overlap
Two runs of the same export must not overlap. rivet’s lease (--lock-wait, default 600 s: the
second run waits) is not released yet. Until then the builders set max_active_runs=1 on the
DAG and max_active_tis_per_dag=1 on every rivet task. This does not protect against a run
started outside Airflow (cron, a shell), nor against a second DAG over the same export.
Airflow does not stop two tries of one task from running at once: a zombie try (its worker lost,
the task still running) and its retry, or a rivet left running by a task process that was killed
(the scheduler counts task instances, and the dead try’s is already failed). With a state
directory every task but plan holds an exclusive lock file while it runs rivet: one per export
for run, apply and cdc_run (a run of the whole config takes the lock of every export the config has, in one
sorted order, so it and a run of one of its exports wait for each other); one per table for load and compact with
--table, else one per export. A lock is named by the export, not the config: two configs that share a state directory
and an export name share its lock (they wait for each other; rivet’s own lease, keyed by export and source, is the
exact one). The lock’s descriptor is passed to every rivet process the task starts, so a rivet keeps the lock
while the task process lives, and when the task process is killed outright, until that rivet exits. A task that ends
normally releases the lock by an explicit unlock even if a process rivet left behind (a grandchild that outlived its
parent) still holds a copy of the descriptor; that process then runs without the lock, and only rivet’s own lease
protects the export from a second holder (measured with a grandchild that kept the descriptor). A task that finds the lock held waits up to
lock_wait seconds for each lock it needs, then starts no rivet and ends retryable (RIVET_AIRFLOW_EXPORT_BUSY; a run of
the whole config takes one lock per export in turn, so it can wait up to the number of its exports times lock_wait before it
gives up; the waiting is logged when it starts, waiting up to <lock_wait> s for the lock of ..., record rivet.lock.wait). The task releases the lock by an explicit unlock once its
rivet has exited.
On Linux each rivet process gets SIGTERM when the task process that started it dies
(PR_SET_PDEATHSIG), so a task runner killed outright (OOM, SIGKILL) no longer leaves rivet
running beside its retry. Where that cannot fire (not Linux; the signal is tied to the thread that
started rivet; a rivet that does not stop on SIGTERM) the lock above still keeps a retry from
starting a second rivet until the first has exited.
Without a state directory (a pod) there is no lock file. Only rivet’s own lease protects the
export: rivet (>= 0.32.2) refuses the second holder with RIVET_STATE_RUN_IN_PROGRESS /
RIVET_LOAD_TABLE_BUSY (both kind busy, exit 2), which the task retries (Retries); a plain mode: full run takes the
run lease too (measured on 0.32.0).
Known limits
- The Kubernetes mode has unit tests only (no pod was run).
- This package’s tests run
loadandcompactonly through the fake binary, which replays rivet’s output and talks to no warehouse. A live run against BigQuery, Snowflake and ClickHouse exists only as the warehouse leg of the live gate (python -m gate --warehouses ..., see “Live gate”), which reads each warehouse back through a second client and compares it with the source. - A failure callback runs where Airflow runs task callbacks, in the task’s process on the worker; exercised live on Airflow 2.10.5 and 3.3.2 by hand (docs/slack.md), not by the live gate.
Development
Running the tests, mutation testing and the live gate.
Development
git clone https://github.com/rivet-lab/rivet ../rivet # the contract fixtures the tests read
uv sync # latest Airflow 3 from uv.lock, plus pytest
uv run pytest -q
The tests read rivet’s scheduler contract fixtures (tests/fixtures/scheduler/) and
src/config/export.rs and src/cli/args.rs (every flag the fake rivet of tests/fake_rivet.py accepts is one
rivet defines; any other is refused with exit 2, as clap refuses it) from a rivet checkout: ../rivet by default, or
the path in RIVET_SRC.
CI checks rivet out at the commit in RIVET_CONTRACT_REF and runs the suite on Airflow 2.10 and
3.x under Airflow’s constraints files.
The tests need no rivet binary and no running Airflow: a fake rivet script replays each
scenario (and enforces rivet’s own query_file rule, tied to the Rust source by a test).
tests/test_dag_runs.py runs the builders’ DAGs through dag.test() against a SQLite metadata
database created in a throwaway AIRFLOW_HOME, with real task instances and trigger rules.
Mutation testing
mutmut 3.8 mutates airflow_provider_rivet/ only (never tests/, gate/ or
examples/) and runs, for each mutant, the tests that cover the mutated function. Run it in Linux, never on the
Mac’s own Python: mutmut forks a worker per mutant, and macOS aborts a forked child of a multithreaded process that
loads an Objective-C class (psutil, under Airflow’s import), so there a mutant’s verdict is the crash, not its tests.
dev/mutants.sh runs it in a Linux container (Docker), as the calling user, which also runs the Linux-only
PR_SET_PDEATHSIG test of tests/test_retry.py (in Linux the two case- and Unicode-folding file-system tests of
tests/test_operators.py skip instead):
make mutants # dev/mutants.sh mutmut run, then the survivors; resumable (mutants/)
make mutants-results # the survivors, timeouts and other non-killed mutants of the last run
dev/mutants.sh mutmut show <mutant name> # the diff of one mutant
dev/mutants.sh python dev/mutants_gate.py pr # what the PR job runs: the mutants of the functions your branch touches
RIVET_SRC applies as for pytest. The configuration is [tool.mutmut] in pyproject.toml. Workers fork from a
server that only collected the tests (process_isolation = "forkserver"), and dev/mutmut_isolation.py gives each
worker its own Airflow metadata database, dags folder and pytest base temp: on one shared SQLite file the
airflow_db fixture’s resetdb of one worker would kill another worker’s DAG runs and count its mutant as
detected. It also caps each worker’s memory (a mutant can loop while growing a list, and on a CI runner the OOM
killer then takes the runner), hands the mutated tree to the child Pythons of tests/test_retry.py and
tests/test_process_io.py (the task processes those tests kill), and has mutmut select those tests for every
mutant, since a child’s calls are invisible to mutmut’s test selection. A timeout is not a detection: a cluster of
timeouts in one function is a finding about its loop or wait.
mutmut does not mutate a decorated function (Outcome.decision, _prctl, _export_lock): their behaviour is
held by tests alone.
When mutants run (.github/workflows/mutation.yml, on Linux, through dev/mutants_gate.py mode):
| change | what runs | fails when |
|---|---|---|
a pull request changes airflow_provider_rivet/ code | the mutants of every function it touches | one that mutates a line the pull request changed is not killed (the other survivors of those functions are listed, not failed) |
| a pull request changes only tests, docs or the harness | nothing | — |
| on demand (workflow_dispatch) | the full run | as above |
There is no full run on push to main and no nightly run. Every run is split into ten parallel shards (the mutants
whose number ends in 0 … 9). Each shard prints shard N: M of TOTAL mutants, its progress as shard N: done/M and
shard N: tested T, killed K, not killed S. The ratchet job prints the per-shard table and fails unless the shards
graded every mutant exactly once (sum(tested) == total) and survivors N <= ratchet M. A survivor of a function
every test passes through (_Session.step) runs the whole suite, so one runner would need most of a day.
Moving the ratchet: it changes only through a full run on demand.
.mutmut-survivors lists the survivors of that run by name (the ratchet job uploads it as mutmut-survivors); the
two are committed together.
Lowering it (after tests kill survivors) is an ordinary PR; raising it needs a dated comment line in that file saying
which mutants are accepted and why.
Live gate
gate/ runs this provider and a rivet Linux binary in real Airflow 2.10.5 and 3.3.2 stacks (the official
compose files, Celery) and grades the result with oracles, never with rivet’s own report:
uv run --only-group gate python -m gate --rivet-bin /path/to/linux/rivet # both Airflow versions
uv run --only-group gate python -m gate --rivet-bin ./rivet --airflow 3.3.2 --keep # one stack, left up
uv run --only-group gate python -m pytest -q gate/tests # the oracles, RED on every mutant
Per stack: four DAGs (incremental batch and CDC with initial: snapshot, each on a shared SQLite state and on
a TLS PostgreSQL state), three cycles (initial load, a delta of inserts / updates / deletes, an idle run). The
SQLite CDC run pauses at cdc_after_open and the SQLite batch run must finish inside that window, so the two
writers on one SQLite file overlap on every cycle. Oracles: DuckDB over the Parquet against the source read by
DuckDB’s postgres scanner (delta == source rows past the previous high-water; newest version per key == source;
CDC snapshot + changes replayed by __seq == source; exact operation counts), the stored cursor read by a plain
SQLite / psql client, and the Airflow REST API (run and task states, XCom rows == rows in the files).
--sabotage drop-delta-file must turn it red. Each stack is torn down with its volumes before and after; the
compose project and the image carry the run tag (--tag, default %m%d%H%M + 4 hex), so two runs never share one.
Options: --rivet-bin (required), --airflow (comma-separated versions, default both), --work (working
directory, default a fresh temporary one), --verdicts <file> (one JSON line per graded cell), --keep,
--sabotage drop-delta-file or warehouse-value, --tag (the run tag), --destinations s3 (below), --workers 2
(the multi-host leg below), --state compose-postgres, --migrate-from <rivet 0.32.1> and --client-override <dir>
(the client stack, below).
Known reds. A cell red by a confirmed product defect is listed in gate/scenario.py KNOWN with its issue: it
grades XFAIL (counted apart, the run still passes) while red and XPASS once it passes, which fails the run until the
entry is removed. Only a defect with an issue and a planned fix goes there; anything else stays a FAIL.
Multi-host leg. --workers 2 runs, instead of the scenario above, a stack with two Celery workers, each a host
with a disk of its own (hosts/a and hosts/b of the stack’s directory, each mounted at /opt/rivet-host in one
worker only): every state_dir (the config copy, sealed plans, locks, crashed ledger, logs, marker) is on the host
that ran the task. rivet’s state is the stack’s TLS PostgreSQL (RIVET_STATE_URL from the rivet_gate_state
Connection; the CDC config’s from rivet_gate_state_mh_cdc, since init names its baseline exports after the tables,
as the batch ones), and the files go to GCS, which both hosts reach: each config is the one rivet init writes against
the live source (--mode incremental / --mode cdc, --include the two tables, --gcs-bucket a bucket of the run’s
own, rivet-afgate-<tag>-<stack>-mh*-batch|cdc), used as written, with the gate_gcp Connection (--gcp-keyfile,
--bq-project, --bq-location as in the warehouse leg). Every task names a queue (gate_a, gate_b, gate_cdc)
and the gate moves each queue to one worker per cycle with Celery’s add_consumer / cancel_consumer, so the two
extracts of one batch run land on both hosts and every export and the stream change host between cycles; each try’s
hostname from the REST API proves it (.../hosts). Four cycles (initial, delta, idle, and retry: a delta whose
orders extract pauses at pg_after_snapshot_open on host a, is SIGKILLed there, and is retried on host b, where its
sealed plan is not). Oracles, reading the buckets through gcloud storage and the source through DuckDB: the batch
delta and latest-version cells of the base scenario, each (id, cursor) version written once across both hosts
(each-version-once), the stored cursor (psql) equal to the source high-water and never moved back
(cursor-not-regressed), XCom rows == file rows; for the stream: the baseline once, each event (__pos, __seq) once,
replay == source, exact operation counts. multihost/budget kills the paused extract on a and its retry on b:
crashed_retries=1 must not grant the second crash (it does today: each host keeps its own crashed ledger).
multihost/chain/load-on-other-host: an extract on a and its load on b, on PostgreSQL state, must run rivet rather than
be refused for the other host’s state_dir marker. Printed as MEASURE lines, not graded: the same batch config on
SQLite state in each host’s state_dir, and init’s default local ./output/ destination (which lands in the state_dir)
on PostgreSQL state. The cleanup deletes the buckets and looks again.
Warehouse leg. --warehouses bigquery,snowflake,clickhouse (any subset) also extracts to GCS and runs
load and compact into those warehouses from Airflow Connections (connections=). It needs a GCP credential
(--gcp-keyfile, default the gcloud application-default credentials), the bucket --gcs-bucket, the BigQuery
--bq-project and --bq-location, the bq, gcloud and snow CLIs on the host (ClickHouse runs inside the
stack), and for Snowflake a local snow connection (--sf-connection) whose login the gate’s Connection copies,
--sf-warehouse, --sf-database and the storage integration --sf-integration (a role that cannot create
schemas needs the run’s AFGATE_<TAG>_<stack> schema made beforehand: pass --tag). Each warehouse is read back by a
client the loader does not use (google-cloud-bigquery, snowflake-connector-python with the key of the local snow
connection, ClickHouse over HTTP as JSON), every value is brought to one form (integer, integer cents, epoch
microseconds, text) and compared with the source: the batch current state equals the source with exactly the keys the
cycle deleted left over (an incremental extract cannot see a delete); the CDC current state without the rows flagged
__is_deleted equals the source; the BigQuery batch buffer <table>__changes is gone after compact, which only
that DAG may not skip, on the delta cycle (the first load creates the base from its pass, rivet #652, and the idle load
buffers nothing, so there a skip is right). --sabotage warehouse-value adds a cent to one BigQuery row after the delta load and must turn
it red. The cleanup lists the dataset, schema and GCS prefix again and fails on anything left; the sweep of runs older
than a day drops only names of the gate’s own shape.
Source legs. --sources mysql (needs --warehouses with bigquery) adds another source engine beside the
postgres one: a MySQL 8.4 container in the stack (row binlog with binlog_row_metadata=FULL, GTIDs, utf8mb4) with
the same tables in MySQL types (DATETIME(6) and TIMESTAMP(6) cursors, DECIMAL(12,2), Cyrillic text), the same
three cycles, and two DAGs: incremental batch and one CDC stream, each extracted to GCS and loaded and compacted into
BigQuery from the rivet_gate_mysql and gate_gcp Connections. Every rivet config of the leg is the one
rivet init writes against the live source inside the stack (--mode incremental / --mode cdc, --gcs-bucket,
--bigquery-project, --bigquery-dataset, --include with the scenario’s tables), used as written: init’s prefixes are fixed (exports/<table>/ for a batch export and for the recipes beside a MySQL stream),
so the gate gives each config a bucket of the run’s own (rivet-afgate-<tag>-<stack>-<engine>-<batch|cdc>: two configs
in one bucket would list each other’s runs), and since init names the batch exports after their tables, the batch and CDC loads get a dataset each; the export and stream names the DAGs
run are read from what init wrote. Each config has a TLS PostgreSQL state database of its own in the stack
(RIVET_STATE_URL, the rivet_gate_state_<engine>_<batch|cdc> Connection) that init and its DAGs share, so the primary
keys init records are the ones the runs read, nothing is left beside the config (the leg fails if init leaves a
.rivet_state.db there), and the two configs do not share their progress. init derives a MySQL stream’s replica id from
the -o file’s stem. --sources mssql is the same leg on SQL Server 2022 (linux/amd64,
SQL Server Agent on for the CDC capture job, READ_COMMITTED_SNAPSHOT on as rivet asks of an incremental read; init
with --tls require, SQL Server encrypts every login): DATETIME2(7)
cursors, a DATETIMEOFFSET(7) at a non-UTC offset, DECIMAL(12,2), Cyrillic NVARCHAR, UNIQUEIDENTIFIER and
VARBINARY. SQL Server captures per table, so its init writes one CDC export per table and the leg runs one CDC DAG
each (gate_src_mssql_cdc_<export>), loaded into the folded dbo_<table>; one table’s capture instance has a non-default name (gate_orders_v2), which init must read from
cdc.change_tables, and the changes wait for the
capture job before a CDC run reads. Both engines run with --sources mysql,mssql. Oracles: each compacted BigQuery
base, read by google-cloud-bigquery, equals the source value by value (read by DuckDB’s mysql scanner, or as FOR JSON
through sqlcmd, an instant cut to the microseconds rivet keeps; batch: with exactly the keys the cycle deleted left
over; CDC: without the rows flagged __is_deleted), and no __changes buffer is left. The cleanup deletes both buckets
and both datasets and looks again; the sweep drops gate-shaped buckets older than a day.
The MySQL client stack (MySQL → GCS → BigQuery, --warehouses bigquery --sources mysql) adds, on init’s configs as
written: initial/mysql/<batch|cdc>/load-block-as-written (init’s load: block is BigQuery, layout: base_buffer,
cleanup_source: true); for every rivet task of each cycle (run, apply.*, load.*, compact.*), its XCom unit
(decision success, every unit done, the rows the gate made: a CDC run the cycle’s change events, plus the baseline
on the first; a CDC load its table’s; a batch extract or load the source rows past the previous high-water) and its task
log (the rivet … → headline says OK, or SKIPPED where every unit skipped, with the XCom’s rows):
<cycle>/<dag>/<task>/xcom-unit|task-log; and <cycle>/mysql/<kind>/staged-parts-cleaned (no Parquet left in the
bucket once loaded). After the cycles, a column added while the CDC run is open (rivet #665): hot-ddl-open runs the
stream in gate_src_mysql_cdc_hot (the same config, export and state, paused 45 s at cdc_after_open); inside the pause
the gate reads the source (the run’s read bound), runs ALTER TABLE gate_orders ADD COLUMN note VARCHAR(40) NULL and
writes rows that use it (alter-inside-the-open-run fails if the pause ended first). init’s stream is bounded
(until_current: true), so that run delivers the writes before the ALTER, compared with the source as read in the
window; hot-ddl-after runs the stream and the batch export again: the CDC base equals the source value by value with
note (rows nobody changed after the ALTER read NULL, as at the source; note-reached fails when the source holds no
value of it), the batch base, whose query: init wrote with the columns of its day, equals the source on those. Then a
second CDC config on the first stream’s checkpoint (rivet #664): init writes it in a directory of its own (so no sibling
names its checkpoint), and its DAG (gate_src_mysql_cdc_shared) runs in the first stream’s state_dir, where the
operator’s copies of both configs resolve init’s relative cdc.checkpoint to one file (one-checkpoint). Its run must
stop on RIVET_SOURCE_CDC_CHECKPOINT_SHARED, exit 5, on Airflow’s first try, nothing after it running
(shared-checkpoint/mysql/cdc/refused-by-code; when init refuses the config instead, that cell is init’s
RIVET_INIT_CDC_NAME_TAKEN, exit 5, nothing written). shared-checkpoint-after then runs the first stream over three
more updates: its base equals the source value by value and its tasks moved those three rows. Last, git-sync: from the
first cycle on, the stream’s DAGs read init’s config, unchanged, through a git-sync checkout
(configs/mysql_cdc_sync/repo -> rev-A, the DAG’s config= the path under repo/). After the other phases the gate
publishes a new revision as git-sync does (the config copied unchanged into rev-B, a new link renamed over repo,
rev-A removed), makes three updates and runs the stream: git-sync/mysql/cdc/run-after-flip (the run and its tasks
succeed and the run moved those rows) and git-sync/mysql/cdc/current-equals-source (every table’s base equals the
source value by value). The config’s copy in the state_dir must not change its name with the revision: a copy named by
the resolved path leaves the old copy owning the checkpoint, and the run is refused RIVET_SOURCE_CDC_CHECKPOINT_SHARED.
The cell git-sync/mysql/cdc/stale-copy-of-old-provider-not-refused puts, before the first cycle, the copy the previous
provider made (named by the sha256 of the resolved rev-A path, the same text, no .owner record) in the state_dir,
and requires the first stream run through repo/ to succeed. Before the git-sync flip, recreate/mysql/cdc/continues- after-worker-recreate runs docker compose up -d --force-recreate airflow-worker (under Celery the tasks run only in
the worker; the state_dir is the bind mount <stack>/rivet:/opt/rivet, so it outlives the container), makes seven
changes and requires the stream’s next run to move exactly those (no gap, no duplicate) and its base to equal the source.
Before that, two overlapping runs of the stream: the hot DAG’s run held inside rivet (its 45 s pause after it opened)
and a run of gate_src_mysql_cdc_second (the same config and state_dir, lock_wait 30 s, one retry after 60 s)
started beside it. overlap/mysql/cdc/second-run-busy: the held run goes through, the second’s first try ends on a busy
code (RIVET_AIRFLOW_EXPORT_BUSY, the provider’s export lock, or rivet’s RIVET_STATE_RUN_IN_PROGRESS /
RIVET_STATE_LOCK_TIMEOUT, read from that try’s task log) and its retry goes through, and the two moved each change once;
overlap/mysql/cdc/current-equals-source: BigQuery equals the source value by value.
The client’s own files. --client-override <dir> --airflow 2.10.2 --migrate-from <rivet 0.32.1> runs the client’s
delivered compose override (docker-compose.rivet.yml, Dockerfile.rivet, env.rivet.example, README.md,
README.en.md, copied as delivered) between the official 2.10.2 docker-compose.yaml (gate/stand/airflow-2.10.2.yaml,
the official file unchanged, metadata on postgres:13) and the gate’s overlay: docker compose -f docker-compose.yaml -f docker-compose.rivet.yml -f docker-compose.gate.yaml. Its image is built by its own build: (Dockerfile.rivet, its two
pins found in ./wheels: a rivet-cli wheel of the binary under test, laid out as rivet’s own, and this provider’s wheel
built under the version the file pins), its state server rivet-state, its rivet_state and rivet_mysql Connections
(AIRFLOW_CONN_* JSON from RIVET_STATE_* / RIVET_MYSQL_*), its ./rivet-state mount and its
GOOGLE_APPLICATION_CREDENTIALS=/etc/gcloud_cred.json run as written, and no GCP Connection exists (--gcp-auth env-file). The gate’s own configs keep a state database and a state_dir of their own on that server. Its README’s
migration runs as written (gate/client.py): a cron job (rivet 0.32.1 in a folder of its own: the config, its
.rivet_state.db, cdc/) runs, loads and compacts twice; step 5 copies the folder to ./rivet-state/migration-src, runs
its rivet state copy line verbatim (client-override/readme/step5-verbatim: the line is the README’s, exit 0) and
copies the checkpoint to ./rivet-state/mysql/cdc/; step 6 runs the same config under Airflow with its kwargs, and the
stream must continue (client-override/readme/step6-continues: exactly the changes made since the cron job stopped;
client-override/readme/current-equals-source; client-override/mysql/cdc/checkpoint-on-host). With it:
client-override/files/as-delivered, client-override/conn/env-json-connection (the JSON variable in every worker, host
rivet-state, sslmode=disable, resolved by Airflow, the stream’s rows in rivet_state) and
client-override/gcp/env-key-file (the variable in every worker, the key read-only, no GCP Connection, the stream’s run
and loads went through). What the gate adds on top, each a gap in the delivered files: the wheels, the key file mounted
at /etc/gcloud_cred.json (the files say the base compose mounts it), the variables env.rivet.example lists, and the
MySQL source. MEASURE client-override/readme/step5-variables says whether the RIVET_STATE_* variables step 5 reads
are in the worker’s environment.
The client stack. --state compose-postgres keeps the source legs’ state where the client does: in a database of
its own (rivet_state_<engine>_<kind>), owned by a role of its own (rivet_state, LOGIN, its own password), on the
compose file’s postgres server beside Airflow’s metadata database airflow, reached through a Connection
(postgresql://rivet_state:…@postgres:5432/<db>?sslmode=disable: the compose postgres has no TLS, and rivet refuses a
remote state URL that names no sslmode, RIVET_STATE_URL_TLS_REQUIRED) the DAGs read with env_from_connections={"RIVET_STATE_URL": …}; init
runs with that RIVET_STATE_URL. compose-pg/mysql/state-in-own-database reads the server as its superuser: each state
database is owned by rivet_state and holds tables owned by it, and airflow holds none of rivet’s tables (none of
their names, none owned by the role). The default (--state gate, the gate’s TLS gate-state) is unchanged.
The migration leg. --migrate-from <rivet 0.32.1> (beside --sources mysql) mounts that binary at
/opt/rivet/bin/rivet-0.32.1 and runs a MySQL CDC stream over a database of its own (rivet_mig) into a bucket and a
dataset of its own: its config is rivet 0.32.1’s init (0.32.1 keeps SQLite beside -o, so init writes into a scratch
folder and the DAG reads the file copied unchanged). gate_mig_mysql_sqlite (0.32.1, SQLite at <state_dir>/.rivet_state.db,
single_host) runs the baseline and a delta; then, with changes made before the switch, rivet state copy -c <state_dir>/<config copy> (the target from RIVET_STATE_URL) fills the empty PostgreSQL state; gate_mig_mysql_pg
(this binary, the state Connection) runs after more changes, twice. Cells migrate/mysql/cdc/*: each run succeeded and
moved exactly the changes made since the run before (fewer is a gap, more a duplicate), BigQuery equals the source value
by value with the deletes applied, the PostgreSQL state holds the SQLite state’s rows (per table) and cursors, and the
checkpoint file is byte for byte what 0.32.1 left, through the copy and the switch. The way back (gate_mig_mysql_back:
this binary on the SQLite file the copy left, whose load ledger knows nothing of the runs loaded on PostgreSQL) runs the
whole DAG and is graded as wayback/mysql/cdc/*: the run moved exactly the new changes, each table’s load moved only
the runs it had not loaded (a PostgreSQL-era run loaded again is a duplicate), BigQuery equals the source, each base holds
every key once, and no __changes buffer is left; the bucket’s staged objects before and after and each task’s units
are printed as MEASURE lines. The incremental batch pipeline of the same tables goes the same way (rivet 0.32.1’s init,
gate_migb_mysql_sqlite / _pg / _back): migrate/mysql/batch/* and wayback/mysql/batch/*, with what the extract
after the way back takes again measured (MEASURE wayback/mysql/batch/re-exported). The migration
database’s tables are mig_customers / mig_orders: rivet refuses an unqualified CDC table another database of the
server also holds. Last of all, unqualified/mysql/cdc/same-names-in-another-db makes that case on purpose: a database
rivet_dup with the scenario’s table names, then init’s CDC config over rivet (its own bucket, dataset and state),
used as written, run once. It must run (init named <db>.<table>: BigQuery equals the source) or be refused by code at
exit 5 on Airflow’s first try (rivet-lab/rivet#675, fixed in 0.32.2; earlier builds stop the run at exit 1). Every
command a client runs is printed as a COMMAND line.
--sources mongodb and --sources oracle (together: --sources mongodb,oracle) are the same leg where rivet can run
it, and a known-limit cell where it cannot. MongoDB 7 runs as a one-member replica set (a change stream needs one)
with users and a key file, the member named gate-mongodb:27017 so clients inside the stack reach the primary it
advertises; the collections hold ObjectId and int64 _ids, documents nested two deep with arrays, Decimal128, dates,
an int64 past 2^53, doubles, binary and nulls. init writes one CDC export per collection (<collection>_cdc, one
DAG each), loaded and compacted into BigQuery, where document is a JSON column. init --mode incremental is refused
(RIVET_CONFIG_SOURCE_MODE_UNSUPPORTED: MongoDB’s only batch mode is full), so the leg has no MongoDB batch DAG; the
cell initial/mongodb/batch/known-limit runs that init on every stack and fails when it does anything but that
refusal. Oracle 23ai Free (gvenzl/oracle-free:23-slim-faststart, rivet’s own stand image, arm64 too) gets
LogMiner’s prerequisites as rivet’s stand sets them (dev/oracle/init/02-logminer.sh: ARCHIVELOG, minimal and per-table
ALL COLUMNS supplemental logging); its tables hold NUMBER(19) identity keys, NUMBER(12,2), a TIMESTAMP(6) WITH TIME ZONE at +03:00 (the delta’s at -05:30), Cyrillic NVARCHAR2, RAW and BLOB, with TIMESTAMP(6) cursors.
init names Oracle’s batch exports after the upper-case tables (GATE_ORDERS); they run as incremental batch, loaded
and compacted. Oracle CDC cannot feed a load: block (rivet’s oracle.md, Known limits), and init --mode cdc writes
the config without one: initial/oracle/cdc/known-limit fails when init writes a load: block (the leg must then load
and compact Oracle CDC). Oracles: MongoDB is read by pymongo, each document brought to one canonical text (every type
tagged: ObjectId, Decimal128 with its digits, a double apart from an integer, a date at its millisecond, binary with
its subtype) and compared with BigQuery’s document read back as extended JSON by pymongo’s own parser, beside the
_id text; Oracle is read by python-oracledb (exact decimals, LOBs as bytes, the zoned instant as TO_CHAR text with
its offset).
The source legs through build_source_dags. --source-dags (beside --sources, on the gate’s own state) runs the
same engines the way docs/dag-builders.md (“One DAG per database”) tells an operator to: the gate runs no rivet init
and writes no config. Each engine’s sources are names, <engine>_<batch|cdc> (MongoDB: mongodb_cdc only): MySQL,
SQL Server and Oracle are data sources of an odbc.ini the stack mounts read-only at /etc/odbc.ini in every Airflow
container (MySQL ODBC 8.0 Unicode Driver, ODBC Driver 18 for SQL Server with Server = tcp:host,port, Oracle 21 ODBC driver with ServerName = host:port/FREEPDB1; Oracle CDC signs in as the common user c##rivetcdc LogMiner needs,
with --schema RIVET), and no Airflow Connection has those names; MongoDB is an Airflow Connection. The DAG file
(gate/stand/dags/rivet_source_dags.py) makes one build_source_dags call per engine and mode (their init_args
differ: --tls require for SQL Server), names only, state_connection the stack’s gate-state, init_args naming
each source’s bucket and dataset with {name}, schedule="@once". The gate unpauses each DAG, waits for its init
run and for the DAG the next parse builds from the config init wrote, then runs the cycles on those DAGs, graded by the
source legs’ oracles (Oracle CDC, which has no load: block: its Parquet parts in the bucket replayed in commit-SCN
order by oracle.cdc_replay against the source, and each cycle’s change parts counted by oracle.cdc_ops). Cells:
<engine>/source-dags/<kind>/init (the config written, rivet_state_<name> absent before and created by init, the
source read from odbc.ini or the Connection, every CDC checkpoint in <state_root>/<name> after the first cycle),
<engine>/source-dags/<kind>/shape (the task ids after the rebuild equal what the config promises: one stream at the
top on MySQL, a group per stream on SQL Server, Oracle and MongoDB), mongodb/source-dags/odbc-refused (a MongoDB data
source of the odbc.ini with no Connection: its init fails once with RIVET_AIRFLOW_CONNECTION_UNSUPPORTED and the
BI Connector reason), <cycle>/oracle/source-dags/cdc/GATE_ORDERS/known-limit (Oracle CDC refuses a table with a
LOB column by name), and the source legs’ data cells. build_source_dags passes init no --mode for batch, so a
batch config is init’s suggestion (full for the scenario’s small tables): a full export’s target keeps no
deleted key and each extract moves every row. The phases after the cycles (hot ALTER, overlap, git-sync, …) belong
to the gate’s own DAGs and are not run.
Destination legs. --destinations s3 (needs no cloud) adds a MinIO container to the stack and runs the postgres
scenario to S3 on the configs rivet init --s3-bucket <bucket> --s3-region us-east-1 writes, used as written: an
extract-only half (incremental batch and the CDC stream, gate_s3_batch / gate_s3_cdc) and a load half that adds
--clickhouse-url http://gate-clickhouse:8123 --clickhouse-database gate_s3_<batch|cdc> --clickhouse-user loader and
runs load and compact into the stack’s ClickHouse from the S3-staged parts (gate_s3_ch_batch / gate_s3_ch_cdc).
Both halves read gate-source: init names each CDC config’s replication slot after its -o file (rivet #639), so each
config is written to a file of its own name (configs/s3_<kind>/s3_<kind>.yaml), and since rivet #664 a CDC config’s
parts sit under <stem>/cdc/, which the gate reads from the config. init writes cleanup_source: true in every
load: block (the staged parts are deleted once loaded), so only the extract-only half’s Parquet is left to read. The S3 credential and the endpoint reach rivet
only through an Airflow aws Connection (rivet_gate_s3: login and password, extras region_name and endpoint_url
http://gate-minio:9000, as AWS_ENDPOINT_URL, which rivet’s S3 client reads when the config names no endpoint);
init writes neither an endpoint nor a key variable. Each config has a TLS PostgreSQL state of its own
(rivet_gate_state_s3_<kind>). Oracles: the Parquet in MinIO read by DuckDB’s httpfs (path-style, the stack’s own
MinIO password) and graded as the local Parquet is (each delta, the newest version per key, the CDC snapshot + changes
replayed, exact operation counts, XCom rows, the stored cursor read by psql); each ClickHouse current-state view read
over HTTP as JSON and compared value by value with gate-source (warehouse.py’s canonical forms: batch with
exactly the keys the cycle deleted left over, CDC without the rows flagged __is_deleted). A third config names a
bucket that is never made: its DAG (gate_s3_missing) runs once after the cycles and must stop on
RIVET_DEST_CONTAINER_NOT_FOUND within 120 s with exit 1 (rivet declares the code an environment error: 2 only
when transient), on Airflow’s first try (s3/missing-bucket/coded-final-stop).
One more config (init’s --mode incremental with ClickHouse, over a database of its own, cleanup_source: true as
init writes it) grades rivet’s three promises about deleting staged Parquet (gate/cleanup.py, cells cleanup/...),
with the bucket listed by mc, the ledger read with psql and ClickHouse compared with the source: a load narrowed
to one export cleans that export’s prefix and keeps the other’s unloaded runs, which the other’s own load later takes
(unloaded-runs-survive); a load whose ClickHouse table refuses every row (a CHECK constraint) fails with a code and
deletes nothing, and once mended the next load delivers every row and cleans (failed-load-deletes-nothing); while
an extract is held running after its snapshot opened (RIVET_TEST_PAUSE_AT=pg_after_snapshot_open), a load of
its export succeeds and deletes nothing, a load of the other export beside it cleans, and after the run ends the next
load cleans (live-run-blocks).
Everything lives in the stack and goes with its down -v.
There is no Azure leg: the gate’s configs come only from rivet init, and no leg runs one against an Azure container
(init has --azure-container; the gate has no Azure stand or credentials).
Connection legs. Each stack runs with passwords made for it (32 random hex digits for the source, state,
ClickHouse and metastore databases and the admin user) and a generated Fernet key, so no task log masks a word it
carries: the cells hygiene/no-masked-words (no *** in any task log) and hygiene/fernet-key-set (no
empty cryptography key in the task or service logs) hold every stack to it. With the warehouse leg,
--connections env (the default) passes the Connections as AIRFLOW_CONN_* variables in a 0600 env file, the
worst place (see Connections and secrets); --connections gsm puts each one in Google Secret Manager as
airflow-connections-afgate_<tag>_<stack>_<conn_id> and points the stack’s [secrets] backend at it, with no
AIRFLOW_CONN_* variable left. The backend runs as the service account --gsm-reader (default
afgate-secrets-reader@<project>.iam.gserviceaccount.com, which holds secretmanager.secretAccessor only on
names starting airflow-connections-afgate_), impersonated from the credential file --gcp-keyfile mounted
read-only; the cells connections/<conn_id>/from-secret-manager require the variable absent from every Airflow
container (docker inspect), no metastore row, the secret listed, and airflow connections get in the worker
resolving the published fields. --gcp-auth adc leaves gate_gcp with only project and mounts the same
file read-only at the containers’ ADC path, so rivet runs as that identity (connections/gate_gcp/keyless).
Local only: that file is the operator’s own gcloud login, wider than a worker’s identity; on GKE or Composer it is
Workload Identity and no file exists. The cleanup deletes the stack’s secrets and lists again; the sweep drops
gate-shaped secrets older than a day. One-time setup of the project for gsm:
gcloud services enable secretmanager.googleapis.com iamcredentials.googleapis.com --project rivet-data-tool
gcloud iam service-accounts create afgate-secrets-reader --project rivet-data-tool
gcloud projects add-iam-policy-binding rivet-data-tool \
--member serviceAccount:afgate-secrets-reader@rivet-data-tool.iam.gserviceaccount.com \
--role roles/secretmanager.secretAccessor \
--condition='title=afgate-connections-only,expression=resource.name.startsWith("projects/1034205769011/secrets/airflow-connections-afgate_")'
gcloud iam service-accounts add-iam-policy-binding afgate-secrets-reader@rivet-data-tool.iam.gserviceaccount.com \
--member user:<you> --role roles/iam.serviceAccountTokenCreator
rivet’s own release gate does not run this gate: rivet has no hook for it. The Live gate workflow here runs it
against a released binary, on demand and inside the release: an airflow-v* tag publishes to PyPI only after it passes; a release older than the minimum the package runs (MIN_RIVET_VERSION, read by
dev/min_rivet.py) is refused before the binary is downloaded.