Skip to content
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion .claude/rules/warehouse-adapters.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ The ABC is warehouse-agnostic. v0.2 Snowflake/Postgres slot under `adapters/` wi

**Snowflake skeleton (issue #119, v0.2 epic #118).** `adapters/snowflake.py` graduates the stub pattern to the vendor the epic targets: `SnowflakeAdapter` captures the forward-compat conn surface (`account` / `user` / `password` / `role` / `warehouse` / `database` / `schema`), `dialect()` returns `SNOWFLAKE_DIALECT` (`quote_char='"'`, **`identifier_case='upper'`** — Snowflake folds unquoted identifiers to upper-case, the *opposite* of Postgres `'lower'`, which #121's anchor-contract column matching depends on; `supports_qualify=True`), and the three abstract op methods raise `NotImplementedError("…issue #118…")`. at the #119 skeleton stage `materialise_sample` / `estimate_query_bytes` were **not** overridden — the ABC's typed degrade (`MaterialisationNotSupportedError` / `EstimateNotSupportedError`) was the correct skeleton-era behaviour (`materialise_sample` was later implemented in #122; `estimate_query_bytes` graduated to a real `EXPLAIN USING JSON` override in #130 — see the graduation note below). `from_profile` dispatches `profile.type == "snowflake"` (lazy import; passes only `database=profile.project, schema=profile.dataset` — the profile-model relaxation to carry `account`/`user`/`role`/`warehouse` is deferred to #120). Three #119-specific notes: (1) **`__repr__` shows only `account` + `warehouse`, never credentials** (`user`/`password`/`role`/`database`/`schema`) — the repr-redaction rule below, pinned by a test asserting the secret substrings are absent. (2) The one-shim-per-vendor rule now has a **warehouse-side confinement test** (`tests/warehouse/test_snowflake_client_confinement.py`): every `snowflake-connector-python` type/pyright-ignore must live only in `adapters/_snowflake_client.py`. (3) `_SnowflakeClientProtocol` (connection: `cursor()` / `close()`) is split from `_SnowflakeCursorProtocol` (`execute(...)` / `fetchall()` / `close()`) so the protocol honestly describes the real DB-API shape — query execution lives on the cursor, not the connection (a CodeRabbit catch; getting the seam shape right now keeps #118's `conn.cursor().execute(...)` path type-checking against a faithful protocol). `snowflake-connector-python` ships under the `[snowflake]` optional extra (+ dev group); the SDK import stays lazy inside `make_real_client`.

**Databricks skeleton (issue #221, epic #219).** `adapters/databricks.py` is the **fourth** adapter through the skeleton precedent (after BigQuery, the Postgres stub, and Snowflake), mirroring the #119 Snowflake skeleton verbatim: `DatabricksAdapter` captures the conn surface (`host` / `http_path` / `token` / `catalog` / `schema`) plus forward-compat OAuth-M2M params (`auth_type` / `client_id` / `client_secret` — epic open-decision: **PAT only for v0.x**, so `make_real_client` consumes only `token`); `dialect()` returns `DATABRICKS_DIALECT` (`quote_char='`'` backtick, **`identifier_case='lower'`** — Unity Catalog lower-folds, the *opposite* of Snowflake `'upper'`, like Postgres; `supports_qualify=True`; 64-bit **sign-bit-masked** `(xxhash64(to_json(struct(*))) & 9223372036854775807)` sampling hash — `xxhash64` not Murmur3-**32** (Spark's bare `hash(*)`) for collision stability, and the `& Long.MAX` mask not `ABS` because Spark's `ABS(Long.MIN_VALUE)` stays negative in non-ANSI mode and would skew `MOD(<expr>, bucket) < 1` (CodeRabbit catch on PR #254); `quote_qualified_per_component=True` for `` `catalog`.`schema`.`table` ``). `sample_rows` / `column_stats` / `run_test_sql` raise `NotImplementedError("…#219…")`; `materialise_sample` / `estimate_query_bytes` / `get_row_count` / `run_stats_query` **inherit the ABC typed degrade** (the four `*NotSupportedError` defaults). `from_profile` dispatches `profile.type == "databricks"` (lazy import; passes only `catalog=profile.project, schema=profile.dataset` — the real `host`/`http_path`/`token`/`catalog` profile fields + per-type validator are deferred to **#222**, exactly the Snowflake #119→#120 deferral). Same three #119 notes apply: (1) **`__repr__` shows only `host` + `http_path` + `catalog`, never `token` / `schema` / `client_secret`** (repr-redaction, pinned by a secret-substring-absent test); (2) **warehouse-side confinement test** (`tests/warehouse/test_databricks_client_confinement.py`) — every `databricks-sql-connector` type/pyright-ignore lives only in `adapters/_databricks_client.py`; (3) `_DatabricksClientProtocol` (connection: `cursor()` / `close()`) split from `_DatabricksCursorProtocol` (`execute(...)` / `fetchall()` / `description` / `close()`). `databricks-sql-connector` ships under the `[databricks]` optional extra (+ dev group — **mirrored unlike `[airflow]`**, since the connector is lightweight + not constraints-pinned); the SDK import stays lazy inside `make_real_client`. The minimal `map_databricks_exception` stub maps auth-flavoured messages → `WarehouseAuthError`, else passthrough (message-marker based, no SDK import); the full table/column/syntax taxonomy + offline fake + gated live e2e land in **#226**.
**Databricks skeleton (issue #221, epic #219).** `adapters/databricks.py` is the **fourth** adapter through the skeleton precedent (after BigQuery, the Postgres stub, and Snowflake), mirroring the #119 Snowflake skeleton verbatim: `DatabricksAdapter` captures the conn surface (`host` / `http_path` / `token` / `catalog` / `schema`) plus forward-compat OAuth-M2M params (`auth_type` / `client_id` / `client_secret` — epic open-decision: **PAT only for v0.x**, so `make_real_client` consumes only `token`); `dialect()` returns `DATABRICKS_DIALECT` (`quote_char='`'` backtick, **`identifier_case='lower'`** — Unity Catalog lower-folds, the *opposite* of Snowflake `'upper'`, like Postgres; `supports_qualify=True`; 64-bit **sign-bit-masked** `(xxhash64(to_json(struct(*))) & 9223372036854775807)` sampling hash — `xxhash64` not Murmur3-**32** (Spark's bare `hash(*)`) for collision stability, and the `& Long.MAX` mask not `ABS` because Spark's `ABS(Long.MIN_VALUE)` stays negative in non-ANSI mode and would skew `MOD(<expr>, bucket) < 1` (CodeRabbit catch on PR #254); `quote_qualified_per_component=True` for `` `catalog`.`schema`.`table` ``). `sample_rows` / `column_stats` / `run_test_sql` raise `NotImplementedError("…#219…")`; `materialise_sample` / `estimate_query_bytes` / `get_row_count` / `run_stats_query` **inherit the ABC typed degrade** (the four `*NotSupportedError` defaults). `from_profile` dispatches `profile.type == "databricks"` (lazy import; at the #221 skeleton stage it passed only `catalog=profile.project, schema=profile.dataset` — the real `host`/`http_path`/`token`/`catalog` profile fields + per-type validator were deferred to **#222**, exactly the Snowflake #119→#120 deferral; **#222 has since landed** — see § "Unified multi-warehouse `DbtProfileTarget`" → "Databricks arm"). Same three #119 notes apply: (1) **`__repr__` shows only `host` + `http_path` + `catalog`, never `token` / `schema` / `client_secret`** (repr-redaction, pinned by a secret-substring-absent test); (2) **warehouse-side confinement test** (`tests/warehouse/test_databricks_client_confinement.py`) — every `databricks-sql-connector` type/pyright-ignore lives only in `adapters/_databricks_client.py`; (3) `_DatabricksClientProtocol` (connection: `cursor()` / `close()`) split from `_DatabricksCursorProtocol` (`execute(...)` / `fetchall()` / `description` / `close()`). `databricks-sql-connector` ships under the `[databricks]` optional extra (+ dev group — **mirrored unlike `[airflow]`**, since the connector is lightweight + not constraints-pinned); the SDK import stays lazy inside `make_real_client`. The minimal `map_databricks_exception` stub maps auth-flavoured messages → `WarehouseAuthError`, else passthrough (message-marker based, no SDK import); the full table/column/syntax taxonomy + offline fake + gated live e2e land in **#226**.

**`DATABRICKS_DIALECT` values are provisional at the skeleton stage** — the prune compiler is never invoked for a Databricks profile yet (every op raises / degrades), so the dialect's SQL-fragment fields (the `xxhash64` hash, Spark `DATE_TRUNC('unit', date)` / `DAYOFWEEK(date)` / `PERCENTILE_CONT … WITHIN GROUP` date-arithmetic, `TIMESTAMP '{value}'` literals) are grounded-but-unexecuted. They are **certified by the #223 `sqlglot` `databricks`-dialect parse-guard + the #226 gated live run** — snapshot equality alone certifies shape, not validity (the #121/#171 lesson). `identifier_case='lower'` is ⚠️ load-bearing for #223's anchor-contract column matching; verify against a real `CREATE TABLE` round-trip before the compiler locks on it.

Expand Down Expand Up @@ -63,6 +63,15 @@ Minimal `map_snowflake_exception` (in the shim, lazy SDK-error import) maps auth
- **Drift detector is mandatory for the new read-back fields.** Even though the *class* isn't new, the Snowflake field set is — `tests/warehouse/test_profiles.py` ships a `StrictSnowflakeModel(extra="forbid")` mirror + `tests/fixtures/profiles/dbt_snowflake_drift_v1_x.yml`. The strict mirror uses `dataset = Field(alias="schema")`, NOT a `schema:` field, to avoid the Pydantic `BaseModel.schema` shadow (`safety-layer.md` issue #93).
- **`from_profile` wires every parsed field, import stays lazy.** The `snowflake` branch passes `account`/`user`/`password`/`role`/`warehouse`/`database`/`schema=profile.dataset` + the key-pair/SSO fields into `SnowflakeAdapter`; the `SnowflakeAdapter` import stays inside the branch so the no-eager-BigQuery-SDK-import contract holds.

### Databricks arm (issue #222) — the third realized warehouse; two new conventions over the Snowflake template

#222 added the `databricks` arm to the same single `DbtProfileTarget` + `_validate_type_field_coherence` validator, mirroring the Snowflake (#120) shape. New fields: `host` / `http_path` / `catalog` / `client_id` / `auth_type` plus secret `token` / `client_secret` (`repr=False`). `_DATABRICKS_ONLY` is the per-type frozenset (incl. `auth_type`; `catalog` is the Databricks analogue of BQ `project` / SF `database`); it was added to the bigquery + snowflake arms' foreign-field rejection in lockstep (the rejection is now `_BIGQUERY_ONLY | _SNOWFLAKE_ONLY | _DATABRICKS_ONLY` minus self). `from_profile`'s databricks branch wires every field with a lazy `DatabricksAdapter` import (replacing the #221 placeholder `catalog=profile.project`). Identifier hygiene: `catalog`/`schema` → strict `validate_identifier` (no length bound, so short Unity catalogs `main`/`workspace` pass — do NOT route catalog through `validate_project_id`); `host`/`http_path` → the permissive non-SQL `validate_databricks_hostname` / `validate_databricks_http_path` (US-001, mirroring `validate_snowflake_account`'s "never SQL — log-injection hygiene only" posture). Two conventions are NEW vs the Snowflake template — reach for them in any future warehouse arm with the same shape:

- **Conditional required-set keyed on an auth-mode field.** Unlike Snowflake's flat `_SNOWFLAKE_REQUIRED`, Databricks' required keys depend on `auth_type`: base `_DATABRICKS_REQUIRED = ("host", "http_path")`, then PAT (`None`/`"pat"`) adds `token`; OAuth (`"oauth"`) adds `client_id` + `client_secret`. The **auth-validity check runs FIRST** (an unsupported `auth_type` → `UnsupportedAuthMethodError` reusing `_DATABRICKS_DEFERRED_AUTH_REMEDIATION`, a `_`-prefixed sibling of `_SNOWFLAKE_DEFERRED_AUTH_REMEDIATION`, NOT in `__all__`) so a bad method fails with the auth error rather than a misleading "missing client_id". Then the conditional required-set is resolved and ALL missing keys collect into one `IncompleteProfileError`. v0.x is **PAT-only at the connector** (`make_real_client` uses `token`); the OAuth required-set is *validated* now but the OAuth *connection* is deferred — "validate forward-compat auth fields coherently, defer the connection."
- **Empty/whitespace counts as MISSING for non-shape-validated credentials.** The required-key check is `not str(getattr(self, k) or "").strip()`, NOT `is None`. Credentials (`token`/`client_id`/`client_secret`) are deliberately not shape-validated (opaque), so an `is None`-only check lets `token: ""` slip through — and the realistic trigger is `token: "{{ env_var('DATABRICKS_TOKEN', '') }}"` with the var unset rendering to `""` (the loader's `_render_env_vars` honours the empty default). Fail loud at profile load, not as a cryptic connection error later. (The Snowflake arm still uses `is None` — a pre-existing same-class gap, left untouched as out of #222 scope.)

**Shared connection knobs join `threads`.** `connect_retries` / `connect_timeout` / `connect_max_idle` were added as accepted-but-unused **shared** fields (NOT in any `_*_ONLY` set) because real dbt-databricks (and dbt-snowflake) profiles routinely set them and `extra="forbid"` would otherwise reject an operator's working profile. Same rationale as `threads` in #120 — when a real-world profile ubiquitously carries a connection knob SignalForge ignores, add it as a shared optional field rather than forcing the operator to delete it. Drift detector mandatory as always: `StrictDatabricksModel(extra="forbid")` + `tests/fixtures/profiles/dbt_databricks_drift_v1_x.yml` (strict mirror uses `dataset = Field(alias="schema")`). No new public error class — reuses `IncompleteProfileError` / `UnsupportedAuthMethodError` / `InvalidIdentifierError` (no exit-code-table / `__all__`-sort churn). #222 is parse-only; the live connection is #226.

## ABC + lazy-import factory (DEC-019)

```python
Expand Down
24 changes: 19 additions & 5 deletions docs/warehouse-adapter-ops.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,11 +67,25 @@ with WarehouseAdapter.from_profile(profile) as adapter:

`WarehouseAdapter.from_profile` dispatches on `profile.type`.
`profile.type == "bigquery"` is fully implemented; `profile.type ==
"postgres"` (v0.2 stub, #53) and `profile.type == "snowflake"` (v0.2
skeleton, #119) dispatch to their adapters, whose warehouse-operation
methods raise `NotImplementedError` until the full implementations land.
"postgres"` (v0.2 stub, #53), `profile.type == "snowflake"` (v0.2
skeleton, #119), and `profile.type == "databricks"` (v0.x skeleton, #221)
dispatch to their adapters, whose warehouse-operation methods raise
`NotImplementedError` until the full implementations land.
Any other `profile.type` raises `UnsupportedProfileTypeError` with a
remediation pointing at the v0.2 roadmap entry.
remediation pointing at the roadmap entry.
Comment thread
wjduenow marked this conversation as resolved.
Resolved

A `type: databricks` target parses end-to-end (#222) into a
`DbtProfileTarget` carrying `host`, `http_path`, `token` (or the OAuth-M2M
`auth_type: oauth` + `client_id` + `client_secret`), `catalog`, and
`schema`. Required keys are auth-conditional: `host` + `http_path` always,
plus `token` for PAT (the default / `auth_type: pat`) or
`client_id` + `client_secret` for OAuth. A missing required key (incl. an
empty-string credential, e.g. an unset `env_var('DATABRICKS_TOKEN', '')`)
raises `IncompleteProfileError`; an unsupported `auth_type` raises
`UnsupportedAuthMethodError` (PAT + OAuth-M2M are supported in v0.x; the
OAuth *connection* is deferred — the connector uses PAT). A BigQuery-only
(`location:`) or Snowflake-only (`account:`) field on a `databricks`
target fails loud, and vice versa. The connection is opened in #226.

## dbt profile resolution

Expand Down Expand Up @@ -783,7 +797,7 @@ on a `↳ Remediation:` line by `__str__`.
| ---------------------------------------- | -------------------------------------------------------------------------------------------------------- | ---------------------------------------------------- | ----------------------------------------------------------------------------------------------- |
| `WarehouseError` | Base class; never raised directly. | `message`, `remediation` | _(no remediation set — base class)_ |
| `WarehouseAuthError` | Wraps `google.auth.exceptions.DefaultCredentialsError` / `RefreshError`. | `message` | Run `gcloud auth application-default login` to set up ADC. |
| `UnsupportedProfileTypeError` | dbt profile's `type` is not `"bigquery"`, `"postgres"`, or `"snowflake"`. | `profile_type` | `bigquery` is fully implemented; `postgres`/`snowflake` dispatch to v0.2 stub/skeleton adapters (warehouse ops raise `NotImplementedError`). Other types are unsupported. |
| `UnsupportedProfileTypeError` | dbt profile's `type` is not `"bigquery"`, `"postgres"`, `"snowflake"`, or `"databricks"`. | `profile_type` | `bigquery` is fully implemented; `postgres`/`snowflake`/`databricks` dispatch to v0.x stub/skeleton adapters (warehouse ops raise `NotImplementedError`). Other types are unsupported. |
Comment thread
wjduenow marked this conversation as resolved.
Resolved
Comment thread
wjduenow marked this conversation as resolved.
Resolved
| `UnsupportedAuthMethodError` | dbt profile's `method` is not `"oauth"` (or unset). | `method` | v0.1 supports `method: oauth` (or unset) only; run `gcloud auth application-default login`. |
| `ProfileNotFoundError` | None of the three search paths yielded a `profiles.yml` (or the project file is missing/malformed). | `searched_paths` | Create a `profiles.yml` at one of the searched paths, or set `DBT_PROFILES_DIR`. |
| `ProfileTargetNotFoundError` | The profile resolved but the requested `target` is missing. Inherits `ProfileNotFoundError`. | `profile_name`, `target`, `searched_paths` | Add the target to `profiles.yml`, or pass an explicit `target=` that exists in the profile. |
Expand Down
Loading
Loading