Skip to content

Commit 0786b26

Browse files
mstrathmanclaude
andcommitted
docs: fit/predict/backtest reference, skills, and receipts
Document the new surface for a first-time reader: the functions reference (fit/predict/backtest, predict_batch's optional train_query and required apply_query, the JSON-object-label convention), the models and options pages, the sqlite-predict / distill-lifecycle / interpret-backtest skills, README, and the CHANGELOG. Scope the read-only guarantee to the serving functions (registration writes to _predict_models). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
1 parent 5db8f4d commit 0786b26

12 files changed

Lines changed: 273 additions & 160 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,24 @@ project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
66

77
## [Unreleased]
88

9+
### Changed
10+
11+
- **The tabular and evaluation surface is now the scikit-learn `fit`/`predict`
12+
shape.** `fit(f1, ..., fN, label [, options])` is a new aggregate that trains a
13+
native student over your rows (the label is the last positional argument).
14+
With the `'{"register":"name"}'` option it registers the trained model and
15+
returns its id; without it, `fit()` returns the student as a serialized blob.
16+
`predict(model, f1, ..., fN [, options])` is now a per-row **scalar** that
17+
serves a student (a registered id or a `fit()` blob) and composes with
18+
`WHERE`, joins, and ORMs. `backtest(ts, value, horizon [, options])` is now an
19+
**aggregate** over your rows like `forecast`/`detect_anomalies`, one JSON
20+
document per group, expanded with the new `backtest_rows()`. The former
21+
`predict(train_query, apply_query)` table-valued function is renamed
22+
**`predict_batch`** (the batched, in-context `knn5-incontext`, and ONNX serving
23+
path); the old query-string `backtest(query, horizon)` TVF is removed. This is
24+
a pre-1.0 break; `distill_predict`/`distill_forecast`, `forecast`, and
25+
`detect_anomalies` are unchanged.
26+
927
## [0.1.0] - 2026-07-30
1028

1129
### Changed

‎README.md‎

Lines changed: 35 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -109,8 +109,7 @@ SELECT model_id, holdout_metric FROM distill_predict(
109109
'{"target":"churned","student_id":"churn-v1","student_kind":"gbt"}');
110110

111111
-- forever: serve the student per row, in microseconds, no runtime attached
112-
SELECT * FROM predict(NULL, 'SELECT id, tenure, spend FROM customers',
113-
'{"model":"churn-v1"}');
112+
SELECT id, predict('churn-v1', tenure, spend) FROM customers;
114113

115114
-- the same move for time series: distill a Chronos-class teacher's forecasts
116115
-- into a DLinear/TiDE student, then serve it through forecast()
@@ -159,25 +158,32 @@ skills-capable agent, or read them as the condensed operator's manual.
159158
| --- | --- | --- |
160159
| `forecast(ts, value, horizon [, options])` | Where is this metric going? | an aggregate over your rows: forecast steps with prediction intervals, one JSON document per group |
161160
| `detect_anomalies(ts, value [, options])` | Which points are abnormal? | an aggregate over your rows: per-point anomaly probability and interval, one JSON document per group |
162-
| `predict(train_query, apply_query [, options])` | Classify/regress unseen rows | a prediction and confidence per row, zero-shot from in-context examples |
163-
| `distill_predict(train_query [, options])` | Compress a slow teacher into a fast student | a tiny native model (decision tree or gradient-boosted forest), registered and ready for `predict()` |
164-
| `distill_forecast(train_query [, options])` | Compress a forecast foundation model into a fast student | a native DLinear/TiDE forecast net (a linear skip plus a small residual), registered and ready for `forecast()` |
165-
| `backtest(query, horizon [, options])` | How accurate is the model here? | per-fold accuracy (MAE, RMSE, MASE, sMAPE) and interval coverage from a rolling-origin evaluation |
166-
167-
One calling convention per operation. `forecast` and `detect_anomalies` are
168-
**aggregates**: your statement supplies the rows, so `WHERE`, joins, bound
169-
parameters, and `GROUP BY` all compose naturally, from the CLI or from an ORM
170-
(Drizzle, SQLAlchemy, Diesel). They are **pure functions**: nothing is ever
171-
written, so they run on read-only databases and inside views. Each group
172-
returns one JSON document; expand it with `forecast_rows()` /
173-
`anomaly_rows()`, or `JSON.parse` it in your app. Each language's
161+
| `backtest(ts, value, horizon [, options])` | How accurate is the model here? | an aggregate over your rows: per-fold MAE, RMSE, MASE, sMAPE and coverage from rolling-origin evaluation |
162+
| `fit(f1, ..., fN, label [, options])` | Train a model on labeled rows | an aggregate over your rows: a native tabular student, registered by id or returned as a blob |
163+
| `predict(model, f1, ..., fN [, options])` | Classify or regress a row | a scalar: one prediction per row from a fitted student |
164+
| `distill_predict(train_query [, options])` | Compress a slow teacher into a fast student | a tiny native model (decision tree, gradient-boosted forest, or MLP), registered and served by `predict` |
165+
| `distill_forecast(train_query [, options])` | Compress a forecast foundation model into a fast student | a native DLinear/TiDE forecast net (a linear skip plus a small residual), registered and served by `forecast` |
166+
167+
One rule for the whole surface. `forecast`, `detect_anomalies`, `backtest`, and
168+
`fit` are **aggregates**: your statement supplies the rows, so `WHERE`, joins,
169+
bound parameters, and `GROUP BY` all compose naturally, from the CLI or from an
170+
ORM (Drizzle, SQLAlchemy, Diesel). The first three are **pure functions**:
171+
nothing is written, so they run on read-only databases and inside views. Each
172+
returns one JSON document; expand it with `forecast_rows()` / `anomaly_rows()` /
173+
`backtest_rows()`, or `JSON.parse` it in your app. `predict` is a **scalar**,
174+
one prediction per row, so it drops into any `SELECT` beside your other columns.
175+
Each language's
174176
[getting-started guide](https://code.purestorage.com/sqlite-predict/getting-started/python/)
175177
shows the pattern through its native ORM (SQLAlchemy, Drizzle, Diesel).
176178

177-
`backtest`, `predict`, and the `distill_*` operations take read-only SELECT
178-
queries (training needs labeled or windowed row sets); their results are
179-
ordinary rows you can join, filter, and materialize. Options everywhere are a
180-
trailing JSON object (`'{"confidence_level":0.9}'`).
179+
`distill_predict`, `distill_forecast`, and `predict_batch` take read-only SELECT
180+
queries (training needs labeled or windowed row sets, batched serving re-runs a
181+
query); their results are ordinary rows you can join, filter, and materialize.
182+
`predict_batch(train_query, apply_query, ...)` scores the rows of `apply_query`,
183+
which is required; `train_query` is optional, used only by in-context models, and
184+
is `NULL` when serving a registered model: `predict_batch(NULL, apply_query,
185+
'{"model":"..."}')`.
186+
Options everywhere are a trailing JSON object (`'{"confidence_level":0.9}'`).
181187

182188
### Calibrated intervals, auto-selection, and backtesting
183189

@@ -200,8 +206,8 @@ trailing JSON object (`'{"confidence_level":0.9}'`).
200206

201207
```sql
202208
-- confirm the conformal band actually covers at the nominal 90%
203-
SELECT avg(coverage) FROM backtest('SELECT ts, value FROM readings', 6,
204-
'{"interval_method":"conformal","confidence_level":0.9,"folds":25}');
209+
SELECT avg(coverage) FROM backtest_rows((SELECT backtest(ts, value, 6,
210+
'{"interval_method":"conformal","confidence_level":0.9,"folds":25}') FROM readings));
205211
```
206212

207213
## Models
@@ -219,7 +225,7 @@ well-studied statistical models:
219225
subsequence-reconstruction detector (windowed PCA reconstruction error), the
220226
method family that leads the TSB-AD-U benchmark; ~2x the residual detector on
221227
the typical series there
222-
- `knn5-incontext` (z-scored 5-NN) for `predict()`
228+
- `knn5-incontext` (z-scored 5-NN) for `predict_batch()`
223229

224230
Foundation models are treated as *teachers*, not serving paths: in
225231
benchmarking they were far too slow to call per query on CPU. The path to
@@ -298,8 +304,8 @@ count), so the common case is one line:
298304

299305
```sql
300306
SELECT predict_register('churn', '/models/churn.onnx');
301-
SELECT * FROM predict(NULL, 'SELECT id, tenure, spend FROM customers',
302-
'{"model":"churn"}');
307+
SELECT * FROM predict_batch(NULL, 'SELECT id, tenure, spend FROM customers',
308+
'{"model":"churn"}');
303309
```
304310

305311
Feature columns map by position (apply-query order); pass an explicit
@@ -384,10 +390,12 @@ build `make loadable-onnx-gpu`.
384390

385391
## How it works
386392

387-
`forecast` and `detect_anomalies` are SQL aggregate functions; `backtest`,
388-
`predict`, and the `distill_*` operations are [eponymous table-valued
389-
functions][tvf] (virtual table modules) over the rows of an inner query.
390-
Statistical models run in-process on CPU and are deterministic. Registered
393+
`forecast`, `detect_anomalies`, `backtest`, and `fit` are SQL aggregate
394+
functions; `predict` is a scalar; `distill_predict`, `distill_forecast`, and
395+
`predict_batch` are [eponymous table-valued functions][tvf] (virtual table
396+
modules) over the rows of an inner query (`predict_batch` takes two: an optional
397+
`train_query` and the required `apply_query`). Statistical models run in-process on
398+
CPU and are deterministic. Registered
391399
models and distilled students live in one `_predict_models` table the
392400
extension manages, content-addressed so the exact bytes are pinned and
393401
verified before deserialization.

‎skills/distill-lifecycle/SKILL.md‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,10 +34,18 @@ SELECT model_id FROM distill_forecast('SELECT series_key, value FROM obs',
3434
'{"context":96,"horizon":24,"student_id":"traffic-v1"}');
3535
```
3636

37+
For your own hard labels, `fit(f1, f2, label, '{"register":"churn-v1"}')` is
38+
the one-call training path. `distill_predict` trains on hard labels too; on top
39+
of that it supports two optional inputs, either or both: teacher relabeling (a
40+
registered model relabels the rows before fitting) and soft-label distillation
41+
(pass `proba`/`classes` to fit probability targets). Omit both to train on the
42+
labels exactly as given, which is what the examples above do.
43+
3744
Students register in `_predict_models` as content-hashed rows; they
38-
snapshot, fork, and sync with the database. Serve by name:
39-
`predict(NULL, apply_sql, '{"model":"churn-v1"}')` or
40-
`forecast(ts, value, 24, '{"model":"traffic-v1"}')`.
45+
snapshot, fork, and sync with the database. Serve a tabular student per
46+
row with the `predict` scalar, `SELECT id, predict('churn-v1', f1, f2)
47+
FROM rows`, and a forecast student through `forecast(ts, value, 24,
48+
'{"model":"traffic-v1"}')`.
4149

4250
## Verify before serving
4351

‎skills/interpret-backtest/SKILL.md‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,13 @@ metadata:
1414

1515
`backtest` answers "how would this model have done on my series" with
1616
rolling-origin evaluation: it repeatedly hides the tail of the series,
17-
forecasts it, and scores against what actually happened.
17+
forecasts it, and scores against what actually happened. It is an
18+
aggregate over your rows, like `forecast`, and returns one JSON document;
19+
expand it with `backtest_rows(...)`.
1820

1921
```sql
20-
SELECT * FROM backtest('SELECT ts, value FROM readings', 24,
21-
'{"model":"theta-classic","folds":5}');
22+
SELECT * FROM backtest_rows((SELECT backtest(ts, value, 24,
23+
'{"model":"theta-classic","folds":5}') FROM readings));
2224
```
2325

2426
## The metrics that matter
@@ -43,9 +45,9 @@ the repo). When interval truth matters, request conformal intervals in
4345
the same call:
4446

4547
```sql
46-
SELECT * FROM backtest('SELECT ts, value FROM readings', 24,
47-
'{"model":"theta-classic",
48-
"interval_method":"conformal"}');
48+
SELECT * FROM backtest_rows((SELECT backtest(ts, value, 24,
49+
'{"model":"theta-classic","interval_method":"conformal"}')
50+
FROM readings));
4951
```
5052

5153
Conformal intervals calibrate to measured out-of-sample residuals and

‎skills/sqlite-predict/SKILL.md‎

Lines changed: 28 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -13,23 +13,29 @@ metadata:
1313
# Using sqlite-predict
1414

1515
The extension turns prediction into SQL. Load `predict0` (pip/npm/cargo
16-
package `sqlite-predict`), then call functions over your own rows. Serving
17-
is pure: no writes, works on read-only databases and inside views.
16+
package `sqlite-predict`), then call functions over your own rows. Serving is
17+
pure: `forecast`, `detect_anomalies`, `backtest`, `predict`, and `fit` without
18+
`register` do not write, so they run on read-only databases and inside views.
19+
Registering a model (`fit` with `'{"register":"m"}'`, and the distillers)
20+
persists to `_predict_models` and needs a writable database.
1821

1922
## Which operation for which question
2023

2124
| Question | Call |
2225
| --- | --- |
2326
| "What will this metric do next?" | `SELECT forecast(ts, value, horizon) FROM t` |
2427
| "Which points are anomalous?" | `SELECT detect_anomalies(ts, value) FROM t` |
25-
| "Predict a label/value for these rows" | `SELECT * FROM predict(train_sql, apply_sql, options)` |
26-
| "How accurate would this be on my data?" | `SELECT * FROM backtest(series_sql, horizon)` |
28+
| "Train a model on labeled rows" | `SELECT fit(f1, ..., fN, label, '{"register":"m"}') FROM t` |
29+
| "Predict a label/value per row" | `SELECT predict('m', f1, ..., fN) FROM t` |
30+
| "How accurate would this be on my data?" | `SELECT backtest(ts, value, horizon) FROM t` |
2731
| "Make serving instant and self-contained" | `distill_predict` / `distill_forecast` (see the distill-lifecycle skill) |
2832

29-
`forecast` and `detect_anomalies` are aggregates: plain SQL supplies the
30-
rows, `GROUP BY` splits series, `WHERE` and joins compose, ORMs work
31-
unchanged. `predict`, `backtest`, and the distillers are table-valued
32-
functions that take a query string.
33+
`forecast`, `detect_anomalies`, `backtest`, and `fit` are aggregates:
34+
plain SQL supplies the rows, `GROUP BY` splits series or segments, `WHERE`
35+
and joins compose, ORMs work unchanged. `predict` is a scalar, one
36+
prediction per row, so it drops into any `SELECT` beside your other
37+
columns. The distillers and `predict_batch` are table-valued functions
38+
that take a query string.
3339

3440
## Reading results
3541

@@ -40,6 +46,10 @@ Each aggregate group returns one JSON document: `{"model", "status",
4046
SELECT r.* FROM forecast_rows((SELECT forecast(ts, value, 24) FROM t)) AS r;
4147
```
4248

49+
`anomaly_rows(...)` and `backtest_rows(...)` expand anomaly and backtest
50+
documents the same way. `predict` returns its value directly, no
51+
expansion.
52+
4353
- `model` reports the model that actually served. With no model named,
4454
`auto` selects the best available per series and reports the winner's
4555
id, never the string "auto".
@@ -74,8 +84,16 @@ problem and often the fix.
7484
on smooth data; pass `'{"interval_method":"conformal"}'` for
7585
calibrated coverage (statistical models only) and verify with
7686
`backtest` (see the interpret-backtest skill).
77-
- `predict` with `NULL` train_query serves a distilled student; with a
78-
train query it runs the in-context `knn5-incontext` model zero-shot.
87+
- `fit(f1, ..., fN, label)` trains over your rows; the label is the last
88+
argument, there is no `target` option. `'{"register":"churn-v1"}'`
89+
registers the model and returns its id; otherwise it returns a model
90+
blob you can pass to `predict`. Default kind is `gbt`; `'{"kind":"tree"}'`
91+
for a single tree.
92+
- `predict(model, f1, ..., fN)` serves a native student per row; the
93+
model is a registered id or a `fit()` blob, and features are positional,
94+
so a count mismatch fails loud. Pass `'{"proba":true}'` for a
95+
`{"prediction": "1", "confidence": 0.98}` document. For in-context `knn5-incontext`
96+
(a train query, no fit step) or ONNX serving, use `predict_batch`.
7997

8098
## Checking the environment
8199

‎website/src/content/docs/guides/backtesting.md‎

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,21 +3,22 @@ title: Backtesting
33
description: Score a model's accuracy on your own data with rolling-origin evaluation.
44
---
55

6-
`backtest(query, horizon [, options])` runs a rolling-origin evaluation: for each
7-
of several past cutoffs it fits the model, forecasts, and compares to the held-out
8-
actuals. It returns per-fold accuracy and interval quality, so a caller (say, an
9-
agent auditing its own forecasts) can measure quality locally.
6+
`backtest(ts, value, horizon [, options])` runs a rolling-origin evaluation: for
7+
each of several past cutoffs it fits the model, forecasts, and compares to the
8+
held-out actuals. It is an aggregate over your rows, like `forecast`, so `WHERE`,
9+
joins, and `GROUP BY` compose. Each group returns one JSON document of per-fold
10+
results; expand it to typed rows with `backtest_rows()`:
1011

1112
```sql
12-
SELECT fold, model, mae, rmse, mase, smape, coverage, mean_interval_width
13-
FROM backtest('SELECT ts, value FROM readings', 6, '{"folds":20}');
13+
SELECT r.fold, r.model, r.mae, r.rmse, r.mase, r.smape, r.coverage, r.mean_interval_width
14+
FROM backtest_rows((SELECT backtest(ts, value, 6, '{"folds":20}') FROM readings)) AS r;
1415
```
1516

16-
Aggregate in plain SQL:
17+
Aggregate over the folds in plain SQL:
1718

1819
```sql
19-
SELECT avg(mase) FROM backtest('SELECT ts, value FROM readings', 6,
20-
'{"model":"auto","folds":20}');
20+
SELECT avg(mase) FROM backtest_rows((SELECT backtest(ts, value, 6,
21+
'{"model":"auto","folds":20}') FROM readings));
2122
```
2223

2324
## Options
@@ -31,10 +32,10 @@ SELECT avg(mase) FROM backtest('SELECT ts, value FROM readings', 6,
3132

3233
## Validate conformal coverage
3334

34-
Because `backtest()` reports coverage for the chosen interval method, you can
35+
Because `backtest` reports coverage for the chosen interval method, you can
3536
confirm the conformal band actually covers at the nominal level on your data:
3637

3738
```sql
38-
SELECT avg(coverage) FROM backtest('SELECT ts, value FROM readings', 6,
39-
'{"interval_method":"conformal","confidence_level":0.9,"folds":25}');
39+
SELECT avg(coverage) FROM backtest_rows((SELECT backtest(ts, value, 6,
40+
'{"interval_method":"conformal","confidence_level":0.9,"folds":25}') FROM readings));
4041
```

‎website/src/content/docs/guides/distillation.md‎

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -22,17 +22,20 @@ SELECT model_id, holdout_metric FROM distill_predict(
2222
'SELECT f1, f2, label FROM training',
2323
'{"target":"label","student_id":"churn-v1","student_kind":"gbt"}');
2424

25-
-- forever: serve it. train_query is NULL because the student already
26-
-- learned; only the rows to predict are needed.
27-
SELECT row_ref, prediction, confidence FROM predict(NULL,
28-
'SELECT id, f1, f2 FROM customers',
29-
'{"model":"churn-v1"}');
25+
-- forever: serve it per row with the predict scalar
26+
SELECT id, predict('churn-v1', f1, f2) AS prediction FROM customers;
3027
```
3128

32-
The `NULL` first argument is the signature of serving a student: `predict`
33-
normally takes a training query for in-context models, but a student carries
34-
its training inside its blob, so passing a query alongside a student is
35-
rejected (`PREDICT_ERR_OPTIONS`) rather than silently ignored.
29+
`predict('churn-v1', f1, f2)` serves the registered student one row at a
30+
time, so it drops into any `SELECT` beside your other columns and composes
31+
with `WHERE` and joins. Features are positional and must match what the
32+
student was trained on: a count mismatch fails loudly rather than guessing.
33+
Pass `'{"proba":true}'` for a `{"prediction": "1", "confidence": 0.98}` document.
34+
35+
If the teacher is just your own labels, with no relabeling or soft targets,
36+
`fit(f1, f2, label, '{"register":"churn-v1"}')` trains and registers in one
37+
call; `distill_predict` is the fuller path that adds teacher relabeling and
38+
soft-label distillation.
3639

3740
`student_kind` is `tree` (a single CART), `gbt` (a gradient-boosted forest
3841
with second-order leaves, which matches or beats tuned XGBoost on most

0 commit comments

Comments
 (0)