From 361d074ef0af3174a4cec82e852d7ea2b2366b5a Mon Sep 17 00:00:00 2001 From: wjduenow Date: Wed, 27 May 2026 11:34:58 -0700 Subject: [PATCH 1/2] #140: vendor-neutral get_row_count seam for sample-bucket sizing MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Sample-scope prune sized the deterministic-sample bucket by reaching for a BigQuery-only `getattr(adapter, "_get_client")` crack in `prune.engine._resolve_sample_bucket`, so `prune.scope: sample` + `prune.sample_strategy: oneshot` raised `PruneError` on any non-BigQuery adapter (SnowflakeAdapter exposes `_get_num_rows`, not `_get_client`). Add a vendor-neutral `WarehouseAdapter.get_row_count(table) -> int | None` seam following the established `materialise_sample` / `estimate_query_bytes` pattern: a concrete ABC default raising the new typed `RowCountNotSupportedError` (tier 3), overridden by BigQuery (cached `_get_table().num_rows`) and Snowflake (`_get_num_rows` → INFORMATION_SCHEMA.TABLES.ROW_COUNT). Route `_resolve_sample_bucket` through it; the fail-loud unknown-count `PruneError` and BigQuery snapshot/behaviour parity are preserved. Tests: ABC default-raise; BigQuery + Snowflake overrides (offline fakes); engine vendor-neutral routing regression (a non-BQ adapter with no `_get_client` resolves the bucket); gated live `@pytest.mark.snowflake` oneshot prune e2e. Docs + rules updated to mark bd_1-scaffolding-tft fixed. Co-Authored-By: Claude Opus 4.7 (1M context) --- .claude/rules/warehouse-adapters.md | 2 +- docs/warehouse-adapter-ops.md | 33 +++-- src/signalforge/cli/_helpers.py | 8 ++ src/signalforge/prune/engine.py | 65 ++++----- src/signalforge/warehouse/__init__.py | 2 + .../warehouse/adapters/bigquery.py | 17 +++ .../warehouse/adapters/snowflake.py | 16 +++ src/signalforge/warehouse/base.py | 39 ++++++ src/signalforge/warehouse/errors.py | 35 +++++ tests/prune/test_engine.py | 101 +++++++++++++- tests/warehouse/test_base.py | 29 ++++ tests/warehouse/test_bigquery_unit.py | 40 ++++++ tests/warehouse/test_errors.py | 6 +- tests/warehouse/test_snowflake_prune_live.py | 125 +++++++++++++++++- tests/warehouse/test_snowflake_sampling.py | 28 ++++ 15 files changed, 481 insertions(+), 65 deletions(-) diff --git a/.claude/rules/warehouse-adapters.md b/.claude/rules/warehouse-adapters.md index 0d47a316..a101442d 100644 --- a/.claude/rules/warehouse-adapters.md +++ b/.claude/rules/warehouse-adapters.md @@ -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 diff --git a/docs/warehouse-adapter-ops.md b/docs/warehouse-adapter-ops.md index 10de91d4..8f0db767 100644 --- a/docs/warehouse-adapter-ops.md +++ b/docs/warehouse-adapter-ops.md @@ -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) @@ -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`: - **`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 diff --git a/src/signalforge/cli/_helpers.py b/src/signalforge/cli/_helpers.py index 20ccf5e8..446d563b 100644 --- a/src/signalforge/cli/_helpers.py +++ b/src/signalforge/cli/_helpers.py @@ -168,6 +168,7 @@ ProfileNotFoundError, ProfileTargetNotFoundError, QuerySyntaxError, + RowCountNotSupportedError, SamplingError, SamplingRequiresPartitionFilterError, TableNotFoundError, @@ -414,6 +415,13 @@ # price-only preview and renders ```` 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. diff --git a/src/signalforge/prune/engine.py b/src/signalforge/prune/engine.py index a862a432..5d8ba826 100644 --- a/src/signalforge/prune/engine.py +++ b/src/signalforge/prune/engine.py @@ -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 + 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 " diff --git a/src/signalforge/warehouse/__init__.py b/src/signalforge/warehouse/__init__.py index 9978f152..88d15d19 100644 --- a/src/signalforge/warehouse/__init__.py +++ b/src/signalforge/warehouse/__init__.py @@ -42,6 +42,7 @@ ProfileNotFoundError, ProfileTargetNotFoundError, QuerySyntaxError, + RowCountNotSupportedError, SamplingError, SamplingRequiresPartitionFilterError, TableNotFoundError, @@ -89,6 +90,7 @@ "ProfileNotFoundError", "ProfileTargetNotFoundError", "QuerySyntaxError", + "RowCountNotSupportedError", "SNOWFLAKE_DIALECT", "SamplingError", "SamplingRequiresPartitionFilterError", diff --git a/src/signalforge/warehouse/adapters/bigquery.py b/src/signalforge/warehouse/adapters/bigquery.py index 7e026124..b8778adf 100644 --- a/src/signalforge/warehouse/adapters/bigquery.py +++ b/src/signalforge/warehouse/adapters/bigquery.py @@ -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. # ------------------------------------------------------------------ diff --git a/src/signalforge/warehouse/adapters/snowflake.py b/src/signalforge/warehouse/adapters/snowflake.py index f36c1335..a5ccef65 100644 --- a/src/signalforge/warehouse/adapters/snowflake.py +++ b/src/signalforge/warehouse/adapters/snowflake.py @@ -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, diff --git a/src/signalforge/warehouse/base.py b/src/signalforge/warehouse/base.py index 9d2c8de5..e9fc787d 100644 --- a/src/signalforge/warehouse/base.py +++ b/src/signalforge/warehouse/base.py @@ -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. diff --git a/src/signalforge/warehouse/errors.py b/src/signalforge/warehouse/errors.py index 65c40b91..19e13aa5 100644 --- a/src/signalforge/warehouse/errors.py +++ b/src/signalforge/warehouse/errors.py @@ -576,6 +576,40 @@ def __init__(self, adapter_name: str, *, remediation: str | None = None) -> None super().__init__(message, remediation=remediation) +class RowCountNotSupportedError(WarehouseError): + """The :class:`WarehouseAdapter` ABC default impl of ``get_row_count`` + raises this; concrete adapters override the method to provide a real + implementation (issue #140). + + ``get_row_count`` is the vendor-neutral seam the prune layer uses to + size the deterministic-sample bucket under ``prune.scope: sample`` + (it replaced the BigQuery-only ``getattr(adapter, "_get_client")`` + crack). v0.2 ships the BigQuery and Snowflake overrides; the Postgres + stub (and any future adapter without a row-count primitive) inherits + the default raise. + + Mirrors :class:`MaterialisationNotSupportedError` / + :class:`EstimateNotSupportedError`: the default raise IS the correct + behaviour for an adapter that has not grown the primitive yet — the + remediation tells the operator to fall back to ``prune.scope: full``, + which sizes nothing and so needs no row count. + + Tier-3 in the CLI exit-code taxonomy via inheritance from + :class:`WarehouseError`. + """ + + default_remediation: ClassVar[str] = ( + "Set 'prune.scope: full' in signalforge.yml to skip " + "deterministic-sample sizing, or wait for this adapter to grow a " + "get_row_count override." + ) + + def __init__(self, adapter_name: str, *, remediation: str | None = None) -> None: + self.adapter_name = adapter_name + message = f"Adapter {_format_value(adapter_name)} does not support row-count lookup." + super().__init__(message, remediation=remediation) + + # Sorted alphabetically (verified by tests/warehouse/test_errors.py). __all__ = [ "BytesBilledExceededError", @@ -592,6 +626,7 @@ def __init__(self, adapter_name: str, *, remediation: str | None = None) -> None "ProfileNotFoundError", "ProfileTargetNotFoundError", "QuerySyntaxError", + "RowCountNotSupportedError", "SamplingError", "SamplingRequiresPartitionFilterError", "TableNotFoundError", diff --git a/tests/prune/test_engine.py b/tests/prune/test_engine.py index e61d6d09..24ae9b78 100644 --- a/tests/prune/test_engine.py +++ b/tests/prune/test_engine.py @@ -43,13 +43,15 @@ from signalforge.prune import engine as engine_module from signalforge.prune.audit import PruneEvent from signalforge.prune.config import PruneConfig -from signalforge.prune.engine import prune_tests +from signalforge.prune.engine import _resolve_sample_bucket, prune_tests from signalforge.prune.errors import ( PruneAuditRecordTooLargeError, PruneAuditWriteError, + PruneError, PruneTrustedModelNotFoundError, ) from signalforge.warehouse.adapters.bigquery import BigQueryAdapter +from signalforge.warehouse.base import WarehouseAdapter from signalforge.warehouse.errors import ( BytesBilledExceededError, MaterialisationFailedError, @@ -1427,6 +1429,103 @@ def test_prune_tests_sample_mode_unknown_num_rows_raises_prune_error( fake.assert_all_expectations_met() +class _RowCountOnlyAdapter(WarehouseAdapter): + """A non-BigQuery adapter that implements ONLY the vendor-neutral + ``get_row_count`` seam and deliberately exposes NO ``_get_client``. + + Regression guard for issue #140: before the fix, + :func:`_resolve_sample_bucket` reached for ``getattr(adapter, + "_get_client")`` and raised on any adapter (e.g. Snowflake) that did + not expose that BigQuery-internal seam. This stub proves the engine + now sizes the bucket through ``get_row_count`` alone. + """ + + def __init__(self, num_rows: int | None) -> None: + self._num_rows = num_rows + self.get_row_count_calls: list[TableRef] = [] + + def __enter__(self) -> WarehouseAdapter: + return self + + def __exit__(self, exc_type: object, exc: object, tb: object) -> None: + return None + + def dialect(self): # type: ignore[no-untyped-def] + from signalforge.warehouse.models import SNOWFLAKE_DIALECT + + return SNOWFLAKE_DIALECT + + def sample_rows(self, table, n, *, partition_filter=None): # type: ignore[no-untyped-def] + raise NotImplementedError("not exercised") + + def column_stats(self, table, column): # type: ignore[no-untyped-def] + raise NotImplementedError("not exercised") + + def run_test_sql(self, sql, *, capture_failures=0): # type: ignore[no-untyped-def] + raise NotImplementedError("not exercised") + + def get_row_count(self, table: TableRef) -> int | None: + self.get_row_count_calls.append(table) + return self._num_rows + + +def test_resolve_sample_bucket_uses_vendor_neutral_get_row_count() -> None: + """``_resolve_sample_bucket`` sizes the bucket through the vendor-neutral + ``get_row_count`` seam — NOT a BigQuery-only ``_get_client`` (issue #140). + + The stub adapter has no ``_get_client`` attribute at all; before #140 + this raised ``PruneError`` on any non-BigQuery adapter. The bucket is + ``max(num_rows // sample_size, 1)`` mirroring the adapter's own + ``sample_rows`` derivation. + """ + adapter = _RowCountOnlyAdapter(num_rows=1_000_000) + assert not hasattr(adapter, "_get_client") # the exact crack #140 removed + table_ref = TableRef(project="fake_project", dataset="dataset", name="orders") + + bucket = _resolve_sample_bucket( + adapter=adapter, + table_ref=table_ref, + scope="sample", + sample_size=1000, + ) + + assert bucket == 1000 + assert adapter.get_row_count_calls == [table_ref] + + +def test_resolve_sample_bucket_full_scope_skips_row_count_lookup() -> None: + """``scope="full"`` returns ``None`` and never calls ``get_row_count`` — + full-scan prune does no deterministic-sample sizing (issue #140).""" + adapter = _RowCountOnlyAdapter(num_rows=1_000_000) + table_ref = TableRef(project="fake_project", dataset="dataset", name="orders") + + bucket = _resolve_sample_bucket( + adapter=adapter, + table_ref=table_ref, + scope="full", + sample_size=1000, + ) + + assert bucket is None + assert adapter.get_row_count_calls == [] + + +def test_resolve_sample_bucket_unknown_count_raises_prune_error() -> None: + """An unknown row count (``None``) from the seam fails loud with a + :class:`PruneError` rather than silently degrading to "every row" + (issue #140 preserves the pre-existing fail-loud cost-model guard).""" + adapter = _RowCountOnlyAdapter(num_rows=None) + table_ref = TableRef(project="fake_project", dataset="dataset", name="orders") + + with pytest.raises(PruneError): + _resolve_sample_bucket( + adapter=adapter, + table_ref=table_ref, + scope="sample", + sample_size=1000, + ) + + # --------------------------------------------------------------------------- # US-005 of issue #22 — sample_strategy dispatch + conservative routing. # diff --git a/tests/warehouse/test_base.py b/tests/warehouse/test_base.py index 977493a0..8f659665 100644 --- a/tests/warehouse/test_base.py +++ b/tests/warehouse/test_base.py @@ -27,6 +27,7 @@ from signalforge.warehouse.base import WarehouseAdapter from signalforge.warehouse.errors import ( MaterialisationNotSupportedError, + RowCountNotSupportedError, UnsupportedProfileTypeError, ) from signalforge.warehouse.models import ( @@ -208,6 +209,34 @@ def test_materialise_sample_default_impl_raises_not_supported() -> None: assert "prune.sample_strategy: oneshot" in rendered +def test_get_row_count_default_impl_raises_not_supported() -> None: + """An adapter that does NOT override ``get_row_count`` inherits the ABC + default which raises :class:`RowCountNotSupportedError` (issue #140). + + Pins the seam introduced to replace ``_resolve_sample_bucket``'s + BigQuery-only ``getattr(adapter, "_get_client")`` crack. The error must + be a typed ``WarehouseError`` subclass (not ``NotImplementedError``) so + the four-tier exit-code taxonomy maps it to CLI tier 3 and the operator + sees the ``prune.scope: full`` remediation. + """ + adapter = _StubAdapter() + table = TableRef(project="my-project", dataset="ds", name="t") + + with pytest.raises(RowCountNotSupportedError) as exc_info: + adapter.get_row_count(table) + + err = exc_info.value + assert err.default_remediation == ( + "Set 'prune.scope: full' in signalforge.yml to skip " + "deterministic-sample sizing, or wait for this adapter to grow a " + "get_row_count override." + ) + rendered = str(err) + assert "_StubAdapter" in rendered + assert "↳ Remediation:" in rendered + assert "prune.scope: full" in rendered + + def test_materialise_sample_signature_matches_dec_004() -> None: """The published signature is ``materialise_sample(table, n, *, partition_filter=None, ttl_seconds=3600) -> TableRef`` (DEC-004 of #22). diff --git a/tests/warehouse/test_bigquery_unit.py b/tests/warehouse/test_bigquery_unit.py index 8f11deb7..20f18c7a 100644 --- a/tests/warehouse/test_bigquery_unit.py +++ b/tests/warehouse/test_bigquery_unit.py @@ -137,6 +137,46 @@ def test_dialect_returns_bigquery_constant(adapter: BigQueryAdapter) -> None: assert adapter.dialect() is BIGQUERY_DIALECT +# --------------------------------------------------------------------------- +# get_row_count — issue #140 (vendor-neutral row-count seam) +# --------------------------------------------------------------------------- + + +def test_get_row_count_returns_num_rows( + adapter: BigQueryAdapter, + fake_client: FakeBigQueryClient, + table_ref: TableRef, +) -> None: + """The BigQuery override returns ``Table.num_rows`` via the cached + ``_get_table`` seam (issue #140) — this is what the prune engine's + ``_resolve_sample_bucket`` calls to size the deterministic-sample bucket.""" + fake_client.expect_get_table( + ref=table_ref, + returns=FakeTable(num_rows=1_234_567, schema=[]), + ) + + assert adapter.get_row_count(table_ref) == 1_234_567 + fake_client.assert_all_expectations_met() + + +def test_get_row_count_returns_none_when_num_rows_unknown( + adapter: BigQueryAdapter, + fake_client: FakeBigQueryClient, + table_ref: TableRef, +) -> None: + """``Table.num_rows is None`` (views / stale metadata) surfaces as + ``None`` — a first-class result, NOT an error. The prune layer decides + that an unknown count is a fail-loud condition; the adapter only reports + what the SDK returns (issue #140).""" + fake_client.expect_get_table( + ref=table_ref, + returns=FakeTable(num_rows=None, schema=[]), + ) + + assert adapter.get_row_count(table_ref) is None + fake_client.assert_all_expectations_met() + + # --------------------------------------------------------------------------- # sample_rows — DEC-006 / DEC-024 # --------------------------------------------------------------------------- diff --git a/tests/warehouse/test_errors.py b/tests/warehouse/test_errors.py index eb1dee2d..6496c373 100644 --- a/tests/warehouse/test_errors.py +++ b/tests/warehouse/test_errors.py @@ -62,6 +62,7 @@ "MaterialisationNotSupportedError": {"adapter_name": "SnowflakeAdapter"}, "EstimateNotSupportedError": {"adapter_name": "SnowflakeAdapter"}, "EstimateUnavailableError": {"detail": "EXPLAIN plan lacked GlobalStats"}, + "RowCountNotSupportedError": {"adapter_name": "PostgresAdapter"}, "IncompleteProfileError": { "profile_type": "snowflake", "missing": ["account", "warehouse"], @@ -100,12 +101,13 @@ def test_each_subclass_has_default_remediation() -> None: # EstimateNotSupportedError → 19; issue #47 adds # ProfileEnvVarUnsetError (supports init-demo profile env_var # rendering) → 20. - assert len(errors_module.__all__) == 22, ( + assert len(errors_module.__all__) == 23, ( "DEC-026 enumerates 15 typed subclasses + 1 base; #22 US-001 " "adds 2 more (MaterialisationFailed/NotSupported); #36 US-002 " "adds EstimateNotSupportedError; #47 QG pass-3 adds " "ProfileEnvVarUnsetError; #120 US-002 adds IncompleteProfileError; " - "#130 US-001 adds EstimateUnavailableError. " + "#130 US-001 adds EstimateUnavailableError; #140 adds " + "RowCountNotSupportedError. " "Update tests and __all__ together if this changes." ) for name in errors_module.__all__: diff --git a/tests/warehouse/test_snowflake_prune_live.py b/tests/warehouse/test_snowflake_prune_live.py index 0e22d6b1..28300381 100644 --- a/tests/warehouse/test_snowflake_prune_live.py +++ b/tests/warehouse/test_snowflake_prune_live.py @@ -19,12 +19,12 @@ Before #139, ``materialised`` sample-mode emitted ``MOD(ABS(HASH(*)), n)`` in WHERE / ORDER BY, which Snowflake rejects (``002079``: ``HASH(*)`` is valid only in the SELECT projection); that bug (bead ``bd_1-scaffolding-cdp``) is fixed by -the projection-subquery shape + ``render_sample_select``. (A *separate*, -still-open bug — ``oneshot`` routes the sample row-count through a BigQuery-only -``_get_client`` / the not-yet-built ``WarehouseAdapter.get_table_metadata`` seam, -bead ``bd_1-scaffolding-tft`` — is NOT in scope here; this test exercises the -``materialised`` path, which colocates its temp table via the connection-bound -session and does not hit that seam.) This module is the belt-and-suspenders half +the projection-subquery shape + ``render_sample_select``. (The ``oneshot`` sample path — +which routes the sample row-count through the vendor-neutral +``WarehouseAdapter.get_row_count`` seam introduced by issue #140, bead +``bd_1-scaffolding-tft`` — is certified by the second test in this module, +``test_prune_drops_always_passes_not_null_live_oneshot_sample``.) This module +is the belt-and-suspenders half — a ``@pytest.mark.snowflake``-gated test that drives a **real** :class:`SnowflakeAdapter` through :func:`signalforge.prune.prune_tests` end to end against a live warehouse and asserts the v0.1 differentiator (Architectural @@ -345,3 +345,116 @@ def test_prune_drops_always_passes_not_null_live_materialised_sample() -> None: teardown_cursor.execute(f"DROP TABLE IF EXISTS {quoted}") finally: teardown_cursor.close() + + +@pytest.mark.snowflake +def test_prune_drops_always_passes_not_null_live_oneshot_sample() -> None: + """Prune a hand-crafted ``not_null`` against a live engineered table in + ``oneshot`` sample-mode — the live certification for the issue #140 + vendor-neutral ``get_row_count`` seam (bead ``bd_1-scaffolding-tft``). + + The ``oneshot`` path sizes the deterministic-sample bucket by calling + :func:`signalforge.prune.engine._resolve_sample_bucket`, which (post-#140) + reaches the row count through :meth:`SnowflakeAdapter.get_row_count` + (``INFORMATION_SCHEMA.TABLES.ROW_COUNT``) rather than the BigQuery-only + ``getattr(adapter, "_get_client")`` crack that previously made every + Snowflake ``oneshot`` prune raise ``PruneError``. Then it samples the + SOURCE table directly (no temp-table CTAS — that is the ``materialised`` + path's job) via the #139 projection-subquery sample CTE and runs the + compiled ``not_null`` against it. + + Same engineered-determinism contract as the materialised sibling: the + ``region`` column is the literal ``'austin'`` on every row, so a + ``not_null`` over it returns zero failing rows → ``always-passes`` (drop), + mathematically not probabilistically. + + Skips cleanly under ``pytest -m snowflake`` when any prerequisite is + missing. Creates + drops its own per-run-unique engineered table (the + ``oneshot`` path needs no writable temp table, but the SOURCE table must + still exist and carry a populated ``ROW_COUNT`` — Snowflake maintains + ``INFORMATION_SCHEMA.TABLES.ROW_COUNT`` promptly after the INSERT commits, + the same dependency the materialised sibling already relies on). + """ + if reason := _skip_reason(): + pytest.skip(reason) + + database = os.environ["SNOWFLAKE_DATABASE"] + schema = os.environ["SNOWFLAKE_SCHEMA"] + table_name = _unique_table_name() + quoted = _quoted_table(database, schema, table_name) + + setup_adapter = _make_adapter() + with setup_adapter: + cursor = setup_adapter._get_connection().cursor() + try: + cursor.execute(f"DROP TABLE IF EXISTS {quoted}") + cursor.execute(f"CREATE TABLE {quoted} (id INTEGER, region VARCHAR)") + cursor.execute( + f"INSERT INTO {quoted} (id, region) VALUES " + f"(1, 'austin'), (2, 'austin'), (3, 'austin'), (4, 'austin')" + ) + finally: + cursor.close() + + try: + model = Model.model_validate( + { + "unique_id": f"model.signalforge_live.{table_name}", + "name": table_name, + "resource_type": "model", + "package_name": "signalforge_live", + "original_file_path": f"models/{table_name}.sql", + "path": f"{table_name}.sql", + "database": database, + "schema": schema, + "columns": { + "id": Column(name="id"), + "region": Column(name="region"), + }, + "config": Config(materialized="table"), + } + ) + manifest = Manifest(metadata={}, nodes={model.unique_id: model}) + + candidates = CandidateSchema( + name=table_name, + description="engineered live-e2e table", + columns=( + CandidateColumn( + name="region", + description="literal region constant", + tests=( + CandidateTestNotNull( + column="region", + rationale="region is a literal constant; not_null should always pass", + ), + ), + ), + ), + ) + + # ``scope="sample"`` + ``sample_strategy="oneshot"`` — the engine sizes + # the bucket via ``_resolve_sample_bucket`` → ``adapter.get_row_count`` + # (the #140 seam) and samples the SOURCE table directly. NO temp-table + # CTAS. Pre-#140 this raised ``PruneError`` on any Snowflake table. + config = PruneConfig(scope="sample", sample_strategy="oneshot") + + result = prune_tests(model, _make_adapter(), candidates, manifest, config=config) + + always_passes_drops = [ + d for d in result.decisions if d.decision == "dropped" and d.reason == "always-passes" + ] + assert always_passes_drops, ( + "expected at least one PruneDecision with decision='dropped' and " + "reason='always-passes' under oneshot sample-mode — proving the " + "#140 get_row_count seam sized the bucket without a BigQuery-only " + f"_get_client. Got decisions={result.decisions!r}" + ) + finally: + teardown_adapter = _make_adapter() + with teardown_adapter: + teardown_cursor = teardown_adapter._get_connection().cursor() + try: + teardown_cursor.execute(f"DROP TABLE IF EXISTS {quoted}") + finally: + teardown_cursor.close() diff --git a/tests/warehouse/test_snowflake_sampling.py b/tests/warehouse/test_snowflake_sampling.py index 7512d853..eee9fc0d 100644 --- a/tests/warehouse/test_snowflake_sampling.py +++ b/tests/warehouse/test_snowflake_sampling.py @@ -113,6 +113,34 @@ def test_sample_sql_is_byte_identical_across_two_calls() -> None: # --------------------------------------------------------------------------- +# --------------------------------------------------------------------------- +# get_row_count — issue #140 (vendor-neutral row-count seam) +# --------------------------------------------------------------------------- + + +def test_get_row_count_returns_information_schema_row_count() -> None: + """The Snowflake override returns ``INFORMATION_SCHEMA.TABLES.ROW_COUNT`` + via :meth:`_get_num_rows` (issue #140). This is the seam the prune engine + calls under ``prune.scope: sample`` — before #140 it reached for a + BigQuery-only ``_get_client`` and raised on every Snowflake table.""" + conn = FakeSnowflakeConnection() + conn.expect_execute(matching=_SIZE_QUERY, returns=[(2_500_000,)]) + adapter = _make_adapter(conn) + + assert adapter.get_row_count(_TABLE) == 2_500_000 + + +def test_get_row_count_returns_none_for_view_without_row_count() -> None: + """``ROW_COUNT`` NULL (view / materialised view) surfaces as ``None`` — + a first-class result. The prune layer treats unknown as fail-loud; the + adapter just reports what INFORMATION_SCHEMA returns (issue #140).""" + conn = FakeSnowflakeConnection() + conn.expect_execute(matching=_SIZE_QUERY, returns=[(None,)]) + adapter = _make_adapter(conn) + + assert adapter.get_row_count(_TABLE) is None + + def test_null_row_count_no_filter_raises_unknown_table_size() -> None: """``ROW_COUNT`` NULL (view/MV) + no partition_filter → fail loud.""" conn = FakeSnowflakeConnection() From 05fa4305ffd2b5ec8b95588212012680a03babfc Mon Sep 17 00:00:00 2001 From: wjduenow Date: Wed, 27 May 2026 11:45:45 -0700 Subject: [PATCH 2/2] #140: Address PR review feedback - engine: fail-loud message reports actual observed count (None vs 0) - test stub: type _RowCountOnlyAdapter methods instead of suppressing no-untyped-def - docs: resolve conflicting oneshot guidance (earlier paragraph still said blocked); note prune-live now covers materialised + oneshot Co-Authored-By: Claude Opus 4.7 (1M context) --- docs/warehouse-adapter-ops.md | 9 +++++---- src/signalforge/prune/engine.py | 3 ++- tests/prune/test_engine.py | 22 +++++++++++++++++----- 3 files changed, 24 insertions(+), 10 deletions(-) diff --git a/docs/warehouse-adapter-ops.md b/docs/warehouse-adapter-ops.md index 8f0db767..c5786642 100644 --- a/docs/warehouse-adapter-ops.md +++ b/docs/warehouse-adapter-ops.md @@ -616,8 +616,9 @@ materialised sampling against a read-only shared database (e.g. projection-subquery shape from #139 (`SELECT * EXCLUDE (_sf_sample_hash) FROM (SELECT t.*, ABS(HASH(*)) AS _sf_sample_hash …)`), so `prune.scope: sample` + `prune.sample_strategy: materialised` works on live Snowflake (against a -writable source). The `oneshot` strategy is still blocked at a separate engine -seam — see "Known limitations" below. +writable source). The `oneshot` strategy also works since #140 routed its +sample row-count through the vendor-neutral `WarehouseAdapter.get_row_count` +seam (no CTAS, so no writable source needed) — see "Known limitations" below. **Session cleanup is fail-soft with no manual command.** A Snowflake temp table is unreachable outside its owning session, so there is no @@ -729,8 +730,8 @@ covers both the offline `fakesnow`/`sqlglot` suites (which run with no env vars) and the gated live tests (which self-skip without credentials): `tests/prune/test_compiler_fakesnow.py`, `tests/warehouse/test_snowflake_adapter_fakesnow.py` (offline); -`tests/warehouse/test_snowflake_prune_live.py` (live, materialised, writable -schema), `tests/warehouse/test_snowflake_estimate_live.py` (live EXPLAIN), +`tests/warehouse/test_snowflake_prune_live.py` (live, materialised + oneshot, +writable schema), `tests/warehouse/test_snowflake_estimate_live.py` (live EXPLAIN), `tests/cli/test_e2e_snowflake_smoke.py` (live full pipeline vs `TPCH_SF1`, `oneshot`). diff --git a/src/signalforge/prune/engine.py b/src/signalforge/prune/engine.py index 5d8ba826..0b1d5eb0 100644 --- a/src/signalforge/prune/engine.py +++ b/src/signalforge/prune/engine.py @@ -635,9 +635,10 @@ def _resolve_sample_bucket( # 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: + observed = "None" if num_rows is None else "0" raise PruneError( f"sample-mode prune requires Table.num_rows for " - f"{table_ref.qualified_name!r} but the warehouse returned None.", + f"{table_ref.qualified_name!r} but the warehouse returned {observed}.", remediation=( "Verify the table is materialised and accessible. " "If it is genuinely empty (or num_rows is unavailable on the " diff --git a/tests/prune/test_engine.py b/tests/prune/test_engine.py index 24ae9b78..db56f7dd 100644 --- a/tests/prune/test_engine.py +++ b/tests/prune/test_engine.py @@ -58,7 +58,13 @@ TableNotFoundError, UnknownTableSizeError, ) -from signalforge.warehouse.models import PartitionFilter, TableRef +from signalforge.warehouse.models import ( + ColumnStats, + Dialect, + PartitionFilter, + TableRef, + TestResult, +) from tests.warehouse._fake import FakeBigQueryClient, FakeTable # --------------------------------------------------------------------------- @@ -1450,18 +1456,24 @@ def __enter__(self) -> WarehouseAdapter: def __exit__(self, exc_type: object, exc: object, tb: object) -> None: return None - def dialect(self): # type: ignore[no-untyped-def] + def dialect(self) -> Dialect: from signalforge.warehouse.models import SNOWFLAKE_DIALECT return SNOWFLAKE_DIALECT - def sample_rows(self, table, n, *, partition_filter=None): # type: ignore[no-untyped-def] + def sample_rows( + self, + table: TableRef, + n: int, + *, + partition_filter: PartitionFilter | None = None, + ) -> list[dict[str, Any]]: raise NotImplementedError("not exercised") - def column_stats(self, table, column): # type: ignore[no-untyped-def] + def column_stats(self, table: TableRef, column: str) -> ColumnStats: raise NotImplementedError("not exercised") - def run_test_sql(self, sql, *, capture_failures=0): # type: ignore[no-untyped-def] + def run_test_sql(self, sql: str, *, capture_failures: int = 0) -> TestResult: raise NotImplementedError("not exercised") def get_row_count(self, table: TableRef) -> int | None: