diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1f08710..59e0ba0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -23,10 +23,10 @@ jobs: with: python-version: ${{ matrix.python-version }} - - name: Install package + - name: Install package with DuckDB parity dependency run: | python -m pip install --upgrade pip - python -m pip install -e . + python -m pip install -e ".[duckdb]" - name: Run tests run: python -m pytest diff --git a/README.md b/README.md index a671391..2f66aa9 100644 --- a/README.md +++ b/README.md @@ -2,123 +2,110 @@ [![CI](https://github.com/pavanamthomas/sql-ml-feature-engineering-lab/actions/workflows/ci.yml/badge.svg)](https://github.com/pavanamthomas/sql-ml-feature-engineering-lab/actions) -Point-in-time SQL feature engineering for relational event data, with -deliberate leaky queries and planted future-only sentinels. +Point-in-time SQL feature engineering for relational event data, with deliberate leaky queries, future-only sentinels, and independent cross-engine checks. -This repository is a laboratory. It answers a single question: **how do -we create analytical and ML features from relational event data without -leakage or temporal inconsistencies?** It is not a set of beginner JOIN -exercises. It is not a feature-store product. It is not an empirical -study of real customers. +This repository asks one question: **does a feature use only information that was available at the prediction cutoff?** It is not a beginner JOIN catalogue, a feature-store product, or an empirical study of real customers. Author: Dr. Pavanam Thomas ([GitHub](https://github.com/pavanamthomas), thomaspavanam@gmail.com). -The object is the information set at a cutoff, not a catalogue of JOIN exercises. +The object is the information set at a cutoff. Model performance is secondary to whether the feature was legally computable at that time. -## Information set +## Start here -1. [`FLAGSHIP_POINT_IN_TIME_FAILURE.md`](FLAGSHIP_POINT_IN_TIME_FAILURE.md) — two pipelines, similar column names; one includes the future; in-sample logistic AUC inflates; a sentinel test catches the leak without the model. -2. [`sql/correct/`](sql/correct/) versus [`sql/leaky/`](sql/leaky/) — read the time predicates, not the SELECT lists. -3. [`docs/failures_and_corrections.md`](docs/failures_and_corrections.md) — failures the tests are required to keep visible. -4. [`tests/test_sentinel.py`](tests/test_sentinel.py), [`tests/test_pit.py`](tests/test_pit.py), [`tests/test_flagship.py`](tests/test_flagship.py), [`tests/test_sql_pandas_equality.py`](tests/test_sql_pandas_equality.py) — properties, not smoke tests. -5. [`docs/point_in_time_correctness.md`](docs/point_in_time_correctness.md) and [`docs/sql_leakage.md`](docs/sql_leakage.md) — information set, date truncation, `LEAD`. -6. [`ROADMAP.md`](ROADMAP.md) — bounds. Process: [`docs/lab_process.md`](docs/lab_process.md). +1. [`FLAGSHIP_POINT_IN_TIME_FAILURE.md`](FLAGSHIP_POINT_IN_TIME_FAILURE.md) — two pipelines with similar columns; one admits future information. A sentinel catches the problem without relying on AUC. +2. [`sql/correct/`](sql/correct/) versus [`sql/leaky/`](sql/leaky/) — inspect the time predicates, not only the SELECT lists. +3. [`docs/cross_engine_parity.md`](docs/cross_engine_parity.md) — deterministic SQLite/DuckDB/Pandas checks on the same point-in-time object. +4. [`docs/failures_and_corrections.md`](docs/failures_and_corrections.md) — failures that tests are required to keep visible. +5. [`tests/test_sentinel.py`](tests/test_sentinel.py), [`tests/test_pit.py`](tests/test_pit.py), [`tests/test_sql_pandas_equality.py`](tests/test_sql_pandas_equality.py), and [`tests/test_cross_engine_parity.py`](tests/test_cross_engine_parity.py) — property checks rather than smoke tests. +6. [`ROADMAP.md`](ROADMAP.md) — remaining bounds, including event time versus ingest time. Reproduce: ```bash -python -m pip install -e . +python -m pip install -e ".[duckdb]" python -m pytest python scripts/run_all.py ``` -Python 3.11 or newer. SQLite is the stdlib dialect. DuckDB is optional and is not in CI. +Python 3.11 or newer. SQLite remains the stdlib execution path for the main laboratory. DuckDB now runs in CI as a second engine on a compact deterministic parity fixture. ## Query design -- **Event time \(\le\) cutoff as the information set.** Checkable on a known DGP. Not a full CDC story (ingest time is out of scope; see ROADMAP). -- **SQL files as the artefact.** Tests execute `sql/correct/*.sql` and `sql/leaky/*.sql`. The query text is what a reviewer should argue with. -- **SQLite in CI.** No server. PostgreSQL-style `FILTER`, windows, and CTEs where SQLite supports them. Gaps (`DISTINCT ON`, `date_trunc`) are documented in [`docs/dialect_differences.md`](docs/dialect_differences.md), not papered over. -- **Sentinels instead of code review alone.** A planted post-cutoff amount of `99999.0` must be absent from correct features and present in leaky ones. -- **Pandas as a second engine** for counts, spend, recency, tenure, sessions — not a second copy of the SQL parser. Fillna: counts 0, spend 0, recency NULL. -- **In-sample logistic on the flagship.** If leakage inflates fit for a linear model, a more flexible model is not needed to see the artefact. The AUC is a diagnostic, not a leaderboard. -- **EXPLAIN QUERY PLAN, not milliseconds.** [`docs/query_performance.md`](docs/query_performance.md). +- **Event time at or before cutoff defines the implemented information set.** That is checkable on a known DGP. It is not a full CDC or late-arriving-data story. +- **SQL text is an artefact.** Tests execute the correct and deliberately leaky query files; a reviewer can point to the exact predicate that changes the information set. +- **Future-only sentinels instead of code review alone.** A planted post-cutoff amount of `99999.0` must be absent from correct historical features. +- **Pandas is an independent calculation.** Counts, spend, recency, tenure, and other features are recomputed without parsing the SQL. +- **DuckDB is a second SQL engine, not a badge.** On the parity fixture, SQLite and DuckDB must agree with the independent Pandas result on count, spend, recency, NULL/no-history behavior, and the tested ranking-window semantics. +- **In-sample AUC is only a leakage diagnostic.** It is not reported as out-of-sample skill or as a production benchmark. +- **Query plans are interpreted as plans, not timing claims.** SQLite `EXPLAIN QUERY PLAN` is documented separately; no PostgreSQL optimizer claim is made. -## Designed leakages +## Designed failures | Case | What goes wrong | | --- | --- | -| A. GROUP BY vs window | Customer totals destroy txn-level amount | -| B. Dedup | `ROW_NUMBER` on ingest time; the later amount is the one that must survive | -| C. Cohort table | Month buckets via `strftime`; not a causal retention estimate | -| D. Ranking ties | `ROW_NUMBER` / `RANK` / `DENSE_RANK` disagree on a known score list | -| E. LAG vs LEAD | `LEAD` of the next transaction is often after cutoff | -| F. Full PIT table | Correct join predicate `ts <= cutoff` | -| G. Pandas parity | Same estimand, second implementation | -| H. Indexes | Plan text mentions `idx_txn_customer_ts` after `CREATE INDEX` | - -Leaky SQL: join without time, label-window `+30 days`, label-day `+1 day`, date truncation at midnight, `LEAD`. Details: [`docs/failures_and_corrections.md`](docs/failures_and_corrections.md). - -## SQL / pandas parity - -Tests check properties: - -- Primary keys unique; row counts in band; generator identical under seed 2026. -- Dedup cardinality equals `transactions`; later ingest wins. -- Correct features: `sentinel_spend = 0`; leaky features: known ids show `99999.0`. -- Date truncation includes same-day-after-midnight rows planted for that purpose. -- SQL vs pandas after sort on `prediction_id`; recency NULL stays NULL. -- LEFT JOIN keeps NULL segments; INNER JOIN drops them; `NULL = NULL` does not match. -- Ranking identities on `rank_demo`. -- Leaky in-sample AUC exceeds correct AUC on this DGP. +| GROUP BY vs window | Customer totals destroy transaction-level amount | +| Deduplication | Wrong ordering keeps the wrong version of a duplicate | +| Cohort buckets | Calendar grouping is not a causal retention estimate | +| Ranking ties | `ROW_NUMBER`, `RANK`, and `DENSE_RANK` encode different tie semantics | +| LAG vs LEAD | `LEAD` can expose a transaction after prediction time | +| Missing cutoff predicate | Joining only on customer admits future rows | +| Date truncation | Same-day events after the cutoff clock time can slip in | +| Cross-engine parity | Matching syntax is insufficient; the computed object must agree | + +The deliberately leaky paths include joins without time restrictions, post-cutoff label windows, midnight truncation, and future-looking window logic. Details: [`docs/failures_and_corrections.md`](docs/failures_and_corrections.md). + +## Three-way parity check + +The compact cross-engine fixture contains prediction cutoffs, historical transactions, a no-history customer, and a post-cutoff sentinel transaction. Tests require: + +- SQLite result equals DuckDB result for the tested point-in-time features; +- both SQL results equal an independently computed Pandas table; +- customer 1 excludes the `99999.0` future sentinel; +- zero-history rows retain zero aggregates and NULL recency; +- `ROW_NUMBER`, `RANK`, and `DENSE_RANK` preserve the expected tie pattern across engines. + +This is intentionally narrower than claiming database equivalence. PostgreSQL-specific behavior, time zones, late-arriving facts, and optimizer semantics remain outside the tested object. ## Reproducibility ```bash -python -m pip install -e . +python -m pip install -e ".[duckdb]" python -m pytest python scripts/run_all.py python scripts/generate_data.py # optional: data/lab.sqlite ``` -`scripts/run_all.py` writes `outputs/figures/flagship_auc.png`, -`outputs/tables/run_summary.csv`, cohort and rank CSVs, and -`outputs/tables/explain_plans.txt`. Those files are regenerable. The -source of truth is the SQL plus the tests. +`scripts/run_all.py` regenerates the flagship AUC figure, summary table, cohort and ranking outputs, and SQLite plan text. The source of truth is the query code plus the tests, not checked-in output files. + +CI installs the DuckDB validation extra, runs the full test suite, and runs the reproduction script. ## Known limitations -- The DGP is stylised. It is a tool for checking queries, not a model of a bank. -- Point-in-time on **event** timestamps is not point-in-time on **ingest** time. +- The DGP is stylised; it is a procedural test bed, not a model of a real customer system. +- Point-in-time correctness on **event time** is not point-in-time correctness on **ingest time**. - Time zones are not modelled. +- DuckDB parity covers a deterministic subset, not every SQL file or every dialect feature. +- PostgreSQL-specific execution and query plans are not tested. - In-sample AUC is not out-of-sample skill and not a causal effect. -- SQLite plans are not PostgreSQL plans. - No result here is an empirical finding about real customers. Data policy: [`docs/data_policy.md`](docs/data_policy.md). -## Remaining information-set bounds - -Event time is not ingest time: a late-arriving row with an old `txn_ts` still -passes the sentinel test. DuckDB is not in CI. Time zones are not modelled. -See `ROADMAP.md`. - ## Repository structure ```text sql-ml-feature-engineering-lab/ ├── FLAGSHIP_POINT_IN_TIME_FAILURE.md -├── sql/correct/ # PIT queries -├── sql/leaky/ # intentional information-set bugs +├── sql/correct/ +├── sql/leaky/ ├── src/sqlfeat/ -├── scripts/run_all.py -├── scripts/generate_data.py +├── scripts/ ├── tests/ ├── docs/ -└── outputs/ # regenerable +└── outputs/ ``` -Package: `sqlfeat`. Related laboratories: [statistical-reasoning-validation](https://github.com/pavanamthomas/statistical-reasoning-validation), [time-series-forecasting-lab](https://github.com/pavanamthomas/time-series-forecasting-lab). +Related laboratories: [computational-ml-stem-problem-forge](https://github.com/pavanamthomas/computational-ml-stem-problem-forge), [statistical-reasoning-validation](https://github.com/pavanamthomas/statistical-reasoning-validation), and [time-series-forecasting-lab](https://github.com/pavanamthomas/time-series-forecasting-lab). ## Citation diff --git a/ROADMAP.md b/ROADMAP.md index 488c119..855a9e4 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -6,30 +6,34 @@ Current as of August 2026. - Synthetic relational DGP (customers, accounts, transactions, sessions, events, products, orders, predictions, outcomes) with seed 2026. - Point-in-time SQL features and leaky counterparts under `sql/correct/` and `sql/leaky/`. -- Sentinel tests, SQL/pandas parity, ranking ties, NULL joins, EXPLAIN QUERY PLAN. +- Sentinel tests, SQL/Pandas parity, ranking ties, NULL joins, and EXPLAIN QUERY PLAN. +- A compact SQLite/DuckDB parity fixture for point-in-time count, spend, recency, NULL behavior, and ranking-window semantics. - Flagship in-sample logistic comparison on leaky versus correct training tables. -- CI: `python -m pytest` and `python scripts/run_all.py`. +- CI runs `python -m pytest` and `python scripts/run_all.py`; the test suite installs DuckDB and exercises the cross-engine checks. ## Failures that are part of the design - Joining transactions on `customer_id` without `txn_ts <= cutoff_ts` admits planted sentinels. -- `LEAD` of the next transaction timestamp is often after cutoff. -- Date truncation at a midnight cutoff includes same-calendar-day events after the cutoff clock time. -- GROUP BY customer totals cannot recover txn-level amounts. +- `LEAD` of the next transaction timestamp can cross the prediction cutoff. +- Date truncation at a midnight cutoff can include same-calendar-day events after the cutoff clock time. +- GROUP BY customer totals cannot recover transaction-level amounts. +- A query can match across SQLite and DuckDB and still be wrong if both engines are given the same invalid information set; the independent Pandas route and sentinel are retained for that reason. -Details: `docs/failures_and_corrections.md`. +Details: `docs/failures_and_corrections.md` and `docs/cross_engine_parity.md`. ## Open (issues) -1. DuckDB is not in CI. A second engine would be an independent check of the same SQL text where the dialect overlaps. -2. Late-arriving facts (a row with `txn_ts <= cutoff` inserted after cutoff) are not modelled. Point-in-time on event time is not the same as point-in-time on ingest time. -3. Time zones are not modelled. All timestamps are naive UTC strings. +1. Late-arriving facts are not modelled. A row with event time before cutoff but ingestion after cutoff can still pass an event-time predicate. Event-time correctness is not ingestion-time correctness. +2. Time zones are not modelled. Timestamps in the main synthetic DGP are naive UTC-style strings. +3. PostgreSQL-specific behavior is not executable in CI. DuckDB provides a second SQL engine, not a guarantee of PostgreSQL equivalence. +4. Query-plan parity is not claimed. The cross-engine work checks result semantics on deterministic fixtures, not optimizer behavior. ## Explicitly not in scope - Treating simulated AUC as a production model result. -- A feature store product, Spark jobs, or a warehouse migration. +- A feature-store product, Spark jobs, or a warehouse migration. - Invented empirical findings about real customers. - Causal claims from predictive features. +- Claiming broad database expertise from one cross-engine fixture. -Close an issue only with a test or a limitation sentence. +Close an issue only with executable evidence or a limitation sentence that narrows the claim. diff --git a/docs/cross_engine_parity.md b/docs/cross_engine_parity.md new file mode 100644 index 0000000..ce02659 --- /dev/null +++ b/docs/cross_engine_parity.md @@ -0,0 +1,35 @@ +# Cross-engine point-in-time parity + +The main laboratory already compares SQL features with an independent Pandas calculation. This extension adds a second SQL execution engine for a deliberately small fixture so dialect differences can be tested rather than discussed only in prose. + +The fixture contains three prediction cutoffs and four transactions. Customer 1 has two historical transactions worth 10 and 20, plus a post-cutoff sentinel worth 99999. Customer 2 has one historical transaction. Customer 3 has no transaction history. + +Both SQLite and DuckDB must therefore return the same customer-level objects: + +- customer 1: count 2, spend 30, recency 1 day; +- customer 2: count 1, spend 7.5, recency 5 days; +- customer 3: count 0, spend 0, recency NULL. + +The 99999 sentinel is not an ML metric. It is a direct information-set test: if it appears in the historical feature table, the cutoff predicate failed before any model is fitted. + +The third route is Pandas. It iterates over prediction rows and explicitly filters transactions to the customer's id and timestamp at or before the cutoff. That implementation does not execute either SQL statement. + +A second fixture checks `ROW_NUMBER`, `RANK`, and `DENSE_RANK` on a known tie pattern. This matters because matching column names across engines is not enough; window semantics must also agree on the object being computed. + +## What this supports + +- deterministic SQLite/DuckDB equality for the tested point-in-time aggregates; +- an independent Pandas calculation of the same feature object; +- explicit NULL/no-history behavior; +- a future-only sentinel that must remain excluded; +- cross-engine checks of basic ranking-window semantics. + +## What it does not support + +- full SQLite/DuckDB/PostgreSQL dialect equivalence; +- equivalence of query optimizers or execution plans; +- point-in-time correctness under late-arriving data, because event time is not ingest time; +- time-zone correctness; +- feature-store or warehouse claims. + +The purpose is not to add another database name to the README. The purpose is to make one information-set definition survive a second SQL engine and an independent non-SQL calculation. diff --git a/pyproject.toml b/pyproject.toml index 1264dab..35adb40 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -36,6 +36,9 @@ dependencies = [ "pytest>=7.4", ] +[project.optional-dependencies] +duckdb = ["duckdb>=1.0"] + [project.urls] Homepage = "https://github.com/pavanamthomas/sql-ml-feature-engineering-lab" Repository = "https://github.com/pavanamthomas/sql-ml-feature-engineering-lab" diff --git a/src/sqlfeat/cross_engine.py b/src/sqlfeat/cross_engine.py new file mode 100644 index 0000000..49e2a12 --- /dev/null +++ b/src/sqlfeat/cross_engine.py @@ -0,0 +1,220 @@ +"""Cross-engine point-in-time checks on one deterministic relational fixture. + +This module is intentionally small. It does not claim that SQLite and DuckDB +are interchangeable databases. It asks a narrower question: given the same +prediction cutoffs and transaction rows, do both engines produce the same +point-in-time feature table once their date-difference syntax is made explicit? +""" + +from __future__ import annotations + +import sqlite3 +from dataclasses import dataclass + +import pandas as pd + + +@dataclass(frozen=True) +class ParityFixture: + predictions: pd.DataFrame + transactions: pd.DataFrame + + +def build_fixture() -> ParityFixture: + """Return rows containing a planted post-cutoff sentinel transaction.""" + predictions = pd.DataFrame( + [ + ("p1", 1, "2026-01-10 00:00:00"), + ("p2", 2, "2026-01-10 00:00:00"), + ("p3", 3, "2026-01-10 00:00:00"), + ], + columns=["prediction_id", "customer_id", "cutoff"], + ) + transactions = pd.DataFrame( + [ + ("t1", 1, "2026-01-01 00:00:00", 10.0), + ("t2", 1, "2026-01-09 00:00:00", 20.0), + # Deliberately future-only. A correct point-in-time query excludes it. + ("sentinel", 1, "2026-01-11 00:00:00", 99999.0), + ("t4", 2, "2026-01-05 00:00:00", 7.5), + ], + columns=["txn_id", "customer_id", "txn_ts", "amount"], + ) + return ParityFixture(predictions=predictions, transactions=transactions) + + +_SQLITE_QUERY = """ +WITH eligible AS ( + SELECT + p.prediction_id, + p.customer_id, + p.cutoff, + t.txn_id, + t.txn_ts, + t.amount + FROM predictions AS p + LEFT JOIN transactions AS t + ON t.customer_id = p.customer_id + AND t.txn_ts <= p.cutoff +), aggregated AS ( + SELECT + prediction_id, + customer_id, + cutoff, + COUNT(txn_id) AS txn_count, + COALESCE(SUM(amount), 0.0) AS spend, + MAX(txn_ts) AS last_txn_ts + FROM eligible + GROUP BY prediction_id, customer_id, cutoff +) +SELECT + prediction_id, + customer_id, + txn_count, + spend, + CASE + WHEN last_txn_ts IS NULL THEN NULL + ELSE CAST(julianday(cutoff) - julianday(last_txn_ts) AS INTEGER) + END AS recency_days +FROM aggregated +ORDER BY prediction_id +""" + + +_DUCKDB_QUERY = """ +WITH eligible AS ( + SELECT + p.prediction_id, + p.customer_id, + p.cutoff, + t.txn_id, + t.txn_ts, + t.amount + FROM predictions AS p + LEFT JOIN transactions AS t + ON t.customer_id = p.customer_id + AND CAST(t.txn_ts AS TIMESTAMP) <= CAST(p.cutoff AS TIMESTAMP) +), aggregated AS ( + SELECT + prediction_id, + customer_id, + cutoff, + COUNT(txn_id) AS txn_count, + COALESCE(SUM(amount), 0.0) AS spend, + MAX(txn_ts) AS last_txn_ts + FROM eligible + GROUP BY prediction_id, customer_id, cutoff +) +SELECT + prediction_id, + customer_id, + txn_count, + spend, + CASE + WHEN last_txn_ts IS NULL THEN NULL + ELSE date_diff('day', CAST(last_txn_ts AS TIMESTAMP), CAST(cutoff AS TIMESTAMP)) + END AS recency_days +FROM aggregated +ORDER BY prediction_id +""" + + +_RANK_QUERY = """ +SELECT + id, + score, + ROW_NUMBER() OVER (ORDER BY score DESC, id) AS row_number_value, + RANK() OVER (ORDER BY score DESC) AS rank_value, + DENSE_RANK() OVER (ORDER BY score DESC) AS dense_rank_value +FROM rank_demo +ORDER BY id +""" + + +def sqlite_point_in_time_features(fixture: ParityFixture | None = None) -> pd.DataFrame: + fixture = fixture or build_fixture() + conn = sqlite3.connect(":memory:") + try: + fixture.predictions.to_sql("predictions", conn, index=False) + fixture.transactions.to_sql("transactions", conn, index=False) + return pd.read_sql_query(_SQLITE_QUERY, conn) + finally: + conn.close() + + +def duckdb_point_in_time_features(fixture: ParityFixture | None = None) -> pd.DataFrame: + try: + import duckdb + except ImportError as exc: # pragma: no cover - exercised only without optional dependency + raise ImportError("install sqlfeat[duckdb] to run DuckDB parity checks") from exc + + fixture = fixture or build_fixture() + conn = duckdb.connect(database=":memory:") + try: + conn.register("predictions_df", fixture.predictions) + conn.register("transactions_df", fixture.transactions) + conn.execute("CREATE TABLE predictions AS SELECT * FROM predictions_df") + conn.execute("CREATE TABLE transactions AS SELECT * FROM transactions_df") + return conn.execute(_DUCKDB_QUERY).df() + finally: + conn.close() + + +def independent_expected_features(fixture: ParityFixture | None = None) -> pd.DataFrame: + """Pandas calculation that does not execute either SQL query.""" + fixture = fixture or build_fixture() + p = fixture.predictions.copy() + t = fixture.transactions.copy() + p["cutoff_dt"] = pd.to_datetime(p["cutoff"]) + t["txn_dt"] = pd.to_datetime(t["txn_ts"]) + + rows: list[dict[str, object]] = [] + for pred in p.itertuples(index=False): + eligible = t[(t["customer_id"] == pred.customer_id) & (t["txn_dt"] <= pred.cutoff_dt)] + if eligible.empty: + recency: int | None = None + spend = 0.0 + else: + last = eligible["txn_dt"].max() + recency = int((pred.cutoff_dt - last).days) + spend = float(eligible["amount"].sum()) + rows.append( + { + "prediction_id": pred.prediction_id, + "customer_id": int(pred.customer_id), + "txn_count": int(len(eligible)), + "spend": spend, + "recency_days": recency, + } + ) + return pd.DataFrame(rows).sort_values("prediction_id").reset_index(drop=True) + + +def rank_fixture() -> pd.DataFrame: + return pd.DataFrame( + [("a", 9.0), ("b", 9.0), ("c", 7.0), ("d", 4.0)], + columns=["id", "score"], + ) + + +def sqlite_rank_results() -> pd.DataFrame: + conn = sqlite3.connect(":memory:") + try: + rank_fixture().to_sql("rank_demo", conn, index=False) + return pd.read_sql_query(_RANK_QUERY, conn) + finally: + conn.close() + + +def duckdb_rank_results() -> pd.DataFrame: + try: + import duckdb + except ImportError as exc: # pragma: no cover + raise ImportError("install sqlfeat[duckdb] to run DuckDB parity checks") from exc + conn = duckdb.connect(database=":memory:") + try: + conn.register("rank_df", rank_fixture()) + conn.execute("CREATE TABLE rank_demo AS SELECT * FROM rank_df") + return conn.execute(_RANK_QUERY).df() + finally: + conn.close() diff --git a/tests/test_cross_engine_parity.py b/tests/test_cross_engine_parity.py new file mode 100644 index 0000000..8f71bd3 --- /dev/null +++ b/tests/test_cross_engine_parity.py @@ -0,0 +1,60 @@ +"""Cross-engine point-in-time parity checks.""" + +from __future__ import annotations + +import pandas as pd + +from sqlfeat.cross_engine import ( + duckdb_point_in_time_features, + duckdb_rank_results, + independent_expected_features, + sqlite_point_in_time_features, + sqlite_rank_results, +) + + +def _normalise(df: pd.DataFrame) -> pd.DataFrame: + out = df.copy().sort_values("prediction_id").reset_index(drop=True) + out["customer_id"] = out["customer_id"].astype(int) + out["txn_count"] = out["txn_count"].astype(int) + out["spend"] = out["spend"].astype(float) + out["recency_days"] = out["recency_days"].astype("Int64") + return out + + +def test_sqlite_duckdb_and_pandas_agree_on_point_in_time_features() -> None: + sqlite = _normalise(sqlite_point_in_time_features()) + duckdb = _normalise(duckdb_point_in_time_features()) + expected = _normalise(independent_expected_features()) + + pd.testing.assert_frame_equal(sqlite, expected, check_dtype=False, atol=1e-12, rtol=0) + pd.testing.assert_frame_equal(duckdb, expected, check_dtype=False, atol=1e-12, rtol=0) + + +def test_future_sentinel_is_excluded_without_using_model_performance() -> None: + result = _normalise(duckdb_point_in_time_features()) + row = result.loc[result["prediction_id"] == "p1"].iloc[0] + assert row["txn_count"] == 2 + assert row["spend"] == 30.0 + assert row["spend"] < 99999.0 + assert row["recency_days"] == 1 + + +def test_no_history_preserves_zero_aggregates_and_null_recency() -> None: + result = _normalise(sqlite_point_in_time_features()) + row = result.loc[result["prediction_id"] == "p3"].iloc[0] + assert row["txn_count"] == 0 + assert row["spend"] == 0.0 + assert pd.isna(row["recency_days"]) + + +def test_window_rank_semantics_match_across_engines() -> None: + sqlite = sqlite_rank_results().sort_values("id").reset_index(drop=True) + duckdb = duckdb_rank_results().sort_values("id").reset_index(drop=True) + pd.testing.assert_frame_equal(sqlite, duckdb, check_dtype=False) + + # Tied score 9 gets rank 1 in both rows; the next ordinary rank is 3, + # while dense rank advances to 2. ROW_NUMBER is made deterministic by id. + assert list(sqlite["rank_value"]) == [1, 1, 3, 4] + assert list(sqlite["dense_rank_value"]) == [1, 1, 2, 3] + assert list(sqlite["row_number_value"]) == [1, 2, 3, 4]