2026-11-27 16:19 UTC

tsfm-pg brings Chronos-2 and Timestral forecasting into PostgreSQL SQL

state: expiredheat: mediumuncertainty: mediumrelevance: mediumtime-series-models postgresql inferencebarddoo

What is this?

tsfm-pg is an open-source PostgreSQL extension by GitHub user barddoo, announced in a Show HN post on 12 November 2026. Its repository says it embeds the tsfm-zig forecasting engine and supports Chronos-2 and Timestral checkpoints, exposing forecasts through SQL functions. Model files are installed on the database host; queries do not send time series to a cloud API. The project documents PostgreSQL 16/17 support, CPU-only builds by default, optional GPU support, and local performance figures, but the supplied evidence does not independently validate those figures or establish adoption. It does not work on managed PostgreSQL services that prohibit custom shared libraries and host-filesystem access.

Why it matters

This makes pretrained time-series forecasting callable where data already lives: SQL users can produce forecasts and quantiles without exporting series to a separate inference service. That could simplify local or self-hosted analytics and reduce data movement, but access is limited to operators able to install custom database extensions; it is not a drop-in option for managed Postgres. The release expands deployment choices rather than demonstrating a new forecasting capability or broad uptake.

Current assessment

New: barddoo’s tsfm-pg repository presents a PostgreSQL extension that runs Chronos-2 or Timestral locally and exposes single-series, multivariate/covariate, batch, and timestamp-oriented forecast functions through SQL. The README says model downloads happen at installation or container startup, never from a SQL query; configured weights reside on the database host. This may let analytics workflows forecast near stored data and avoid sending series to an inference API, though the evidence does not quantify privacy, cost, or operational benefits. The project documents PostgreSQL 16/17 and Zig 0.17.1 requirements, superuser installation/configuration, and support for self-hosted, Docker, and Kubernetes deployments; it explicitly says managed services such as RDS, Cloud SQL, Azure, Supabase, and Neon are unsupported where custom libraries/filesystem access are unavailable. CPU is the default, with opt-in Metal/CUDA. Repository-reported M4 timings are 155 ms for one 365-to-90 forecast and 4.4 s for a batch of 32 at one thread (38 ms and 1.0 s at eight threads); these are project claims, not independently verified benchmarks. No adoption evidence is supplied. Chronos-2 weights are described as Apache-2.0; Timestral weights are subject to Modified MIT revenue-cap terms and are not redistributed. Track installation usability, parity/performance validation, security and operational experience, and whether managed database providers enable similar local inference.

Measured heat

now 0 pts/hpeak 0 pts/hcomments 0/hpeers p17momentum: steady2 platformsage 336h
points/hour across evidence · reading as of 2026-11-26 11:23:00.801938+11:00 · deterministic, not a model opinion

How the heat travelled

11-12 00:22 (minted)⭐ origin echo-reconstructedThe repository describes a PostgreSQL extension that runs Chronos-2 and Timestral forecasts through SQL, with model weights on the database
barddoo on github (echo) · attributed from hn.story.50460864 · published time unknown
—
11-12 00:00first on hacker news · published · lag ?Show HN: Tsfm-pg: Run Chronos-2/Timestral forecasts inside Postgres with SQL
pseudocharles
—
11-12 00:00amplified on hacker news 👑hn.story.50460864
pseudocharles
peak 1 · 1 comments · 104% of case engagement
11-12 00:20our radar first saw it · lag ?discovery anchor: hn.story.50460864—

Evidence (2) — ⭐ canonical anchor

sourceobjectauthorscorecomments
🟧 hnShow HN: Tsfm-pg: Run Chronos-2/Timestral forecasts inside Postgres with SQL
Retrieved article excerpt

Open article · Retrieved 2026-11-12T00:21:34.660826+00:00

# tsfm-pg

`tsfm-pg` runs the [tsfm-zig](https://github.com/barddoo/tsfm-zig) forecaster
inside Postgres. It supports **Chronos-2** and **Timestral** checkpoints. The
model and weights sit on the database host, and a query never ships the series to
a cloud API.

The engine is linked as a Zig module: no C ABI, no `dlopen`, no second artifact.
`tsfm.so` is the whole extension.

## Quickstart

Requires Zig 0.17.1 and PostgreSQL 16 or 17 with server headers. `PG_HOME` is a
Postgres install prefix:

```
export PG_HOME=/path/to/postgres
export PG_CONFIG="$PG_HOME/bin/pg_config"

zig build -Dcpu=native -p "$PG_HOME"                 # CPU-only; see GPU below
"$PG_HOME/bin/psql" -U postgres -c 'CREATE EXTENSION tsfm'

# install-time download, never from SQL; defaults to amazon/chronos-2
scripts/fetch-model.sh "$("$PG_HOME/bin/pg_config" --sharedir)/tsfm/models"
```

The default `tsfm.model_dir` is `<sharedir>/tsfm/models`, so the fetched
checkpoint is found without further settings. Run a forecast:

```
SELECT step, quantile, value
FROM tsfm_forecast(
       (SELECT array_agg(value ORDER BY ts) FROM metrics WHERE name = 'sku-123'),
       90)
WHERE quantile IN (0.1, 0.5, 0.9)
ORDER BY step, quantile;
```

The engine loads lazily on first use. `tsfm_load()` warms it explicitly (useful
for connection pools). A new session is needed to change `tsfm.model_dir` or
`tsfm.model` after the engine has loaded.

## SQL API

| function | returns |
| --- | --- |
| `tsfm_version()` | `text`: extension and pinned engine version |
| `tsfm_model_info()` | `jsonb`: model, dir, quantiles, context/prediction lengths, threads, SIMD |
| `tsfm_model_status()` | `jsonb`: is the configured directory usable, and if not, what to do |
| `tsfm_quantiles()` | `double precision[]`: the model's quantile levels |
| `tsfm_load()` | `boolean`: explicit warmup |
| `tsfm_forecast(history, horizon)` | `TABLE(step, quantile, value)` |
| `tsfm_forecast_ex(history, horizon, n_variates = 1, past = NULL, known = NULL, cat_past = NULL, cat_known = NULL)` | `TABLE(variate, step, quantile, value)` |
| `tsfm_forecast_batch(history, horizon, n_series, n_variates = 1, past = NULL, known = NULL, cat_past = NULL, cat_known = NULL)` | `TABLE(series, variate, step, quantile, value)` |
| `tsfm_forecast_matrix(history, horizon)` | `double precision[]`, `[step][quantile]` |
| `tsfm_forecast_matrix_ex(history, horizon, n_variates = 1, past = NULL, known = NULL, cat_past = NULL, cat_known = NULL)` | `double precision[]`, `[variate][step][quantile]` |
| `tsfm_forecast_ts(timestamps, history, horizon, step_size)` | `TABLE(ts, step, quantile, value)` |

All forecast functions are `STABLE PARALLEL RESTRICTED`; `tsfm_load()` is
`VOLATILE`. The long form arrives step-major, with `step` starting at 1.

## Data conventions

- `history` is ordered oldest → newest.
- `NULL` and `'NaN'::float8` elements are missing values.
- Values are converted to float32 for the engine. Infinities and values beyond
  the float32 range become missing; integers above 2^24 lose precision, so
  scale or offset large series such as epoch seconds first.
- Arrays are flattened row-major:
  - `history`: `V × T` (variates × steps)
  - `past` / `cat_past`: `C × T`
  - `known` / `cat_known`: `C × (T + horizon)`
  - batch `history`: `B × V × T`; batch covariates: `B × C × T` or
    `B × C × (T + horizon)`
- `variate` and `series` are numbered from 1.
- Chronos-2 accepts only `n_variates = 1` with no covariates. Timestral accepts
  multiple variates and numeric/categorical covariates.

## Functions by example

Every series in a table, one forecast each. The outer executor calls the
function once per group, so `statement_timeout`, `LIMIT` and cancellation work
between series:

```
SELECT m.name, f.step, f.value
FROM (SELECT name, array_agg(value ORDER BY ts) AS h
      FROM metrics GROUP BY name) m,
     LATERAL tsfm_forecast(m.h, 90) f
WHERE f.quantile = 0.5;
```

Two variates with one past-only and one known-future covariate:

```
SELECT variate, step, quantile, value
FROM tsfm_forecast_ex(
       ARRAY[10, 11, 12, 20, 21, 22]::float8[], -- 2 variates × 3 steps
       2,
       2,
       ARRAY[0, 1, 0]::float8[],                -- 1 past covariate × 3
       ARRAY[0, 1, 0, 1, 0]::float8[],          -- 1 known × (3 + 2)
       NULL,
       NULL)
WHERE quantile IN (0.1, 0.5, 0.9);
```

`tsfm_forecast_batch` passes `B` independent series in one engine call, reusing
each weight read across the batch. It checks for query cancellation between
chunks of 64 series; one forward pass is still not interruptible:

```
SELECT series, step, value
FROM tsfm_forecast_batch(ARRAY[/* B × 365 values */], 90, 100, 1)
WHERE quantile = 0.5;
```

The matrix forms return one array instead of rows:

```
SELECT tsfm_quantiles();
SELECT tsfm_forecast_matrix(ARRAY[1, 2, 3, 4, 5]::float8[], 4);       -- [step][quantile]
SELECT tsfm_forecast_matrix_ex(ARRAY[1, 2, 3, 10, 20, 30]::float8[], 2, 2);
```

Timestamps are attached from the last value and a step:

```
SELECT ts, step, quantile, value
FROM tsfm_forecast_ts(
       ARRAY['2024-01-01','2024-01-02','2024-01-03']::timestamptz[],
       ARRAY[10, 11, 12]::float8[],
       7,
       interval '1 day')
WHERE quantile = 0.5;
```

`tsfm_forecast_ts` assumes a regular step; it does not inspect gaps or
calendars.

## Privileges

`CREATE EXTENSION` is superuser-only, and the extension revokes `EXECUTE` from
`PUBLIC`. Grant it explicitly to application roles:

```
GRANT EXECUTE ON FUNCTION tsfm_version() TO analyst;
GRANT EXECUTE ON FUNCTION tsfm_model_info() TO analyst;
GRANT EXECUTE ON FUNCTION tsfm_model_status() TO analyst;
GRANT EXECUTE ON FUNCTION tsfm_quantiles() TO analyst;
GRANT EXECUTE ON FUNCTION tsfm_load() TO analyst;
GRANT EXECUTE ON FUNCTION tsfm_forecast(double precision[], integer) TO analyst;
GRANT EXECUTE ON FUNCTION tsfm_forecast_ex(double precision[], integer, integer, double precision[], double precision[], double precision[], double precision[]) TO analyst;
GRANT EXECUTE ON FUNCTION tsfm_forecast_batch(double precision[], integer, integer, integer, double precision[], double precision[], double precision[], double precision[]) TO analyst;
GRANT EXECUTE ON FUNCTION tsfm_forecast_matrix(double precision[], integer) TO analyst;
GRANT EXECUTE ON FUNCTION tsfm_forecast_matrix_ex(double precision[], integer, integer, double precision[], double precision[], double precision[], double precision[]) TO analyst;
GRANT EXECUTE ON FUNCTION tsfm_forecast_ts(timestamptz[], double precision[], integer, interval) TO analyst;
```

`tsfm_forecast_ts` calls `tsfm_forecast`, so a role needs `EXECUTE` on both.

## Settings

Settings that decide what runs or what is read from disk are **superuser-only**
(`SUSET`): `tsfm.model_dir`, `tsfm.model`, `tsfm.threads`, `tsfm.enabled` and
`tsfm.stub`. Set them in `postgresql.conf`, with `ALTER SYSTEM`, or per
role/database with `ALTER ROLE ... SET`. That makes `tsfm.enabled = off` a real
kill switch and stops ordinary roles from pointing the server at arbitrary
files. The decoding knobs are `USERSET`, so `SET LOCAL` works for them.

`tsfm.symmetric` is an SQL keyword: write `SET tsfm."symmetric" = off`.

| GUC | default | notes |
| --- | --- | --- |
| `tsfm.model_dir` | `<sharedir>/tsfm/models` | directory with `config.json` + `model.safetensors` |
| `tsfm.model` | `auto` | `auto`, `chronos-2`, `timestral`; `auto` reads `config.json` |
| `tsfm.threads` | `1` | 0..64, larger values clamped; `0` = auto (up to 4 workers by CPU count); fixed after load |
| `tsfm.max_context` | `0` | keep the most recent N values; `0` = model default |
| `tsfm.sort_quantiles` | `on` | per-step monotonic quantiles; off for raw parity |
| `tsfm.enabled` | `on` | kill switch; forecasts, `tsfm_load()` and `tsfm_quantiles()` error when off |
| `tsfm.stub` | `off` | naive last-value engine, for tests without weights |
| `tsfm.block_patches` | `32` | Timestral only: patches decoded per block (1..1024) |
| `tsfm.symmetric` | `on` | Timestral only: average with the mirrored forecast |
| `tsfm.clip_nonnegative` | `on` | Timestral only: clamp non-negative series at 0 |
| `tsfm.quantile_real_cap_k` | `1e4` | Timestral only: clamp to observed range + k×scale; 0 disables |
| `tsfm.extreme_value_threshold` | `1e30` | Timestral only: fed-back medians at/above this become 0 |

The engine is process-global per backend and loaded lazily. `tsfm.model_dir`
and `tsfm.model` are fixed once loaded; changing them later raises an error with
a hint to reconnect. `tsfm.threads` sizes the worker pool once.
`tsfm_model_info()` reports the values actually in use.

`tsfm.threads > 1` is opt-in. Workers touch only engine memory: they never call
`ereport`, never touch `palloc`, and never check PostgreSQL interrupts. The
default stays `1` because many backends each starting a pool can oversubscribe
the host.

The checkpoint is a read-only mmap. Every backend shares its file-backed pages
through the page cache, so the per-connection private cost is the model structs
plus forward-pass scratch (a few MB), not the weights. Engine allocations use
libc, not `palloc`, so they can outlive transactions and be used by workers. A
failed or partial checkpoint load is freed in one arena step. One forecast
result is capped at 16 million f32 values (64 MiB).

## Build and install

```
export PG_CONFIG="$PG_HOME/bin/pg_config"
zig build -Dcpu=native -p "$PG_HOME"
```

| option | meaning |
| --- | --- |
| `-Dcpu=` | target CPU (e.g. `native`, `baseline`, `x86_64_v3`) |
| `-Dtarget=` | target triple for cross-compilation |
| `-Doptimize=` / `--release=` | defaults to `ReleaseSafe` |
| `-Dgpu=` | `none` (default), `metal`, `cuda` |
| `-Dpg-port=` / `-Dpg-user=` | defaults for `pg_regress` |

`zig build` defaults to `ReleaseSafe`: a bounds or overflow bug in the model must
become a Postgres error, not a segmentation fault that takes the backend down.
Use `ReleaseFast` only for benchmarks.

`tsfm` is fetched from the commit pinned in `build.zig.zon`. `pgzx` is a path
dependency (`../pgzx`) because its published package omits `build.zig.zon` from
`.paths`; clone it next to this repository. Both commits are recorded in
`build.zig.zon` / `Dockerfile`.

### Dev loop script

```
scripts/dev.sh build      # build + install into $PG_HOME
scripts/dev.sh start      # start the local cluster if needed
scripts/dev.sh stop
scripts/dev.sh test       # engine tests, no Postgres
scripts/dev.sh regress    # build + start + pg_regress
scripts/dev.sh smoke      # one real forecast; needs TSFM_TEST_MODEL
scripts/dev.sh all
```

Env: `PG_HOME` (default `out/16`), `PGPORT` (5432), `PGUSER` (postgres),
`TSFM_CPU` (native), `TSFM_TEST_MODEL`.

## CPU and SIMD

Model GEMMs come from `tsfm-zig` built with `-Dblas=builtin`; the extension's
hot loops use Zig `@Vector` too. Vector width comes from the build's CPU, so
`-Dcpu=native` gives the best result on the build machine. `tsfm_model_info()`
reports `cpu_arch` and `simd_f32_lanes` (1 means scalar). Check a deployment
with:

```
SELECT tsfm_model_info()->>'simd_f32_lanes';
```

## GPU

The default build is **CPU-only**: `-Dcpu=native` only widens SIMD, it does not
enable a GPU. GPU offload is opt-in because the backend keeps a second copy of
the model's GEMM weights in device memory:

```
zig build -Dgpu=metal -Dcpu=native -p "$PG_HOME"   # macOS (MPS)
zig build -Dgpu=cuda  -Dcpu=native -p "$PG_HOME"   # Linux + NVIDIA driver
```

Only large matrix products are offloaded; elementwise work and small products
stay on the CPU. A product goes to the device when `m * n * k` reaches the
backend's per-call threshold: `1 << 28` on Metal for both linear and activation
GEMMs, and `1 << 20` (linear) / `1 << 24` (activation) on CUDA.

The extension is still one `tsfm.so`: the CUDA backend loads
`libcudart`/`libcublas` with `dlopen` at model-load time, so the build needs no
CUDA toolkit or link-time libraries. At runtime, a normal CUDA installation is
found automatically; set `TSFM
pseudocharles11
🟧 echo.github ⭐The repository describes a PostgreSQL extension that runs Chronos-2 and Timestral forecasts through SQL, with model weights on the database barddoo——

Interpretation history

Decision trace