Metadata-Version: 2.4
Name: sqlfluff-templater-dbt2
Version: 4.6.0
Summary: Experimental dbt v2 render-trace templater for SQLFluff
License-Expression: MIT
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE.md
Requires-Dist: sqlfluff==4.6.0
Requires-Dist: packaging
Requires-Dist: pyarrow>=14
Dynamic: license-file

# Experimental dbt v2 templater for SQLFluff

This plugin lints and fixes original Jinja SQL using render traces from dbt's
Rust renderer. The public Parquet exporter is available in the standalone dbt
nightly **`2.1.0.dev20261202`**, which is the version used in CI. The exporter
and trace format are experimental.

## Choose the matching templater

| Runtime | Package | SQLFluff configuration |
| --- | --- | --- |
| Legacy Python dbt Core 1.x | `sqlfluff-templater-dbt` | `templater = dbt` |
| Rust dbt v2 with render tracing | `sqlfluff-templater-dbt2` | `templater = dbt2` |

The [legacy templater](../sqlfluff-templater-dbt/README.md) cannot use Rust dbt's
Python namespace as if it contained the old compiler internals. Both plugins
report the correct package and configuration when the wrong generation is
selected. The legacy package also constrains its dependency to dbt Core 1.x.
Use the matching runtime in the environment where you install that plugin.

## Install and try the plugin

Install the [standalone dbt v2 CLI](https://docs.getdbt.com/docs/dbt/dbt-releases#current-versions)
and select the exact nightly:

```sh
dbt system update --version 2.1.0.dev20261202
dbt --version
```

Set `runtime_path` to that executable or put it on `PATH`.

With a development install of this SQLFluff checkout active:

```sh
python -m pip install -e ./plugins/sqlfluff-templater-dbt2
```

Provide a trace-capable dbt v2 runtime in any of three ways (checked in order):

1. Set `runtime_path = /absolute/path/to/dbt` in `.sqlfluff` to target a
   specific standalone CLI binary.
2. Install a `dbt` or `dbt-core` v2 Python wheel in the active SQLFluff
   environment (invoked in a child process via `dbt.cli.main.cli()`).
3. Put a standalone dbt v2 CLI binary named `dbt` on `PATH` (for example from
   the official dbt installer, Homebrew, or `cargo build -p dbt-sa-cli`).

[UPSTREAM.md](UPSTREAM.md) documents the pinned build and producer contract.
In every mode dbt runs in an isolated child process, never imported into
SQLFluff's worker processes.

```ini
[sqlfluff]
templater = dbt2
dialect = duckdb

[sqlfluff:templater:dbt2]
project_dir = /absolute/path/to/project
profiles_dir = /absolute/path/to/profiles
# profile = my_profile
# target = dev
timeout = 300

# Optional: use a separately installed, trace-capable dbt CLI instead.
# runtime_path = /absolute/path/to/dbt

[sqlfluff:templater:dbt2:context]
some_variable = value
```

`timeout` takes a positive whole number of seconds and defaults to 300.
`context` is forwarded as dbt CLI vars. The selected runtime is responsible for
project semantics, packages, adapters and warehouse access. Compilation can make
introspective warehouse queries, as with the existing dbt templater.

```sh
sqlfluff lint path/to/model.sql
sqlfluff fix path/to/model.sql
```

The CLI reports compilation progress once for the selected batch, before the
individual file results:

```text
=== [dbt2 templater] Compiling dbt project...
=== [dbt2 templater] Project Compiled.
```

A failed compilation reports `Compilation Failed.` and the usual templater
errors. Quiet mode and machine-readable output suppress these status messages.
Use `-vvvv` for debug logging of captured dbt stdout/stderr, batch size, loaded
artifacts and per-file trace reuse. Library calls without a formatter emit no
progress output.

Install the dbt runtime separately from the Python plugin. A dbt v2 binary
must provide the experimental exporter. In particular, the stable `2.0.14`
build lacks the export flag.

## How the consumer works

1. Compile the selected models together once per lint pass with
   `DBT_ENGINE_EXPERIMENTAL_WRITE_RENDER_TRACE=1` and `--generate-info-schema`,
   using fresh
   temporary target and log directories. Load the manifest and trace artifacts once,
   then serve per-file traces from memory after removing the temporary output.
2. Read the protocol-v2 Parquet snapshot when present, or protocol-v1
   `*.render_trace.json` sidecars from the original proposal. Verify the source
   path, exact input, node identity and invocation against the compilation manifest.
3. Validate protocol version, render stage, UTF-8 byte boundaries, literal
   equality and event coverage. Translate events into SQLFluff source slices.
4. Run SQLFluff's usual lexer, parser, rules and fixer on that `TemplatedFile`.

### Parquet producer compatibility

Upstream [`dbt-labs/dbt`](https://github.com/dbt-labs/dbt) `main`
([`ef88177667`](https://github.com/dbt-labs/dbt/commit/ef88177667f151d3085184d8c25b4e797f0f7030))
writes
`target/info_schema/v1/dbt.render_traces.parquet`.
Public export requires `--generate-info-schema` alongside
`DBT_ENGINE_EXPERIMENTAL_WRITE_RENDER_TRACE=1`. The environment variable alone records private epochs. `--target-path`
relocates the target root. Private incremental epochs remain producer-owned;
consumers read only this latest-row public table. The intermediate single-file
`target/render_traces.parquet` layout is not supported.

Each row contains the same identity, source, rendered SQL and ordered events as
the JSON proposal, plus an `ingested_at` microsecond timestamp (signed 64-bit
integer). The `events` column is a `LIST<STRUCT<kind, source_start, source_end, rendered_start, rendered_end>>`;
offsets are signed 64-bit UTF-8 byte positions. The `info_schema/v1/` directory and
`protocol_version = 2` describe separate versioned contracts.

The plugin uses PyArrow to read these nested rows. It accepts only rows matching
the fresh manifest's invocation, selects the greatest `ingested_at` per node,
and preserves event order and repeated source ranges. Conflicting rows with the
same timestamp are rejected. A retained trace from an older invocation cannot
authorize a source fix. Corrupt Parquet causes a templater error rather than a
fallback to possibly stale JSON.

The protocol-v1 JSON reader remains available for the original producer. This
does not support the intermediate JSON layout that groups spans by event kind.
Both supported representations pass through the same source-mapping validation.

dbt performs all rendering and execution. Python only lexically classifies the
original Jinja source to account for source-only tags and skipped text. The
consumer never guesses an executed branch from identical output strings.
Repeated loop output can map to the same original source region. Generated
macro output remains nonliteral and is not eligible for direct source fixes.
Whitespace omitted by Jinja2's source tokenization is retained as source-only
text. Replacements within a proven literal emission use that exact source span;
edits crossing emission boundaries retain SQLFluff's conservative mapping.
Loop-control tags are standalone source-only statements. Generated output with
a zero-width producer anchor has no editable source origin; the consumer uses
the whole input as a conservative nonliteral boundary to prevent source
insertions. Empty-loop closing events are consumed explicitly, including
recursive invocations that reuse the same source tag.

The trace describes Jinja SQL **before ephemeral CTE injection**. The consumer
uses the trace's own `rendered` string, not the final compiled SQL file.
Unknown, stale, ambiguous or incomplete provenance is rejected.
After a successful compile, a missing trace is skipped with a warning only
when the same invocation's manifest explicitly lists that source as disabled.
An enabled or unknown model without a trace still produces a templater error;
a failed compilation is never interpreted as a disabled model.
Unbalanced Jinja layout is rejected before lexer work is dispatched, so malformed
traces from an older exporter produce templater errors instead of block-stack
panics in lint workers.

## Tests

CI runs the full suite, including the live DuckDB tests, on Linux and Windows
with the same pinned standalone dbt nightly.

Ordinary tests use 21 artifacts captured from the actual upstream PR runtime.
They require no dbt installation or Rust compiler:

```sh
python -m pytest plugins/sqlfluff-templater-dbt2/test
```

With a trace-capable dbt v2 CLI on `PATH`, configured via `runtime_path`, or
installed as a `dbt`/`dbt-core` wheel, enable the live tests:

```sh
# POSIX shell; in PowerShell use $env:SQLFLUFF_DBT2_INTEGRATION = "1".
SQLFLUFF_DBT2_INTEGRATION=1 python -m pytest plugins/sqlfluff-templater-dbt2/test/live_test.py
```

The tests compile a DuckDB project with config(), return(), ref(), loops and an
ephemeral parent; fix the original source; recompile to check idempotence;
and run the real SQLFluff CLI to persist a source fix. The Parquet contract test
inspects the public snapshot before loading, checks the nested types and invocation
identity, and compares the producer event order with the loaded trace.

To regenerate recorded artifacts using that same installed runtime:

```sh
python plugins/sqlfluff-templater-dbt2/scripts/record_traces.py
```

See [VALIDATION.md](VALIDATION.md) for executed checks.

## Scope

This is a reference implementation, not a claim of Core-templater parity.
It requires current on-disk source. The normal CLI/lint-paths flow compiles all
selected files in one invocation and reuses those traces for that lint pass.
A new pass recompiles; changed per-file settings use a separate invocation,
and source edited after the batch is rejected. Direct process() calls outside
a lint pass compile individually.
Unsaved buffers, source-rewritten snapshots and alternate
branch renders still need work. Broad adapter/warehouse and product-specific
Fusion compatibility remain unvalidated.

The upstream flag and schema are experimental. A stable upstream contract and
compatibility tests would let one plugin support multiple dbt releases by
protocol version, without carrying patched runtimes. See [OPTIONS.md](OPTIONS.md)
for the alternatives and [UPSTREAM.md](UPSTREAM.md) for interface assumptions.
