Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
10 changes: 10 additions & 0 deletions .claude/rules/warehouse-adapters.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,11 @@ src/signalforge/warehouse/
adapters/
bigquery.py # the v0.1 concrete adapter
postgres.py # v0.2 stub (issue #53)
snowflake.py # v0.2 concrete adapter (epic #118)
databricks.py # v0.x skeleton (epic #219, issue #221)
_client.py # pyright-noise shim around google.cloud.bigquery
_snowflake_client.py # one-shim seam around snowflake-connector-python
_databricks_client.py # one-shim seam around databricks-sql-connector
```

The ABC is warehouse-agnostic. v0.2 Snowflake/Postgres slot under `adapters/` without restructuring (DEC-001). `_`-prefixed helpers stay reachable via dotted import but are absent from the package namespace.
Expand All @@ -26,6 +30,12 @@ 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_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.

**⚠️ `TableRef.project` length blocks Unity Catalog catalog names (gotcha for #224).** `TableRef.project` validates as a GCP project id (`validate_project_id`, 6–30 chars), so a Unity Catalog catalog like `main` (4 chars) **fails `TableRef` construction**. The #221 skeleton tests sidestep with `project=None` (two-part `dataset.name`). #224's sampling path threads catalog names into `TableRef.project` (three-part `catalog.schema.table` via `quote_qualified_per_component=True`) and will hit this — either relax the project-id validation for the Databricks dialect or carry the catalog on a separate field. Surfaced while writing the skeleton stub tests; do NOT assume `TableRef` accepts arbitrary catalog identifiers.

**Snowflake sampling + connection-bound session (issue #122).** `SnowflakeAdapter` implements the sampling surface — `sample_rows`, `materialise_sample`, `run_test_sql` (`column_stats` stays `NotImplementedError`; `estimate_query_bytes` was the ABC degrade pending #123 at the time of #122, then graduated to a real `EXPLAIN USING JSON` override in #130 — see the `estimate_query_bytes` graduation note below). Five load-bearing conventions, most diverging from BigQuery because Snowflake's session model differs:

- **The connection IS the session (no `session_id` string).** BigQuery threads a server-side `session_id` via `connection_properties` on every query (§ "Session/connection state"); Snowflake's *connection* holds the session, so `self._active_session` stores the **connection object** itself and every op runs on the one connection. A `connection=` injection seam on `__init__` (mirrors BigQuery's `client=`) + lazy `_get_connection()` (builds via the shim's `make_real_client` on first use) is the testability seam. `_get_connection()` sets `_active_session` on first open.
Expand Down
12 changes: 10 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,16 @@ dependencies = [
# Retained for `pip install -e ".[dev]"` back-compat. CI runs uv (`uv sync --dev`)
# which consumes `[dependency-groups].dev` below; the two lists are kept in sync.
# pyright pinned exactly: tool bumps are tested via deliberate maintainer upgrades, not CI surprise from a new release.
dev = ["ruff", "pyright==1.1.409", "pytest", "pytest-asyncio>=0.23,<1", "dbt-core>=1.8,<2", "types-PyYAML>=6,<7", "pytest-cov>=5.0", "pytest-xdist>=3.6,<4", "snowflake-connector-python>=3,<4", "fakesnow>=0.9", "openai>=1.40,<3.0", "tiktoken>=0.7,<1.0", "google-genai>=0.5,<1", "sqlglot>=30,<31"]
dev = ["ruff", "pyright==1.1.409", "pytest", "pytest-asyncio>=0.23,<1", "dbt-core>=1.8,<2", "types-PyYAML>=6,<7", "pytest-cov>=5.0", "pytest-xdist>=3.6,<4", "snowflake-connector-python>=3,<4", "fakesnow>=0.9", "databricks-sql-connector>=3,<4", "openai>=1.40,<3.0", "tiktoken>=0.7,<1.0", "google-genai>=0.5,<1", "sqlglot>=30,<31"]
# Optional warehouse extra: pulls the Snowflake SDK only when the operator
# installs `signalforge-dbt[snowflake]`. The base install stays BigQuery-only.
snowflake = ["snowflake-connector-python>=3,<4"]
# Optional warehouse extra: pulls the Databricks SQL connector only when the
# operator installs `signalforge-dbt[databricks]`. The base install stays
# BigQuery-only. Unlike `[airflow]`, this IS mirrored into `[dependency-groups].dev`
# (the connector is lightweight + not constraints-pinned, so the normal
# python-build.md mirror convention applies). Epic #219; skeleton #221.
databricks = ["databricks-sql-connector>=3,<4"]
# Optional LLM provider extra: pulls the OpenAI SDK + tiktoken local
# tokeniser only when the operator installs `signalforge-dbt[openai]`. The
# base install stays Anthropic-only. tiktoken powers the local pre-send
Expand Down Expand Up @@ -76,6 +82,7 @@ dev = [
"build>=1.2,<2",
"snowflake-connector-python>=3,<4",
"fakesnow>=0.9",
"databricks-sql-connector>=3,<4",
"openai>=1.40,<3.0",
"tiktoken>=0.7,<1.0",
"google-genai>=0.5,<1",
Expand Down Expand Up @@ -158,7 +165,7 @@ testpaths = ["tests"]
# `--import-mode=importlib` lets us share basenames across test dirs (e.g.
# tests/manifest/test_errors.py and tests/warehouse/test_errors.py) without
# adding tests/__init__.py — keeps `testing-signal.md`'s no-init rule intact.
addopts = "-ra --strict-markers --import-mode=importlib -m 'not bigquery and not anthropic and not cli_subprocess and not e2e and not wheel_smoke and not snowflake and not openai and not gemini and not airflow' --cov=signalforge --cov-report=xml --cov-report=term-missing --cov-fail-under=80"
addopts = "-ra --strict-markers --import-mode=importlib -m 'not bigquery and not anthropic and not cli_subprocess and not e2e and not wheel_smoke and not snowflake and not openai and not gemini and not airflow and not databricks' --cov=signalforge --cov-report=xml --cov-report=term-missing --cov-fail-under=80"
minversion = "7.0"
strict_markers = true
asyncio_mode = "strict"
Expand All @@ -176,6 +183,7 @@ markers = [
"e2e: end-to-end smoke test against real Anthropic + real BigQuery (gated by SF_RUN_BQ=1, ANTHROPIC_API_KEY, GOOGLE_CLOUD_PROJECT; skipped by default)",
"wheel_smoke: maintainer-only; builds the wheel via `python -m build --wheel` and inspects the artifact for the demo file set (run with --no-cov)",
"snowflake: maintainer-only; offline compiled-SQL validation via fakesnow AND the gated live EXPLAIN-estimate certification (run with --no-cov; live tests self-skip without SF_RUN_SNOWFLAKE + connection env vars)",
"databricks: maintainer-only; offline sqlglot/fake validation AND the gated live Free-Edition certification (run with --no-cov; live tests self-skip without SF_RUN_DATABRICKS + DATABRICKS_SERVER_HOSTNAME/HTTP_PATH/TOKEN). See docs/research/databricks-test-environment.md.",
"openai: real-API smoke test against OpenAI (requires SF_RUN_OPENAI=1 + OPENAI_API_KEY; excluded from default CI)",
"gemini: real-API smoke test against Gemini (requires SF_RUN_GEMINI=1 + GOOGLE_API_KEY; excluded from default CI)",
"airflow: requires Apache Airflow installed under its constraints file (excluded from default CI; run in the gated `airflow` job or locally with `uv run --no-sync pytest -m airflow --no-cov`; DAG-parse + operator legs run unconditionally, the live-DAG leg self-skips without SF_RUN_AIRFLOW=1 + warehouse/LLM env). See docs/research/airflow-test-environment.md.",
Expand Down
8 changes: 6 additions & 2 deletions src/signalforge/warehouse/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@
:class:`ColumnStats`, :class:`TestResult`, :class:`DbtProfileTarget` —
warehouse-agnostic value objects callers consume / construct.
- :data:`BIGQUERY_DIALECT`, :data:`POSTGRES_DIALECT`,
:data:`SNOWFLAKE_DIALECT` — the canonical :class:`Dialect` instances for
each supported warehouse flavour (DEC-003).
:data:`SNOWFLAKE_DIALECT`, :data:`DATABRICKS_DIALECT` — the canonical
:class:`Dialect` instances for each supported warehouse flavour (DEC-003).
- The full :class:`WarehouseError` hierarchy, so callers can catch typed
failures without reaching into private modules.

Expand All @@ -25,6 +25,7 @@
"""

from signalforge.warehouse.adapters.bigquery import BigQueryAdapter
from signalforge.warehouse.adapters.databricks import DatabricksAdapter
from signalforge.warehouse.adapters.snowflake import SnowflakeAdapter
from signalforge.warehouse.base import WarehouseAdapter
from signalforge.warehouse.errors import (
Expand Down Expand Up @@ -55,6 +56,7 @@
)
from signalforge.warehouse.models import (
BIGQUERY_DIALECT,
DATABRICKS_DIALECT,
POSTGRES_DIALECT,
SNOWFLAKE_DIALECT,
ColumnStats,
Expand All @@ -75,6 +77,8 @@
"BytesBilledExceededError",
"ColumnNotFoundError",
"ColumnStats",
"DATABRICKS_DIALECT",
"DatabricksAdapter",
"DbtProfileTarget",
"Dialect",
"EstimateNotSupportedError",
Expand Down
Loading
Loading