Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
2 changes: 1 addition & 1 deletion .claude/rules/warehouse-adapters.md
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ When introducing a new fail-soft cleanup boundary (Postgres temp-table cleanup,

The gated `snowflake` marker now spans offline (`fakesnow`/`sqlglot`, run with no env vars) AND live (`SF_RUN_SNOWFLAKE=1` + conn vars, +`SNOWFLAKE_DATABASE`/`SCHEMA` writable for the engineered prune-live table, +`ANTHROPIC_API_KEY` for the full pipeline) tests under one `uv run pytest -m snowflake --no-cov`. The `docs/warehouse-adapter-ops.md` § "Snowflake adapter (v0.2)" carries the consolidated operator story incl. the **cost guidance** (resource monitor FIRST, XS warehouse, aggressive auto-suspend) that any live Snowflake test must surface in its module docstring.

**Live-harness findings — fakesnow/fakes hid multiple live-only adapter bugs (the #124 payoff).** Running the gated suite against a real warehouse surfaced bugs that the offline `fakesnow` + hand-fakes could not, because fakesnow's DuckDB cursor/result shapes diverge from the real connector's. The lesson generalises the #121 "parser/executor in the loop" rule: a vendor adapter is NOT certified until a live run exercises every path; fakes prove behaviour-against-a-contract, not behaviour-against-the-vendor. Concretely #124's live run found, in order: (1) **`_quote` case-folding** (fixed here — the adapter must fold-then-quote identically to the compiler, else CREATE-vs-REFERENCE diverge); (2) **`ARRAY_AGG(OBJECT_CONSTRUCT(*))` capture-failures samples come back as a JSON *string*** (a VARIANT), not a Python list — `run_test_sql` must `json.loads` it before iterating (fakesnow returned a list, so offline passed); (3) **`HASH(*)` is invalid in WHERE/ORDER BY** on Snowflake → all sample-mode SQL was rejected (bead `bd_1-scaffolding-cdp`) — **FIXED by #139**: the shared `_sample_sql.render_sample_select` now emits the projection-subquery shape (`SELECT * EXCLUDE (_sf_sample_hash) FROM (SELECT t.*, ABS(HASH(*)) AS _sf_sample_hash …)`) driven by `Dialect.sample_hash_in_projection`, so `materialise_sample` / `sample_rows` / the compiler sample CTE all compute the hash in the SELECT projection rather than the rejected predicate position; (4) **oneshot sample-bucket row-count routes through a BigQuery-only `_get_client`** the engine never made vendor-neutral (bead `bd_1-scaffolding-tft`, still open). Net operator contract: **live Snowflake works today with `safety: schema-only` + `prune.scope: full` OR `prune.scope: sample` + `prune.sample_strategy: materialised`** (the #139 projection-subquery fix) — `prune.sample_strategy: oneshot` (bead `bd_1-scaffolding-tft`) + `aggregate-only` (`column_stats`) remain deferred/beaded. When the next vendor adapter ships, budget a live-debugging pass; expect VARIANT/array columns as JSON strings, identifier case-folding mismatches, AND vendor clause-position constraints (a SQL fragment legal in one clause may be rejected in another — the #139 `HASH(*)` lesson) as the first things to break.
**Live-harness findings — fakesnow/fakes hid multiple live-only adapter bugs (the #124 payoff).** Running the gated suite against a real warehouse surfaced bugs that the offline `fakesnow` + hand-fakes could not, because fakesnow's DuckDB cursor/result shapes diverge from the real connector's. The lesson generalises the #121 "parser/executor in the loop" rule: a vendor adapter is NOT certified until a live run exercises every path; fakes prove behaviour-against-a-contract, not behaviour-against-the-vendor. Concretely #124's live run found, in order: (1) **`_quote` case-folding** (fixed here — the adapter must fold-then-quote identically to the compiler, else CREATE-vs-REFERENCE diverge); (2) **`ARRAY_AGG(OBJECT_CONSTRUCT(*))` capture-failures samples come back as a JSON *string*** (a VARIANT), not a Python list — `run_test_sql` must `json.loads` it before iterating (fakesnow returned a list, so offline passed); (3) **`HASH(*)` is invalid in WHERE/ORDER BY** on Snowflake → all sample-mode SQL was rejected (bead `bd_1-scaffolding-cdp`) — **FIXED by #139**: the shared `_sample_sql.render_sample_select` now emits the projection-subquery shape (`SELECT * EXCLUDE (_sf_sample_hash) FROM (SELECT t.*, ABS(HASH(*)) AS _sf_sample_hash …)`) driven by `Dialect.sample_hash_in_projection`, so `materialise_sample` / `sample_rows` / the compiler sample CTE all compute the hash in the SELECT projection rather than the rejected predicate position; (4) **oneshot sample-bucket row-count routed through a BigQuery-only `_get_client`** the engine never made vendor-neutral (bead `bd_1-scaffolding-tft`) — **FIXED by #140**: a vendor-neutral `WarehouseAdapter.get_row_count(table) -> int | None` seam (ABC concrete-default-raise `RowCountNotSupportedError`, mirroring `materialise_sample` / `estimate_query_bytes`; BigQuery wraps its cached `_get_table().num_rows`, Snowflake wraps `_get_num_rows`) replaced the `getattr(adapter, "_get_client")` crack in `prune.engine._resolve_sample_bucket`, so `oneshot` sample-mode prune now works on any adapter that implements the seam (certified by the gated live `test_prune_drops_always_passes_not_null_live_oneshot_sample`). Net operator contract: **live Snowflake works today with `safety: schema-only` + `prune.scope: full` OR `prune.scope: sample` + either `prune.sample_strategy: materialised` (the #139 projection-subquery fix) or `oneshot` (the #140 row-count seam)** — only `aggregate-only` (`column_stats`) remains deferred/beaded. When the next vendor adapter ships, budget a live-debugging pass; expect VARIANT/array columns as JSON strings, identifier case-folding mismatches, AND vendor clause-position constraints (a SQL fragment legal in one clause may be rejected in another — the #139 `HASH(*)` lesson) as the first things to break.

## Reference

Expand Down
33 changes: 19 additions & 14 deletions docs/warehouse-adapter-ops.md
Original file line number Diff line number Diff line change
Expand Up @@ -366,9 +366,10 @@ the v0.2 stop-gap, not a permanent surface.
> (`SELECT * EXCLUDE (_sf_sample_hash) FROM (SELECT t.*, ABS(HASH(*)) AS
> _sf_sample_hash …)`) so the `HASH(*)` row-hash sits in the SELECT projection
> rather than the rejected `WHERE`/`ORDER BY` position. **`materialised`
> sample-mode prune now works on live Snowflake.** The `oneshot` strategy
> remains blocked at a separate engine seam (its row-count routes through a
> BigQuery-only `_get_client`); see "Known limitations on live Snowflake" below.
> sample-mode prune now works on live Snowflake.** The `oneshot` strategy works
> too since #140 routed its sample row-count through the vendor-neutral
> `WarehouseAdapter.get_row_count` seam (it previously reached a BigQuery-only
> `_get_client`); see "Known limitations on live Snowflake" below.

## Query-bytes estimation (v0.2, issue #36)

Expand Down Expand Up @@ -644,22 +645,26 @@ passes through unchanged. No `BytesBilledExceededError` equivalent —
Snowflake has no bytes-billed cap (cost is governed by warehouse size +
auto-suspend, see below).

**Known limitations on live Snowflake (v0.2) — use `safety: schema-only`; for
sampling prefer `prune.sample_strategy: materialised`.** Two
deferred/defective paths remain after #139 fixed the `HASH(*)`-in-predicate bug.
The combination certified green by the gated live e2e is `safety: schema-only` +
`prune.scope: sample` + `prune.sample_strategy: materialised` (or
`prune.scope: full`):
**Known limitations on live Snowflake (v0.2) — use `safety: schema-only`.** One
deferred path remains after #139 fixed the `HASH(*)`-in-predicate bug and #140
added the vendor-neutral row-count seam. Both `prune.sample_strategy` values now
work; the combinations certified green by the gated live e2e are
`safety: schema-only` + `prune.scope: full`, or `prune.scope: sample` with
either `prune.sample_strategy: materialised` or `oneshot`:
Comment thread
wjduenow marked this conversation as resolved.
Resolved

- **`safety: aggregate-only` — unsupported.** Profiles columns via
`adapter.column_stats`, which `SnowflakeAdapter` leaves as a deferred
`NotImplementedError` (the one v0.2 method not yet implemented).
`generate` with `safety.mode: aggregate-only` fails (exit 1).
- **`prune.scope: sample` with `prune.sample_strategy: oneshot` — blocked** at
the engine seam: the sample row-count is fetched through a BigQuery-only
`_get_client`; `SnowflakeAdapter` exposes `_get_num_rows` instead. Needs a
vendor-neutral `WarehouseAdapter.get_table_metadata` seam (bead
`bd_1-scaffolding-tft`). Use `materialised` (the default) instead.

**Fixed by #140:** `prune.scope: sample` + `prune.sample_strategy: oneshot` on a
non-BigQuery adapter no longer raises at the engine seam. The sample row-count is
now fetched through the vendor-neutral `WarehouseAdapter.get_row_count` seam
(BigQuery wraps its cached `get_table`; Snowflake wraps
`_get_num_rows` → `INFORMATION_SCHEMA.TABLES.ROW_COUNT`) rather than a
BigQuery-only `_get_client`. Certified by the gated live
`test_prune_drops_always_passes_not_null_live_oneshot_sample`
(`bd_1-scaffolding-tft`).

**Fixed by #139:** the deterministic row-hash sampling SQL no longer emits
`MOD(ABS(HASH(*)), n) < 1` in `WHERE`/`ORDER BY` (which Snowflake rejected with
Expand Down
8 changes: 8 additions & 0 deletions src/signalforge/cli/_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,7 @@
ProfileNotFoundError,
ProfileTargetNotFoundError,
QuerySyntaxError,
RowCountNotSupportedError,
SamplingError,
SamplingRequiresPartitionFilterError,
TableNotFoundError,
Expand Down Expand Up @@ -414,6 +415,13 @@
# price-only preview and renders ``<unavailable: ...>`` rather than
# misclassifying it as input-shape.
EstimateUnavailableError: 3,
# Row-count seam (issue #140): the active adapter does not expose a
# ``get_row_count`` primitive (the Postgres stub, or any future
# adapter that has not grown one). Sample-scope prune routes the
# bucket-sizing lookup through this seam; the typed exception carries
# its own ``prune.scope: full`` remediation. External-dep tier, like
# the sibling ``*NotSupportedError`` adapter-capability signals.
RowCountNotSupportedError: 3,
# Audit-write durability across every fail-closed seam — when any of
# these fire the disk hand-off didn't happen, which is an external-dep
# state we couldn't recover.
Expand Down
65 changes: 24 additions & 41 deletions src/signalforge/prune/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -607,50 +607,33 @@ def _resolve_sample_bucket(
(DEC-006 of issue #3) so samples drawn through this seam align with
samples the adapter would draw on its own.

Reaches through the warehouse adapter's
:func:`signalforge.warehouse.adapters._client._get_client` path to
fetch ``Table.num_rows``. The adapter's own :meth:`sample_rows`
encapsulates this lookup but does not surface row count separately;
the prune layer needs the row count BEFORE issuing tests, so we
accept the minor encapsulation crack here. v0.2 may add an explicit
:meth:`WarehouseAdapter.get_table_metadata` seam.

Raises :class:`PruneError` when ``num_rows`` is unknown — sampling
against an unsized table would silently degrade to "every row" and
defeat US-003's cost model. The fail-loud signal lands in front of
the operator.
Routes through the vendor-neutral
:meth:`WarehouseAdapter.get_row_count` seam (issue #140). Before #140
this reached for a BigQuery-only ``getattr(adapter, "_get_client")``
crack, so sample-scope prune raised on any non-BigQuery adapter; the
seam lets BigQuery and Snowflake (and future adapters) supply the
row count without the prune layer knowing which warehouse it is. The
adapter's own :meth:`sample_rows` encapsulates this lookup but does
not surface the row count separately, and the prune layer needs it
BEFORE issuing tests.

An adapter without a row-count primitive raises
:class:`RowCountNotSupportedError` from the seam's ABC default; that
propagates (it is a :class:`WarehouseError`) carrying its own
``prune.scope: full`` remediation.

Raises :class:`PruneError` when the row count is unknown (``None`` /
``0``) — sampling against an unsized table would silently degrade to
"every row" and defeat US-003's cost model. The fail-loud signal
Comment thread
wjduenow marked this conversation as resolved.
Resolved
lands in front of the operator.
"""
if scope != "sample":
return None
# Reach through the SDK shim to fetch row count. ``_get_client`` is
# the documented internal seam on the BigQuery adapter (DEC-019 of
# issue #3 — every SDK-noise comment lives in
# ``adapters/_client.py``); the abstract base does NOT declare it,
# so we route through ``getattr`` to keep pyright clean. v0.2 may
# add an explicit ``WarehouseAdapter.get_table_metadata`` seam to
# avoid the encapsulation crack; for now the prune layer needs
# ``num_rows`` BEFORE issuing tests and the adapter's public
# ``sample_rows`` does not surface it.
get_client = getattr(adapter, "_get_client", None)
if get_client is None: # pragma: no cover - defensive; v0.1 only ships BigQuery
raise PruneError(
"sample-mode prune requires the adapter to expose `_get_client`; "
f"{type(adapter).__name__} does not.",
remediation=(
"Set `prune.scope: full` in signalforge.yml until the v0.2 "
"WarehouseAdapter.get_table_metadata seam lands."
),
)
try:
client = get_client()
meta = client.get_table(table_ref)
except WarehouseError:
# Adapter mapped the SDK exception. Re-raise as PruneError so
# the caller's catch surface stays homogeneous: any failure to
# establish the deterministic-sample bucket is a prune-layer
# configuration / setup error.
raise
num_rows = getattr(meta, "num_rows", None)
# Vendor-neutral row-count seam (issue #140). May raise a
# WarehouseError (incl. RowCountNotSupportedError for an adapter that
# has no row-count primitive yet); those propagate to the caller's
# homogeneous WarehouseError catch surface with their own remediation.
num_rows = adapter.get_row_count(table_ref)
if num_rows is None or num_rows == 0:
raise PruneError(
f"sample-mode prune requires Table.num_rows for "
Expand Down
2 changes: 2 additions & 0 deletions src/signalforge/warehouse/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
ProfileNotFoundError,
ProfileTargetNotFoundError,
QuerySyntaxError,
RowCountNotSupportedError,
SamplingError,
SamplingRequiresPartitionFilterError,
TableNotFoundError,
Expand Down Expand Up @@ -89,6 +90,7 @@
"ProfileNotFoundError",
"ProfileTargetNotFoundError",
"QuerySyntaxError",
"RowCountNotSupportedError",
"SNOWFLAKE_DIALECT",
"SamplingError",
"SamplingRequiresPartitionFilterError",
Expand Down
17 changes: 17 additions & 0 deletions src/signalforge/warehouse/adapters/bigquery.py
Original file line number Diff line number Diff line change
Expand Up @@ -456,6 +456,23 @@ def _get_table(self, table: TableRef) -> Any:
cache[table] = meta
return meta

def get_row_count(self, table: TableRef) -> int | None:
"""Return ``Table.num_rows`` for ``table``, or ``None`` when the
BigQuery ``Table`` resource does not carry it (issue #140).

Overrides the ABC default (which raises
:class:`RowCountNotSupportedError`). Routes through the cached
:meth:`_get_table` so a sample-bucket lookup inside an active
context reuses the same metadata fetch the per-test path uses.
``num_rows`` is ``None`` for some resource shapes (freshly
materialised tables with stale metadata, certain views) — the
prune layer treats that as a fail-loud condition; the adapter just
reports what the SDK returns.
"""
meta = self._get_table(table)
num_rows: int | None = getattr(meta, "num_rows", None)
return num_rows

# ------------------------------------------------------------------
# sample_rows — DEC-006 / DEC-024.
# ------------------------------------------------------------------
Expand Down
16 changes: 16 additions & 0 deletions src/signalforge/warehouse/adapters/snowflake.py
Original file line number Diff line number Diff line change
Expand Up @@ -481,6 +481,22 @@ def _get_num_rows(self, table: TableRef) -> int | None:
return None
return int(value)

def get_row_count(self, table: TableRef) -> int | None:
"""Return ``ROW_COUNT`` for ``table``, or ``None`` when unknown
(issue #140).

Overrides the ABC default (which raises
:class:`RowCountNotSupportedError`). Thin wrapper over
:meth:`_get_num_rows` (``INFORMATION_SCHEMA.TABLES.ROW_COUNT``),
which already returns ``None`` for views / materialised views and
for tables absent from ``INFORMATION_SCHEMA``. This is the seam
:func:`signalforge.prune.engine._resolve_sample_bucket` calls to
size the deterministic-sample bucket under ``prune.scope: sample``
— before #140 it reached for a BigQuery-only ``_get_client`` and
raised on every Snowflake table.
"""
return self._get_num_rows(table)

def _resolve_sample_bucket(
self,
table: TableRef,
Expand Down
39 changes: 39 additions & 0 deletions src/signalforge/warehouse/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,45 @@ def estimate_query_bytes(self, sql: str) -> int:

raise EstimateNotSupportedError(adapter_name=type(self).__name__)

def get_row_count(self, table: TableRef) -> int | None:
"""Return the row count of ``table``, or ``None`` when unknown
(issue #140).

The vendor-neutral seam the prune layer uses to size the
deterministic-sample bucket under ``prune.scope: sample`` — it
replaced :func:`signalforge.prune.engine._resolve_sample_bucket`'s
BigQuery-only ``getattr(adapter, "_get_client")`` crack, which made
sample-scope prune raise on any non-BigQuery adapter.

``None`` is a first-class result, NOT an error: it means the
warehouse genuinely could not report a count (e.g. a view /
materialised view with no ``ROW_COUNT``, or stale metadata). The
prune layer decides what to do with an unknown count — the adapter
only reports what the warehouse knows.

Deliberately NOT decorated with ``@abstractmethod``: mirrors
:meth:`materialise_sample` (issue #22) and
:meth:`estimate_query_bytes` (issue #36). The default raise IS the
correct behaviour for an adapter that has not grown a row-count
primitive yet; :class:`RowCountNotSupportedError` is the typed
signal whose remediation tells the operator to fall back to
``prune.scope: full``.

Args:
table: The table whose row count to look up.

Returns:
The row count as a non-negative ``int``, or ``None`` when the
warehouse cannot report it.

Raises:
RowCountNotSupportedError: Always, in the default impl.
Concrete adapters override.
"""
from signalforge.warehouse.errors import RowCountNotSupportedError

raise RowCountNotSupportedError(adapter_name=type(self).__name__)

@classmethod
def from_profile(cls, profile: DbtProfileTarget) -> WarehouseAdapter:
"""Dispatch on ``profile.type`` and instantiate the matching adapter.
Expand Down
Loading
Loading