duckrun-projects
/duckrun-projects
How to build, configure, and run dbt projects on the duckrun adapter — dbt models executed in DuckDB and materialized as Delta Lake tables via delta-rs, locally or on S3/GCS/ADLS/OneLake (Microsoft Fabric) — plus the SQL-first duckrun.connect() notebook API over the same tables. Use this skill whenever a data engineer is setting up a duckrun profile, writing models or sources for it, choosing an incremental strategy (merge, insert, append, delete+insert, microbatch), pointing dbt at OneLake/a Fabric Lakehouse, using duckrun.connect() in a notebook, debugging a duckrun run, working out why a mo
- Author
- djouallah ↗
- Repository
- duckrun ↗
- Licence
- MIT
- Last repository change
- 22.10.2026
Assessment and security
- Files in this package
- 1
- Scripts
- 0
- HTML comments
- 0
- URLs in SKILL.md
- 4
No signals detected. Repository changed on 22.10.2026, without references to retired models or APIs.
MIT, open: use and modify while retaining author attribution.
What it does and when to use it
How to build, configure, and run dbt projects on the duckrun adapter — dbt models executed in DuckDB and materialized as Delta Lake tables via delta-rs, locally or on S3/GCS/ADLS/OneLake (Microsoft Fabric) — plus the SQL-first duckrun.connect() notebook API over the same tables. Use this skill whenever a data engineer is setting up a duckrun profile, writing models or sources for it, choosing an incremental strategy (merge, insert, append, delete+insert, microbatch), pointing dbt at OneLake/a Fabric Lakehouse, using duckrun.connect() in a notebook, debugging a duckrun run, working out why a mo
Original author description
How to build, configure, and run dbt projects on the duckrun adapter — dbt models executed in DuckDB and materialized as Delta Lake tables via delta-rs, locally or on S3/GCS/ADLS/OneLake (Microsoft Fabric) — plus the SQL-first duckrun.connect() notebook API over the same tables. Use this skill whenever a data engineer is setting up a duckrun profile, writing models or sources for it, choosing an incremental strategy (merge, insert, append, delete+insert, microbatch), pointing dbt at OneLake/a Fabric Lakehouse, using duckrun.connect() in a notebook, debugging a duckrun run, working out why a mo
How it works
- Install and profile
- Running in a Fabric Python notebook
- Materializations
- Choosing an incremental strategy — the decision that matters most
- Merge config options
- Sources
- Python models
- Maintenance: already handled — do not add OPTIMIZE/VACUUM jobs
- Contracts and tests
- Troubleshooting
SKILL.md preview
---
name: duckrun-projects
description: How to build, configure, and run dbt projects on the duckrun adapter — dbt models executed in DuckDB and materialized as Delta Lake tables via delta-rs, locally or on S3/GCS/ADLS/OneLake (Microsoft Fabric) — plus the SQL-first duckrun.connect() notebook API over the same tables. Use this skill whenever a data engineer is setting up a duckrun profile, writing models or sources for it, choosing an incremental strategy (merge, insert, append, delete+insert, microbatch), pointing dbt at OneLake/a Fabric Lakehouse, using duckrun.connect() in a notebook, debugging a duckrun run, working out why a model's numbers are wrong (duckrun.dbt_project() — compile a model and inspect it, or one of its CTEs, as a DuckDB relation), or asking "dbt + DuckDB + Delta" questions in general. Consult it BEFORE writing profiles.yml or any incremental model config — several defaults differ from other dbt adapters.
---
# Building dbt projects with duckrun
duckrun is a dbt adapter where **DuckDB executes your model SQL, delta-rs writes the
result as a Delta table, and dbt orchestrates the DAG**. It wraps dbt-duckdb, so
everything dbt-duckdb gives you still works — `view`, `seed`, sources, tests,
snapshots, Python models — and `table` / `incremental` write real Delta tables. The
whole pipeline is pure Python: it runs identically on a laptop, in GitHub Actions, or
in a Fabric Python notebook.
Mental model for every model you write: the SQL runs in an in-memory DuckDB; the result
streams to delta-rs which commits it to `<root_path>/<schema>/<model>`; dbt then sees
that table through a `delta_scan` view, which is how `{{ this }}`, `ref()` and
`is_incremental()` resolve — including across separate dbt processes. The Delta tables
are the ONLY state; there is no database file to manage.
## Install and profile
```bash
pip install "duckrun[dbt]" # brings dbt-duckdb, duckdb, deltalake at the right pins
```
Do NOT separately pin `duckdb` or `deltalake` in your requirements — duckrun sets a
`duckdb>=2.0.0` floor and pins `deltalake` exactly, for documented upstream-bug reasons, and
overriding them is the most common way to break a project.
```yaml
# ~/.dbt/profiles.yml
my_project:
target: dev
outputs:
dev:
type: duckrun
schema: dbo
root_path: './warehouse' # local path, or s3:// gs:// abfss://
# storage_options: {} # credentials, passed straight to deltalake
```
Things that differ from other adapters:
- **`threads:` works, with a caveat.** It's honored like any dbt adapter (default 1), but
concurrent models share ONE DuckDB `memory_limit` — above 1 thread duckrun pins it once
for the run at the tighter share and divides the delta-rs merge pool. So raise it for
many small, network-bound models; leave it at 1 for a single big merge. A microbatch
model's batches always run in order regardless (they all write one table).
- **No database file.** DuckDB is in-memory by default; don't add a `path:` expecting
persistence — persistence is the Delta tables.
- Models land at `<root_path>/<schema>/<model>`; a per-model `config(location=...)`
overrides that.
### Remote stores
Point `root_path` at the store and put credentials in `storage_options` — they flow to
deltalake for writes and merges:
```yaml
remote:
type: duckrun
schema: dbo
root_path: "s3://my-bucket/warehouse"
storage_options:
aws_access_key_id: "{{ env_var('AWS_ACCESS_KEY_ID') }}"
aws_secret_access_key: "{{ env_var('AWS_SECRET_ACCESS_KEY') }}"
```
### OneLake / Microsoft Fabric
On OneLake, `storage_options` can be left **empty**: when no `bearer_token` is supplied,
duckrun self-acquires one (azure-identity is a core dependency) and auto-creates the
matching DuckDB Azure secret, so writes AND `delta_scan` reads work with no extra
config — including read-only commands (`dbt test`, `dbt show`, `dbt docs generate`).
Acquisition order: Fabric notebook (`notebookutils`) → an `AZURE_STORAGE_TOKEN` env
var → GitHub Actions OIDC workload-identity federation (needs `AZURE_CLIENT_ID` +
`AZURE_TENANT_ID` env vars and `id-token: write` job permission — no client secret) →
Azure CLI → interactive browser. Tokens are cached per scope and re-acquired near expiry.
```yaml
fabric:
type: duckrun
schema: dbo
root_path: "abfss://<workspace>@onelake.dfs.fabric.microsoft.com/<lakehouse>.Lakehouse/Tables"
# storage_options: {} # omit entirely — duckrun self-acquires the OneLake token
```
To pin the credential explicitly instead, pass it yourself —
`storage_options: {bearer_token: "{{ env_var('ONELAKE_TOKEN') }}"}` — minted with
`notebookutils.credentials.getToken("storage")` in a Fabric notebook or
`az account get-access-token --resource https://storage.azure.com` in a shell.
**Schema-less Lakehouse** (tables directly under `Tables/`, no schema folders): it's a
layout to avoid, but if stuck with it, drop the trailing `Tables` from `root_path` and
let the schema fill that slot — `schema: Tables`,
`root_path: "abfss://.../<lh>.Lakehouse"`. Models then land at
`<lh>.Lakehouse/Tables/<model>`.
### Multiple Lakehouses in one project (`catalogs:`)
One dbt project can write across several Fabric Lakehouses (or any mix of Delta roots).
Declare extra named write roots in the profile and target one from a model with dbt's
standard `+database` config; models without `+database` land in the default `root_path`:
```yaml
fabric:
type: duckrun
schema: dbo
root_path: "abfss://ws@onelake.dfs.fabric.microsoft.com/bronze.Lakehouse/Tables"
catalogs:
gold:
root_path: "abfss://ws@onelake.dfs.fabric.microsoft.com/gold.Lakehouse/Tables"
# storage_options: {...} # per-catalog override; omit to self-acquire
```
```yaml
# dbt_project.yml
models:
my_project:
marts:
+database: gold
```
`ref()` across catalogs, `docs generate` (each catalog under its own database), and
per-catalog token acquisition all work. Never set the profile-level `database:` field —
the default catalog keys on it internally.
End-to-end reference project (Fabric + OneLake + Direct Lake + scheduled CI):
https://github.com/djouallah/dbt_fabric_python_delta
## Running in a Fabric Python notebook
The reference project's `run.Notebook` is the canonical shape. Reproduce its cell
structure exactly — the ordering is not stylistic.
**Cell 0 — session config first (optional):** `%%configure` must be the very first
cell if used at all. Parameterize `vCores` so a Data Pipeline can size the session per
run (small default, scale up for backfills).
**Cell 1 — install, then restart, nothing else:**
```python
!pip install -q "duckrun[dbt]" --upgrade
notebookutils.session.restartPython()
```
This cell IS the workaround for the central Fabric problem: the runtime preinstalls
older `duckdb` and `deltalake`, and both are native extensions — pip replaces them on
disk but the running interpreter keeps the old binaries loaded. duckrun's install
force-upgrades them (its pins are exact for upstream-bug reasons), so a kernel restart
is mandatory before anything imports them. `restartPython()` restarts the interpreter
and execution continues at the NEXT cell, so the rules are:
- Install + restart live alone in the first code cell. Never put imports, config, or
any work before or beside them — everything in memory is lost at the restart.
- Never `import duckdb`, `deltalake`, or dbt before this cell.
- Don't "optimize away" the restart when the notebook seems to work without it — it
works until the preinstalled version drifts, then fails confusingly mid-run.
**Cell 2 — dual-environment bootstrap.** `try: import notebookutils` for Fabric;
`except ModuleNotFoundError:` falls back to local dev (`AzureCliCredential` for the
token, a yaml file for config). One notebook, runnable in Fabric and on a laptop —
keep this pattern so the dev loop doesn't need a Fabric session. In Fabric, pull
per-environment config from a Variable Library (workspace id, lakehouse name, limits)
rather than hardcoding, resolve the lakehouse **GUID** with
`notebookutils.lakehouse.get(name)['id']` — abfss paths use ids, not names — and get
the token with `notebookutils.credentials.getToken('storage')`. The dbt project itself
lives in the lakehouse `Files/dbt` area and is copied to `/tmp` each run with
`notebookutils.fs.cp(..., True)`: the notebook is a runner, not the project's home.
Deploy it there from a laptop with
`duckrun.connect(tables).copy("dbt", "dbt", git_only=True, sync=True, overwrite=True)` —
git-tracked files only (no `dbt_packages/`, `target/`, local secrets), stale remote
files removed, edited files replaced.
**Cell 3 — env vars are the only interface between notebook and dbt.** Export
`ONELAKE_TABLES_PATH`, `ONELAKE_TOKEN`, `FILES_PATH`, and any limits; keep
`profiles.yml` pure `env_var()` so the same profile serves notebook, laptop, and CI.
**Cell 4 — orchestrate in-process with `dbtRunner`,** not shell `!dbt`:
```python
from dbt.cli.main import dbtRunner
os.chdir(dbt_path)
dbt = dbtRunner()
base = ["--target", dbt_target, "--profiles-dir", "."]
dbt.invoke(["run", "--select", "stg_csv_archive_log", *base]) # 1. ingest log first
new_daily = not dbt.invoke(["run-operation", "check_new_daily", *base]).success # 2. probe
result = dbt.invoke(["run", "--exclude", "stg_csv_archive_log",
"--exclude", "fct_summary", *base]) # 3. main build
if not result.success:
dbt.invoke(["retry", *base]) # retry failures once
dbt.invoke(["run", "--select", "fct_summary", *base]
+ (["--full-refresh"] if new_daily else [])) # 4. conditional rebuild
dbt.invoke(["test", *base]) # 5. tests
```
Patterns worth reusing from this:
- **run-operation as a boolean probe.** A macro that `raise_compiler_error(...)` to
signal "yes" lets the runner branch on `.success` (or the exit code in bash). Inside
such a macro, models are queryable directly — `run_query("select … from main.my_model")`
(or via `ref()`) works: the cursor binds the model's `delta_scan` view on demand when
the catalog misses it. On duckrun < 0.4.42 that bind didn't exist, so older versions
must query **physical paths** instead (`delta_scan('<abfss path>')`, `read_parquet(...)`).
`{{ this }}` has no meaning outside a model either way, and run-operations skip
`on-run-start` hooks, so re-apply any session settings the macro needs.
- **Conditional `--full-refresh` of a single model**, decided by the probe BEFORE the
models that would change its answer get built — order the probe accordingly.
- **`dbt retry` once** on a failed main build, before failing the run.
- **Mirror the exact same step sequence in CI.** The reference repo's GitHub Actions
job runs the identical five steps in bash, authenticating via OIDC. duckrun picks the
OneLake HTTP transport itself (`curl` off a Fabric notebook, so the runner's system CA
bundle is used) — set `AZURE_TRANSPORT_OPTION_TYPE` only to override it. Parity between
notebook and CI means a green laptop run predicts a green scheduled run.
## Materializations
| `materialized` | Backed by | Use when |
|---|---|---|
| `table` | Delta overwrite | Full rebuild every run |
| `incremental` | Delta merge / append | Grow or upsert; strategy below |
| `view` | in-memory DuckDB | Ephemeral staging within a run |
| `seed` | in-memory DuckDB | CSV fixtures |
| `external` | a parquet/csv/json **file** | Exporting to a tool that can't read Delta |
`table`, `incremental` (and the `delta` alias) register a `delta_scan` view after
writing, so downstream `ref()` sees fresh data immediately.
`external` is dbt-duckdb's materialization, unchanged: `COPY … TO` writes the file at
`location` (default `<external_root>/<identifier>.<format>`) and the model becomes a view
over it. Because duckrun only rediscovers *Delta* tables in a fresh process, a run that
reads an external model without rebuilding it needs
`on-run-start: "{{ register_upstream_external_models() }}"`, same as upstream.
## Choosing an incremental strategy — the decision that matters most
```sql
{{ config(materialized='incremental', unique_key='order_id', incremental_strategy='merge') }}
select * from {{ ref('stg_orders') }}
{% if is_incremental() %}
where updated_at > (select max(updated_at) from {{ this }})
{% endif %}
```
| Strategy | Behavior | Requires | Pick it when |
|---|---|---|---|
| `merge` (default with `unique_key`) | upsert: update matched, insert new (delta-rs MERGE) | `unique_key` | Rows change after first load |
| `insert` | insert only keys not present — DuckDB anti-join, committed as a **plain append**, no file rewritten | `unique_key` | Append-only data but you want key-level idempotency |
| `append` (default without `unique_key`) | append; auto-fenced (compare-and-swap) when the model reads `{{ this }}`, blind otherwise | — | Event streams; or your SQL already dedups against `{{ this }}` |
| `delete+insert` | delete target rows whose key appears in the batch, then insert EVERY incoming row (duplicates preserved) | `unique_key` | dbt-duckdb `delete+insert` semantics; duplicate-key sources a `merge` would reject |
| `microbatch` | delete+insert per `event_time` window | `event_time` config; rejects `unique_key` | dbt-driven backfills by time window |
First run, `--full-refresh`, or a missing table always overwrites.
**On a big table, only `merge` is genuinely expensive — and only because it must remove
rows.** A delta-rs MERGE plans a join against the whole pinned target, so its cost scales
with the target's *partition span*, not the batch size, and it splits the memory budget
between DuckDB and delta-rs. `insert` does not: insert-only never removes a row, so
duckrun computes it as a DuckDB anti-join over the target's KEY columns and commits a
plain append — `add` actions only, no existing file rewritten, no delta-rs merge pool,
DuckDB keeps the full write budget. A batch that adds nothing writes no commit at all
(the version does not move). The append is always fenced to the version the anti-join
read, so a concurrent writer fails the run instead of letting a duplicate through.
**So: if the model only ever needs to add rows it has never seen, use `insert`, not
`merge`.** This is the `WHEN MATCHED THEN DO NOTHING` shape other engines spell with a
merge clause; on duckrun it is `incremental_strategy='insert'`. Give it the partition
equality alongside the key so the target probe skips files instead of reading every
partition:
```sql
{{ config(
materialized='incremental', incremental_strategy='insert',
unique_key=['file', 'DUID', 'SETTLEMENTDATE'],
partition_by=['month_key'],
incremental_predicates=['target.month_key = source.month_key'],
) }}
```
duckrun folds the batch's **literal** partition values into the probe
(`"month_key" IN (202601, 202602)`), which the Delta reader pushes down to skip whole
partition directories — something a column-to-column comparison cannot do. Without the
declared equality it will not prune on that column, because that would no longer be
result-neutral. High-cardinality key columns get the batch's min/max instead
(`"id" >= lo AND "id" <= hi`), automatically. Measured on a 20M-row / 12-partition table
inserting a 200k batch: **0.9s and +84 MB RSS, versus 6.7s and +8.4 GB** for the
equivalent delta-rs merge — the memory column is why merges get OOM-killed at scale.
One inherited caveat: the append leaves a small file per partition, so the shared
post-write compaction may still rewrite files once the table's byte debt trips its gate
(no different from plain `append`).
**Same on the notebook API:** `conn.sql("MERGE INTO t USING s ON … WHEN NOT MATCHED THEN
INSERT *")` is the same operation and takes the same anti-join — duckrun routes it at the
shared engine seam, so dbt and SQL cannot execute it two different ways. Any other clause
shape (matched update/delete, by-source, partial insert column list) stays on delta-rs,
because changing or removing a row means rewriting files. To force delta-rs for an
insert-only shape anyway, set `merge_streamed_exec: true`.
**Plain `append` with SQL dedup is still the cheapest of all** — it reads nothing from the
target at all. If the model SQL already excludes rows present in
`{{ this }}` (the classic "load only files not yet seen" pattern), even the anti-join is
redundant. `append` does no target scan and keeps the full DuckDB memory budget — and
because the model reads `{{ this }}`, duckrun **automatically** adds a compare-and-swap
fence: the append commits only if the table version is unchanged since the model
started — captured BEFORE the model read `{{ this }}` — so a concurrent writer makes it
fail with `CommitFailedError` instead of letting a duplicate slip in. There is no
separate strategy to pick (earlier versions exposed this as `append_if_unchanged`;
it's gone — the fence is automatic whenever an `append` model reads `{{ this }}`, and
an append that doesn't read `{{ this }}` stays unfenced by design). Re-running is
safe and idempotent: the SQL dedup excludes whatever the previous attempt loaded. The
canonical shape:
```sql
{{ config(materialized='incremental', incremental_strategy='append') }}
select * from read_csv(getvariable('new_files'))
{% if is_incremental() %}
where file not in (select distinct file from {{ this }}) -- dedup is YOUR job here
{% endif %}
```
**Concurrency expectations to set with the user:** merge/insert are safe — a
conflicting concurrent write makes the run fail loudly (never silently wrong), and both
are strict: ANY concurrent write to the same table aborts them, even to unrelated rows
(delta-rs's own OCC for `merge`, a compare-and-swap on the version for `insert`, whose
anti-join would otherwise go stale). So overlapping schedules or external writers on such
a table mean retries, not corruption — design schedules accordingly. `append` is fenced
only when the model reads `{{ this }}`; a blind append of genuinely new data has no guard,
by design. `delete+insert` commits as a fenced full-table overwrite (same
compare-and-swap).
Microbatch's per-window delete+insert is not protected against concurrent writers —
don't run other writers against a microbatch table during its window.
## Merge config options
| Option | What it does |
|---|---|
| `unique_key` | column(s) to merge on (list for composite) |
| `merge_update_columns` / `merge_exclude_columns` | update only these / all but these on match |
| `merge_update_condition` / `merge_insert_condition` | per-clause predicates (use `target.` / `source.` or dbt's `DBT_INTERNAL_DEST/SOURCE`) |
| `incremental_predicates` | extra predicates AND-ed into the merge condition — use to prune partitions on big targets |
| `on_schema_change` | `ignore` (default) / `append_new_columns` / `fail`. `sync_all_columns` only ADDS — delta-rs cannot drop columns |
| `partition_by` | Delta partition column(s) |
| `sort_by` | column(s) to physically ORDER the write by; the scalar `'auto'` (experimental) picks the key by profiling the model result — same heuristic as the connection API's `SORTED BY AUTO`, unsorted when nothing pays off. Inert on merge/microbatch/delete+insert |
| `max_row_group_size` | explicit parquet row-group ceiling in **rows** for this model's writes (deltalake's spelling; default: the fixed 4M). Overrides the default verbatim — use it when a model must land 16M-row Direct Lake segments (e.g. `16000000`). Preserved by post-write compaction; the delta_rs merge write itself keeps defaults, post-merge compaction folds files into this geometry |
| `target_file_size_mb` | per-model target parquet file size in **MB** (default 256). Same coverage and merge caveat as `max_row_group_size` |
| `merge_schema` | allow schema evolution on write |
| `merge_max_spill_size` | bytes cap on delta-rs's merge pool before it spills to disk; sensible cgroup-aware default; `0` disables |
| `merge_streamed_exec` | `true` streams a HUGE source instead of collecting it — at the cost of losing target-file pruning. Default `false` is right for the normal small-delta-into-big-table case |
| `merge_max_temp_directory_size` | disk cap for delta-rs's merge spill files (default ~80% of free disk) |
| `merge_clauses` / `merge_update_set_expressions` | dbt-duckdb-style custom clause list / per-column SET expressions — translated to delta-rs's full TableMerger clause list |
| `storage_options` | per-model override |
`merge_clauses` follows **dbt-duckdb's spelling exactly**, so a project that targets both
adapters writes the config once: `action` `update` / `delete` / `insert` / `do_nothing`,
`mode` `by_name` / `by_position` / `star` / `explicit`, a `condition` string or list,
`insert: {columns, values}`, `update: {include, exclude, set_expressions}`, and
`by: source`. An omitted `when_matched` / `when_not_matched` key gets dbt-duckdb's
implicit default (update-by-name / insert-by-name), so
`merge_clauses={'when_matched': [{'action': 'do_nothing'}]}` means insert-only — and it
takes the same cheap DuckDB-anti-join-plus-append route as
`incremental_strategy='insert'`, so prefer whichever spelling reads better; they run the
same way. duckrun also accepts a duckrun-only top-level
`when_not_matched_by_source` group (`update` with a `set` map / `delete` / `do_nothing`)
for full-sync deletes; because dbt-duckdb has no such key, a dict that uses it opts OUT of
the implicit defaults — use the portable `{'by': 'source', …}` entry inside
`when_not_matched` to get both.
duckrun validates merge config up front and **refuses** what it cannot honor —
`merge_on_using_columns` and a clause `action: error` (delta-rs has no equivalent for
either) — rather than silently running something else. (`merge_returning_columns` is
ignored: duckrun never surfaces a returned relation, so it changes no table state.) If a
run fails with "duckrun cannot honor these merge configs", that is deliberate — rewrite
the model with the supported controls above, don't look for a bypass.
## Sources
Existing Delta tables, CSVs, or Parquet files become dbt sources via the plugin:
```yaml
sources:
- name: lake
tables:
- name: customers
meta:
plugin: duckrun
location: 's3://bucket/lake/customers' # bare dir => Delta
- name: raw_events
meta:
plugin: duckrun
location: 's3://bucket/landing/events.parquet'
- name: ref_codes
meta:
plugin: duckrun
location: './seeds_ext/codes.csv' # read via read_csv_auto
```
Format is inferred from the extension (`.csv`/`.csv.gz`, `.parquet`/`.pq`, else Delta)
or forced with `meta.format`. `delta_table_path` still works (back-compat, forces
Delta). A source declares location + format ONLY — if a CSV needs hand-tuned parse
options (delimiters, types, skip rows), do that in a model with `read_csv(...)`,
not in the source.
## Python models
Supported for `table` and `incremental`. The function returns a relation/DataFrame;
config goes through `dbt.config(...)`:
```python
def model(dbt, session):
dbt.config(materialized="incremental",
unique_key=["source_type", "source_filename"],
incremental_strategy="merge", schema="source")
return session.sql("select ...")
```
Good fit for ingestion steps (downloads, unzipping, API calls) that end in a relation —
`session` is a DuckDB connection, so heavy lifting stays in SQL.
## Maintenance: already handled — do not add OPTIMIZE/VACUUM jobs
duckrun compacts and vacuums inline on every write: overwrite vacuums every run;
append/merge compact on **byte debt**, not file count — a compaction fires once the
table holds ≥8 small files (under half the 256 MB target size) carrying ≥512 MB of
small bytes combined, and only the partitions with offending files are rewritten (a
healthy big table sitting at hundreds of target-sized files is never touched). Vacuum
runs only after a compaction, at the safe 7-day retention, so concurrent readers are
never broken — superseded files linger up to a week before reclaim, which is the
intended trade. Every table duckrun creates is stamped `delta.checkpointInterval = 10`,
so delta-rs checkpoints the log every 10 commits (no long JSON replay on open).
If a user asks "how do I schedule
OPTIMIZE for these tables", the answer is: you don't, it's built in.
## Contracts and tests
- `contract: {enforced: true}` with `not_null` column constraints IS enforced — a
pre-write guard query fails the model before anything is written, leaving the prior
table version untouched. `check` / `primary_key` / `foreign_key` are NOT enforceable
(models are `delta_scan` views, not DDL tables).
- Regular dbt tests, `store_failures`, and unit tests work (inherited from dbt-duckdb).
Snapshots work too, but they are duckrun's own **Delta-backed** SCD2 materialization
(a Delta MERGE on `dbt_scd_id`, tz-aware timestamps) — dbt-duckdb's default would
live only in the in-memory catalog and vanish across processes.
- `dbt docs generate` works in a fresh process: model/column descriptions are persisted
into the Delta table metadata and re-applied as comments when views are rebuilt.
## Troubleshooting
- **Weird import errors, version mismatches, or delta-log read failures right after
installing in a Fabric notebook**: the kernel is still running the preinstalled
`duckdb`/`deltalake` binaries. The fix is the install cell pattern above —
`pip install "duckrun[dbt]" --upgrade` followed immediately by
`notebookutils.session.restartPython()`, before any import.
- **"schema does not exist" on OneLake** for `dbt test`/`show`/`docs`: the bearer token
is missing or expired — discovery needs it before anything runs. Check
`storage_options.bearer_token` resolves (env var set?) and that the token is fresh
(OneLake tokens expire ~1h; long runs in CI should mint per-run).
- **`CommitFailedError` on a fenced append or merge**: a concurrent writer touched the
table mid-run. Not a bug — re-run; the strategies are idempotent by design. If it's
chronic, two schedules overlap: stagger them.
- **dbt resolved incremental but "Delta table is not found at store time"**: duckrun
refusing to overwrite a whole table with one increment after a transient storage
error or a mid-run delete. Re-run; pass `--full-refresh` only if the table was
deliberately deleted.
- **Merge OOM / slow on a big target**: first ask whether the model actually needs to
UPDATE anything. If matched rows should be left alone, switch `merge` → `insert`: that
becomes a DuckDB anti-join plus a plain append, with no delta-rs merge pool and no file
rewritten — the single biggest win available here. Otherwise add `incremental_predicates`
on the partition column to prune; check the logged "merge spill cap" line; lower
`merge_max_spill_size` in a tight container; consider whether the model qualifies for a
dedup-in-SQL `append` instead. A `merge` whose batch straddles many partitions is the
worst case — its cost is the partition span, not the row count.
- **Huge merge SOURCE (not target)**: set `merge_streamed_exec: true` so the source
streams instead of being collected.
- **NULLs in `unique_key`**: SQL `NULL != NULL` — merge cannot match null keys and you
will get duplicates. Filter or coalesce key columns in the model.
- **A re-run "did nothing"**: correct merge behavior is idempotent — re-merging the
same batch changes nothing. Verify with the watermark/dedup predicate, not row counts.
- **Don't read the Delta path with other tools mid-run** expecting the new version
until dbt reports the model done; the view flips to the new version atomically at
registration.
## Debugging a model that runs but returns the wrong numbers
`dbt show` is the wrong tool for this: it truncates, and `--output json` serializes through
agate, so the schema is gone before the rows arrive — decimals become strings or floats,
dates become strings, and the DataFrame guesses a type per column. Use
`duckrun.dbt_project()` instead. It compiles with dbt and executes on duckrun, so you get
a **DuckDB relation**: real types end to end, and lazy.
```python
from duckrun import dbt_project
p = dbt_project("dbt/", target="dev") # returns at once; parses on first use
p.show("orders_enriched") # DuckDBPyRelation -- .pl() .arrow() .df() .filter()
p.sql("select * from {{ ref('stg_orders') }} where year = 2026")
p.compiled("orders_enriched") # the SQL text
```
**The move that actually finds the bug** is `cte()` — run the model one CTE at a time and
find where the row count or a key goes wrong, instead of copying blocks out of the
compiled SQL by hand:
```python
p.ctes("orders_enriched") # ['base', 'allocated', 'final']
p.cte("orders_enriched", "base").count("*") # -> 41233, fine
p.cte("orders_enriched", "allocated").count("*") # -> 38902, the join drops rows
p.cte("orders_enriched", "allocated").filter("share is null").pl()
```
Things to know before you rely on it:
- **`is_incremental()` models have two compiled forms and the SQL will not tell you
which one you got** — rendering erases the `{% if %}`. duckrun prints the branch, and
`p.compiled(model, incremental=False)` compiles the other one so you can compare.
`p.last_compile.incremental` is `True`/`False`, or `None` when the model does not
branch. Reading the incremental branch as if it were the table's contents is the
classic way to lose an hour here.
- **Read-only is structural** — the session's cursor has no route to delta_rs at all, so
a write cannot reach the lakehouse. `CREATE TEMP TABLE` / `CREATE VIEW` scratch stays
allowed (session-local, never written out). Caveat worth stating plainly: this covers
what the SESSION executes. Compiling is a real `dbt compile` on dbt's own connection,
so an introspective macro (`{% if execute %}` + `run_query`) still runs, exactly as
under `dbt compile`.
- **Ephemeral models** need nothing special: dbt injects them as `__dbt__cte__<name>`, so
they appear in `p.ctes()` of their consumer, and `p.sql("select * from {{ ref('eph') }}")`
works too.
- **`view` models** need nothing special either, though they are the one case that had to
be built: duckrun persists only Delta tables, so a `view` model exists only in the
session that built it. The debug session registers each one it needs as a DuckDB view
first, from the manifest, in dependency order — so a mart over a `view` staging layer
reads normally, and `.filter()` still pushes down through it. Nothing is materialized.
- **Selectors go to dbt untouched** — `"my_model"`, `"path:models/marts/my_model.sql"`,
`tag:` all work. One matching several nodes lists them rather than guessing.
- **Editing a model mid-session is safe**: the manifest is kept warm for speed but
mtime-checked per call, so you never get the SQL from before your last edit.
- The connection is the profile's `DuckrunEnvironment` — dbt's own when it matches — so
secrets, catalog `ATTACH`es and the lazy bind are identical to a real run, and only one
DuckDB instance exists. Never rebuild a debug session out of `duckrun.connect()` with
hand-aligned catalog names; in a multi-Lakehouse project that drifts silently.
Full page: https://djouallah.github.io/duckrun/dbt-debug.html
## Project shape that works well
```
models/
staging/ -- views (or python models for ingestion); cheap, rebuilt every run
dimensions/ -- table or incremental merge on a natural key
marts/ -- big facts: incremental, append where SQL dedups (auto-fenced), else merge
```
Wire file-driven ingestion as: a small `merge` log model tracking which files exist →
fact models that `append` only files not yet in `{{ this }}` (use a `pre_hook` with
`SET VARIABLE` to build the file list, as in the reference project). Keep
`partition_by` low-cardinality (month keys, not timestamps).
## Beyond dbt — the `duckrun.connect()` notebook API
duckrun also ships a storage-neutral, SQL-first session for interactive/notebook work
over the same Delta tables — no dbt project needed. Everything is DuckDB SQL; there is
no DataFrame API to learn:
```python
import duckrun
conn = duckrun.connect("abfss://ws@onelake.dfs.fabric.microsoft.com/lh.Lakehouse/Tables/dbo",
read_only=False) # read-only by default; writes must opt in
conn.sql("CREATE OR REPLACE TABLE orders_copy AS SELECT * FROM orders")
conn.sql("SELECT * FROM orders_copy").show()
```
- `conn.sql(...)` returns DuckDB's native relation (`.df()`, `.arrow()`, `.show()`, …).
Raw DML — `CREATE TABLE AS`, `INSERT`, `UPDATE`, `DELETE`, `MERGE`,
`ALTER TABLE ADD COLUMN`, `DROP TABLE` — is routed to delta-rs, so it lands on the
Delta table identically on a local path and on OneLake. The invariant: **every
`CREATE TABLE` is Delta-backed; only `CREATE TEMP TABLE` and `CREATE VIEW` stay
native DuckDB** (ephemeral, session-local scratch).
- `MERGE`/`UPDATE`/`DELETE` are snapshot-pinned — a concurrent writer fails the commit
loudly (`CommitFailedError`). A self-reading `INSERT INTO a SELECT … FROM a` is
auto-fenced the same way; a plain append of new data is unfenced by design.
`DROP TABLE` is a **tombstone** — a marker commit, no data files deleted.
- Multiple catalogs: `conn.attach(path, name=…, read_only=…)` binds more lakehouses
(or a read-only Fabric Warehouse); read, join, and write across them by three-part
`catalog.schema.table` names.
- `conn.register(name, df)` exposes a local pandas/polars/arrow object to SQL (explicit
because DuckDB's replacement scan can't see the caller's frame). Utilities:
`conn.copy` (`git_only=` / `sync=` for project deploys), `conn.download`,
`conn.list_files`, `conn.get_stats`, and
`conn.convert_to_delta` (one-off zero-copy parquet→Delta ingest — never in a
repeatable pipeline).
- Delta extras with SQL spellings: `SORTED BY AUTO` / `SORTED BY (cols)` /
`PARTITIONED BY (cols)` on CTAS, `VACUUM <t>` (manual compact+vacuum),
`INSERT INTO t REPLACE WHERE <pred> SELECT …`, `INSERT WITH SCHEMA EVOLUTION`,
`DESCRIBE DETAIL` / `DESCRIBE HISTORY`, `RESTORE TABLE t TO VERSION AS OF n`, and
time travel via `delta_scan('<location>', version => N)`.
There is no `INSERT OVERWRITE`, no `CALL` maintenance verbs, and no DataFrame writer —
SQL is the whole surface. Full DML matrix and walkthroughs:
https://djouallah.github.io/duckrun/connection-api.html
Versions
The database has no other skills named duckrun-projects.
Database snapshot: 13.11.2026 · package version 5c6dea3396fc (SHA-256 digest of the entire package)
Downloads in the last 30 days: 0 · ranking
Similar skills
- 100using-duckdb
Query Fabric lakehouse and warehouse data using DuckDB, either locally or inside a Fabric notebook. Automatically invoke when the user mentions "DuckDB", "query Delta tables locally", or asks to "attach DuckDB to a lakehouse", "query OneLake data", "explore lakehouse data",… - 100powerbi-direct-lake
Design and run Power BI semantic models in Direct Lake storage mode on Microsoft Fabric (Delta tables in OneLake), and choose between Import, Direct Lake on OneLake, Direct Lake on SQL analytics endpoint, DirectQuery and composite models. Use when deciding the storage mode of a… - 90fabric-data-engineering
Review Microsoft Fabric data engineering artifacts — Lakehouse and OneLake design, medallion (bronze/silver/gold) architecture, Spark notebooks and Spark job definitions, Data pipelines and Dataflows Gen2, Delta/Parquet storage and OneLake shortcuts, Real-Time Intelligence… - 95fabric-cli
Use Microsoft Fabric CLI (fab) to manage workspaces, semantic models, reports, notebooks, lakehouses, and other Fabric resources via file-system metaphor and commands. Use when deploying Fabric items, running jobs, querying data, managing OneLake files, or automating Fabric… - 100dbt
dbt (data build tool) project structure, SQL patterns, and best practices for the analytics warehouse. Use this skill when working with dbt models, testing SQL queries, or creating new analytical tables. - 100dbt-core
dbt Core skill for SQL-based data transformation in warehouses. Deep expertise in project structure, materializations (view, table, incremental, microbatch), Jinja templating, testing framework, macros, packages, MetricFlow, dbt Mesh, and CI/CD workflows. WHEN: \"dbt\", \"dbt…