Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Introduction

The Improv workspace

Improv is a cross-platform multidimensional spreadsheet written in Rust, in the line of Lotus Improv and Quantrix. It separates three things a traditional grid tangles together:

  • Structure: the named dimensions of a model (categories and their items).
  • Logic: formulas over dimensions, not cell addresses.
  • Data: the raw input values.

You model in named categories, items and measures instead of A1 cell coordinates:

Revenue = Price * Quantity
Total   = SUM(Revenue OVER Time)

Derived values flow through a differential-dataflow graph, so recalculation is always incremental: an edit propagates only to the cells it actually affects.

One model, many ways in

The same model opens in a NeXTSTEP-style desktop GUI, a terminal UI, a scriptable CLI, a streaming pipe, a JSON HTTP server, and inside Postgres, where pg_improv keeps results current as your tables change and LANGUAGE improv turns a formula into a SQL function. A model is a single store file, or lives in a Postgres database. Ways to Use Improv says which to reach for and when.

Status

Version 0.12.2 builds and passes its tests on Linux, macOS and Windows; the Postgres extension supports Postgres 15 to 18. External functions in Python, R, Julia or Pure run under a bubblewrap sandbox on Linux; WebAssembly functions run in-process with fuel and memory limits. On other systems they are refused unless the operator sets IMPROV_EXTFN_ALLOW_UNSANDBOXED=1. The GUI has no Print yet, and the Postgres connection has no TLS (use a loopback port or an SSH tunnel). See the changelog for what changed in each release.

Reading order

  1. Concepts: the ideas, before the syntax.
  2. When to Use Improv, and when not.
  3. Ways to Use Improv: pick a front end.
  4. The Improv Model: categories, items, measures, coordinates.
  5. Getting Started: build a model from the CLI.
  6. The Formula Language: dimension-aware formulas and aggregation.
  7. The Desktop GUI and Improv in Postgres.
  8. Running pg_improv in production: Monitoring, Capacity Planning, Backup and Restore, the Operations Runbook and Troubleshooting.
  9. Architecture & Design and Storage & Persistence: how it works inside.

Concepts

This page is the ideas, before the syntax. Read it once and the rest of the guide is details: The Improv Model maps each idea onto the types, The Formula Language gives the grammar, and Ways to Use Improv picks a front end.

A model is named dimensions, not a grid

A spreadsheet names a cell by where it sits (B7). Improv names it by what it means: the Quantity of Widget A in 2025. A model has four parts.

  • A category is a dimension: Time, Product, Region.
  • An item is a member of one category: 2025 and 2026 in Time.
  • A measure is a named variable over some of the categories: Price over Product, Quantity over Time and Product.
  • A coordinate picks one item from each of a measure's categories: {Time=2025, Product=Widget A}. A measure's value at a coordinate is a cell.
flowchart LR
  subgraph Categories
    T[Time] --- T1(2025) & T2(2026)
    P[Product] --- P1(Widget A) & P2(Widget B)
  end
  Price["Price<br/>over Product"] -.-> P
  Qty["Quantity<br/>over Time, Product"] -.-> T & P
  Qty --> C["cell at<br/>{Time=2025, Product=Widget A}<br/>= 100"]

A measure has a cell only where a value exists: a model is sparse. Six categories of 100 items each name 10^12 coordinates, and a model holding a million of them costs what a million cells cost.

Categories, items and measures carry stable ids; names are labels. Renaming a category never breaks a formula, and moving a category from the rows to the columns of a view (pivoting) changes how the cube is shown, not what it holds.

Input and derived measures

Every measure is one of two kinds:

  • An input measure holds data: typed in, imported from CSV or SQL, or bound to a column of a Postgres table.
  • A derived measure holds a formula and nothing else. Its cells are computed and are never stored as input.
flowchart LR
  Price[(Price<br/>input)] --> Revenue
  Quantity[(Quantity<br/>input)] --> Revenue[Revenue<br/>derived]
  Revenue --> Total[Total<br/>derived]

Data goes in at the inputs; everything else follows. You edit an input cell, never a derived one (the GUI and the TUI refuse it; hover a derived cell to see its formula).

A formula is written once, over categories

Revenue = Price * Quantity

This is one formula for every cell of Revenue, not one per row. It has no cell addresses to copy down a column, and adding 2027 to Time extends Revenue to 2027 with no edit. A derived measure's categories follow from its formula: Quantity is over Time and Product, so Revenue is too.

When the operands have different categories, the smaller one is broadcast: Price is over Product only, so every year reuses the same product's price. Broadcasting needs one operand's categories to be a subset of the other's. Price[Product] + Headcount[Region] has no sensible meaning, and the compiler refuses it as a dimension mismatch rather than guessing.

flowchart LR
  P["Price[Product]"] -- "broadcast over Time" --> M(("×"))
  Q["Quantity[Time, Product]"] --> M
  M --> R["Revenue[Time, Product]"]

OVER and reductions

A reduction collapses categories. OVER names the ones to collapse:

Total = SUM(Revenue OVER Time)      -- Total is over Product
Share = Revenue / SUM(Revenue OVER Product)

SUM(Revenue OVER Time) adds each product's years together, so Total is over Product alone. The second line divides each cell by its year's total across products: the reduction collapses Product, and the division broadcasts the result back over it. The same OVER works with every reduction: AVERAGE, MIN, MAX, COUNT, MEDIAN, RANK, TEXTJOIN and the rest (Aggregations).

flowchart TB
  subgraph "Revenue[Time, Product]"
    a["2025, A: 1000"] & b["2026, A: 1200"]
    c["2025, B: 1000"] & d["2026, B: 1600"]
  end
  a & b --> TA["Total[A] = 2200"]
  c & d --> TB["Total[B] = 2600"]

Only a reduction removes a category. A plain reference must keep every category of its measure, so X = Quantity[Product] is an error: nothing says what to do with Time.

Incremental recalculation

The engine turns the formulas into a differential dataflow graph. An edit is a change to the inputs: the old value out, the new one in. The change flows through the graph, and each operator passes on only the part of its output that changed.

flowchart LR
  E["edit: Quantity[2026, A] 120 → 130"] --> R["Revenue[2026, A]<br/>1200 → 1300"]
  R --> T["Total[A]<br/>2200 → 2300"]
  R -.-> X["Revenue[2025, A], Total[B] …<br/>not touched"]

"Only what changed" means: the cells the edit can reach are recomputed, and nothing else. A single-cell edit on a grid takes the same time at 10k cells as at 100k (about 60 µs; see the benchmark). Two costs do not shrink to the edit:

  • A reduction re-reads its group. Changing one cell under SUM(X OVER W) re-reduces the group it falls in. Over more than 1,024 items, SUM, AVERAGE, MIN, MAX, COUNT and the other simple reductions work in blocks of 1,024 items, so an edit re-reads one block plus the block totals. RANK and SORTBY (with constant orders) keep the group sorted: an edit recomputes the ranks or places of the values it moves past, so a small change is fast, and a new maximum still moves every rank. SORT, RANK.AVG, RANK.DENSE and PERCENTRANK re-read the whole group.
  • Each round has a fixed cost per measure. Every edit is one round of the dataflow, and a round visits every tracked measure, reached or not.

Some changes are not edits. They rebuild: the graph is compiled again and every derived cell recomputed.

  • A change of structure: a new or redefined formula, a new measure or category. The graph's shape is fixed when it is built.
  • A new item in a category that a formula reads the item list of: positions and neighbours (POSITION, PREV, NEXT, recurrences, running windows), per-item and list reductions (RANK, SORT, INTO), FILL, RELABEL/SWAP, and reductions other than the simple ones above. A new item under SUM, AVERAGE, MIN, MAX, COUNT and the like arrives as data and does not rebuild, also when the category grows past 1,024 items (PRODUCT and SUMSQ rebuild once then: their blocked rounding differs).
  • In Postgres, also: two rows landing on one coordinate of a measure bound without an aggregate, a change to a text min/max binding, and any error. The full list is in the pg_improv README (logical mode).

A rebuild costs what loading and computing the model from scratch costs, so a model that rebuilds on every write gets none of the incremental benefit. In Postgres, improv.status(model) counts the rebuilds.

Where data lives

The model is the same everywhere; what holds it differs.

flowchart TB
  subgraph File["store file (model.db)"]
    F1["the whole model as Mentat datoms<br/>in one SQLite file"]
  end
  subgraph PG["Postgres database"]
    P1["improv schema: the model's structure<br/>and its unbound cells"]
    P2["your tables: the bound input measures"]
    P3["improv_‹model› schema: one result<br/>table per derived measure"]
  end
  subgraph DK["DuckDB query"]
    D1["nothing stored: the model is the<br/>query's text, its data the source table"]
  end
  • A store file is one SQLite file holding everything (Mentat datoms: Storage & Persistence). The GUI, TUI, CLI and server open it by path. It is a file to copy, mail or check in.
  • A Postgres model keeps its structure in the improv schema. Its input measures can be bound to columns of your own tables, so the data stays where it is. With pg_improv installed, every derived measure is a table in the schema improv_<model> that SQL reads like any other (Improv in Postgres).
  • DuckDB stores nothing: improv(source, model) reads the source and computes the model for each query (Improv in DuckDB).

Keeping Postgres results current: the sync modes

When the bound tables change, a Postgres model's results must follow. A model's sync mode says when, and who pays.

ModeResults changeThe writer pays
logical (default)shortly after the commit, applied by a background workernothing
triggerinside the writing statementa recompute per write statement
commitinside the writing transaction, just before COMMITone recompute per transaction
manualwhen you call improv.recalc()nothing until then

Pick by the question a writer asks:

flowchart TD
  A{"Must a transaction read the<br/>results of its own writes?"}
  A -- yes --> B{"Many write statements<br/>per transaction?"}
  B -- "no, or the model is small" --> TR[trigger]
  B -- "yes, and the model is small" --> CM[commit]
  B -- "yes, and the model is large" --> RC["logical, plus improv.recalc()<br/>where a writer needs to read back"]
  A -- no --> C{"Results needed continuously?"}
  C -- yes --> LG[logical]
  C -- "no: batch loads, migrations" --> MN["manual + improv.recalc()"]

commit mode reloads every table the transaction wrote in full, so on large models it costs seconds per commit; trigger mode recomputes only the touched coordinates when the formulas allow it. logical mode never slows a writer, and its results lag the commit by about one worker poll. The pg_improv README has the full comparison.

Numbers

Timings on this page are from the v0.10.0 scale benchmark (EC2 c7i.8xlarge, release builds), and the single-cell edit time from the CHANGELOG's post-0.10.0 entry for CoordKey (56 µs at 100k cells, was 64 µs).

When to Use Improv, and When Not

Improv is good at one shape of problem: a model. Named dimensions, formulas written once over them, data that changes, and results that must follow the changes without a full recompute. When the problem has that shape, Improv saves you the SQL you would otherwise write and maintain by hand. When it does not, another tool is simpler and faster. This page lists the common mismatches, what to use instead, and how to tell that you have outgrown Improv.

The limits quoted here were measured on EC2 c7i.8xlarge with release builds. Sources: the v0.10.0 scale benchmark and the post-0.10.0 fixes listed in the CHANGELOG (marked "after the fixes"). Capacity planning turns them into sizing formulas.

Use Improv when

  • The model has dimensions and logic. Revenue by quarter and product, shares of a total, a budget against actuals, a forecast that rolls a balance forward: formulas over categories (Concepts).
  • The inputs change, and the results must follow. In Postgres, a 1,000-row batch into a 2.5M-row table shows up in the results 86–130 ms after its commit, where a REFRESH MATERIALIZED VIEW of the same GROUP BY takes about 5 s (benchmark §1; re-measured on main).
  • People explore it. The GUI and TUI pivot and edit the same model that SQL reads, with no export step.
  • The logic should live in one place, versioned and typed, rather than copied across spreadsheet cells or SQL views.

Ad-hoc GROUP BY: use SQL or DuckDB

A question you ask once ("revenue by region last quarter") is a query, not a model. Plain SQL answers it in one statement, with no model to define, bind or keep. DuckDB's GROUP BY ALL of the benchmark's 2.5M rows takes 0.03–0.06 s; Improv's improv(source, model) over the same rows takes 0.3–0.35 s, most of it building the model (0.12.0 qualification).

Instead: SQL in Postgres, or DuckDB over Parquet and CSV. For a single formula inside such a query, improv_calc in DuckDB or a LANGUAGE improv function in Postgres gives you Improv's function library without a model.

You have outgrown Improv when each new question means a new model, or you define a model and then never edit or refresh it.

Data far bigger than memory: aggregate first

The engine keeps every cell of a model in memory: about 0.7–0.9 GB per million cells at v0.10.0 (benchmark §3a), 0.7–0.8 GB after the fixes. A model does not need your raw rows as cells, though. In Postgres and DuckDB a measure bound with an aggregate (agg => 'sum', count, count_distinct, …) folds the rows to one cell per coordinate. 2.5M fact rows become 44,750 cells, and the fold runs where the data is. Only the logical worker's memory grows with the rows: about 180 bytes per fact row in all, fold state and engine together (benchmark §1).

Instead: bind with agg, or summarize first (a view or a rollup table) and bind the summary. Keep raw event-level analytics in the database or a warehouse.

You have outgrown Improv when the model itself, after aggregation, needs tens of millions of cells: a 5M-cell grid takes 12.7 s to evaluate and 3.4 GB after the fixes, and improv.max_cells refuses more than 5M bound input cells by default.

A single nightly aggregate: use a materialized view

If the results are needed once a day and nobody edits the model, a materialized view is the whole solution. REFRESH MATERIALIZED VIEW CONCURRENTLY of the benchmark's GROUP BY takes about 5 s; nothing runs between refreshes, and there is no replication slot to watch.

Instead: CREATE MATERIALIZED VIEW … ; REFRESH … CONCURRENTLY from cron or pg_cron. If the logic is easier to write as formulas, keep the Improv model in manual mode and call improv.recalc() from the same job (2.4–2.8 s on the same data, measured on main): no worker, no slot.

You have outgrown the view (and want Improv) when the refresh window becomes a staleness complaint, or several views repeat the same logic.

Large graphs: use a graph engine

FIXPOINT runs PageRank-style iterations correctly, and incrementally after an edit, but it holds every edge in memory several times: about 780 bytes per edge with the model (10.1 GB peak at 10M edges, of which the engine is 556 bytes per edge), and a warm re-solve after one edge edit takes 6.6 s at 10M edges. A 20M-edge solve took 3.4 min and 31.8 GB at v0.10.0 (benchmark §2).

Instead: a graph engine or library (NetworkX or igraph for analysis, Apache AGE in Postgres, a dedicated graph database) for anything past a few million edges, or for traversals and path queries, which Improv does not have. Feed the per-node result back into Improv as an input measure if the model needs it.

You have outgrown Improv when the edge count reaches tens of millions, or a solve has to finish in seconds.

High-write tables in trigger or commit mode: use logical mode

trigger and commit modes recompute inside the writer's transaction, which is what makes them read-your-writes. The writer pays for it.

  • Trigger mode: about 290 ms per write statement on the 2.5M-row model (354 ms per 1,000-row statement, 2.9 s for ten one-row statements in one transaction) (benchmark §3e).
  • Commit mode: it reloads every table the transaction wrote. That is 2.1–2.4 s per transaction on the same model after the fixes (5.6 s at v0.10.0).

Instead: logical mode. The writer pays nothing, and results follow about one poll after the commit. Where one transaction must read its own results back, call improv.recalc(model) in that transaction.

The sign: write latency or lock waits on the bound tables rose after you chose trigger or commit, or commit-mode transactions take seconds.

Many models in one database

All logical-mode models in a database share one worker and one replication slot. With 1,000 small models in one database (0.11.0, measured on main for this page), a one-row change was visible in 54–146 ms and a transaction touching every model in 2.6 s. The worker used about 0.6 MB per small model. It applies models one at a time on one core, so a model whose apply is slow delays all the others; parallel apply is planned (B1 in the road to 1.0).

The sign: improv.status shows growing lag_bytes for every model at once while one of them is busy. Split the heavy model into its own database, or put it in manual mode and refresh it on a schedule.

Measured limits at a glance

LimitValueSource
Engine memory per cell0.7–0.9 GB per million cells (v0.10.0); 0.54 GB at 1M, 2.35 GB at 5M after the fixes§3a, CoordKey and B7 entries in the CHANGELOG
Engine evaluate0.9 s per million cells after the fixes (4.7–5.5 s at v0.10.0)same
Single-cell edit56 µs, independent of model size (64 µs at v0.10.0)same
Logical-mode apply, 1,000-row batch, 2.5M rows / 44,750 cells86–130 ms commit → visible§1, re-measured on main
Worker memory, same modelabout 450 MB private (180 B per fact row, engine included)§1, re-measured on main
Trigger mode, same modelabout 290 ms per statement§3e
Commit mode, same model2.1–2.4 s per transaction after the fixesCHANGELOG
Models per database (logical)1,000 small models: 54–146 ms per change, 0.6 MB eachre-measured on main with the §3f harness of the benchmark
FIXPOINTabout 0.6 kB per edge (556 B at 10M edges)§2, CHANGELOG
Store file importlinear since Mentat 1.18.0: 100k rows 7 s, 1M 74–110 s (1.16.0: 100k 21 s, 1M did not finish in 15 min)Mentat 1.18 upgrade, qualification

Tutorial: a household budget on the desktop

You will build a three-month household budget: a monthly budget per spending line, what was actually spent, and the income. Improv then works out what is left on every line and how much was saved each month, and you open the result in the desktop app.

The model is built with the improv command-line tool, one command per step, because each step shows one idea. The same file opens in improv-gui and improv-tui.

This page is tested: cargo test -p improv_cli runs every sh block below in order and checks that each output block matches what the command before it printed (docs/tutorials/mdtest.py, called from crates/cli/tests/tutorials.rs).

You need the improv binary on your PATH (see Getting Started).

1. Create the model file

A model lives in one file. init creates it:

DB=budget.db
improv init "$DB"
initialized store at 'budget.db'

2. The categories and their items

A budget has two dimensions: the month, and the spending line. Each is a category, and its members are items. Every object takes a numeric id that you choose; the categories here are 1 and 2, the months 10 to 12, the lines 20 to 23.

improv add-category "$DB" 1 Month
improv add-category "$DB" 2 Line
improv add-item "$DB" 10 1 Jan
improv add-item "$DB" 11 1 Feb
improv add-item "$DB" 12 1 Mar
improv add-item "$DB" 20 2 Rent
improv add-item "$DB" 21 2 Groceries
improv add-item "$DB" 22 2 Utilities
improv add-item "$DB" 23 2 Fun

3. The input measures

A measure is a quantity, laid out over some of the categories. The budget is set once per line, so Budget is over Line only. What was spent varies by month and line. Income is per month.

improv add-measure "$DB" 100 Budget number input Line
improv add-measure "$DB" 101 Spent  number input Month Line
improv add-measure "$DB" 102 Income number input Month

Now type in the numbers. --at names the cell's coordinate, one Category=Item pair per dimension:

improv set "$DB" 100 1500 --at Line=Rent
improv set "$DB" 100 600  --at Line=Groceries
improv set "$DB" 100 200  --at Line=Utilities
improv set "$DB" 100 300  --at Line=Fun

improv set "$DB" 102 4200 --at Month=Jan
improv set "$DB" 102 4200 --at Month=Feb
improv set "$DB" 102 4500 --at Month=Mar

while read -r month line amount; do
  improv set "$DB" 101 "$amount" --at "Month=$month,Line=$line"
done <<'EOF'
Jan Rent      1500
Jan Groceries  640
Jan Utilities  230
Jan Fun        180
Feb Rent      1500
Feb Groceries  575
Feb Utilities  210
Feb Fun        420
Mar Rent      1500
Mar Groceries  590
Mar Utilities  160
Mar Fun        250
EOF

4. Formulas, written once

In a grid spreadsheet you would copy a formula into every cell. In Improv a formula is written once, over names, and applies to every cell of its measure. Left is what remains of each line's budget in each month; the budget has no Month, so the same budget figure is used for every month:

improv define "$DB" 200 "Left = Budget - Spent"
improv eval   "$DB" 200
defined derived measure 200 'Left'
eval 200 'Left' (12 cells):
  Left[Month=Feb, Line=Fun] = -120
  Left[Month=Feb, Line=Groceries] = 25
  Left[Month=Feb, Line=Rent] = 0
  Left[Month=Feb, Line=Utilities] = -10
  Left[Month=Jan, Line=Fun] = 120
  Left[Month=Jan, Line=Groceries] = -40
  Left[Month=Jan, Line=Rent] = 0
  Left[Month=Jan, Line=Utilities] = -30
  Left[Month=Mar, Line=Fun] = 50
  Left[Month=Mar, Line=Groceries] = 10
  Left[Month=Mar, Line=Rent] = 0
  Left[Month=Mar, Line=Utilities] = 40

eval lists cells sorted by item name. A negative number is an overspent line. OVER adds a measure up along a category. SUM(Spent OVER Line) is a month's total spending, so the savings are:

improv define "$DB" 201 "Saved = Income - SUM(Spent OVER Line)"
improv eval   "$DB" 201
defined derived measure 201 'Saved'
eval 201 'Saved' (3 cells):
  Saved[Month=Feb] = 1495
  Saved[Month=Jan] = 1650
  Saved[Month=Mar] = 2000

Formulas can use other formulas. The quarter's totals add up along Month:

improv define "$DB" 202 "QuarterSpent = SUM(Spent OVER Month)"
improv define "$DB" 203 "QuarterSaved = SUM(Saved OVER Month)"
improv eval   "$DB" 202
improv eval   "$DB" 203
defined derived measure 202 'QuarterSpent'
defined derived measure 203 'QuarterSaved'
eval 202 'QuarterSpent' (4 cells):
  QuarterSpent[Line=Fun] = 850
  QuarterSpent[Line=Groceries] = 1805
  QuarterSpent[Line=Rent] = 4500
  QuarterSpent[Line=Utilities] = 600
eval 203 'QuarterSaved' (1 cells):
  QuarterSaved[] = 5145

5. Change an input

A concert in February was refunded, so Fun in February is 300, not 420. Change the one cell; everything that depends on it follows:

improv set  "$DB" 101 300 --at Month=Feb,Line=Fun
improv eval "$DB" 201
improv eval "$DB" 203
set measure 101
eval 201 'Saved' (3 cells):
  Saved[Month=Feb] = 1615
  Saved[Month=Jan] = 1650
  Saved[Month=Mar] = 2000
eval 203 'QuarterSaved' (1 cells):
  QuarterSaved[] = 5265

6. Save views for the desktop app

A view is a saved layout of one measure: which categories run down the rows and across the columns. Save two, one for spending and one for what is left:

improv save-view "$DB" 1 "Spending"  Spent --rows Line --cols Month
improv save-view "$DB" 2 "Left over" Left  --rows Line --cols Month
improv list "$DB"
saved view 1 'Spending'
saved view 2 'Left over'
categories:
  1 Month
  2 Line
items:
  10 Jan (category 1)
  11 Feb (category 1)
  12 Mar (category 1)
  20 Rent (category 2)
  21 Groceries (category 2)
  22 Utilities (category 2)
  23 Fun (category 2)
measures:
  100 Budget [input] Number
  101 Spent [input] Number
  102 Income [input] Number
  200 Left [derived] Number
  201 Saved [derived] Number
  202 QuarterSpent [derived] Number
  203 QuarterSaved [derived] Number
views:
  1 Spending (measure Spent, 1 matrices)
  2 Left over (measure Left, 1 matrices)
inputs:
  100::{Line=Fun} = 300
  100::{Line=Groceries} = 600
  100::{Line=Rent} = 1500
  100::{Line=Utilities} = 200
  101::{Month=Feb,Line=Fun} = 300
  101::{Month=Feb,Line=Groceries} = 575
  101::{Month=Feb,Line=Rent} = 1500
  101::{Month=Feb,Line=Utilities} = 210
  101::{Month=Jan,Line=Fun} = 180
  101::{Month=Jan,Line=Groceries} = 640
  101::{Month=Jan,Line=Rent} = 1500
  101::{Month=Jan,Line=Utilities} = 230
  101::{Month=Mar,Line=Fun} = 250
  101::{Month=Mar,Line=Groceries} = 590
  101::{Month=Mar,Line=Rent} = 1500
  101::{Month=Mar,Line=Utilities} = 160
  102::{Month=Feb} = 4200
  102::{Month=Jan} = 4200
  102::{Month=Mar} = 4500

7. Open it in the desktop app

improv-gui budget.db

The model browser at the bottom left lists the two views, Spending - Worksheet and Left over - Worksheet. Double-click one to open it: the lines run down the rows and the months across. Click a Spent cell, type a new number and press Enter; the Left over worksheet and the savings update at once. The GUI saves each edit to budget.db as you make it, so improv eval sees it straight away; Ctrl+Z undoes it. The Desktop GUI describes every window.

In a terminal, improv-tui budget.db opens the same file, on the Spending view, as the GUI does.

What you used

CommandDid
initCreated the model file.
add-category, add-itemMade the dimensions.
add-measureMade an input measure over some categories.
setTyped a value into one cell.
defineAdded a formula, written once over names.
evalComputed a formula's cells.
save-viewSaved a layout for the GUI and TUI.

Every command is in the command-line reference. The formula language, including OVER and the other reductions, is in The Formula Language.

Tutorial: a live sales model in Postgres

An online shop keeps its orders in an ordinary Postgres table. You will put an Improv model on top of that table: revenue per month and product, the month's total, each product's share of it, and a target check. Then you switch the model to logical sync, so a background worker keeps the result tables current as orders arrive, with no triggers on the hot table.

This page is tested: crates/pg_improv/tests/tutorial-sales.sh starts a scratch cluster with the settings below, runs every sql block in order through psql, and checks each output block (docs/tutorials/mdtest.py). CI runs it on every Postgres version in ci/pg_improv.sh.

A smaller model than this tutorial's, start to finish: bound to a sales table, an UPDATE reaching the result table through the sync worker, improv.status, a LANGUAGE improv function, and the TUI editing the model by URL.

1. Set up the server

Logical sync needs a logical-decoding WAL level and pg_improv preloaded, so its worker starts with the server. In postgresql.conf:

shared_preload_libraries = 'pg_improv'
wal_level = logical
improv.database = 'shop'
improv.poll_ms = 50

improv.database names the one database the worker serves. poll_ms is how often it reads the slot; the default, 200, is fine in production, and 50 makes this tutorial quick. Restart the server, then create the database and the extension:

createdb shop
psql -d shop
CREATE EXTENSION pg_improv;

2. The orders table

One row per order line. The shop's own tables carry no Improv-specific columns:

CREATE TABLE orders (
    order_id  bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    month     text    NOT NULL,             -- '2026-01'
    product   text    NOT NULL,
    qty       integer NOT NULL,
    price     numeric(10,2) NOT NULL
);
INSERT INTO orders (month, product, qty, price) VALUES
    ('2026-01', 'Kettle',  3, 40.00), ('2026-01', 'Kettle', 2, 40.00),
    ('2026-01', 'Teapot',  4, 25.00), ('2026-01', 'Mug',   20,  8.00),
    ('2026-02', 'Kettle',  6, 40.00), ('2026-02', 'Teapot', 2, 25.00),
    ('2026-02', 'Mug',    15,  8.00), ('2026-02', 'Mug',   10,  8.00);

Improv needs one value per cell, and there are many orders per month and product. Each order line's amount is the cell's input, added up per (month, product); a view computes it:

CREATE VIEW order_amount AS
    SELECT order_id, month, product, qty * price AS amount FROM orders;

A logical-mode model reads the WAL of the tables it binds, and a view has no WAL. So bind the table, with an aggregate: bind_measure's last argument folds the rows that share a cell. Bind two measures from orders: Units, the summed quantity, and Price, the largest price on the cell (each product has one price here).

3. The model

SELECT improv.create_model('shop');
SELECT improv.bind_category('shop', 'Month',   'orders', 'month');
SELECT improv.bind_category('shop', 'Product', 'orders', 'product');
SELECT improv.bind_measure ('shop', 'Units', 'orders', 'qty',   'sum');
SELECT improv.bind_measure ('shop', 'Price', 'orders', 'price', 'max');

The categories take their items from the column values: Month has 2026-01 and 2026-02, Product has Kettle, Mug and Teapot. Now the formulas, each written once for every cell:

SELECT improv.define('shop', 'Revenue = Units * Price');
SELECT improv.define('shop', 'MonthTotal = SUM(Revenue OVER Product)');
SELECT improv.define('shop', 'Share = Revenue / MonthTotal');
SELECT improv.define('shop', 'OnTarget = Revenue >= 250');

MonthTotal adds Revenue up over Product, so it is per month only. Share divides a (month, product) cell by its month's total. OnTarget is a boolean measure.

4. Logical sync

SELECT improv.set_sync_mode('shop', 'logical');

This adds orders to the publication improv_db. The worker makes the replication slot, builds the model from the table, and writes every result table. Each derived measure has one, in schema improv_shop, with one text column per dimension and a typed value:

SELECT month, product, value FROM improv_shop.revenue ORDER BY 1, 2;
2026-01|Kettle|200
2026-01|Mug|160
2026-01|Teapot|100
2026-02|Kettle|240
2026-02|Mug|200
2026-02|Teapot|50
SELECT r.month, r.product, round(s.value::numeric, 3) AS share, t.value AS on_target
FROM improv_shop.revenue r
JOIN improv_shop.share s USING (month, product)
JOIN improv_shop.ontarget t USING (month, product)
ORDER BY 1, 2;
2026-01|Kettle|0.435|f
2026-01|Mug|0.348|f
2026-01|Teapot|0.217|f
2026-02|Kettle|0.490|f
2026-02|Mug|0.408|f
2026-02|Teapot|0.102|f

(The outputs on this page are psql -At: unaligned, no headers.)

5. Orders arrive

The shop takes more orders, in its own transactions. Nothing calls Improv:

INSERT INTO orders (month, product, qty, price) VALUES
    ('2026-02', 'Kettle', 1, 40.00),
    ('2026-02', 'Teapot', 2, 25.00);
INSERT INTO orders (month, product, qty, price) VALUES
    ('2026-03', 'Kettle', 7, 40.00);

Within a poll interval the worker reads the commits from the slot, applies only the changed cells to its live model, and writes the result rows that changed. February's Kettle revenue is now 280, so it is on target, and its total is 580; March is a new item, which appears on its own:

SELECT month, value FROM improv_shop.monthtotal ORDER BY 1;
SELECT month, product FROM improv_shop.ontarget WHERE value ORDER BY 1, 2;
2026-01|460
2026-02|580
2026-03|280
2026-02|Kettle
2026-03|Kettle

A correction is an UPDATE, and a cancelled order a DELETE: both flow through the same way.

DELETE FROM orders WHERE month = '2026-01' AND product = 'Mug';
SELECT month, value FROM improv_shop.monthtotal ORDER BY 1;
SELECT count(*) FROM improv_shop.revenue WHERE month = '2026-01';
2026-01|300
2026-02|580
2026-03|280
2

The January Mug cell is gone: with no orders, it has no Units, so no Revenue either, and its result row was deleted.

6. Is it keeping up?

improv.status reports how the model is kept current:

SELECT sync_mode, slot, last_error IS NULL AS healthy, rebuilds >= 1, incremental_applies >= 1
FROM improv.status('shop');
logical|improv_db|t|t|t

rebuilds counts full loads (the first catch-up is one), and incremental_applies the batches applied to the live model. lag_bytes is the WAL the slot still holds, and last_error says why a model stopped updating. Monitoring explains every column and the alerts to set.

7. What-if, without writing

what_if evaluates the model with edits applied in memory and returns only the cells that would change. Raising February's Teapot price to 30:

SELECT measure, coord->>'Month' AS month, coord->>'Product' AS product,
       round((value#>>'{}')::numeric, 3) AS value
FROM improv.what_if('shop', '[{"measure": "Price",
    "coord": {"Month": "2026-02", "Product": "Teapot"}, "value": 30}]')
ORDER BY 1, 2, 3;
MonthTotal|2026-02||600.000
Revenue|2026-02|Teapot|120.000
Share|2026-02|Kettle|0.467
Share|2026-02|Mug|0.333
Share|2026-02|Teapot|0.200

MonthTotal has no Product, hence the empty column. Nothing was written: the result tables still say 580.

Clean up

SELECT improv.drop_model('shop');

drop_model removes the catalog rows and the improv_shop schema, and takes orders out of the publication. With no logical-mode model left, the worker drops the slot. The orders table is untouched.

Next

Tutorial: analyzing a Parquet file in DuckDB

A team exports its support tickets to Parquet every night. You will load that file in DuckDB, describe a model in a few lines (ticket counts and hours per week and team, each team's share of the week, the change from the week before, and the hours per ticket), and get the answer back as an ordinary table you can filter, join and pivot. Nothing is installed in the database and no model is stored: improv(source, model) computes the model on the fly.

This page is tested: crates/duckdb_improv/test/tutorial.sh feeds every sql block below, in order, to the DuckDB CLI and checks each output block (docs/tutorials/mdtest.py). CI runs it under DuckDB v1.5.6 and v2.0 (ci/duckdb_improv.sh).

The DuckDB v1.5.6 CLI with the extension loaded runs this tutorial's queries, the model a little shorter: improv_calc, the Parquet file, the model, a PIVOT over its result, and a query as the source.

1. Load the extension

Start the DuckDB CLI with a database file. The extension is in the community repository; install it once:

INSTALL improv FROM community;
LOAD improv;

(The tested script loads a local build, duckdb -unsigned and LOAD 'build/release/improv.duckdb_extension', instead.) The outputs below are DuckDB's -list mode without headers.

2. Make the Parquet file

In real use the file comes from somewhere else. Here, DuckDB writes it: a table of tickets, saved with COPY ... (FORMAT parquet):

CREATE TABLE tickets AS
SELECT * FROM (VALUES
    (1, DATE '2026-03-02', 'Billing',  1.5), (2, DATE '2026-03-03', 'Billing',  0.5),
    (3, DATE '2026-03-03', 'Platform', 4.0), (4, DATE '2026-03-04', 'Platform', 2.0),
    (5, DATE '2026-03-05', 'Platform', 3.0), (6, DATE '2026-03-09', 'Billing',  1.0),
    (7, DATE '2026-03-10', 'Billing',  2.0), (8, DATE '2026-03-10', 'Billing',  1.5),
    (9, DATE '2026-03-11', 'Platform', 6.0), (10, DATE '2026-03-12', 'Mobile',  2.5),
    (11, DATE '2026-03-13', 'Mobile',  1.5)
) t(id, opened, team, hours);
COPY tickets TO 'tickets.parquet' (FORMAT parquet);
DROP TABLE tickets;
SELECT count(*), sum(hours) FROM 'tickets.parquet';
11|25.5

3. Shape the source

A model's source is a table, a view, or a query. Its columns become the model's categories and inputs. Here a query reads the Parquet file and turns each ticket's date into its week (as text, 2026-W10) and adds a column of ones to count with:

CREATE VIEW ticket_rows AS
SELECT strftime(opened, '%G-W%V') AS week, team, hours, 1 AS n
FROM 'tickets.parquet';

4. The model

The model is text, one line per item:

  • category makes a dimension from a column: its items are the column's distinct values, in order.
  • input reads a measure from a column; sum adds up the rows that land on the same (week, team) cell.
  • Name = formula is a derived measure, written once over names.
SELECT measure, "Week", "Team", value_text
FROM improv('ticket_rows', '
    category Week = week
    category Team = team
    input Tickets = n sum
    input Hours = hours sum
    PerTicket = Hours / Tickets
    WeekHours = SUM(Hours OVER Team)
    Share = ROUND(Hours / WeekHours, 3)
    Change = Hours - PREV(Hours, Week, 1, 0)
');
PerTicket|2026-W10|Billing|1
PerTicket|2026-W10|Platform|3
PerTicket|2026-W11|Billing|1.5
PerTicket|2026-W11|Mobile|2
PerTicket|2026-W11|Platform|6
WeekHours|2026-W10|NULL|11
WeekHours|2026-W11|NULL|14.5
Share|2026-W10|Billing|0.182
Share|2026-W10|Platform|0.818
Share|2026-W11|Billing|0.31
Share|2026-W11|Mobile|0.276
Share|2026-W11|Platform|0.414
Change|2026-W10|Billing|2
Change|2026-W10|Platform|9
Change|2026-W11|Billing|2.5
Change|2026-W11|Mobile|4
Change|2026-W11|Platform|-3

The result has one row per derived cell. WeekHours has no Team, so that column is NULL. PREV(Hours, Week, 1, 0) is the previous week's hours, or 0 where there is none: in the first week, and for Mobile, which had no tickets in week 10, so its change in week 11 is all of its 4 hours.

5. Use the result as a table

improv(...) is a table function, so the rest of SQL applies. The value is in value (a DOUBLE) and value_text. Pivot the hours per ticket into a week-by-team grid (one measure at a time: a pivot over Team needs rows that have one):

PIVOT (SELECT "Week", "Team", value
       FROM improv('ticket_rows', '
           category Week = week
           category Team = team
           input Tickets = n sum
           input Hours = hours sum
           PerTicket = Hours / Tickets
       ') WHERE measure = 'PerTicket')
ON "Team" USING first(value) GROUP BY "Week" ORDER BY "Week";
2026-W10|1.0|NULL|3.0
2026-W11|1.5|2.0|6.0

6. A query as the source

The source can be a query too, so the model can read the Parquet file directly. Only last week's tickets:

SELECT "Team", value FROM improv(
    'SELECT team, hours FROM ''tickets.parquet'' WHERE opened >= DATE ''2026-03-09''',
    'category Team = team
     input Hours = hours sum
     Share = ROUND(Hours / SUM(Hours OVER Team), 2)')
ORDER BY value DESC;
Platform|0.41
Billing|0.31
Mobile|0.28

Next

Ways to Use Improv

Improv is one modeling engine with several front ends. They all work on the same model: categories, items, measures, formulas, input cells and saved views. A model built in one opens in every other. Pick the one that fits the job, and switch when the job changes.

You want to…UseWhere the model lives
explore a model, pivot it, edit numbers, add formulas with a mousethe desktop GUIa store file, or Postgres
do the same over SSH or in a terminalthe TUIa store file, or Postgres
script a model, build it in CI, diff it, load data in bulkthe CLIa store file, or Postgres
push a live feed through a model and get the changed results outstreaminga store file, or Postgres
model data that already lives in Postgres, and read results with SQLpg_improvPostgres tables plus the improv catalog
write a SQL function as a formulaLANGUAGE improvthe function body
run a formula or a model over data in DuckDB, from SQLthe DuckDB extensionnowhere: computed per query
serve a model to other programs over HTTPthe servera store file, or Postgres

What each front end can do compares them feature by feature.

The model, wherever it lives

A model is a store file or lives in a Postgres database; Concepts: where data lives says what each holds. Every front end takes a store file's path. A Postgres model is named by a URL instead:

postgres://user@host/database?model=plan

Pass that URL to the CLI, TUI, GUI or server. With pg_improv installed, the GUI's edits to a bound measure update your table's rows. See Improv in Postgres.

Two writers never silently overwrite each other. If someone else saved after you loaded, your save is refused with a conflict; choose File ▸ Revert to Saved (GUI) or press R (TUI) to pick up their changes, then redo yours. Both notice another program's save without waiting for a conflict: the GUI checks every two seconds and offers Reload, and the TUI says so on the next key press.

The desktop GUI (improv-gui)

The GUI

Use it for: building and exploring a model by hand. You see several views at once, pivot by dragging, chart, and watch derived cells recompute as you type.

improv-gui sample.db
improv-gui 'postgres://me@127.0.0.1/sales?sslmode=disable&model=plan'
  • Pivot: drag a category tile between a worksheet's strips. Page tiles go top-left, column tiles top-right, row tiles in the bottom strip.
  • Edit: double-click a cell. Derived cells are read-only; hover one to see its formula.
  • Add a formula: type Margin = Revenue - COGS on the last line of the formula list.
  • More views: View ▸ New View opens another worksheet on the same model; Save View keeps the arrangement.

Every change is saved as you make it. The Desktop GUI walks through each window.

The terminal UI (improv-tui)

improv-tui on the sample model: an input typed as 1,500, Revenue recomputed, # giving it two decimals and grouped thousands, paging, pivoting, a range's Sum, and a saved view the next start opens on.

Use it for: the same pivot-and-edit loop without a display, over SSH, or in a tmux pane next to your logs.

improv-tui sample.db
improv-tui new.db     # a new file opens empty: build it with c, n and =
KeyDoes
arrows, clickmove
e / Enteredit the input cell (derived cells recompute live); e on a derived measure edits its formula, and a parse error is marked under the bad token, with a hint. Typing replaces the old value; an arrow first edits it in place; an empty edit clears the cell. A formula that is one value (5) takes a second Enter
a digit, -, .start editing the cell with that key
Tab / mnext measure
ppivot
[ ]page
Shift+arrowsselect a range; its sum shows in the status line
f / Fhide a row item / clear filters
S / v / Vsave the layout as a view, named as you type (Enter takes view N) / cycle views / rename (Old = New) or delete (-Name) a view
I / Eimport / export CSV
cadd a category and its items: Time: 2025, 2026
nadd an input measure over categories: Quantity: Time, Product
r / Drename / delete a category, item or measure: Time = Year, Product.WidgetA; formulas follow a rename, and a delete names the formulas that still need the thing first
=define: Revenue = Price * Quantity adds a derived measure, Margin = LAMBDA(p, q, p - q) a named LAMBDA
#the shown measure's number format: 2, 0 grouped, general
wsave now (each change is already saved as it is made; w retries one that failed, marked "not saved")
Rrevert to the saved model (the status line says when another program saved it); with edits or undo history to lose, press it twice
u / Ctrl+Rundo / redo
Tab (in a formula)complete a function, measure or category name; again to cycle
? / F1the keys, and a search over the functions; Enter inserts NAME( into the edit
qsave and quit; if the save fails (a full disk, another program saved), the TUI stays open with the reason, and q again quits without saving

The CLI (improv)

Use it for: anything you want to repeat. Build a model from a script, load a CSV or SQL query into a measure, evaluate a formula in CI, export results, or check a model into git as the script that builds it.

improv init m.db
improv add-category m.db 1 Time;    improv add-item m.db 10 1 Q1
improv add-category m.db 2 Product; improv add-item m.db 20 2 Widget
improv add-measure m.db 100 Price    number input Product
improv add-measure m.db 101 Quantity number input Time Product
improv set m.db 100 10  --at Product=Widget
improv set m.db 101 100 --at Time=Q1,Product=Widget
improv define m.db 102 "Revenue = Price * Quantity"
improv eval m.db 102

It also imports and exports CSV and SQLite (import-csv, import-sql, refresh-sql, export-csv, export-sql), runs Python functions in a sandbox (register-ext, CALL(...)), and keeps external measures fresh on a schedule (serve-refresh). Getting Started is a tutorial; man improv lists every command.

Streaming (improv stream)

Use it for: a live feed. Something produces new numbers, and you want the derived results that change, as they change, without recomputing the model.

tail -F prices.log | improv stream m.db Revenue Margin | your-consumer

Each input line is <measure> <value> [Cat=Item,...]. Improv applies it to a live incremental engine and prints only the target cells it changed:

$ printf 'Price 15 Product=Widget\nQuantity 8 Time=Q1,Product=Widget\n' \
    | improv stream m.db Revenue
Revenue Time=Q1, Product=Widget = 1500
Revenue Time=Q1, Product=Widget = 120

(Price 15 × the stored Quantity 100, then 15 × the new 8.)

A bad line is reported on stderr and skipped. At end of input the final state is saved to the model.

In Postgres (pg_improv)

pg_improv in psql: a model bound to a sales table, an UPDATE reaching the result table through the sync worker, improv.status, a LANGUAGE improv function, then the TUI editing the same model by URL, and the edit as a row of the table.

Use it for: data that already lives in Postgres. Bind your table's columns to categories and measures, define formulas, and read results from ordinary tables, with no export step and no second copy.

CREATE EXTENSION pg_improv;
SELECT improv.create_model('plan');
SELECT improv.bind_category('plan', 'Time',    'sales', 'quarter');
SELECT improv.bind_category('plan', 'Product', 'sales', 'product');
SELECT improv.bind_measure ('plan', 'Price',    'sales', 'price');
SELECT improv.bind_measure ('plan', 'Quantity', 'sales', 'qty');
SELECT improv.define('plan', 'Revenue = Price * Quantity');
SELECT * FROM improv_plan.revenue;     -- kept current as sales changes

How results follow your writes is the model's sync mode: Concepts: the sync modes is the decision.

Open the same model in the GUI or TUI with its postgres://…?model=plan URL: editing a cell there updates the row in sales. Improv in Postgres covers setup, value types, aggregated bindings and durability, and A Family's Finances is a complete worked example.

In DuckDB (the improv extension)

Use it for: analytics over data DuckDB already reads (tables, Parquet, CSV): a formula as a column, or a model over a table, inside one query. Nothing is stored; each query reads its source and computes.

LOAD improv;
SELECT improv_calc('ROUND(PMT(rate/12, n, -pv), 2)',
                   json_object('rate', rate, 'n', n, 'pv', pv)) FROM loans;
SELECT * FROM improv('sales', '
  category Time = year
  category Product = product
  input Price = price
  input Quantity = qty sum
  Revenue = Price * Quantity
  Share = Revenue / SUM(Revenue OVER Product)');

improv(...) returns one row per computed cell (measure, a column per category, value, value_text), so the result joins and pivots like any table. improv_functions() lists the built-in functions. Improv in DuckDB has the details.

SQL functions (LANGUAGE improv)

Use it for: a calculation you want in plain SQL, written as a formula. No model is needed.

CREATE FUNCTION bonus(sales float8, target float8) RETURNS float8
  LANGUAGE improv IMMUTABLE AS $$
    Ratio = sales / target
    MAX2(Ratio - 1, 0) * 1000
  $$;
SELECT rep, bonus(sales, target) FROM quota;

Arguments are the inputs, by name; each Name = expr line is an intermediate; the last line is the result. A call costs about 0.14–0.24 µs (this two-line bonus is the 0.24), about what PL/pgSQL costs.

The HTTP server (improv-server)

Use it for: letting another program read a model, ask what-if questions, or write input cells over HTTP.

With the model m.db from the CLI example, after the streaming example set Price to 15:

IMPROV_API_TOKEN=secret improv-server m.db 127.0.0.1:3000 &
curl -H 'Authorization: Bearer secret' -X POST localhost:3000/measures/102/eval \
  -H 'content-type: application/json' \
  -d '{"edits":[{"measure":101,"coord":[[1,10],[2,20]],"value":90}]}'
# [{"coord":[["Product","Widget"],["Time","Q1"]],"value":1350.0}]

An edit names its measure and coordinate by id ([[category, item], …]); the answer comes back by name. /eval computes through the live engine and writes nothing unless you ask it to ("persist": true). --static DIR serves a web front end's files beside the API. The HTTP Server lists the routes, tokens and limits.

What each front end can do

Checked against each tool on 2026-10-22 (0.11.0 development). yes: it does it; —: it does not; a note says how, or what is missing. The bold gaps are tracked as tasks for 1.0.

CLITUIGUIserverpg_improvDuckDB
Open a model (file or postgres://)yesfrom the command linefrom the command line (File ▸ Open is disabled)one per processits own catalog— (computed per query)
Create a modelinitopen a new file— (File ▸ New is disabled)—create_modelinline improv(source, model)
Add categories and itemsadd-category, add-itemcvia CSV import—bind_category (items from the column)category lines
Add an input measureadd-measurenvia CSV import—bind_measureinput lines
Open a model (file or postgres://)yesfrom the command lineFile ▸ Open…, or the command lineone per processits own catalog— (computed per query)
Create a modelinit—File ▸ New—create_modelinline improv(source, model)
Add categories and itemsadd-category, add-itemvia CSV importEdit ▸ Add Category / Add Item, or type in a tile—bind_category (items from the column)category lines
Add an input measureadd-measurevia CSV importEdit ▸ Add Input Measure—bind_measureinput lines
Rename, delete—r, DEdit ▸ Rename, Delete…—drop_measure—
Views (saved layouts)save-view, listS save, v cycle, V rename or deleteopen, save, several worksheets at once—— (a GUI's views are kept in the catalog)—
Pivotsave-view --rows --colspdrag tiles—— (result tables are flat)— (rows are flat)
Number formats (decimals, thousands separators)format; show, eval, stream print in it#Format menu— (values as numbers)kept in improv.measure.format; results are numbers—
Edit an input cellsetyesyesPOST /measures/:id/cellswrite your table—
Formulas: editdefine, add-derivede edits the viewed one, = adds oneedit and add—defineName = formula lines
Autocompleteshell completion of commands onlyTabas you type———
Located errorsparse error at Nmarked under the token, with a hintunderlined, explained—parse error at Nmodel line L: … at N
Function helpman improv-functions? / F1Help ▸ Functions…——improv_functions()
Import CSVimport-csvIwizard—COPY into a tableread_csv as the source
Import SQLimport-sql (SQLite), refresh-sql——refreshed by the schedulerbind any tableany query as the source
SQL("…") sourcedefine refuses it; use import-sql———refused—
Exportexport (JSON), export-csv, export-sqlE (CSV)wizard (CSV)GET /model (JSON)the result tablesit is a query
Scenariosscenario, eval --scenario—————
Undo—u, Ctrl+R to redoEdit ▸ Undo, Redo———
Named LAMBDAsdefine=calls work; define them in the CLIcomputes themdefine— (refused; inline LAMBDA works)
Undo——Edit ▸ Undo, Redo———
Named LAMBDAsdefinecalls work; define them in the CLIName = LAMBDA(…) on the formula list's last linecomputes themdefine— (refused; inline LAMBDA works)
FIXPOINTyesyes (the same parser and engine)yesyesyesin improv(…); not in improv_calc
what-if (compute, don't save)through a stored scenario——POST /measures/:id/evalwhat_if—
Live sync (see others' writes)each command reloadssays so on the next key; R reloadsoffers Reload within 2 seach request checks the high-water and reloadslogical, trigger, commit sync—
Controlled English—accepts it as a formulashows and accepts it/nl/parse, /nl/describe——
Keyboard only, screen readersyesyes; works under NO_COLORyes; every control named for AccessKit———

Every front end that saves refuses to overwrite another writer: the save fails with a conflict, and you reload and redo the change.

Choosing quickly

  • One person, a model to think with: GUI, or the TUI over SSH.
  • A model that is code: a CLI script in git, then open it in the GUI.
  • A feed of numbers: improv stream.
  • Data in Postgres, results for SQL users: pg_improv, logical mode. Use trigger if a writer must read its own results in the same transaction.
  • A formula as a SQL function: LANGUAGE improv.
  • Data in DuckDB, Parquet or CSV, answers in one query: the DuckDB extension (improv_calc, improv(source, model)).
  • Another service needs answers: improv-server.

The Improv Model

This page maps the model's vocabulary onto the types in improv_core_model. For the ideas themselves (categories, items, measures, coordinates, input and derived measures, and why formulas are written over categories), read Concepts first.

Categories

A category is a dimension of the model — for example Time, Product, or Region. Each category has a stable numeric id (CategoryId) and a human-readable name.

Items

An item is one member of a category: 2025 and 2026 are items of Time; Widget A and Widget B are items of Product. Each item has an id (ItemId), the id of the category it belongs to, and a name.

Measures

A measure is a named variable indexed by a subset of the categories — its tensor dimensions. Price might be defined over [Product], while Quantity and Revenue are defined over [Time, Product].

A measure is one of two kinds:

  • Input — raw data you enter.
  • Derived — computed from a formula.

Every measure declares a value type: Number, Boolean, Text, DateTime, or Enum. The engine computes with all of them: dates are written as #2025-01-31# literals in formulas, come from date/timestamp columns in Postgres, and display as RFC 3339; an Enum computes as its number. The GUI edits DateTime cells; the TUI and the CLI's add-measure and set take number, boolean or text (CSV and SQL imports bring in numbers).

Coordinates

A coordinate names one cell of a measure's tensor by mapping categories to items — for example {Time=2025, Product=Widget A}. Internally a coordinate is an ordered map (BTreeMap<CategoryId, ItemId>), so it is insertion-order-independent: {Time=2025, Product=WidgetA} and {Product=WidgetA, Time=2025} are the same coordinate. That ordering is what lets the engine derive a stable dataflow key (see Architecture).

Input data lives in the model as a map from (measure, coordinate) to a value. Only input measures have entries; derived measures are computed by the engine.

The canonical example

Throughout these docs the running example is a Time × Product revenue model:

Revenue[Time, Product] = Price[Product] * Quantity[Time, Product]

Price is defined over Product only, so it is broadcast over Time: every year reuses the same per-product price. With

ProductPrice
Widget A10
Widget B20

and

TimeProductQuantity
2025Widget A100
2025Widget B50
2026Widget A120
2026Widget B80

the engine computes:

TimeProductRevenue
2025Widget A1000
2025Widget B1000
2026Widget A1200
2026Widget B1600

These are the values the engine's test suite checks against.

Getting Started

Build

Improv is a Cargo workspace. From the repository root:

cargo build --workspace
cargo test  --workspace

The improv CLI binary is produced by the improv_cli crate. You can run it either through Cargo:

cargo run -p improv_cli -- <command> [args]

or directly once built:

./target/debug/improv <command> [args]

The examples below use the built binary.

The CLI

The CLI is a headless front-end over the model store. Every subcommand opens a store (a single SQLite file, a Postgres model named by a postgres://…?model= URL, or an in-memory database if you pass ""), mutates the loaded model, and saves it back.

The CLI builds a model one command at a time, evaluates Revenue and Total, gives Total a number format, stores a policy template and asks policy check why a cell is denied, then exports Revenue as CSV.

Run improv help for the full command list. The commands, exactly as accepted by the binary, are:

CommandArguments
init<db>
add-category<db> <id> <name>
add-item<db> <id> <category-id> <name>
add-measure<db> <id> <name> <number|boolean|text> input [Category ...]
add-derived<db> <id> <name> <formula>
define<db> <id> "<Name> = <formula>" or "<Name> = CALL(fn, Arg, ...)"
set<db> <measure> <value> [--at Cat=Item,Cat=Item ...]
scenario<db> <scenario> <measure> <value> [--at Cat=Item,...]
list<db>
show<db> <measure>
eval<db> <measure> [--scenario <name>]
save-view<db> <view-id> <name> <measure> [--rows Cat,Cat] [--cols Cat,...]
export<db> (JSON)
stream<db> <target-measure> ... (edits on stdin, changed cells on stdout)
import-csv, export-csvsee man improv
import-sql, refresh-sql, export-sqlsee man improv
register-ext, refresh-ext, refresh-all, serve-refreshexternal functions; see man improv
help(also --help, -h)
--version(also -V)

Notes:

  • Ids (<id>, <category-id>) are plain numbers. A <measure> is its id or its name: improv eval m.db Revenue (an argument of all digits is an id). An unknown name lists the measures.
  • add-measure adds an input measure; the trailing input keyword is required, and any further arguments are category names declaring the measure's dimensions (e.g. ... input Time Product). The type (number, boolean, text) declares how set parses the value.
  • add-derived adds a formula measure from Improv formula text (e.g. "Price * Quantity" or "SUM(Revenue OVER Time)"); its categories are inferred from the measures it references. Compute it with eval.
  • set --at maps category names to item names. Pairs may be comma-joined (--at Time=2025,Product=WidgetA), space-separated (--at Time=2025 Product=WidgetA), or given as repeated --at flags; they are merged, and a category may appear only once. Omit --at for a scalar (zero-dimensional) cell.
  • set parses the value according to the measure's declared type: a number measure wants a float, a boolean measure wants true/false, a text measure takes the string verbatim.

Quick start

Build the Time × Product revenue model from the model chapter, one command at a time:

DB=model.db

improv init          "$DB"
improv add-category  "$DB" 1 Time
improv add-category  "$DB" 2 Product
improv add-item      "$DB" 10 1 2025
improv add-item      "$DB" 11 1 2026
improv add-item      "$DB" 20 2 WidgetA
improv add-item      "$DB" 21 2 WidgetB
improv add-measure   "$DB" 100 Price    number input Product
improv add-measure   "$DB" 101 Quantity number input Time Product
improv set           "$DB" 100 10 --at Product=WidgetA
improv set           "$DB" 100 20 --at Product=WidgetB
improv set           "$DB" 101 100 --at Time=2025,Product=WidgetA
improv set           "$DB" 101 50  --at Time=2025,Product=WidgetB
improv set           "$DB" 101 120 --at Time=2026,Product=WidgetA
improv set           "$DB" 101 80  --at Time=2026,Product=WidgetB

Inspect the model:

improv list "$DB"
categories:
  1 Time
  2 Product
items:
  10 2025 (category 1)
  11 2026 (category 1)
  20 WidgetA (category 2)
  21 WidgetB (category 2)
measures:
  100 Price [input] Number
  101 Quantity [input] Number
views:
inputs:
  100::{Product=WidgetA} = 10
  100::{Product=WidgetB} = 20
  101::{Time=2025,Product=WidgetA} = 100
  101::{Time=2025,Product=WidgetB} = 50
  101::{Time=2026,Product=WidgetA} = 120
  101::{Time=2026,Product=WidgetB} = 80

Save a named view (the GUI opens it from the model browser). --rows and --cols stack category names; leftover categories become pages:

improv save-view "$DB" 1 "Quantity by year" Quantity --rows Time --cols Product

Look at a single measure and its cells:

improv show "$DB" 100
measure 100 Price [input] Number
  cells:
    100::{Product=WidgetA} = 10
    100::{Product=WidgetB} = 20

Dump the whole model as JSON (useful for scripting or diffing):

improv export "$DB"

Define a derived measure and compute it

Define Revenue from a textual formula, then evaluate it through the engine:

improv add-derived "$DB" 102 Revenue "Price * Quantity"
improv eval        "$DB" 102
added derived measure 102 'Revenue'
eval 102 'Revenue' (4 cells):
  Revenue[Time=2025, Product=WidgetA] = 1000
  Revenue[Time=2025, Product=WidgetB] = 1000
  Revenue[Time=2026, Product=WidgetA] = 1200
  Revenue[Time=2026, Product=WidgetB] = 1600

Derived measures can build on other derived measures. Roll Revenue up over Time with an aggregation:

improv add-derived "$DB" 103 RevByProduct "SUM(Revenue OVER Time)"
improv eval        "$DB" 103
added derived measure 103 'RevByProduct'
eval 103 'RevByProduct' (2 cells):
  RevByProduct[Product=WidgetA] = 2200
  RevByProduct[Product=WidgetB] = 2600

Beyond the CLI

Open the same file interactively: improv-tui model.db in a terminal, or improv-gui model.db on the desktop, where the saved view shows up in the model browser. Feed it new numbers with improv stream model.db Revenue. Ways to Use Improv compares the front ends, and man improv lists every CLI command, including CSV and SQL import and export and sandboxed Python functions.

Running Improv

This page is the operator's quick reference: build, run each front end, run the tests, check coverage, and the security knobs. The getting-started guide walks through modeling itself.

Install a release

From 0.12, each GitHub Release also carries packages (all x86_64 Linux, except the formula). Every Linux artifact (the tarball, the packages, pg_improv and the DuckDB extension) is built on EL8 (manylinux_2_28) and needs glibc 2.28 or newer; improv also needs GCC 8's libstdc++ or newer (libstdc++.so.6). Each release installs and runs the packages on Debian 12 and 13, Ubuntu 22.04 and 24.04, Rocky Linux 8 and 9, AlmaLinux 10 and Fedora, and pg_improv under PGDG's PostgreSQL on Debian 12, Ubuntu 22.04 and Rocky Linux 8 and 9. Each package declares its floor, so apt and dnf refuse an older system rather than install a binary that will not start. (0.12.0's own Linux artifacts need glibc 2.39, and pg_improv 2.35.)

PackageInstall
improv_X.Y.Z-1_amd64.deb, improv-X.Y.Z-1.x86_64.rpmsudo apt install ./improv_*.deb or sudo dnf install ./improv-*.rpm: the four binaries in /usr/bin, man pages, bash/zsh/fish completions
postgresql-N-improv_X.Y.Z-1_amd64.debpg_improv for PostgreSQL N (15–18) from apt.postgresql.org, in its paths
postgresqlN-improv-X.Y.Z-1.x86_64.rpmthe same for yum.postgresql.org's postgresqlN-server (/usr/pgsql-N)
improv.rba Homebrew formula for macOS (arm64 and Intel). Homebrew installs only from a tap: brew tap-new --no-git local/improv, cp improv.rb "$(brew --repository local/improv)/Formula/", brew install local/improv/improv
ghcr.io/gburd/improv:X.Y.Zthe server and CLI in a container (see The HTTP server)

pg_improv is also on PGXN, and the DuckDB extension in the community repository (INSTALL improv FROM community).

Build

# Nix (recommended): toolchain + GUI runtime libs + dev tools
nix develop
cargo build --workspace --release

# Or plain Debian/Ubuntu (what the EC2 dev box used):
sudo apt-get install -y build-essential pkg-config libssl-dev libsqlite3-dev \
  libxkbcommon-x11-0 libgl1 libegl1 libgl1-mesa-dri python3 bubblewrap
curl -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain 1.97.0   # MSRV; any newer stable works
cargo build --workspace --release

The binaries land in target/release/: improv (CLI), improv-tui, improv-gui and improv-server.

Verifying a release

Each GitHub Release carries, besides the archives:

FileWhat
SHA256SUMSThe SHA-256 of every other file in the release.
SHA256SUMS.sigstore.jsonA cosign keyless signature of SHA256SUMS: the certificate names the release workflow and the tag, and the signing is logged in Rekor, the public transparency log.
<binary>-vX.Y.Z-<target>.cdx.jsonA CycloneDX SBOM per binary (improv, improv-tui, improv-server, improv-gui) and target, from cargo cyclonedx.
pg_improv-X.Y.Z-pgN-x86_64-linux.cdx.json, improv-X.Y.Z-duckdb-linux_amd64.cdx.jsonThe extensions' SBOMs.
*.deb, *.rpm, improv.rbThe packages above: the .deb/.rpm repackage the Linux tarballs (same binaries, same SBOMs) and are in SHA256SUMS; the formula is made from SHA256SUMS and pins the macOS tarballs by their hash.

Check the signature on the sums, then the files against the sums (cosign 2.4 or later):

tag=v1.0.0
cosign verify-blob SHA256SUMS --bundle SHA256SUMS.sigstore.json \
  --certificate-identity "https://github.com/gburd/improv/.github/workflows/release.yml@refs/tags/$tag" \
  --certificate-oidc-issuer https://token.actions.githubusercontent.com
sha256sum --ignore-missing -c SHA256SUMS    # macOS: shasum -a 256 --ignore-missing -c SHA256SUMS

Verified OK means GitHub Actions signed these sums while running release.yml for that tag in gburd/improv; --ignore-missing checks only the files you downloaded. Without cosign, sha256sum -c still catches a corrupt download, but not a substituted one.

A model to play with

IMPROV=target/release/improv bash docs/demo/sample-model.sh sample.db   # Time × Product × Region
target/release/improv list sample.db

Or build one by hand:

I=target/release/improv
$I init m.db
$I add-category m.db 1 Time;    $I add-item m.db 10 1 Q1; $I add-item m.db 11 1 Q2
$I add-category m.db 2 Product; $I add-item m.db 20 2 Widget
$I add-measure m.db 100 Price number input Time Product
$I add-measure m.db 101 Quantity number input Time Product
$I add-derived m.db 102 Revenue "Price * Quantity"
$I set m.db 100 10 --at Time=Q1 Product=Widget   # or --at Time=Q1,Product=Widget
$I set m.db 101 5  --at Time=Q1 --at Product=Widget
$I eval m.db 102
$I save-view m.db 1 "Revenue by quarter" 102 --rows Time --cols Product

Run each front end

Front endCommandNotes
CLIimprov --helpScriptable; improv help <command> for one command, and see the man pages.
TUIimprov-tui m.dbArrows move, e/Enter edit a cell (typing replaces the old value; e on a derived measure edits its formula), a digit starts an edit, Shift+arrows select a range (Sum in the status line), p pivot, [ ] page, S save a view (named), v cycle views, V rename or delete one, f/F filter, Tab measure, c add a category and items, n an input measure, r/D rename/delete one, = define a measure or LAMBDA, # set the number format, w save (each change already autosaves), R revert to saved, u/Ctrl+R undo/redo, ?/F1 keys and function help, Tab completes names in a formula, q quit.
GUIimprov-gui m.dbNeXTSTEP-style workspace: application menu top-left, worksheet windows, model browser. Double-click or Enter edits a cell; right-click a tile to move or filter it; type Name = formula on the formula list's last line. Run inside nix develop on NixOS so the GL/X11 libraries are found.
Streamingproducer | improv stream m.db RevenueEdits in on stdin, changed cells out on stdout; saved at end of input.
ServerIMPROV_API_TOKEN=secret improv-server m.dbJSON API on 127.0.0.1:3000; see The HTTP Server.
PostgresCREATE EXTENSION pg_improvModels over your tables; see Improv in Postgres.

Ways to Use Improv explains when to pick which.

Example server calls:

curl -s -H 'Authorization: Bearer secret' localhost:3000/measures
curl -s -H 'Authorization: Bearer secret' -X POST localhost:3000/measures/102/eval \
  -H 'content-type: application/json' -d '{"edits":[]}'

Man pages and shell completions

Every command has a man page in docs/man/. The release archive lays them out as man/man1, man/man5 and man/man7, so with its man/ on MANPATH, man -k improv lists them all:

PageWhat
improv(1)the CLI: every command, formulas in brief, examples, environment
improv-<command>(1)one page per command, git-style: improv-init, improv-add-category, improv-add-item, improv-add-measure, improv-add-derived, improv-define, improv-register-ext, improv-refresh-ext, improv-set, improv-list, improv-save-view, improv-show, improv-eval, improv-scenario, improv-export, improv-import-sql, improv-refresh-sql, improv-refresh-all, improv-serve-refresh, improv-export-sql, improv-import-csv, improv-export-csv, improv-stream
improv-gui(1), improv-tui(1), improv-server(1)the desktop, terminal and HTTP front ends
improv-files(5)the model file, the CSV import format, the DuckDB model text
improv-formulas(7)the formula language, in brief
improv-functions(7)every built-in function
pg_improv(7)the Postgres extension's SQL API and settings
man -l docs/man/improv-import-csv.1               # from a checkout
MANPATH=improv-v1.0.0-x86_64-unknown-linux-gnu/man: man improv-import-csv

The (1) pages and improv-functions(7) are generated from the argument parsers and the function registry; the hand-written parts of the (1) pages are in crates/cli/man/. UPDATE_DOCS=1 cargo test -p improv_cli regenerates them, and the test fails when they are stale or groff -man -ww complains. The other pages are written by hand.

Shell completions for all four binaries are in docs/completions/ (and the archive's completions/), generated the same way:

source docs/completions/improv.bash                                  # bash
fpath=(docs/completions $fpath); autoload -Uz compinit; compinit     # zsh
cp docs/completions/*.fish ~/.config/fish/completions/              # fish

Open a Postgres-hosted model

Every front end also accepts a Postgres URL naming a model instead of a file:

improv list      'postgres://me:pw@127.0.0.1/sales?model=plan'
improv-tui       'postgres://me:pw@127.0.0.1/sales?model=plan'
improv-gui       'postgres://me:pw@127.0.0.1/sales?model=plan'
improv-server    'postgres://me:pw@127.0.0.1/sales?model=plan'

?model= is required; the other parameters go to libpq as usual. The model lives in the improv.* catalog (created on first open when the pg_improv extension isn't installed). Input measures bound to a table (improv.binding) are read from it, and their edited cells are written back to that table with UPDATE/INSERT (values only, no DDL). Unbound cells go to improv.cell. As with a file store, a save fails with "reload and retry" when another writer changed the model after you loaded it. There is no TLS in this build, so a non-loopback host needs an explicit sslmode=disable (use an SSH tunnel to a loopback port instead).

Security defaults (and how to relax them)

Everything stored in a model is treated as untrusted: a shared model can carry code or SQL.

BehaviorDefaultOverride
External functions run sandboxed (bubblewrap: read-only /usr, no $HOME, no network, cleared env, rlimits)always, regardless of the model's pure flagIMPROV_EXTFN_TRUSTED=1 (host decides, never the model)
No bubblewrap installedrefuse to run external functionsIMPROV_EXTFN_ALLOW_UNSANDBOXED=1 (rlimits only; not on macOS, which refuses one of the ceilings, so there use IMPROV_EXTFN_TRUSTED=1)
Server's refresh scheduleroffIMPROV_SCHEDULER=1 plus IMPROV_EXTFN_ALLOW=<file> listing sha256(name\0body) digests
Server with no token on a non-loopback addressrefuses to startIMPROV_ALLOW_OPEN=1
Read-only API tokensnoneIMPROV_API_TOKENS_RO=a,b
Server limits1 MiB body, 30 s request, 64 in flight, 10 s header read, 10k edits per /evalIMPROV_HEADER_TIMEOUT_MS
SQL refresh queriessingle SELECT/WITH only, run read-only; DuckDB external access offnone
Postgres transportloopback/socket only (no TLS built in)sslmode=disable in the connection string to accept cleartext to a remote host
CSV export of text starting = + - @ \t \rprefixed with ' (formula-injection safe)ExportSpec { neutralize_formulas: false } (API)
Two processes saving one storethe second save is refused with "reload and retry" (no clobbering)none

Environment

VariableEffect
IMPROV_ENGINE_WORKERS=nThreads (timely workers, 1–64) one batch evaluation uses: improv eval, the server's reads of a derived measure, DuckDB's improv(), pg_improv's trigger and commit modes. Default: one per 10,000 input cells, at most 8 and the cores (in Postgres also at most max_parallel_workers_per_gather + 1). Results are the same on any count. Interactive editing (GUI, TUI, improv stream, the sync worker) always uses one, except that a FIXPOINT's step over at least 20,000 rows (a PageRank's edges) reduces on this many threads (default as above, by rows).

Tests

cargo test --workspace                          # ~1,200 tests
cargo test --workspace --release -- --ignored   # stress: 5M cells verified; the 10M case needs ~7 GB

Live Postgres tests run when IMPROV_TEST_PG is set, e.g.

IMPROV_TEST_PG="host=127.0.0.1 user=improv password=improv dbname=improv_test" \
  cargo test -p improv_storage_sql -p improv_storage_pg -p improv_store

The sandbox tests need python3 and bubblewrap; without them they skip (and say so) rather than fail.

Coverage (≥ 90% functions and branches per crate)

rustup toolchain install nightly -c llvm-tools-preview
cargo install cargo-llvm-cov
scripts/coverage.sh            # prints a per-crate table; exits 1 below 90%
scripts/coverage.sh --html     # also writes target/coverage-html/html/index.html

Inline #[cfg(test)] modules are excluded from the denominator (via the coverage_nightly cfg cargo-llvm-cov sets), so the percentages measure library code. CI runs the same gate (coverage job).

Full quality gate

P=$(ls crates | grep -Ev '^(pg|duckdb)_improv$' | sed 's/^/-p improv_/')   # the two extensions are their own workspaces
cargo fmt $P -- --check
cargo clippy $P --all-targets --all-features -- -D warnings
cargo test --workspace
cargo deny check
typos
RUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-deps
scripts/gui-shot-check.sh       # GUI screenshot vs golden (needs Xvfb, ImageMagick, xdotool)
scripts/coverage.sh             # coverage gate (nightly)
(cd crates/pg_improv && cargo fmt --check \
  && cargo clippy --features pg17 --all-targets -- -D warnings \
  && cargo pgrx test pg17 && ./tests/logical.sh)   # the extension
ci/pg_improv.sh 17                 # all of pg_improv's CI job (as root, in a Debian container)
ci/duckdb_improv.sh ~/duckdb-cli   # the DuckDB extension, under both DuckDB CLIs

The Formula Language

A formula defines a derived measure in terms of other measures and categories — never in terms of cell addresses. This is what makes logic dimension-aware: you write the rule once, and it applies across every cell of the target measure's tensor.

The formula AST lives in improv_core_model::formula. A Formula wraps an Expr, which is one of:

  • Literal(Value) — a constant.
  • Ref(MeasureId, DimensionSpec) — a reference to another measure, with an optional dimension projection.
  • UnaryOp(op, expr) — negation (Neg) or logical not (Not).
  • BinaryOp(op, left, right) — arithmetic (Add, Sub, Mul, Div), logical (And, Or), or comparison (Eq, Ne, Lt, Le, Gt, Ge).
  • Call(FuncId, args) — an aggregation (SUM, AVG, MIN, MAX) or a named scalar function (ABS, ROUND, …).

Writing a formula

You write a formula as text: a target name, =, and an expression.

Revenue = Price * Quantity

The parser (improv_core_model::parser) resolves each name in the expression against the model, so every measure and category it names must exist. The target need not exist yet. An unknown name, or anything the grammar does not allow, is a parse error with a byte position; the parser never panics.

In the examples on this page, a -- note after a formula explains it; it is not part of the formula (the language has no comments), so leave it out when you type one.

The target may carry a bracketed category list, as in Revenue[Time, Product] = …. The parser skips that list; it does not set the measure's categories.

improv add-derived <db> <id> <name> "<expression>" takes only the expression (the part after =). improv define <db> <id> "<Target> = …" takes the whole definition.

Operators and precedence

From lowest to highest precedence:

LevelOperatorsNotes
1ORleft-associative
2ANDleft-associative
3NOTprefix; applies to a whole comparison
4== <> != < <= > >=at most one per level: a < b < c is an error
5&text join, left-associative
6+ -left-associative
7* /left-associative
8unary -prefix
9^power, right-associative
10%postfix: x% is x / 100

Parentheses group as usual. Keywords (AND, OR, NOT, OVER, TRUE, FALSE, function names) are case-insensitive.

= is only the assignment after the target. Inside an expression, equality is ==, and <> and != both mean not-equal. So Flag = Price == 10 is a formula, and X = Price = 10 is an error.

NOT binds looser than a comparison, as in SQL: NOT Price > 15 means NOT (Price > 15), and NOT a AND b means (NOT a) AND b.

^ follows the mathematical convention: it is right-associative and binds tighter than unary minus, so 2^3^2 is 2⁹ = 512 and -2^2 is −(2²) = −4. The spreadsheets read both the other way (64 and 4): write (2^3)^2 and (-2)^2 for their reading. The exponent may be negative (2^-1 is 0.5). 0^0 is 1, 0^-1 is #DIV/0! and a negative base with a fractional exponent is #NUM!; POWER(x, y) is the same as x ^ y.

& joins two values as text ("Q" & 3 is Q3; numbers print as they display, booleans as TRUE/FALSE). 50% is 0.5.

Type rules, checked when the formula compiles:

OperatorsOperandsResult
+ - * / ^numbersnumber
&any two valuestext
AND ORbooleansboolean
comparisonstwo values of the same typeboolean
unary -numbernumber
NOTbooleanboolean

Limits

A formula's tree may be at most 256 levels deep, where a measure, number or other leaf is one level and every operator or call adds one: Price + Price is 2, and a chain of n + terms is n. A SWITCH, IFS or CHOOSE counts one level per case, since it compiles to nested IFs. Past 256 the formula is refused where it is written (the CLI, the GUI and TUI editors, improv.define, LANGUAGE improv, the DuckDB model text, controlled English, the server):

parse error at 2046: formula nests too deeply (257 levels; the limit is 256)

The position is the operator where a chain passes the limit, or the start of the expression. Split such a formula into intermediate measures, or sum with SUM(...) rather than a long + chain. The limit holds after LET, LAMBDA and named LAMBDAs are expanded. A formula is also limited to 100,000 nodes once expanded, so a LET whose bindings each use the previous one twice fails at once rather than doubling its way to millions of terms.

Every formula at the limit saves and opens again in any store, improv export writes it, and the engine evaluates it, on any thread Improv runs on (a 1 MiB Windows main thread, a server's 2 MiB worker, a Postgres backend). (0.11 allowed 40 levels: its JSON reader stopped at 128 levels of nesting.)

Formulas saved before 0.11, which had no limit, keep working up to 256 levels; a 45-term sum defined with improv.define in 0.10 still computes. Past 256:

  • Stored as text (Postgres improv.measure, LANGUAGE improv bodies, the Postgres model store): the model refuses to load, and the error names the measure; improv.drop_measure or improv.define(…, replace => true) of that measure still works, to fix it.
  • Stored as JSON (the embedded store, improv files): the measure loads as #REF! in every cell, and its description says why; the rest of the model opens. Redefine it with improv add-derived or improv define to fix it.

Errors

An error is a value, shown as the spreadsheets show it:

ErrorProduced by
#DIV/0!division by zero (x / 0, including 0 / 0)
#NUM!a numeric domain error (SQRT(-1), LN(0)) or a result too large for a number
#VALUE!a value of the wrong kind (VALUE("abc"), CHOOSE out of range), or text longer than 32,767 characters (Excel's limit, for &, REPT, SUBSTITUTE, TEXTJOIN and every other text result)
#N/Ano value available (NA(), IFS with no true test)
#NAME?, #REF!, #NULL!ERROR("#NAME?") etc.; Improv itself does not produce them

An operator or function given an error returns that error (the left operand, or the first argument, first). An aggregation over a category containing an error returns the error (the smallest ERROR.TYPE code if there are several). ISERROR, ISERR, ISNA and ERROR.TYPE inspect errors, and IFERROR, IFNA and CLEARERROR replace them.

A missing cell is not an error: where an input has no cell, the result has no cell either (an aggregation skips it).

Typing formulas in your language

The formula bar (GUI) and improv define / add-derived (CLI) read formulas in the formula locale: IMPROV_LOCALE, else the OS locale (LANG). In German (de) a formula uses LibreOffice's German function names, a decimal comma and ; between arguments, and the GUI shows stored formulas the same way:

English (stored)German
IF(Price > 1.5, ROUND(Price, 2), 0)WENN(Price > 1,5; RUNDEN(Price; 2); 0)
SUM(Revenue OVER Time)SUMME(Revenue OVER Time)

The English spelling is always accepted as well. Models store formulas in the English form, so a model opens the same in every locale. Measure and category names, text in "…" and OVER are never translated. English and German are the locales so far; another is a table of names (crates/core_model/src/locale/<tag>.tsv).

Literals

LiteralExampleNotes
number42, 1.07, 1e-10, 6.02E+23digits, an optional .digits, an optional exponent (e or E, a sign, digits); no leading . (.5)
text"hello", "say ""hi"""double quotes; "" inside is one ", as in Excel (the only escape)
booleanTRUE, FALSE
date#2025-01-01#midnight UTC
date and time#2025-01-01T09:30:00Z#RFC 3339

A literal may stand alone (X = 42) or appear inside an expression (Price * 1.07). A literal has no categories, so it broadcasts over the other operand.

A number with an exponent is one token: 2e3 is 2000, and 2 * e3 multiplies 2 by the measure e3. A name cannot start with a digit, so the two never collide, and e, E and e1 stay names. An exponent without digits (1e, 1e+) is an error at the number. A number too large for a 64-bit float (1e999) is an error too, number out of range, rather than Excel's #NUM!: it is a typing mistake, caught before the formula is saved. One too small (1e-999) reads as 0, as in Excel. A formula prints its numbers the shortest way that reads back exactly, with an exponent below 0.000001 and from 1e21 up (1e-10, 6.02e23).

Names

A bare name starts with a letter or _ and continues with letters, digits or _. Any other name goes in single quotes:

X = 'Unit Price' * 2
X = 'Bob''s Rate' + 1

Inside single quotes, write '' for one ': 'Bob''s Rate' names the measure Bob's Rate. A quoted name is always a measure or category name, never a keyword or function, so 'SUM' and 'Over' name measures. '' (empty) and an unclosed quote are errors. Single quotes are names; double quotes are text.

A qualified name like Matrix.Measure parses, but is always rejected: Improv has no matrices to qualify a name with. The error names the qualifier.

Measure references and BY

Measure[Cat, …] sets the reference's by list: keep only the listed categories. Inside an aggregation the categories it leaves out are collapsed, so SUM(Quantity[Product] OVER Time) is a per-Product total. Outside one, the list must name every category of the measure (Quantity[Time, Product]): Quantity[Product] alone is refused, because nothing would collapse Time (see Dimension projection below).

Aggregations

Total = SUM(Revenue OVER Time)

The form is AGG(Measure OVER Categories, …). The aggregations include SUM, AVERAGE (or AVG), MIN, MAX, PRODUCT, SUMSQ, over booleans AND, OR and XOR, the ordered FIRST, LAST, S and TEXTJOIN, and the statistics (COUNT, MEDIAN, STDEV, PERCENTILE, COUNTIF, CORREL, SLOPE, TTEST, …); see the Function Reference.

Total    = SUM(Revenue OVER Time, Region)        -- several categories
Others   = SUM(Revenue OVER ALL EXCEPT Product)  -- all but Product
Big      = SUM(Revenue OVER Time WHERE Revenue > 1000)
Names    = TEXTJOIN(", ", TRUE, Label OVER Product)
Opening  = FIRST(Balance OVER Time)
Spread   = STDEV(Revenue OVER Time)
Top3     = LARGE(Revenue OVER Time, 3)
Fit      = CORREL(Price, Quantity OVER Time)
Big      = COUNTIF(Revenue OVER Time, ">1000")
Sold     = SUMIFS(Revenue, Region OVER Time, "N*", Quantity, ">=10")
Rank     = RANK(Revenue OVER Product)                -- per item: keeps Product
Tier     = RANK.DENSE(Score OVER Person)             -- ties share a rank, no gaps
Buyers   = COUNTUNIQUE(Customer OVER Order)          -- distinct values
  • The reduced arguments must be measure references (with an optional […] list), not expressions: SUM(Price * 2 OVER Product) is an error; define the expression as a measure first.
  • OVER follows a reduced argument and applies to all of them. Several categories are separated by commas; a comma followed by anything but a category name starts the next argument (TEXTJOIN("-", TRUE, x OVER T)).
  • OVER ALL EXCEPT Cat, … reduces every category of the measure but those.
  • WHERE condition keeps only the cells where the condition is true; the condition may use the measure and any measure over its categories. If no cell passes, the group has no cell.
  • Rows reach the reduction in item order along the reduced categories, which is what FIRST, LAST and TEXTJOIN see.
  • Other arguments are parameters with one value per group: a literal, or a measure over the categories the result keeps (TEXTJOIN(Sep, TRUE, x OVER T) with Sep per Product).
  • The cash-flow functions (NPV, IRR, MIRR, XNPV, XIRR, FMRR, FVSCHEDULE) read the flows in item order: the first item with a cell is period 0 (NPV discounts it one period, as Excel does). An item with no cell is skipped, not a zero flow, so the flows after it move up a period; enter 0 for a period without a flow.
  • Without OVER, nothing is reduced (each cell is its own group).
  • The …IF and …IFS functions take Excel's criteria: a number or boolean means equality, and text may start with =, <>, <, <=, > or >=. Text is compared without regard to case, and =/<> text takes the wildcards * (any run), ? (any one character) and ~ (the next character literally). In SUMIFS(x, c1 OVER T, k1, c2, k2) the summed measure and every criteria measure are reduced together.
  • Measures reduced together join on the categories they share. Each must range over the OVER categories; any others broadcast and the result keeps them: with r over Src and M over Src × Dst, SUMPRODUCT(r, M OVER Src) is the matrix-vector product, one value per Dst.
  • Per-item reductions (RANK, RANK.AVG, RANK.DENSE, PERCENTRANK, TREND, GROWTH) give one result per item of their single OVER category, and the result keeps it. RANK.DENSE is SQL's dense_rank() OVER (ORDER BY x DESC) (order 1: ASC): tied values share a rank and the next value ranks one after them, so 9, 7, 7, 4 rank 1, 2, 2, 3.
  • COUNTUNIQUE (Google Sheets' name) is SQL's count(DISTINCT x): the number of distinct values among the cells, numbers by value and text case-sensitively. Neither LibreOffice nor Gnumeric has it or a dense rank.
  • An error among the rows is the result, except that COUNT skips errors, COUNTA counts them, the …IF functions skip rows whose criteria cell is an error, and AGGREGATE's options 2, 3, 6 and 7 ignore them.

SUM etc. are functions only when ( follows; otherwise the word is an ordinary measure name.

Positions, neighbours and running totals

Every category has an order: its items' order. Formulas can use it.

Rank     = POSITION(Time)                          -- 1, 2, 3, …
Year     = @ITEM(Time)                             -- the item's name
Growth   = Revenue - PREV(Revenue, Time, 1, 0)     -- change since last year
Ahead    = NEXT(Revenue, Time)                     -- next year's value
Running  = SUM(Revenue OVER Time[FIRST..THIS])     -- running total
Trailing = AVERAGE(Revenue OVER Time[THIS-2..THIS]) -- three-period average
ToGo     = SUM(Budget OVER Time[THIS..LAST])
  • POSITION(T) is the 1-based position of each item of T; @ITEM(T) its name; @ITEMCOUNT(T) how many items T has. They are measures over T, so they broadcast like any other.
  • PREV(x, T, [n = 1], [default]) is x at the n-th previous item along T, NEXT at the n-th next. Before the first item (or where that item has no cell) the result is the default, or no cell without one.
  • A window OVER T[from..to] gives one result per item: the aggregation over the items from from to to, where each bound is FIRST, LAST, THIS, THIS-n or THIS+n. An empty window is #N/A.

Roles: RELABEL and SWAP

One dimension often plays two roles: Src and Dst are both Person in an interaction graph. Make each role its own category with the same item names, and move values between them:

RankBySrc  = RELABEL(Rank[Dst, Iter], Dst, Src)   -- ranges over Src × Iter
Reciprocal = W > 0 AND SWAP(W, Src, Dst) > 0      -- W[a, b] > 0 and W[b, a] > 0
  • RELABEL(x, From, To) is x with category From replaced by To: each cell's From item becomes the To item with the same name. x must range over From and not over To.
  • SWAP(x, A, B) exchanges two categories x ranges over: its value at A = a, B = b is x at A = b, B = a (items matched by name).
  • Items are matched by name. A cell whose item has no namesake in the other category is dropped (no cell), so a role with extra items loses them: relabel to a category that has them all.
  • Both are a map over the cells (a key rewrite), so they stay incremental.

LET and LAMBDA

Margin = LET(rev, Price * Quantity, cost, Unit * Quantity, (rev - cost) / rev)
Double = MAP(Quantity, LAMBDA(q, q * 2))
Square = (LAMBDA(x, x * x)(Price - 1))
Running = SCAN(0, Deposits OVER Time, LAMBDA(acc, d, acc * 1.01 + d))
Final   = REDUCE(0, Deposits OVER Time, LAMBDA(acc, d, acc * 1.01 + d))
  • LET(name, value, …, body) names values for the body (a later value may use an earlier name). A name shadows a measure with the same name.
  • LAMBDA(p, …, body) is a function of its parameters. Call it on the spot (LAMBDA(x, x * x)(Price)) or pass it to MAP, REDUCE or SCAN. A definition whose whole right-hand side is a LAMBDA is a named LAMBDA (below), so a measure that calls one on the spot puts it in parentheses, as Square does.
  • MAP(x, …, LAMBDA(p, …, body)) applies the body cell by cell.
  • SCAN(init, x OVER T, LAMBDA(acc, v, body)) folds along T in item order: each item's result is the body with acc the previous item's result (init before the first) and v the item's value. REDUCE keeps only the last. Both are recurrences underneath, so they update incrementally.

More forms of the same kind:

Grid  = MAKEARRAY(Row, Col, LAMBDA(r, c, r * 10 + c))   -- over Row × Col
Steps = SEQUENCE(Month, 100, 5)                          -- 100, 105, 110, …
Range = BYROW(Sales OVER Product, LAMBDA(row, MAX(row) - MIN(row)))
Total = BYCOL(Sales OVER Month, LAMBDA(col, SUM(col)))
  • MAKEARRAY(R, C, LAMBDA(r, c, body)) evaluates the body over R × C with r and c the item positions.
  • SEQUENCE(T, [start = 1], [step = 1]) is (POSITION(T) - 1) * step + start: a category, not a count, sets its length.
  • BYROW(x OVER C, LAMBDA(row, body)) runs the body once per item of x's other categories, row being x's values along C; the body must reduce it (SUM(row), MAX(row) - MIN(row)). BYCOL is the same form: in a dimensional model a row and a column differ only in the category named.

LET, LAMBDA, MAP, MAKEARRAY, SEQUENCE and BYROW expand when the formula is read: the stored formula (and what the formula bar shows) is the expanded expression. A LAMBDA cannot call itself, so every formula still terminates.

Named LAMBDAs (Excel's Name Manager functions) are defined once and called by name:

improv define model.db 1 "Margin = LAMBDA(price, cost, (price - cost) / price)"
improv define model.db 120 "Pct = Margin(Price, Cost) * 100"

In the TUI, type the same lines after =.

A call is stored as a call, not its expansion, so redefining Margin changes every formula that uses it. A named LAMBDA reads only its parameters (pass measures as arguments), may call LAMBDAs defined before it, and never itself. They persist with the model (Mentat and Postgres stores). In the GUI, type the same Margin = LAMBDA(…) line on the formula list's last line.

A parameter the body uses where a category goes (OVER c, POSITION(c), RELABEL's categories) is a category parameter: the call passes a category name, and a parameter the body reduces (MAX(x OVER c)) takes a measure:

LOGNORM = LAMBDA(x, c, LN1P(x) / LN1P(MAX(x OVER c)))
An      = LOGNORM(Authored, Person)   -- LN1P(Authored) / LN1P(MAX(Authored OVER Person))

A parameter used both as a value and as a category is an error.

List results: INTO

A function that returns a list says where the list lands: INTO a category, whose items take the results in order.

Top = SORT(Sales OVER Product, -1 INTO Rank)   -- largest first
Ids = UNIQUE(Customer OVER Order INTO Slot)

The result keeps the measure's other categories and gains Rank: the k-th value lands at Rank's k-th item. Results beyond Rank's last item are dropped; if there are fewer, the later items have no cell. INTO must name a category the measure does not range over.

INTO R, C lays the list over two (or more) categories row by row, the last varying fastest, as Excel spills a block:

Fit  = LINEST(Sales, Price, Promo OVER Week, TRUE, TRUE INTO StatRow, StatCol)
Grid = SORT(Sales OVER Week INTO Row, Col)

Matrices are a measure over two categories: MDETERM(A OVER R, C). Matrix results (MINVERSE, MPSEUDOINVERSE, CHOLESKY, EIGEN) come row by row, so INTO R2, C2 lays them out as a block: Inv = MINVERSE(A OVER R, C INTO R2, C2).

A matrix product needs no function: operands that share a category join over it, so with A over R × K and B over K × C,

AB = A * B              -- over R × K × C
P  = SUM(AB OVER K)     -- over R × C: the product

(LINSOLVE is MINVERSE then the same product.) Two measures with no category in common are still refused, as a likely mistake.

LINEST and LOGEST take any number of x's (every measure before the options is reduced): the coefficients come last x first, then b, and with stats Excel's 5 × (k + 1) block. SORTBY(x, by1 OVER T, order1, by2, order2, …) sorts by several keys. SELECTS(values, tests OVER T, condition) keeps the values whose test meets a SUMIF-style criterion.

Lookups

A lookup is a reduction whose key is a parameter: it searches a table along a category and returns the value at the matching item.

Rate  = XLOOKUP(Grade, GradeKey OVER Band, GradeRate, 0)
Slot  = MATCH(Score, Threshold OVER Band)      -- 1-based position along Band
Third = INDEX(Sales OVER Month, 3)
Name  = SELECT(Label, Code OVER Item, Wanted)  -- Quantrix argument order
Names = SELECTLIST(Label, Code OVER Item, Wanted)  -- Wanted over its own category

The key may range over categories the table lacks: with Grade per Employee and the table per Band, Rate is per Employee, each cell looking its own grade up in the whole table. Positions (MATCH, XMATCH, INDEX) are item positions along the category, so an item with no cell still counts. A table row needs every reduced measure: an item with a key but no value is not found. The approximate modes do not assume sorted keys; they pick the nearest key (for MATCH/LOOKUP type 1, the largest ≤ the key, the last on a tie). XLOOKUP's binary search modes (±2) are the linear search. Database functions are the aggregations under their spreadsheet names, with the criteria as WHERE: DSUM(Sales OVER Region WHERE Year == 2025); DGET wants exactly one match.

Recurrences

A measure may read its own earlier values through PREV:

Balance = PREV(Balance, Time, 1, Opening) + Deposits - Withdrawals

Along Time, each period's balance starts from the previous period's (Opening, a measure per account, before the first). The engine computes it as a scan in item order, per group of the other categories, and updates it incrementally: an edit re-runs the chain it is in. Rules:

  • every reference to the measure itself is PREV(itself, T, n, default) along one of its own categories (NEXT cannot refer back);
  • the rest of the formula is element-wise (no aggregation or other positional function inside it; define those as measures first);
  • the measures it reads together range over all of its categories (they supply its cells);
  • other cycles between measures are still errors.

Every evaluation still terminates: a scan is as long as the category.

Fixed points: FIXPOINT

A measure can be the fixed point of a step: start from a value and apply the step until the value stops changing. PageRank over a person-to-person graph, with Src and Dst two roles of Person, W[Src, Dst] the edge weights, damping 0.85 and the rank of a person with no out-edge spread over everyone:

Out      = SUM(W OVER Dst)                -- out-weight per Src
M        = W / Out                        -- transition weights
Dangling = FILL(0 * Out, 1)               -- 1 where Src has no out-edge
PR       = FIXPOINT(SEQUENCE(Src, 1 / @ITEMCOUNT(Src), 0),
             LAMBDA(r, RELABEL((1 - 0.85) / @ITEMCOUNT(Src)
               + 0.85 * (FILL(SUMPRODUCT(r, M OVER Src), 0)
                         + SUMPRODUCT(r, Dangling OVER Src) / @ITEMCOUNT(Src)),
               Dst, Src)),
             100, 1e-10)

SUMPRODUCT(r, M OVER Src) is Σ over Src of r·M, one value per Dst, and RELABEL(…, Dst, Src) reads it back over Src for the next round.

  • FIXPOINT(init, LAMBDA(r, body), [max_iter = 100], [tolerance = 1e-10]) sets r to init, then r to body evaluated at r, until the cells move by at most tolerance in total (Σ|Δ| over the cells), or max_iter rounds have run.
  • Exceeding max_iter gives the last iterate, not an error, and never a hang: max_iter is a whole number from 0 to 10,000 (0 gives init). The language stays total.
  • max_iter and tolerance are constant numbers.
  • r has init's type and categories, plus any the body adds: a constant init with a body over Src iterates over every Src item. Give init its categories with SEQUENCE(Src, x, 0) when the body needs r over Src to begin with (SUMPRODUCT(r, M OVER Src) does). The body must keep r's categories and type. A cell is in the result where it is in both the last iterate and its step; the convergence test treats a cell in only one of them as an infinite change.
  • A FIXPOINT is a measure's whole formula, and it may not read its own measure (r stands for it). Other measures may read it, and its body may read other FIXPOINT measures.
  • The engine solves it round by round. A round evaluates the body's compiled plan in memory at the iterate: the measures it reads (here M and Dangling) are fixed for the solve, the joins over them are indexed once, and a reduction's rows (which iterate cell meets which edge) are laid out once and refilled each round, as long as the coordinates stay the same. Those measures still update incrementally on the dataflow when an input changes. A body with a node the in-memory evaluator does not take (PREV, a recurrence) runs each round as one dataflow update instead. Both use the same cell operations and give the same cells bit for bit. After an edit it starts from the previous result (if that converged) and agrees with a full recompute; a FIXPOINT whose inputs did not change is not re-solved. A start that fails to converge within max_iter rounds restarts from init, so a result cut off at max_iter is the same as a fresh evaluation's.
  • On 1,500 people and 100,000 edges this PageRank matches a plain power iteration to 3e-15 (L1) in 14 rounds, in 0.44 s in a release build (4 ms a round once the rows are laid out; the dataflow over the edges takes 0.25 s), and re-solves after an edge edit in 0.07 s. On 10,000 people and 1,000,000 edges: 13 rounds of 75 ms, 6.9 s in all (3.7 s of it the dataflow), 1.2 s to re-solve after an edit, 3.3 GB at peak.

Functions

Improv has the spreadsheet functions people expect, with Excel's names: ROUND(Price, 2), MOD(Units, 12), LEFT(Code, 3), SUM(a, b, c). The Function Reference lists every one, generated from the code. The argument count and types are checked when the formula is parsed and compiled: ROUND(Price, 1, 2) is a parse error that shows the signature, and LEN(Price) (a number where text is wanted) a type error.

Arguments are expressions and broadcast like a binary operator's operands: ROUND(Revenue / Units, 2) ranges over the union of the arguments' categories. A literal argument costs nothing extra.

Named arguments. After the positional arguments, name => value gives a parameter by its name in the Function Reference: PMT(0.05, 12, Loan, type => 1), XLOOKUP(Id, Key OVER Row, Name, search_mode => -1), FIXPOINT(0, LAMBDA(r, r / 2 + 1), max_iter => 50). Names are case-insensitive. The rules:

  • named arguments come after every positional one;
  • each name once, and not for a parameter a positional argument already gave;
  • an optional parameter a name skips takes its default, the = value in the reference ([fv=0]): PMT(0.05, 12, Loan, type => 1) is PMT(0.05, 12, Loan, 0, 1). A parameter with no default ([next], [replacement]) cannot be skipped: give it, by position or by name;
  • a function whose last parameter repeats (SUM(number1, …), LINEST(known_ys, known_xs1, … OVER T), IFS, SWITCH) takes its arguments by position only.

A misspelt name is an error that suggests the right one. The formula is stored as the positional call, so the formula bar shows PMT(0.05, 12, Loan, 0, 1) after you enter the named form; both mean the same. The editors offer the names of the call's remaining parameters (type => ) where an argument starts.

R-style distributions. R.DNAME(x, params…, [give_log]) is the density or mass at x (or its logarithm); R.PNAME(x, params…, [lower_tail], [log_p]) is P(X ≤ x), or P(X > x) when lower_tail is FALSE, as a logarithm when log_p is TRUE; R.QNAME(p, …) inverts it, reading p the same way (a discrete quantile is the smallest k with P(X ≤ k) ≥ p). Parameters out of range are #NUM!. CAUCHY(x, a, TRUE) is the right tail P(X > x), as in Gnumeric. Improv does not copy Gnumeric's defects: CUM_BIV_NORM_DIST is exact (Owen's formula), R.DSNORM is right for a non-zero location, R.PST honours log_p.

Math extras follow Gnumeric, within Improv's limits so every call is quick: ITHPRIME and NT_PI stop at the 10⁷-th prime, PARTITIONS at n = 4000, the Erlang functions at 10⁶ circuits, other number theory at 2⁵²; past a limit the answer is #NUM!. HDATE_MONTH numbers Tishri 0 to Elul 11 (12 and 13 for Adar I and II). ROMAN takes Excel's TRUE/FALSE forms; ARABIC accepts a leading -; ENCODEURL keeps RFC 3986's unreserved characters.

Complex numbers are text in Excel's form, "3+4i", "-j", "2.5e-3-i": suffix i or j, no spaces, the same suffix in every argument of one call. A plain number is a real complex number. Results print with 15 significant digits, and a real result is still text (IMSUM("1+i", "1-i") is "2").

Option pricing. The OPT_* functions follow Gnumeric: the first argument is "c" or "p" ("a"/"e" first for OPT_BINOMIAL, "cc"/"cp"/"pc"/"pp" for OPT_ON_OPTIONS); OPT_BINOMIAL takes at most 10,000 steps (Gnumeric 100,000: the tree is quadratic, and that took seconds). Times are in years; rates, volatilities and cost of carry are annual fractions (cost of carry is r for a stock, r − q with a dividend yield, 0 for a future, r − rf for a currency). OPT_BARRIER, OPT_TOUCH, OPT_PROB_HIT and OPT_PROB_INMONEY follow LibreOffice, with case-sensitive flags ("c"/"p", "i"/"o" knock in/out, "c"/"e" barrier watched continuously or at expiry, "f"/"d" pays foreign/domestic) and an optional Greek ("delta", "gamma", "theta", "vega", "volga", "vanna", "rho", "rhof"). Where Gnumeric 1.12's bivariate normal is wrong (some Roll–Geske–Whaley, compound, extendible and two-asset inputs), Improv returns the correct value.

IF and friends

Bonus = IF(Sales > Target, Sales * 0.1, 0)
Label = IF(Price > 15, "dear", "cheap")
Safe  = IFERROR(Revenue / Units, 0)

IF(test, then, [else]) needs a boolean test and two branches of the same type. It is lazy: where the test is true only then matters, so a missing cell or an error in else never shows (and the other way round). Without else, a false test gives no cell. Where the test is an error, the result is that error.

The result ranges over the categories of the test and both branches. If the test has fewer categories than the result (IF(Price > 15, Revenue, 0), with Price over Product and Revenue over Time×Product), the cells are those of the test joined with a branch that has the rest (here Revenue): Improv never invents coordinates. A formula where neither branch fills in the test's missing categories is a dimension error.

IFS, SWITCH, CHOOSE, IFERROR, IFNA, CLEARERROR and CLEARZERO are built on IF and behave the same way.

Missing cells: COALESCE and FILL

A formula over a missing cell has no cell, and IF, IFNA and ISNUMBER cannot change that: they only see the cells their test has. Two functions give a value where an input has none:

An    = COALESCE(Authored, Vol * 0)   -- Authored, else 0 wherever Vol has a cell
An    = FILL(Authored, 0)             -- Authored, else 0 for every Person
Merit = 0.30 * Vn + 0.25 * FILL(Authored, 0)
Best  = COALESCE(Final, Draft, Estimate, 0)
  • COALESCE(a, b, …, default) has a cell wherever an argument that ranges over all of the result's categories has one, and takes the first argument with a cell there (the last argument is the default). With Authored set for 2 of 4 people and Vol for all 4, COALESCE(Authored, Vol * 0) has 4 cells.
  • FILL(x, default) has a cell at every item combination of x's categories: x where it has a cell, else the default.
  • The arguments' categories must nest, and the result ranges over the largest set. An argument over fewer categories (a literal, or Vol over Person under a Person × Year result) broadcasts onto the cells the others supply but adds none of its own: COALESCE(Mail, Vol) with Mail over Person × Year has Mail's cells, FILL(Mail, Vol) every Person × Year. FILL's default may not range beyond x's categories.
  • The arguments must have one type (an error-only argument, NA(), takes the others'). An error is a value, so COALESCE keeps it: IFERROR replaces errors.
  • FILL's cells come from the item list, which is fixed for the life of an engine: an edit to an input moves the result incrementally, but a new item takes a rebuild, as any structural change does.

Source forms: CALL and SQL

Two forms are allowed only as the whole right-hand side, and only through parse_definition (the improv define command):

Score = CALL(myfn, Price, Quantity)
Sales = SQL("SELECT product, amount FROM sales")
  • CALL(fn, m1, m2, …) makes an external-function measure: fn is a registered external function, followed by zero or more argument measure names (bare or quoted). The function runs outside the dataflow and its results become input cells.
  • SQL("query") takes one double-quoted query string. It describes a SQL-sourced input measure; the caller maps the result columns to dimensions.

Neither may appear inside a larger expression.

Not in the grammar

WrittenResult
M.Priceerror: unknown qualifier: M
Quantity EXCEPT Timeerror: no EXCEPT syntax

Differences from Excel

Improv uses Excel's function names and, where it can, Excel's results. The items below are where it does not, each decided for 1.0: what Excel does, what Improv does, and why. Most come from the model itself, which has categories instead of a grid. Five that looked accidental (number to text, UNIQUE's case, "" in a string, TEXTSPLIT's options, LINEST with collinear x's) were aligned with Excel before 1.0; only TEXTSPLIT's row delimiter stays, below, with its reason. The stability policy covers these items like the rest of the language.

Syntax

  • Equality is ==. Excel writes =A1=B1. In Improv = is only the assignment after the target (Flag = Price == 10), so a single = inside an expression is an error, never a silent comparison. <> and != both mean not-equal.
  • NOT is an operator that binds looser than a comparison, as in SQL: NOT Price > 15 is NOT (Price > 15). Excel has only the function NOT(x), which Improv also reads, since NOT(x) is the operator applied to (x). One consequence: NOT(a) > b is NOT (a > b) in Improv, while Excel compares NOT(a) with b. Write (NOT a) > b for Excel's reading.
  • ^ is right-associative and binds tighter than unary minus: 2^3^2 is 512 and -2^2 is −4, the mathematical convention. Excel gives 64 and 4. Write (2^3)^2 and (-2)^2 for Excel's reading. The usual written meaning wins over spreadsheet compatibility, and a reader of -x^2 expects −x².
  • One comparison per level: a < b < c is an error. Excel reads it as (a < b) < c, comparing a boolean with a number, which is never what was meant.
  • No leading .: .5 is an error; write 0.5.
  • A number too large for a float is a parse error. 1e999 is the error number out of range when the formula is entered; Excel accepts it and shows #NUM!. A literal that cannot be a number is a typing mistake, and the editor reports it where it was typed.
  • No cell references, ranges or sheets. A1, A1:B5, Sheet1!A1, OFFSET, INDIRECT, ROW and COLUMN have no meaning in a model: formulas name measures and categories. M.Price parses, but is refused with a message naming the qualifier. This is the point of the design.
  • Ranges are measures reduced OVER categories. Excel's SUM(B2:B13) is SUM(Revenue OVER Time). In a function with several arguments, OVER follows the measures it reduces, and everything else is a parameter with one value per group: LARGE(x OVER T, 2), NPV(rate, cf OVER T), SUMIFS(sum, crit1 OVER T, ">5"). The argument order is Excel's. Only the OVER keyword is new.
  • Missing arguments. Excel allows IF(x, , 1) (an empty argument); Improv does not. Leave trailing optional arguments out, or name the later one (PMT(r, n, pv, type => 1)): Excel has no named arguments.

Values and types

  • Types are checked when the formula compiles; there is no coercion. Excel turns TRUE + 1 into 2, "3" + 1 into 4, and IF(1, …) treats 1 as TRUE. In Improv each is a compile error: arithmetic takes numbers, IF, AND and OR take booleans, and a comparison takes two values of one type (1 == TRUE and "1" == 1 are errors, where Excel gives FALSE). Convert explicitly with VALUE, N, TEXT or a comparison. A formula is defined once for every cell, so a type mismatch is a bug in the formula, better found at entry than as #VALUE! in some cells.
  • Dates are not numbers in arithmetic. In Excel a date is a number, so date * 2 and ABS(date) are valid. In Improv a date is its own type: date + 1 is the next day, date - date is days, N(date) is its serial number and ISNUMBER(date) is TRUE, as in Excel, but date * 2, ABS(date) and date == 45658 are compile errors. A number given to a date function (YEAR(45658)) is read as a serial date. & joins any two values as text.
  • Text comparison is case-sensitive. "a" == "A" is FALSE and "a" < "B" is FALSE (code-point order); Excel ignores case in = and <. The criteria of the …IF functions, lookups (MATCH, XLOOKUP, SELECT) and SORT do ignore case, as in Excel. The operators compare exactly, as SQL's = does in Postgres and DuckDB, where a model's data usually comes from, and < is code-point order, as under COLLATE "C": a test in WHERE or IF never matches text that only looks alike. EXACT behaves the same in both products. To compare without case, write UPPER(a) == UPPER(b). UNIQUE ignores case too, as in Excel, and keeps the first spelling: "Fig" and "fig" are one value.
  • Numbers are 64-bit floats, with no integer type and no 15-digit truncation. Excel stores 15 significant digits and treats a result within an ulp or so of a "round" value as equal; Improv keeps the full float and compares exactly, so 0.1 + 0.2 == 0.3 is FALSE in both products, while near-equal values Excel would round together stay unequal in Improv. Text built from a number ("x" & n, TEXT) and the grid show 15 significant digits in Excel's General form, as Excel does: "x" & 1e21 is x1E+21, "x" & 1e-10 is x1E-10 (an exponent below 1E-4 and from 1E+15; LibreOffice and Gnumeric each switch at other points). Exports keep every bit. Arguments that must be whole numbers (LEFT(t, n), CHAR, max_iter) are truncated toward zero, as in Excel. == and != compare numbers by value, so -0 == 0 is TRUE, as in Excel.
  • Dates are timestamps, not serial numbers. A date is a UTC instant with millisecond precision. Where a number is given for a date, or a date is turned into a number (N(date)), it is a serial date on the 1900 system with the fictitious 1900-02-29 left out, as LibreOffice and Gnumeric do: serial 61 is 1900-03-01 in both Improv and Excel, but below 61 Improv is one day off from Excel (serial 1 is 1899-12-31, not 1900-01-01; serial 60 is 1900-02-28, not Excel's 1900-02-29). There is no 1904 system. NOW() and TODAY() are UTC. Excel's leap-year bug is not worth copying, and a model's dates come from typed #…# literals and imports, not serial arithmetic.
  • A missing cell is not zero. Where an input has no cell, a formula over it has no cell, and an aggregation skips it. Excel treats a blank as 0 (or as ""). COALESCE and FILL give a value where an input has none. A model has cells only where data is, so inventing zeros would fill the whole cross product.
  • IF without else: a false test gives no cell, where Excel gives FALSE.

Errors

  • Errors are values, as in Excel, with Excel's names and ERROR.TYPE codes. An operator or function given an error returns it (the left operand, the first argument first, as in Excel), and an aggregation over several errors returns the one with the smallest ERROR.TYPE code. Excel returns the first one it meets, which in a model has no fixed meaning: the smallest code is deterministic.
  • No #CALC!, #SPILL! or #FIELD!. An empty list (FILTER with nothing included and no if_empty, TAKE of 0, UNIQUE with nothing left) is #N/A, where Excel gives #CALC!. #N/A already means "no value", IFNA handles it, and a 1.0 error set that matches the codes of ERROR.TYPE in every product (LibreOffice and Gnumeric have no #CALC! either) keeps imports and exports lossless. A list never spills over other cells, so there is no #SPILL!.
  • #NAME?, #REF! and #NULL! are never produced. An unknown name or function is a parse error when the formula is entered, with a suggestion, not a #NAME? cell; there are no references to break and no range intersections. ERROR("#NAME?") makes one, so imported values survive.

Functions

  • List results land INTO a category. Excel's dynamic arrays spill into the cells below and to the right. Improv has no "below", so a function that returns a list (SORT, UNIQUE, FILTER, TAKE, FREQUENCY, LINEST, TEXTSPLIT, …) names the category the list lands on, as the last thing in the call: SORT(Sales OVER Product, -1 INTO Rank). INTO R, C lays a 2-D result row by row, the order in which Excel spills a block. Results beyond the category's last item are dropped, where Excel would give #SPILL!.
  • FREQUENCY takes its bins as separate numbers: FREQUENCY(x OVER T, 10, 20 INTO Bin), where Excel takes a range, FREQUENCY(data, bins). A range of bins would be a second measure over its own category; the bins are almost always a few constants, and numbers keep the call on one line. The counts are Excel's: ≤ b1, (b1, b2], …, > bn.
  • TEXTSPLIT splits into one list. It keeps Excel's arguments, TEXTSPLIT(text, col_delimiter, [row_delimiter], [ignore_empty], [match_mode], [pad_with]), with INTO added; match_mode => 1 matches the delimiter ignoring case, as in Excel. A row_delimiter other than "" is #VALUE!, and so pad_with, which pads the short rows of a 2-D result, never applies. A 2-D split would land on two categories (INTO R, C), and a list result is laid there row-major in a fixed grid, so each row would need as many columns as the widest, known only after the split; a text with several rows is better split twice, by rows into one category and then each row by columns. Since #VALUE! is an error caused by the missing feature, a 1.x release may still add it.
  • SORT and UNIQUE take one option. SORT(x OVER T, [sort_order]) has no sort_index or by_col, and UNIQUE(x OVER T, [exactly_once]) has no by_col: a list has one column. Use SORTBY to sort by another measure.
  • SEQUENCE and MAKEARRAY take categories, not sizes. SEQUENCE(Month, 100, 5) numbers Month's items; Excel's SEQUENCE(rows, [columns], [start], [step]) takes counts. A model's length is its category's item count.
  • Database functions take WHERE, not a criteria range: DSUM(Sales OVER Region WHERE Year == 2025), where Excel writes DSUM(database, field, criteria). A model has no header row to name a field by.
  • No volatile or random functions. RAND, RANDBETWEEN, RANDARRAY, INDIRECT and OFFSET are not in the language: recalculation is incremental and must give the same result every time. NOW() and TODAY() are the exceptions, read when the model recalculates.
  • No grid functions. VLOOKUP, HLOOKUP, TRANSPOSE, HSTACK, VSTACK, TOCOL, WRAPROWS, CHOOSECOLS and the other reshaping functions rearrange a grid; in Improv the layout is a view (pivot the categories). Use XLOOKUP or SELECT for lookups.
  • Cash flows and blanks. NPV, IRR and the other cash-flow functions skip a period with no cell (Excel's rule for a blank in a range), so the flows after it move up a period; enter 0 for an empty period.
  • LAMBDA. A named LAMBDA cannot call itself (every formula terminates); write a recurrence with SCAN, PREV or FIXPOINT instead. A LAMBDA cannot be named like a built-in function.
  • Financial and statistical functions follow Excel's documented results where LibreOffice and Gnumeric depart from them (DURATION on actual/actual, PRICE/YIELD with one coupon left, and others listed in the CHANGELOG). Functions Excel lacks follow Gnumeric or LibreOffice, and the Function Reference says which.

Language stability

From 1.0.0 the formula language follows Semantic Versioning: a formula that is valid in 1.0 is valid in every 1.x, with the same meaning.

A 1.x release may add:

  • new functions, and new aliases of existing ones;
  • new optional trailing arguments to a function (an omitted argument keeps today's result);
  • new syntax, but only where today's text is a parse error (as named arguments and "" inside a string were, or a leading . in a number): no valid formula changes meaning;
  • new error messages and better suggestions, and new locales;
  • results where today's are an error caused by a missing feature, for example a TEXTSPLIT row delimiter, which is #VALUE! today.

A 1.x release will not change:

  • the result, the result type or the categories of a valid formula, other than to fix a documented bug (below);
  • the name, the argument order or the argument meaning of a function; the meaning of an alias; what an omitted optional argument means;
  • operator precedence and associativity, the keywords, and the literal forms;
  • the error a formula gives: which of #DIV/0!, #NUM!, #VALUE! and #N/A, and which one wins when several meet;
  • the stored form: function ids (FuncId) are permanent and never reused, so a model saved by 1.0 opens in every 1.x unchanged.

Adding a keyword or a function can take a word some model uses as a measure name. That is a compatible change: a name followed by ( is a call, and a measure called like a function still parses as long as it is not followed by (. A quoted name ('Over') is never a keyword. The parser already reads keywords only where they belong, so a release that adds one says so in the CHANGELOG and checks that existing names keep their meaning.

Bug fixes. Where a result disagrees with this guide, with the Function Reference or with the reference products the CHANGELOG names for a function (Excel's documentation, LibreOffice, Gnumeric), the result is a bug and a 1.x release may fix it. The fix is listed under Fixed in the CHANGELOG with the old and new result. Results that change in the last bits of a float, for a documented reason such as a more accurate summation, are listed the same way.

Deprecation. A function or form is never removed in 1.x. To retire one:

  1. A minor release marks it deprecated: the Function Reference and the CHANGELOG say so and name the replacement. The formula still parses and gives the same result.
  2. The formula editors (GUI, TUI, improv define) warn when a deprecated form is entered or a model that uses it is opened. Stored models are never rewritten without being asked.
  3. It is removed only in the next major release (2.0), whose CHANGELOG lists every removal, and a model that uses a removed form still opens: the formula is reported as an error, not dropped.

The Differences from Excel are part of the 1.0 language and covered by this policy. A follow-up there that changes a valid formula's result (as UNIQUE's case and number-to-text formatting did) is a bug fix in the sense above and lands in a 1.x release with a Fixed entry; one that only accepts more (string escapes, more TEXTSPLIT options) is an addition.

Broadcasting: the Revenue example

The canonical formula is:

Revenue[Time, Product] = Price[Product] * Quantity[Time, Product]

Price ranges over Product only; Quantity ranges over Time and Product. Their dimensions differ, so the compiler must align them before it can multiply element-wise. One dimension is a subset of the other ({Product} ⊆ {Time, Product}), so Price is broadcast over Time: the result is defined over the union, [Time, Product], and each Time reuses the matching product's price.

The rule is strict: for a binary op, one operand's dimension must be a subset of the other's. If neither is (say, Product-only added to Region-only), the compiler rejects it with a dimension mismatch rather than guessing.

Dimension projection: BY / OVER / EXCEPT

A measure reference carries a DimensionSpec with three category lists that reshape which dimensions the reference exposes:

FieldMeaning
byCategories to keep (group by). If non-empty, only these survive.
overCategories to aggregate over (collapse). Used with an aggregation call.
exceptCategories to drop.

Starting from the measure's base categories, the compiler keeps a category if it passes by (or by is empty), is not in except, and is not in over. The over set specifically marks the dimensions an enclosing aggregation collapses.

In the text syntax, Measure[Cat, …] fills by and AGG(Measure OVER Cat) fills over. Nothing fills except.

Only an aggregation collapses categories. So a bare reference whose by leaves a category out is a compile error: X = Quantity[Product], with Quantity over [Time, Product], says "Quantity[…] leaves out category Time, which only an aggregation can collapse". Inside an aggregation, the result keeps the categories that by keeps and over does not name.

Aggregation

Aggregation is expressed as a Call whose single argument is a measure reference. The reference's over list names the categories to collapse; the result is defined over the remaining categories.

Every function has a fixed FuncId, stored in saved formulas and never reused (crates/core_model/src/functions.rs). The aggregations:

FunctionFuncId
SUM1
AVERAGE (AVG)2
MIN3
MAX4
PRODUCT5
SUMSQ6
AND, OR, XOR7, 8, 9

For example, SUM(Revenue OVER Time) takes Revenue[Time, Product] and collapses Time, producing a per-product total Revenue[Product]. In the compiler this becomes an Aggregate plan node grouped by the surviving categories (Product), with func = FuncId(1).

AVERAGE divides the sum by the count of contributing cells; MIN and MAX take the extremum. An aggregation's argument must be numeric, except AND, OR and XOR, which take booleans.

Summation. SUM and AVERAGE are exactly rounded: the engine adds the values with no rounding at all (a fixed-point accumulator wide enough for any sum of doubles) and rounds the total once, to the nearest double, ties to even. AVERAGE is that sum divided by the count. So SUM(0.1, 0.2, 0.3) is 0.6, where a left-to-right fold gives 0.6000000000000001; SUM(1E16, 1, -1E16) is 1; and the result does not depend on the order of the cells or how they are grouped. A sum that is exact anyway, of integers say, has the same bits as a plain fold. An infinity or NaN among the values gives what IEEE addition gives, and a total beyond the largest double is #NUM!. LibreOffice 25.2 compensates its sums (its SUM of 250 such values matched the exact sum's nearest double), but it rounds a near-total cancellation to zero: SUM(1E16, 1, -1E16) is 0 there and 1 here. Improv promises exact rounding for 1.x.

Large categories. Over a single category of more than 1,024 items, the aggregations above and COUNT and COUNTA reduce in two levels, so that an edit to one cell costs a block of the group rather than all of it: the cells split into blocks of 1,024 item ids, each block folds in item order, and the block results combine in block order. The counts, MIN, MAX, AND, OR and XOR give the same result as one pass. SUM and AVERAGE keep each block's exact sum and round once at the end, so they are bit for bit the flat sum. PRODUCT and SUMSQ of fractional values are a fixed two-level fold: deterministic, identical in every evaluation path, but they can differ from one left-to-right pass in the last bits. Over up to 1,024 items nothing changes.

The exact sum costs about 1.5 ns per value more than the Neumaier compensation it replaced (SUM of 1,000,000 values through the scalar path: 4.8 ms against 3.3 ms, and 0.5 ms for a plain fold), which no engine benchmark shows: on the 1,000,000-item SUM(X OVER W) a full evaluate takes 1.31 to 1.33 s (1.30 to 1.32 s before) and an edit 0.15 to 0.66 ms (p50), as before.

The goldens in crates/engine/tests/sum_10k.rs pin it: three sets of 10,000 fractional values, whose SUM and AVERAGE must equal the bits mpmath gives for the exact sum (scripts/goldens/sum_10k.py), in evaluate, the live engine before and after an edit, and over two categories.

Type and dimension checking

Compiling a formula (improv_engine::compiler::compile_formula) runs two passes:

  1. infer — walks the AST, resolving each measure reference against the model's metadata and computing every subexpression's value type and dimension. It rejects type errors (e.g. multiplying non-numbers, Not on a number) and structural errors (dimensions that cannot be broadcast).
  2. build_plan — lowers the typed tree to a PlanNode graph, inserting a Join where operand dimensions differ (to broadcast) and an Aggregate node for each aggregation call.

The result is an operator plan that maps directly onto differential-dataflow operators — see Architecture.

Scope today

The engine evaluates input-measure references, literals (standalone or as operands), unary negation and NOT, the arithmetic, logical and comparison operators, dimension-aligning joins, aggregations (several measures, parameters, WHERE, windows, per-item results such as RANK, lookups, list results with INTO), LET and LAMBDA, the 681 built-in functions of the Function Reference (math, rounding, text, dates, statistics and distributions, financial, engineering), the lazy IF family, positions and neighbours (POSITION, PREV, NEXT), recurrences, bounded fixed points (FIXPOINT), typed error values, non-numeric (Text, Boolean, DateTime) values, and derived measures that reference other derived measures.

External functions use the CALL(...) definition form and are evaluated host-side by improv_extfn. Python, R, Julia and Pure run in a sandboxed subprocess; Wasm runs in-process. SQL-sourced measures use SQL("...").

Gaps:

  • no EXCEPT on a plain reference (only OVER ALL EXCEPT … inside an aggregation);
  • a window or per-item reduction takes one OVER category;
  • TEXTSPLIT takes no row delimiter (see Differences from Excel);
  • named LAMBDAs are defined with improv define, improv.define, the TUI's = line or the GUI formula list's last line;
  • no MMULT or LINSOLVE function: a matrix product is a join and a sum (see Matrices); FORECAST.ETS.CONFINT is #N/A for seasonal models (LibreOffice's interval is a random simulation);
  • NETWORKDAYS and WORKDAY take no holiday list yet.

The Desktop GUI

improv-gui is the egui/eframe desktop front-end, styled after the original NeXTSTEP Lotus Improv: NeXT's four-level grayscale (no color anywhere, a gray selection), flat controls with 1 px black outlines, worksheet windows with NeXT title bars on a dark gray workspace, white grid cells, a formula list in each worksheet window, a floating application menu, on-grid category tiles for pivoting, a model browser window and an Info panel.

Run it (from the Nix dev shell, which provides the GUI runtime libraries):

bash docs/demo/sample-model.sh sample.db
nix develop -c cargo run -p improv_gui -- sample.db

A model opens on its first saved view, or, with none, on its first measure.

Pivoting by dragging the Region tile, paging, editing a Quantity cell while the Revenue worksheet recomputes, selecting a range for its Sum, and adding a formula. Recorded by docs/demo/gui-movie.sh.

The pivot grid

Improv GUI — pivot grid

The window has five regions:

  • Application menu (floating, top left) — NeXTSTEP's vertical menu. Drag its black Improv title bar to move it. An item marked with a triangle opens a submenu to its right; click it again, press Escape or click elsewhere to close it. The menus are Lotus Improv 1.0's, in its order and with its key equivalents, holding the commands this GUI has. Info ▸ Info Panel… shows or hides the Info panel; Context Help… and Point for Help open the Help window (see Context help). File ▸ Open… opens a store file or URL and New starts an empty model (type a new file, a postgres:// URL, or nothing for an in-memory one), both in a small panel whose path field has the keyboard (Esc closes it); Save saves the model, Save As… writes it to a new file or URL and carries on there (Save does that too for an in-memory model), Revert to Saved reloads it from the store (the way out of a save conflict), Model Browser… shows or hides the model browser, Close closes the model to an empty desk (unsaved edits warn first, as Quit does; a second Close drops them), and Import/Export CSV… opens the CSV wizard. Edit has Undo and Redo (which Improv 1.0 lacked), Cut, Copy, Paste (see Copy and paste) and Select All, the whole worksheet, Select Items Only and Select Cells Only (see Selecting), Inspector… (see The Inspector and the Format panel), Add Category, Add Item and Add Input Measure (see Building a model from scratch), Rename and Delete… (see Renaming and deleting). Format has the Format Panel…, sets how the selected measure's numbers show (see Number formats), and has Report Layout… and Page Layout… (see Printing). Print… prints the focused worksheet. Worksheet has Recalculate (the formula pane's Calc) and Save View. View has New View, another worksheet window on the model, Close Window (Ctrl+W), and Swap Rows/Columns, then the saved views, with a check on the current one; picking one switches the workspace to it. Graph ▸ New Graph opens the graph window. Help ▸ Functions… (also F1) opens the function help, Help ▸ Keys… a window listing the keys, and Help ▸ User Guide this guide, online, in the browser. Hide minimizes and Quit closes the window. Print and Services are not built yet and draw grayed out. Key equivalents are shown at the right of their item; a capital letter means Shift too. See the key equivalents.
  • Model browser (window, bottom left of the workspace) — titled <file> - Model. It leads with a white list of saved views, one Name - Worksheet row each with a worksheet icon: click a row to select it and read its description below (measure, categories, pages); double-click to open it (a view saved by improv save-view, which has no window position, opens right of the menu). Under that, a name field and Save view save the current canvas. Collapsed below are Categories (with their items) and Measures (each labeled input or formula at the right; click one to select it), each list ending in a line that adds one, and the named LAMBDAs, once there are any. Its close box hides it; File ▸ Model Browser… brings it back.
  • Worksheet windows (center) — the dark gray workspace holds one window per matrix, titled <matrix> - Worksheet - <file>. Drag a title bar to move a window and its bottom bar to resize it (left of its left notch drags the bottom-left corner, right of the right notch the bottom-right, between them the bottom edge). Clicking a window makes it key (black title bar) and gives its matrix the keyboard; while a panel has the keyboard the worksheet you were in keeps a dark-gray title bar, and other windows' are light gray, as on NeXTSTEP. The close box is drawn broken while the model has unsaved changes, and the button at the title bar's left minimizes the GUI's window. With more than one matrix open, each window's close box removes its matrix. View ▸ New View opens another window the size of the last one, beside it, or below it, where the workspace has room and no window is covered; else it cascades from the last one, its title bar showing. Save View records every window's place and size. A fresh window opens right of the menu, sized to its grid.
  • Pivot grid (in each worksheet window) — the measure projected onto the current axes. Here Revenue is shown with Product on columns, Time on rows, and Region paged. The category tiles are dark-gray chips, placed as in NeXT Improv: page tiles top-left, each above a white item field (click it to pick the page shown; [ / ] and PageUp / PageDown step it too), column tiles top-right, row tiles bottom-left beside the scroller. Drag a tile to another strip to re-pivot without touching the formula (the strips light up as drop targets only while you drag), or right-click it and choose Move to Rows / Columns / Pages. The same menu filters the category: uncheck an item to hide it from this worksheet, or choose Show all; a filtered tile reads Name*. Its last line, New item, adds an item to the category: type the name and press Enter. Cells are white with thin black rules; the selection and its row and column headers turn gray. Click a cell to select it and type to replace its value; double-click it (or press Enter / F2) to edit it with its value selected. Enter commits, Esc cancels. A number cell takes 1500, -3.5, 1,500.25 and $1,500 (a leading $, €, £ or ¥; in a German locale, IMPROV_LOCALE=de, 1.500,25 and €1.500). An entry the cell refuses (1,50 in a number cell) stays in the editor, with the reason and the forms it takes in the status line, to correct or cancel. Input cells carry a faint underline; hover a derived cell to see its formula. Arrows (or h j k l) move the cursor, and n / Shift+n show the next or previous measure. Shift+arrows, Shift+click or a drag select a range, and the status bar shows its Sum.
  • Formula list (bottom of each worksheet window) — every formula, numbered, with a Calc button above, a checkbox that enables it, and Improv's status indicator: a check when the formula checks, a cross when it has an error. Click a row to select its measure; the selected row becomes an editor: Enter commits (re-typechecks and recomputes), Esc reverts. Type Name = formula on the last line and press Enter to add a measure, or Name = LAMBDA(p, …, body) to define a named LAMBDA (as improv define does); typing an existing LAMBDA's name redefines it. A formula that fails, in either editor, stays as typed with the fault underlined (see Formula errors).
  • Info panel (window, top right of the workspace, closed at start) — opened by Info ▸ Info Panel…: the selected measure's id, kind, value type, number format, dimensions, dependencies, and formula. An input measure has a box per category, checked for its dimensions: check one to add it (the cells go to its first item), uncheck one to drop it (the cells at its first item stay, the rest go; the status line counts them). The formulas that read the measure take their new shape, and a change that would break one is refused with the reason. It is one undo step. Its close box closes it.
  • Status bar (bottom) — the last action's outcome (saved model, or saving… until File ▸ Save's write lands, recalculated, undo, added Margin, or an error) on the left, cleared after 5 seconds, and the selection's Sum on the right. While the formulas recompute after a structural change (a new or edited formula, an import, its undo, opening a model), it also says Recalculating…. While a model opens, the window shows at once and says Loading… (the desk and the title too) until its store has been read; only Quit, Hide and User Guide work until then. That takes a second or two at a million cells. The window keeps responding: the grid shows the last results until the new ones are ready, and cell edits made meanwhile are applied to them.

The native window title reads Improv — <file> (Untitled in memory), with a trailing • while the model has edits that are not saved: any edit of an in-memory model, or a model whose autosave is still running or failed. To keep an in-memory model, choose File ▸ Save and type a path: the model is written there, the window switches to it and autosaves to it from then on, and Undo still works. Quitting an edited in-memory model asks for a second Quit.

Every edit autosaves, in one transaction, in the background: the window does not wait for the file. The title's • stays until the store has the edit. If a save fails, the edit stays in the window, still marked •, and the status line says it is not saved yet and why:

  • The disk is full (or the file can't be written): free some space. The next edit, or File ▸ Save, writes everything that was not saved, and the status line says so.
  • Another program changed this model since you opened it: nothing is overwritten, and nothing from this window is saved until you reload. The Changed panel opens; Reload (File ▸ Revert to Saved) loads their changes and drops yours, which you then make again.

Quit and the window's close box wait for a save that is still running. If a change could not be saved, the first Quit says so and a second one discards it; File ▸ Open… refuses until it is saved or reverted.

Every two seconds the GUI checks whether another program saved the model. When one has, a Changed panel offers Reload (File ▸ Revert to Saved: their changes come in and the undo history is dropped) or Not Now, which hides it until they save again. Until you reload, a save from this window is refused as above, so nothing is overwritten.

A crash or a kill -9 during a save loses only that save. The file reopens with every earlier edit and nothing half-written.

Building a model from scratch

Start improv-gui with no model, or choose File ▸ New and type a path for the new store. The empty workspace says where to begin, right of the menu. Then, all undoable with Ctrl+Z and autosaved after each step:

  1. Edit ▸ Add Category opens the model browser's Categories list at its New category line. Type Time, Enter; the line clears, so type Product and Enter again.
  2. Add Item: open a category in the browser and type into its New item line, or right-click the category's tile in a worksheet and type into the tile's New item line. Edit ▸ Add Item jumps to the line of the worksheet's first row category.
  3. Edit ▸ Add Input Measure: type Price for a measure over every category, or name its categories after a colon, Price: Product, as the TUI's n takes them (Price: alone is a single cell). An empty worksheet shows it. Click a cell and type its value.
  4. Add formulas on the formula list's last line: Revenue = Price * Quantity, or a named LAMBDA, Margin = LAMBDA(p, c, p - c), which the browser then lists under LAMBDAs and any formula can call: Net = Margin(Revenue, Cost).

A name already used by a category, a measure or a LAMBDA is refused, and the status line says why; so is a measure name with a comma.

Renaming and deleting

Click a category, an item, a measure or a saved view in the model browser to pick it. Edit ▸ Rename and Delete… act on the pick, or on the focused worksheet's measure when nothing is picked. Worksheet ▸ Save View with the browser's name field empty saves "view N" and opens its rename line, so typing names it.

  • Rename: the row turns into a line holding the name, selected. Type the new name and press Enter; Esc keeps the old one. Double-clicking an item or a measure does the same. Formulas follow the new name. A name already used is refused, and the line stays open with the reason in the status line.
  • Delete… asks first, in a small panel that says what goes with it: an input measure's cells, an item's cells, a category's items. Delete (or Enter) deletes, Cancel (or Esc) keeps it. A saved view loses a deleted measure's worksheets, and is deleted if none is left. A measure that a formula reads cannot be deleted, nor can a category that a measure ranges over or names. The status line names what still needs it, as improv.drop_measure does: cannot delete Revenue: Margin still references it (delete or redefine it first). Deleting a view leaves its worksheets open. A view's name need only differ from the other views'.

Each rename and delete autosaves and is one undo step.

Number formats

Format sets how the selected measure's numbers show, in every worksheet: General (as many digits as the value needs, at most 15 significant), 0 Decimals to 4 Decimals, and Thousands Separators, which turns grouping on or off and keeps the decimals. A check marks the format in effect. 299.666666666667 shows as 299.67 at two decimals, 1234567.891 as 1,234,568 at none with separators. Decimals round half away from zero (2.5 shows as 3). The separators follow the formula locale (IMPROV_LOCALE): 1.234,50 in German.

A format is presentation only. The value keeps every digit: formulas, the CSV and SQL exports and Postgres see it unrounded, and editing a cell starts from the value as typed, not as shown. The Sum in the status bar and the Info panel follow the format. Each change autosaves and is one undo step; the measure keeps its format in the file or database. Format is grayed out for a measure that holds text, booleans or dates.

The Inspector and the Format panel

Improv's two multiform panels: a pop-up list at the top picks the page, and each works on the focused worksheet, following the focus to another one as a NeXT panel follows the selection.

Edit ▸ Inspector… has three pages; OK applies them to the worksheet and Revert reads it back:

  • Grid: Show Grid Lines, and Lines In the Cell Area, the Item Area (the item headers) or Both.
  • Layout: Show Markers ▸ Hidden Items, the * on a filtered category's tile.
  • Formulas: Show Errors In Line. Off, a formula's error moves from under its row to its status indicator's tip.

Format ▸ Format Panel… (Ctrl+Shift+F) has two pages over a sample; Set applies both:

  • Number: General or Specific with its Decimal Places (0 to 15), and Commas (thousands separators). It sets the measure's format, as the Format menu's rows do, as one undo step.
  • Alignment: Smart (numbers right, text left), Left, Center or Right, for the worksheet's cells.

The worksheet's options (the Inspector's, and the alignment) stay with its window for the session; they are not saved in the view yet. Improv's Inspector also had its recalculation controls and group-collapse and page-break markers, and its Format panel Line Style, Color, custom and date/time pages; those have no engine or view state to set here.

Printing

Print… (Ctrl+P) prints the focused worksheet as it shows: its item names and cells in their number format and alignment, ruled as the Inspector's Grid page says, split across as many pages as it needs with the item names repeated on each. The Print panel has Copies, Pages (All, or From and To), and Print Selected Data Only (when more than one cell is selected), then:

  • Print: to the platform's print system. On Linux, macOS and the BSDs that is CUPS's lp (or BSD lpr), sent as PDF; on illumos the LP service's lp, sent as PostScript. Printer names a queue; empty is the default one. On Windows, Print opens the Windows print dialog and prints with the printer it picks. With no lp or lpr, Print is grayed.
  • Save as PDF and Save as PostScript: write the pages to File (.pdf or .ps; it starts as the model's name).

Format ▸ Page Layout… sets the Paper Size (Letter, Legal, A4), the Orientation (Portrait or Landscape) and the Scale (50% prints at half size, so more fits on a page).

Format ▸ Report Layout… sets the Header and Footer, each with a left, a centered and a right part, the First Page Number, Number Pages (Top to Bottom: down a column of pages first; Left to Right: across first), and the Content: Data (the items and cells), Formulas (the numbered formula list, on pages of its own), or both. A header or footer can hold Improv's markers, typed or inserted from its field's right-click menu: <Date>, <Time>, <View Name>, <Worksheet Name>, <Model Name> and <Page #>. The default header is the worksheet's name and the default footer Page <Page #>.

The layouts are kept for the session, not saved with the model yet. Pages are in Helvetica, which every printer and PDF reader has.

Graphs

Graph ▸ New Graph charts the focused worksheet in a graph window, <worksheet> - Graph - <file>, at the workspace's bottom right. Select a range first to graph just that; with one cell selected the whole grid is graphed. The graph follows the worksheet as it changes, as Improv's did.

The line above the graph is its inspector:

  • Type: Improv's seven graph types, Line, Bar (the default), Scatter, Pie, Area (stacked), Stock (the first three series are high, low and close) and 3D Bar. A pie shows the first series.
  • Series by: whether each Rows or each Columns of the selection is a series, or Smart, Improv's rule: a single selected row makes each column a series, a single column makes each row one, and otherwise the longer side is the series.
  • Color: series in NeXT's named colors (red, blue, yellow, green, orange, cyan, purple, brown); unchecked, in the four NeXT grays, as on a monochrome NeXTstation.

Every bar, wedge and marker is outlined in black, and the legend at the right names the series. A screen reader hears the graph as "Bar graph of 2 series over Time".

Scrollers

NeXT's scrollers: a gray trough with a raised knob, and the arrow buttons grouped at one end (the bottom of a vertical scroller, the left of a horizontal one). An arrow scrolls a line; Alt+click an arrow scrolls a whole view, less a line so the last one stays in sight (NeXT's Alternate-click). A click in the trough makes the knob jump there; drag the knob to scroll continuously.

Keyboard and screen readers

Everything works from the keyboard. In a worksheet the arrows move, typing replaces the cell's value, Enter or F2 edits it, Enter commits and Esc cancels; [ and ] page. The grid's own keys (h j k l n [ ]) keep their jobs, so a text value that starts with one is typed after Enter. Tab moves through the menu, the windows' fields and buttons, and Enter or Space presses the focused one, so Tab to a menu item and Enter opens its submenu or runs it. The key equivalents work anywhere outside a text field. Help ▸ Keys… lists them all.

Key equivalents

NeXT's Command key is Ctrl on Linux, the BSDs, illumos and Windows, and Cmd on macOS. The letters are Improv 1.0's (from its main menu) and NeXTSTEP's reserved ones; a capital means Shift too.

KeysCommandMenu
Ctrl+?Context Help…Info
Ctrl+OOpen…File
Ctrl+NNewFile
Ctrl+SSaveFile
Ctrl+Shift+SSave As…File
Ctrl+Shift+WCloseFile
Ctrl+ZUndoEdit
Ctrl+Shift+Z, Ctrl+YRedoEdit
Ctrl+XCutEdit
Ctrl+CCopyEdit
Ctrl+VPasteEdit
Ctrl+ASelect AllEdit
Ctrl+[Select Items OnlyEdit
Ctrl+]Select Cells OnlyEdit
Ctrl+Shift+FFormat Panel…Format
Ctrl+PPrint…main menu
Ctrl+RRecalculateWorksheet
Ctrl+Shift+VNew ViewView
Ctrl+WClose WindowView
Ctrl+/Swap Rows/ColumnsView
Ctrl+HHidemain menu
Ctrl+QQuitmain menu

Improv's Ctrl+T (Font panel) belongs to a command not built yet, so it does nothing. Ctrl+W is NeXTSTEP's reserved Close for the key window; here it closes the focused worksheet window, as View ▸ Close Window does.

Selecting

Click a cell to select it; Shift+click, Shift+arrows or a drag select a range of cells. Click an item (a row or column heading) to select it and its cells, the whole row or column; Shift+click another item extends to it. On stacked categories, an outer item selects its group: every row or column under it. Edit ▸ Select All (Ctrl+A) selects every item and cell.

Edit ▸ Select Items Only (Ctrl+[) keeps the selection's item names and lets its cells go (the cells are no longer shaded): Copy then copies the names, a line each, Cut copies them (an items-only selection cannot be cut), and Paste and the Sum are refused. Edit ▸ Select Cells Only (Ctrl+]) keeps the cells. The plain [ and ] still page.

Copy and paste

Edit ▸ Copy (Ctrl+C) puts the worksheet's selection on the clipboard as text, a tab between cells and a line per row, the way the cells show, so it pastes into another spreadsheet or a text editor. Edit ▸ Paste (Ctrl+V) writes tab-separated text into an input measure from the cursor right and down, stopping at the grid's edge (the status line says how many values were clipped there, as Improv warned); an empty field clears its cell. Each value must be one the cell takes (1,500 and $1,500 are fine in a number cell), or nothing is pasted and the status line says which value it refused. A paste is one undo step. Derived cells are computed, so a paste there is refused. Edit ▸ Cut (Ctrl+X) copies the selection as Copy does and clears its input cells, as one undo step; on a derived measure use Copy.

Every control has an accessible name (through AccessKit, which egui feeds to Orca, VoiceOver and Narrator): menu items by their label, a cell by its row and column items and its value (2025, WidgetA: 100), a tile by its category and axis, and text fields by what they ask for. The four grays meet WCAG contrast: black text is 21:1 on cells and 9:1 on panels, white tile text 7.5:1.

Context help

Info ▸ Context Help… (Ctrl+?) opens the Help window on the page for the window in front: the Inspector's page when the Inspector was the last window clicked, the worksheet's when a worksheet was. Info ▸ Point for Help turns the pointer into a question mark: the next click opens the page for what it lands on (the menu, a panel, or a worksheet's tiles, grid or formula pane) and does nothing else; Esc cancels. Each page is a few lines, with More in the User Guide to open its section of this guide and its own Point for Help button. Help ▸ Functions… (F1) is the function browser.

Function help

Help ▸ Functions…, or F1 from anywhere (a formula edit included), opens the Functions window at the workspace's right: a search line, the matching functions grouped by category with their signatures, and the selected one's details. The search matches names, aliases and descriptions, best first (pmt finds PMT, then IPMT, PPMT, …; payment finds them by description). Up and Down move the selection. The details show the signature with the parameter names (PMT(rate, nper, pv, [fv], [type]), [optional], … repeating), the category and aliases, the description, and the argument types. Insert, a double-click or Enter puts NAME( into the formula you were editing (the selected row's, else the Name = formula line), at the caret, and returns the keyboard to it.

The Functions window

Autocomplete

Both formula editors complete as you type. Start a name (PM, Qua, or a quoted 'Unit) and a list drops under the edit: matching functions with their signatures and a dimmed one-line description, then the model's measures and categories, at most eight. Up and Down move the selection; Tab or Enter accepts it, Esc closes the list. With the list closed, Enter commits the formula as before. Accepting a function writes NAME( with the caret after the (; a measure or category named with spaces is quoted for you ('Unit Cost').

While the caret is at the end of the text, the rest of the selected name and its parameters trail it in light gray (PM shows T(rate, nper, pv, [fv], [type])). Inside a call the parameters still to give trail it: after PMT(0.05, they read nper, pv, [fv], [type]). A tooltip over the edit shows the signature with the argument the caret is in bold and underlined, the description and the category.

Completing PM

Inside PMT: the current argument marked

Formula errors

When a formula fails, the place it fails is underlined in the editor, and under the row are the message and, dimmed, why. The editor keeps the keyboard, with the caret at the start of the underlined part, so you can correct it and press Enter again:

  • an unknown measure or category: did you mean Price?, the nearest names in the model (a misspelled function's suggestion is in the message itself: unknown function: PMTT; did you mean PMT?);
  • the wrong number of arguments: the call's name is underlined, the message spells the parameters, and the hint says what is off, missing pv: 2 given;
  • a ( never closed: that ( is underlined, ( opened here is never closed: add );
  • an aggregation without OVER: its form, IRR(values OVER T, [guess=0.1]).

A type or dimension error has no position, so the editor underlines the first function or measure the message names (in Quantity + LEN(Price), LEN). A row whose saved formula no longer compiles shows its error the same way. Editing the text clears the mark.

Stacked axes

Drag the Region tile from the top-left pages strip onto the bottom row strip and the row axis becomes the stacked product of Time × Region:

Improv GUI — stacked axes

Each Time group (2024Q1, 2024Q2, …) now expands into its Region rows (North / South), with the outer Time label printed once per group. Any number of categories can stack on either axis; the grid renders the full Cartesian product, and rows are virtualized so a stacked axis of millions of lines stays responsive.

Incremental recalculation

Editing an input cell propagates as a delta through differential dataflow — only the touched cells and their dependents recompute. The same behavior on the CLI:

Incremental recalculation

A model in Postgres

The GUI opens a model stored in Postgres from its URL, improv-gui 'postgres://me@127.0.0.1/sales?sslmode=disable&model=plan'. Input measures bound to a table show that table's rows, and editing a cell updates the row. Here the price of Q1 Widget was changed in SQL, and the GUI shows the recomputed revenue (1200):

The GUI on a Postgres model

Platforms

PlatformStatus
Linux (Wayland, X11)Builds and runs.
FreeBSDBuilds and runs (X11).
illumos (Solnix)Builds with ci/solnix-gui.sh (below); runs in a Solnix COSMIC (Wayland) session.
Windows 11 (x64, arm64)Builds and runs; arm64 tested on santorini, x64 in CI.
macOSBuilds and passes its tests in CI.

illumos

eframe draws with OpenGL through glutin, and glutin 0.32's EGL and GLX crates leave illumos out of their target lists, so it does not compile there as published. Until a glutin release has the fix (docs/reviews/patches/glutin-illumos.patch), build on a Solnix host with:

ci/solnix-gui.sh build --release   # or: ci/solnix-gui.sh test
UMEM_OPTIONS=backend=mmap target/release/improv-gui sample.db

The script vendors the locked crates (cargo vendor --locked), applies Solnix's illumos fixups to them (the ones its own COSMIC applications are built with, found from the installed cosmic-comp), then the glutin patch, and builds with --locked --offline against the session's libxkbcommon, Wayland and Mesa. It needs rustup's x86_64-unknown-illumos toolchain, gcc and an installed COSMIC session; it vendors again only when Cargo.lock or the patch changes. UMEM_OPTIONS=backend=mmap is there because libumem's default allocator backend fails the renderer's first large allocation.

Recording the movie and screenshots

docs/demo/gui-movie.sh rebuilds the demo model, runs the GUI on a headless X server and records the movie above with ffmpeg, driving it with xdotool. scripts/gui-shot.sh takes the screenshot the CI compares against its golden image.

The COSMIC Desktop GUI

improv-cosmic is a second desktop front end, built on libcosmic, the toolkit the COSMIC desktop (System76, Pop!_OS) is made of. It is a native COSMIC application: it takes the desktop's theme, light or dark, and its accent color, and it opens, saves and prints through the XDG desktop portals. It works on the same models as improv-gui, the NeXTSTEP-style workspace, and both stay: pick the one that fits your desktop.

improv-cosmic: the Price measure, its category tiles and the formula list

The demo model's Price measure in COSMIC's dark theme: the header bar, the Rows, Columns and Pages strips of category tiles, the grid (the cursor in the accent color), and the formula list.

It is a preview. It covers the everyday work on a model (see What it does), not yet all of improv-gui; see Not yet.

Running it

improv-cosmic is its own Cargo workspace, crates/gui_cosmic (libcosmic pins its own toolkit stack, apart from the egui GUI's). From a checkout:

cd crates/gui_cosmic
cargo run --locked --release -- ../../sample.db
cargo run --locked --release -- 'postgres://me@127.0.0.1/sales?model=plan'

On Linux the build needs libxkbcommon-dev and libwayland-dev (Debian names). It runs on Wayland (COSMIC's own compositor, or any other) and on X11. ICED_BACKEND=tiny-skia selects the software renderer, for a machine with no GPU backend. Without an argument the model is in memory only.

What it does

  • The grid. The shown measure (pick it in the header bar's list) as a grid that draws only the cells in view, so a measure of a million cells scrolls as fast as a small one. Arrows, Tab, Page Up and Down, Home and End move; Ctrl+Home and Ctrl+End go to the first and last cell; Shift extends a range.
  • Editing. Type on a cell, or press Enter or F2, or double-click it, to edit it; Enter commits and moves down, Escape cancels, Delete clears. The text is read by the measure's value type, as everywhere in Improv: 42 in a Text measure is text, and text that is not a number in a Number measure is refused with the reason. Derived cells are computed, not entered.
  • Formulas. Under the grid, every formula in Improv's numbered list, 1. Revenue = Price * Quantity. Click one to edit it. A formula that does not parse stays open with the error located: the text with carets under the wrong part, the message, and a hint (did you mean Quantity?). While a name is typed, the names and functions that complete it appear; Tab or Enter takes the first.
  • Pivoting. Above the grid, the measure's categories as tiles in three strips: Rows, Columns and Pages. Drag a tile to another strip to pivot; several on one strip stack. A page tile has a list of its items. Swap exchanges rows and columns. No formula changes, only the layout.
  • Views. Save view stores the layout under a name; the Views list opens one. Views are the model's, shared with improv-gui, the TUI and improv save-view.
  • Charts. Chart shows the measure as grouped bars in its current layout, in the theme's accent and palette colors.

The same measure as a chart

  • Copy and paste. Ctrl+C copies the range as tab-separated values and, where the clipboard takes several formats (Wayland), as an HTML table with its headers too, so spreadsheets and editors paste it as a table. Ctrl+V pastes a range from either at the cursor, as one change.
  • Open, Save As and Print. Through the desktop's file chooser and print dialog (the XDG portals); on Windows, the native file dialogs, and Print opens the PDF in the default viewer. A model file dropped on the window opens. Every change is saved as it is made, as in the other front ends.
  • Undo. Ctrl+Z undoes a cell edit, a paste, a formula or a saved view; Ctrl+Shift+Z or Ctrl+Y redoes.

The model loads, recalculates and saves on a thread of its own: the window keeps drawing while a large model opens or a formula rebuilds the engine.

Platforms

PlatformStatus
Linux (Wayland, X11)Builds and runs.
FreeBSDBuilds and runs (X11).
illumos (Solnix)Builds with Solnix's own COSMIC fixups (crates/gui_cosmic/ci/solnix-build.sh); runs in a Solnix COSMIC session with ICED_BACKEND=tiny-skia.
Windows 11 (x64, arm64)Builds and starts. Known limitation: no accessibility on Windows yet. Release blockers for a Windows release, waiting on libcosmic: copying ranges as more than plain text, and drag and drop with other applications.

Not yet

What improv-gui has and improv-cosmic does not, yet: several matrices on one canvas, filters, the CSV import wizard, number formats, scenarios, named LAMBDAs, adding and deleting categories, items and measures, the function browser, and live refresh of a Postgres model another writer changes. The grid is drawn on a canvas, so a screen reader sees the header bar and the formula list but not the cells yet.

See also

improv-cosmic(1), and the design note docs/reviews/2026-11-02-cosmic-gui.md (the stack, the pins, the platform matrix and the plan).

The Web GUI

The web GUI is the desktop GUI's NeXT worksheet in a browser. egui draws it into a WebGL canvas, from the desktop's own theme, window, menu and formula-highlighting code. The model, the engine and the store stay in improv-server: the browser draws what the server sends and sends back what you type, and it computes nothing. A derived cell is always the server's answer, which is what lets the server hide what a user may not see (see Access).

Serve it

Build it once (it needs the wasm32-unknown-unknown Rust target and wasm-bindgen-cli at the version in Cargo.lock; build.sh says which when it is missing), then serve it beside the API:

rustup target add wasm32-unknown-unknown
cargo install wasm-bindgen-cli --version 0.2.127 --locked
crates/gui_web/build.sh --release web        # index.html, the .js and the .wasm, in ./web
IMPROV_API_TOKEN_FILE=/etc/improv/tokens improv-server sales.db 127.0.0.1:3000 --static ./web

Open http://127.0.0.1:3000/. The page and the API share one origin, so no CORS is needed. For anything past your own machine, put TLS in front (a proxy, as The HTTP Server shows): the token travels on every request.

Log in

A server with tokens asks for one. Type it in the login panel. The page holds it in memory only, never in the URL, a cookie or the browser's storage, and sends it as Authorization: Bearer. Nothing rides on a cookie, so another site cannot make your browser act for you (CSRF). A reload asks for the token again. A read-only token (IMPROV_API_TOKENS_RO) shows the model and refuses edits. A server in open mode (no tokens, loopback only) logs in at once.

What it does

  • Worksheets. Each measure in its own window, NeXT-style: the title bar, close box and resize bar. The first view, or else the first three measures, open at start. Windows move and resize as on the desktop.
  • Pivoting. Each worksheet has Pages, Columns and Rows gutters, with a tile for each category. Drag a tile to another gutter to pivot, or right-click it for Move to…. Several categories may stack on one axis. A page category's tile has a list to pick the page item from, and every item of a page category can be picked.
  • Cells. Double-click an input cell to edit it, then Enter writes it (Esc cancels). A value is read by the measure's type: numbers as the desktop reads them ($1,500), text, true/false, dates (2025-01-31). An empty cell clears it. A refused edit says why, and the cell shows the server's value again.
  • Formulas. The key window (the one with the black title bar) has the formula pane: every formula, as typed. Click one to edit it, then Enter saves. The Name = formula line adds a formula (or a LAMBDA). Both editors autocomplete measures, categories and functions (Up and Down pick, Tab accepts, Esc closes). A formula the server refuses is underlined where it went wrong, with the message and a hint, as on the desktop.
  • Menus. The NeXT main menu. Edit has Undo and Redo (Ctrl+Z, Ctrl+Shift+Z). Format has decimals and thousands separators. Worksheet has Pivot, Add Matrix (another window on the same measure), Remove Matrix, Save View, Add Category, Add Item, Add Input Measure, Rename and Delete. View opens a saved view. Help ▸ User Guide opens this guide. The Model Browser (View ▸ Model Browser) lists measures, categories and items, to open, rename, add and delete them.
  • Undo is per window session: each page load is a session, and its Undo undoes its own changes, not another user's.
  • Live updates. The page reads the server's change stream (GET /v1/changes). An edit in another browser, the CLI or the desktop GUI shows within a fraction of a second (about 0.1 s measured on one machine), with the cells it recalculated. The status bar says live while the stream is up. When the connection drops, the page retries with backoff and resumes from the last version it saw, so nothing is missed. A structural change (a new category, a renamed measure) makes it re-read the model.

What it does not do yet

The CSV wizard, the chart, the Info panel, function help (F1), scenarios, item filters, keyboard navigation of the grid, and range selection with Copy and Paste are desktop-only. A model with more than about 200,000 cells on one page needs paging the grid does not do yet.

Access

Every request goes through the server's token check, then through one policy hook in improv_service for each measure, item and cell it touches. With Cedar policies on the model (the security design, docs/reviews/2026-11-02-cedar-policies.md), a hidden measure, item or cell is absent from what the page receives. Totals stay computed over everything, by the server.

Accessibility

Not screen-reader accessible. eframe's web runner does not pass egui's AccessKit tree to the browser (as of eframe 0.37), so a screen reader sees one canvas. The desktop GUI is accessible (AccessKit, H2). Building a hidden DOM table that mirrors the visible grid for screen readers is on the plan (road-to-1.0 I2). Until then, use the desktop GUI or the TUI with a screen reader.

Testing it

scripts/web-e2e.sh runs it all: it builds the web GUI, improv and improv-server, runs the end-to-end check below, and compares the first frame with the golden, docs/reviews/golden/web-1280x713.png (--update replaces it). crates/gui_web/e2e/e2e.sh builds a model with the CLI, serves it and a web build with improv-server, and drives two browser sessions in headless Chromium over the DevTools protocol (drive.py). It edits a cell in one and checks the other shows it, recalculated, within a second. It restarts the server mid-session and checks the other session catches up, then pivots by dragging a tile and types a misspelled formula to check where the error lands. The app publishes its visible cells, tiles and formula error on <body data-…>, which is how a test reads a canvas.

Improv in Postgres (pg_improv)

pg_improv brings Improv's models to data that already lives in Postgres. Your tables stay the source of truth for the data; the structure — the categories, measures and formulas — is an Improv model stored in the improv schema; the results of every derived measure land in ordinary tables (improv_<model>.<measure>) that any SQL client can read, index, GRANT or replicate. The same model opens in the desktop GUI.

Five-minute tour

# postgresql.conf (then restart)
shared_preload_libraries = 'pg_improv'
wal_level = logical
improv.database = 'sales'
CREATE EXTENSION pg_improv;
CREATE TABLE sales (quarter text, product text, price float8, qty float8,
                    PRIMARY KEY (quarter, product));
INSERT INTO sales VALUES ('Q1','Widget',10,100), ('Q1','Gadget',20,30),
                         ('Q2','Widget',10,200), ('Q2','Gadget',20,60);

SELECT improv.create_model('plan');
SELECT improv.bind_category('plan', 'Time',    'sales', 'quarter');
SELECT improv.bind_category('plan', 'Product', 'sales', 'product');
SELECT improv.bind_measure ('plan', 'Price',    'sales', 'price');
SELECT improv.bind_measure ('plan', 'Quantity', 'sales', 'qty');
SELECT improv.define('plan', 'Revenue = Price * Quantity');
SELECT improv.define('plan', 'Total = SUM(Revenue OVER Time)');

SELECT * FROM improv_plan.revenue;     -- kept current from here on
improv-gui "postgres://me@localhost/sales?model=plan"

A migration can re-run improv.define('plan', 'Revenue = …', replace => true): the same formula changes nothing (no version bump, no row written), and a new one recomputes the measure and its dependents in the same transaction, writing only the rows whose value changed. It is an ERROR, naming the dependent, when the new formula would change the type a dependent reads. improv.drop_measure('plan', 'Total') drops a measure and its result table (an input's binding), and refuses while another measure references it.

A named LAMBDA is defined the same way and called by any formula of the model:

SELECT improv.define('merit', 'LOGNORM = LAMBDA(x, c, LN1P(x) / LN1P(MAX(x OVER c)))');
SELECT improv.define('merit', 'An = LOGNORM(Authored, Person)');

c is a category parameter: the call passes a category. The lambda lives in improv.lambda. Redefining it with replace => true recomputes every measure that calls it, as redefining a measure does; improv.drop_measure('merit', 'LOGNORM') drops it once nothing calls it. The GUI shares the table, so a lambda defined in either place is called from the other.

The GUI shows the model as worksheet windows. Editing a formula there redefines it in Postgres; editing an input cell updates the bound row of sales; everyone's SQL view of improv_plan.revenue follows.

Ways to keep results current

Transactions. In trigger and commit modes, and with improv.recalc(), the results change inside the writer's transaction: other sessions see them only once it commits, and ROLLBACK, an error or ROLLBACK TO SAVEPOINT undo them with the change. trigger recomputes after every write statement, so the writer reads its own new results. commit recomputes once, just before COMMIT, so a read earlier in the transaction sees the old results (call improv.recalc('plan') there to read your writes). In logical mode the results follow the commit in the worker's own transaction, and an aborted write never reaches them at all, because logical decoding carries committed transactions only. A batch's results and the model's recorded position commit together, so a crash neither loses nor doubles a change. The worker reads one replication slot per database (improv_db), however many models there are, and routes each change to the models bound to its table.

logical (default)triggercommitimprov.recalc()
Results updateafter the commit, by a background workerinside the writer's statementinside the writer's transaction, just before COMMITwhen you call it
Consistencyeventual (lags the commit by one poll plus the change's own work)transactional, read-your-writestransactional; reads before COMMIT see the old resultstransactional, in your snapshot
Writer paysnothing (the worker applies only the changed cells)the recompute, on every write statementone recompute per transaction, of the written tables' dependentsthe recompute, when you choose
On your tablesmembership of the publication improv_db (and REPLICA IDENTITY FULL if no PK)four statement triggers eachnothing (four statement triggers each with improv.commit_capture = 'rows')nothing
Needswal_level = logical, preload, a PK or REPLICA IDENTITY FULL (set for you)nothingpreloadnothing

Switch with SELECT improv.set_sync_mode('plan', 'commit') (or 'logical', 'trigger', 'manual'). Entering trigger or commit mode recomputes once. commit mode needs pg_improv in shared_preload_libraries (or session_preload_libraries), because the hooks that notice a write must be in every backend; set_sync_mode refuses it otherwise. A recompute that fails at COMMIT rolls the transaction back with an error naming the model. improv.recalc('plan') works in every mode, and improv.recalc('plan', ARRAY['Price']) recomputes only what depends on Price. improv.what_if('plan', '[{"measure":"Price","coord":{"Time":"Q1","Product":"Widget"},"value":12}]') returns the derived cells that would change, writing nothing. Its value column is jsonb: a number, true/false, a string, or a date as an RFC 3339 string, and an edit's "value" takes the same forms. improv.status('plan') shows the mode and, in logical mode, the slot's lag and how the worker applied its batches: incremental_applies counts the batches it fed to the live engine, rebuilds its full reloads. On an append-only fact table rebuilds stays put while incremental_applies grows.

Several rows per coordinate

A fact table often has many rows per coordinate (one per order, say). Bind the measure with an aggregate and each coordinate's rows are folded into one input cell: improv.bind_measure('plan', 'Amount', 'orders', 'amount', agg => 'sum') (also avg, min, max, count, and count_distinct, SQL's count(DISTINCT value_col); over a bool column, min and max are SQL's bool_and and bool_or). Without agg, two rows on one coordinate are an error. An aggregated measure is read-only from the GUI: a save that edits one of its cells fails, so change the rows in SQL.

In logical mode the sync worker folds each change into the cell, and the result is the aggregate a fresh improv.recalc computes, with these cases:

  • Text min and max order by the column's collation: C and POSIX by bytes, any other deterministic collation (libc, ICU, builtin) by Postgres's own compare.
  • Nondeterministic collations (CREATE COLLATION … deterministic = false) can find texts with different bytes equal. Only Postgres can tell, so a text min, max or count_distinct over such a column reloads the model on every change (rebuilds grows, the log says nondeterministic collation). The result is still exact.
  • Sums of float4 and float8 columns are the values' exact sum rounded once. Postgres adds the floats in scan order, so a fresh sum can differ in the last bits, as two scans of the same table can in Postgres itself. The fold's total does not depend on the order of the changes: inserting and deleting the same rows gives the same bits.
  • numeric values with more than 9 decimals, or written with an exponent, are read as float8 and summed exactly as floats. Integer columns, and numeric values with up to 9 decimals, sum exactly, as Postgres does.

Value types

A measure's type comes from its column: numbers (int*, float*, numeric), bool, text (text, varchar, char) and dates (date, timestamp, timestamptz, kept to the millisecond in UTC). A derived measure has the type of its formula, so improv.define('plan', 'Pricey = Price > 15') makes improv_plan.pricey a boolean column. Result tables' value columns are double precision, boolean, text or timestamptz. Other column types are refused by bind_measure. A derived measure with no dimensions (MaxVol = MAX(Vol OVER Person) over a measure of Person alone) gets a one-row result table with just the value column; it has no row while the formula has no cell. Logical and trigger sync follow a table's row changes, so in those modes only tables bind; a view binds in manual mode (refresh with improv.recalc()).

Choosing: use logical for busy tables (writers stay fast; measured at 100k cells: 8 ms per UPDATE and its results visible ~50 ms later, vs ~1.1 s with a trigger). Use trigger when a writer must read derived results in its own transaction. Use commit when results must commit with the write but a transaction makes many writes (100 one-row updates in one transaction at 10k cells: 82 ms, against 6.6 s in trigger mode), or when you can't put triggers on the tables. Use recalc after bulk loads or inside migrations.

Commit mode's cost. By default commit mode knows which tables a transaction wrote, not which rows, so each COMMIT reloads and recomputes everything those tables feed: about 2.1 s at 2.5M rows, whatever the transaction wrote. With SET improv.commit_capture = 'rows' before improv.set_sync_mode('plan', 'commit'), entering the mode also puts four statement triggers on each bound table. They note the coordinates each statement touched, and COMMIT recomputes only those, once per table: a 1,000-row INSERT then commits in 145 ms, and ten one-row INSERT statements in one transaction in 112 ms (PG 18, 2.5M rows, no index; an index on the dimension columns helps as in trigger mode). The triggers cost the writer about 30% on a 1M-row INSERT (2.24 s → 2.97 s, the transition tables), and under 3 ms on a 1,000-row one. COMMIT falls back to the full recompute when it cannot trust the capture: a statement that wrote a bound table without firing it (ALTER TABLE … DISABLE TRIGGER, session_replication_role = replica, a table bound after the mode was entered), a TRUNCATE, a partitioned or inherited bound table, a formula that is not element-wise over the written measures (an aggregation OVER a category), or more than 100,000 touched coordinates. Re-run set_sync_mode after binding a new table.

Trigger mode's cost is one read of the touched coordinates' rows in each bound table, per statement, plus the engine's recompute of those coordinates. Without an index the read is a sequential scan, so it grows with the table: at 2.5M rows a one-row INSERT takes about 105 ms and a 1,000-row INSERT about 160 ms (PG 18, two aggregated bindings). An index on the bound dimension columns, in the model's category order (CREATE INDEX ON contribution_rows (person, year, release, scope)), makes the read an index lookup: 15 ms for a one-row INSERT, 50 ms for ten in one transaction, 79 ms for 1,000 rows. Integer, text, bool, numeric and uuid columns compare as themselves, so such an index serves them; float, date and timestamp columns compare as their text, and no plain index helps.

Functions written in Improv's language

LANGUAGE improv lets any role write a SQL function as an Improv formula:

CREATE FUNCTION bonus(sales float8, target float8) RETURNS float8
  LANGUAGE improv IMMUTABLE AS $$
    Ratio = sales / target
    MAX2(Ratio - 1, 0) * 1000
  $$;
SELECT rep, bonus(sales, target) FROM quota;

The SQL arguments are the inputs, by name; Name = expr lines define intermediate measures; the last line is the result. Lines may be the DSL or controlled English (price times qty). The semantics are the engine's: a NULL argument gives NULL wherever the result depends on it, and an error value (#DIV/0! from a division by zero, …) is NULL, or an ERROR with improv.raise_errors = on. Aggregations need categories, so SUM(x OVER Time) is rejected; put it in a model. A call costs about 0.14 µs for a one-line body and 0.24 µs for bonus above. See crates/pg_improv/README.md for the types and rules.

Upgrades and backups

pg_improv supports Postgres 15–18. To upgrade, install the new release, restart Postgres, then run ALTER EXTENSION pg_improv UPDATE. pg_dump keeps the models and their results. A restored database's worker makes a new replication slot and catches up with one recompute. Updating to 0.11.0 moves logical-mode models from one slot each (improv_<model>) to the shared improv_db: the update drops the old publications, the worker drops the old slots and catches each model up with one recompute.

Privileges

A model reads its bound tables and writes its results as its owner, the role that called create_model (improv.model.owner), in every sync mode and in recalc, whoever writes the tables. Row-level security and privileges therefore apply to a model as they do to its owner: its results aggregate only the rows the owner may read, and are as visible as their tables' grants. If the owner loses SELECT on a bound table, the next logical apply fails with a last_error naming the columns; nothing is read as a superuser. Only a role that may act as a model's owner (a superuser, or a member of the owner with SET) may change the model, or its owner: row-level security on the improv.* tables enforces it, by the API and by direct DML alike, so no one can make a model read, as a role that sees more than they do, what they cannot. Its names and formulas stay readable; its items (the bound tables' keys) and input cells are readable by the same roles only. what_if is theirs too: it computes as the owner, so its results reveal what the owner can read. Give it to an analyst with a SECURITY DEFINER wrapper the owner creates for one model, which grants what_if on that model and nothing else, or by GRANT alice TO analyst WITH INHERIT FALSE, SET TRUE, which also lets the analyst change alice's models.

A non-superuser builds models as a member of improv_user, which the extension creates: GRANT improv_user TO alice, plus SELECT (and, for trigger and commit mode, TRIGGER) on the tables alice binds. No CREATE on the database is needed. A role a model's access policies restrict needs improv_reader (the filtered functions and the model names) and the owner's grants on the result tables it queries. improv_admin grants and revokes improv_user and improv_reader and acts on no one else's model. Acting on a model means acting as its owner, so only a superuser acts on every model. improv.models lists every model with its owner, sync mode, result schema, and may_change for the caller. See the pg_improv README for the mechanism, the wrapper's text, and the full privilege matrix (superuser, improv_admin, owner, SET member, improv_user, improv_reader, writer, PUBLIC), which tests/privileges.sh checks cell by cell.

Access policies

Access policies in pg_improv: the owner sets policies and grants ann; as ann, the result table and improv.cells lack Falcon, a hidden item answers as a missing one, a Price edit is refused and a Quantity edit written; the owner sees why a cell is hidden, and the audit log.

A model's Cedar access policies (Access Policies) are stored and enforced by pg_improv, for every client. The owner, a role that may act as it and superusers are never restricted. Everyone else sees, through every read path, only what the policies allow: a result table's rows are filtered by row-level security, and improv.categories, items, measures and cells list only what the role may read. A hidden measure or item answers as one that does not exist. improv.set_cells, define and drop_measure let a role edit cells and define measures where the policies allow it, as the owner; every change is audited.

SELECT improv.set_policies('plan', $$
  permit (principal in Improv::Role::"staff", action in Improv::Action::"Read", resource);
$$);
SELECT * FROM improv.explain_access('plan', 'ReadCell',
  '{"measure": "Revenue", "at": {"Time": "Q1", "Product": "Widget"}}', 'ann');

The Cedar user is the current role; its roles are the roles whose privileges it has. A change to the policies, the groups or a role's memberships applies from another session's next statement. See the pg_improv README for every path, the audit log and what is not covered, which tests/policies.sh checks.

Durability

In logical mode the worker writes a model's share of a batch and records that model's position in one transaction, and confirms the shared slot once every model has applied the batch, so after a crash or pg_terminate_backend it re-reads and re-applies only what was not recorded; nothing is lost or counted twice, and rolled-back writes never appear. A model that fails records last_error and rebuilds from its tables on its next poll, so it never holds the other models' slot back. A slot retains WAL until confirmed, so set max_slot_wal_keep_size and watch improv.status(model).lag_bytes.

See crates/pg_improv/README.md for the full SQL API, limits (improv.max_cells), and the benchmark table.

A family's finances in Postgres (pg_improv)

This chapter walks through a complete example: one family's books for January to June 2026, kept in ordinary Postgres tables, with four Improv models on top that reconcile the bank statements, track the budget, add up net worth, and project the savings goals. The files are in crates/pg_improv/examples/family-finance/ and crates/pg_improv/tests/finance.sh runs them end to end and checks the numbers below. The example's schema needs Postgres 17 or later (its ledger uses MERGE … WHEN NOT MATCHED BY SOURCE); pg_improv itself runs on 15 and 16 too.

crates/pg_improv/tests/finance.sh       # scratch cluster on port 55460, ~10 s
KEEP=1 crates/pg_improv/tests/finance.sh  # leave it running to explore
psql -h ~/pgi-finance -p 55460 -U improv family

Or, in a database of your own (with pg_improv preloaded, see Improv in Postgres):

psql -d family -f schema.sql -f data.sql -f model.sql -f queries.sql

The family

Dana (software engineer, W-2) and Sam (teacher, W-2, plus a design consulting business paid on 1099s) and their kids Maya (10) and Leo (6). They have:

  • Bank accounts: joint checking, a joint savings account that holds three sinking funds, a tax-reserve savings account for the consulting income, and a high-yield savings rainy-day fund.
  • Foreign currency: a euro checking account in Germany, plus euro and yen cash, converted to dollars at month-end rates.
  • Two credit cards, paid in full by autopay.
  • Retirement: Dana's 401(k) with an employer match, Dana's rollover traditional IRA, Sam's Roth IRA, and a family health savings account.
  • College: a 529 plan for each child.
  • Investing: a joint brokerage account and a crypto wallet (BTC, ETH), held as units and valued at each month's price.
  • Property and debt: a house with a mortgage (interest, principal and escrow), a financed SUV with a car loan, and a paid-off sedan.

The schema at a glance

schema.sql creates schema finance. The tables fall into five groups:

GroupTablesNotes
Referencecurrency, household, person, period, fx_rate, institution, account, envelopeaccount.account_type is one of checking, savings, credit, loan, mortgage, retirement, 529, health_savings, brokerage, crypto, fx_cash, asset. account.tracking says how its value is known: ledger, holdings or valuation.
Ledgertxn, ledger_month, statementtxn is what the family recorded: date, account, amount, currency, payee, envelope, transfer_id pairing the two legs of a transfer, and status (cleared or pending). statement is what each bank reports.
Income and taxesincome_source, invoice, income, tax_setasideW-2 paystubs with withholdings and pre-tax deferrals; consulting invoices and the payments for them, with nothing withheld.
Investments, property, debtsecurity, price, holding, valuation, loan, loan_scheduleUnits × price for investment accounts; a market estimate or depreciation for the house and cars; the amortization schedule for the two loans.
Planbudget, plan_settings, savings_goal, goal_account, goal_horizon, goal_expense_windowMonthly budgets per envelope; goals with targets, contributions and return assumptions; precomputed compounding factors.

Money is numeric(14,2) in the account's own currency. Signs follow the household: a deposit is positive, a charge negative, so a credit card, loan or mortgage has a negative balance (money owed). Banks report those as a positive "balance owed", and account.balance_sign = -1 says how to compare the two. Every table has a primary key, foreign keys and CHECKs (for example income.net_deposit must equal gross minus every withholding and deferral), and every table has a COMMENT.

There are 17 budget envelopes: housing, utilities, groceries, transport, childcare, kids' activities, healthcare, insurance, subscriptions, dining, travel and fun, gifts, giving, debt payments, estimated taxes, savings, and bank fees. Each is essential, discretionary, savings, tax or fees.

What Improv does, and what SQL does

Improv's formulas compute over categories: SUM(Actual OVER Month) and Price * Units. When this example was written they had no IF, no POWER, no "previous month", and a result had to keep at least one dimension, so it handles those in SQL. Improv now has all three (IF, ^ / POWER, PREV and running windows such as SUM(x OVER Month[FIRST..THIS]); see The Formula Language); the example still shows the SQL route, which works on every Improv version. A formula over a missing cell still has no cell unless it says otherwise with COALESCE or FILL (IFERROR covers errors, not missing cells):

NeedWhereHow
Running balance per accountSQL: ledger_monthA table refreshed by statement-level triggers on txn and fx_rate (a MERGE of the running sum). Improv cannot refer to the previous period, and pg_improv cannot sync from a view (see below).
Compound growth (1 + r/12)^n and annuity factorsSQL: goal_horizonFilled by refresh_goal_horizon() with power(). Improv has no POWER.
"Is this envelope essential?", "is this money owed?"Columns0/1 numbers (envelope.is_essential, account.balance_sign) multiplied into formulas. Improv has no IF, and a boolean cannot be multiplied.
A household-wide totalImprov, kept per Month or per GoalUnreconciledCount[Month], NetWorth[Month]. There are no dimensionless results.
Loan amortizationSQL: loan_scheduleA recursive query, run once when the data is loaded.
Everything elseImprovDifferences, flags, variances, year to date, savings rate, the employer match, net worth, projections, shortfalls, what-ifs.

All four models bind tables, not views. pg_improv can bind a view only in manual mode: logical mode needs REPLICA IDENTITY and trigger mode needs transition tables, and Postgres gives a view neither. So the running balances are a trigger-maintained table, and that is also what lets the logical sync below see a new transaction.

Model 1: reconciliation (recon)

Question: does each account's ledger match the bank statement, month by month?

Inputs, per (Month, Account): LedgerBalance and ClearedBalance (the running sums from ledger_month), FxRate, TransfersHome (that month's transfer legs in dollars), StatementBalance (from statement); per Account: BalanceSign.

BankBalance       = StatementBalance * BalanceSign      -- a card's "$439.02 owed" is -439.02
Difference        = BankBalance - ClearedBalance        -- the bank has not seen pending charges
Reconciled        = ABS(Difference) < 0.005
Pending           = LedgerBalance - ClearedBalance
DifferenceHome    = Difference * FxRate                 -- euros in dollars
Unreconciled      = MIN2(FLOOR(ABS(Difference) * 200), 1)   -- 1 if off by >= half a cent
UnreconciledCount = SUM(Unreconciled OVER Account)      -- per Month
AbsDifferenceHome = ABS(DifferenceHome)
OffByHome         = SUM(AbsDifferenceHome OVER Account)
TransfersNet      = SUM(TransfersHome OVER Account)     -- both legs present: 0
TransfersBalanced = ABS(TransfersNet) < 0.005

Unreconciled is the IF workaround: FLOOR(|d| × 200) is at least 1 exactly when |d| ≥ 0.005, and MIN2(…, 1) caps it, so it is a 0/1 count.

data.sql plants five problems in June. The model finds four of them and lists the fifth as pending:

== 1. Which accounts do not reconcile in June, and by how much?
   account   | bank_says | ledger_cleared | difference | difference_usd | pending
-------------+-----------+----------------+------------+----------------+---------
 amex        |   -439.02 |       -1963.14 |    1524.12 |        1524.12 | -412.00
 visa        |  -1668.40 |       -1754.80 |      86.40 |          86.40 |    0.00
 checking    |  21402.97 |       21427.97 |     -25.00 |         -25.00 |    0.00
 eur_account |   9183.10 |        9170.60 |      12.50 |          13.50 |    0.00

== 2. Reconciliation summary by month (accounts off, total off in USD, transfers in balance?)
  month  | accounts_off | off_by_usd | transfers_net | transfers_balanced
---------+--------------+------------+---------------+--------------------
 2026-05 |            0 |       0.00 |          0.00 | t
 2026-06 |            4 |    1649.02 |      -1524.12 | f

Reading it:

  • Amex, +1524.12: a missing transaction. The June autopay was entered on the checking side only. The card's leg is missing, so the ledger still owes the May balance (1524.12), and June's transfers do not net to zero (TransfersNet = -1524.12).
  • Visa, +86.40: a duplicate. The June 20 Corner Market charge was entered twice.
  • Checking, -25.00: a fee nobody entered. The bank charged an outgoing wire fee.
  • Euro account, +12.50 EUR ($13.50): an FX difference. The family entered EUR 1,000 for the June wire; the bank's conversion credited EUR 1,012.50.
  • Amex pending -412.00: a hotel hold that has not posted. It is in the ledger as pending, the bank does not show it yet, and Difference compares cleared balances, so it is not counted as a problem.

Reconciling a statement

Enter the bank's closing balance (positive for money owed), then look at improv_recon.difference for that month. Fix the ledger and the results update on their own. tests/finance.sh commits these four fixes:

BEGIN;
INSERT INTO finance.txn (txn_date, account_id, amount, payee, transfer_id)   -- the missing leg
VALUES ('2026-06-25', 'amex', 1524.12, 'Autopay, thank you', 'pay-amex-2026-06');
DELETE FROM finance.txn WHERE memo = 'entered twice';                         -- the duplicate
INSERT INTO finance.txn (txn_date, account_id, amount, payee, memo)           -- the FX difference
VALUES ('2026-06-05', 'eur_account', 12.50, 'Sparkasse Rhein', 'FX difference on the June wire');
INSERT INTO finance.txn (txn_date, account_id, amount, payee, envelope_id)    -- the fee
VALUES ('2026-06-05', 'checking', -25.00, 'Harbor CU: outgoing wire fee', 'bank_fees');
COMMIT;

Nothing calls improv.recalc. The txn triggers refresh ledger_month in the same transaction. The pg_improv worker decodes the commit and applies the changed rows. Within about 0.2 s every June Difference is 0, UnreconciledCount is 0 and TransfersBalanced is true. The budget and net-worth models follow too: groceries lose the duplicate, bank fees gain the wire fee, and net worth rises by $1,599.02. The pending hotel hold is still pending.

Model 2: cash flow and budget (budget)

Question: where did the money go, against the plan?

Outflow[Month, Envelope] is the ledger itself, bound with agg => 'sum': every txn row with an envelope is summed into its (month, envelope) cell. Rows with no envelope (income, opening balances, the receiving leg of a transfer) have a NULL dimension and are skipped. Budget comes from the budget table, IsSpending (0 for the savings envelope) from envelope, and income from the income paystubs (again agg => 'sum', per (Month, Source)).

Actual        = NEG(Outflow)                  -- spending is negative in the ledger
Variance      = Actual - Budget               -- > 0: overspent
OverBudget    = Actual > Budget               -- a boolean result
YtdActual     = SUM(Actual OVER Month)        -- per Envelope, January to date
YtdBudget     = SUM(Budget OVER Month)
YtdVariance   = YtdActual - YtdBudget
Spending      = SUM(SpendingPart OVER Envelope)   -- SpendingPart = Actual * IsSpending
SavedFromChecking = SUM(SavedPart OVER Envelope)  -- SavedPart = Actual * (1 - IsSpending)
EmployerMatch = MIN2(K401, Gross * MatchCap) * MatchRate
PayrollSaved  = SUM(PayrollSavedPart OVER Source) -- 401(k) + health savings deferrals + match
SavingsRate   = (SavedFromChecking + PayrollSaved) / TotalGross
Unallocated   = TotalNetPay - Spending - SavedFromChecking
SetAsideDue   = Gross * SetAsideRate              -- 30% of consulting income
SetAsideGap   = SetAsideDue - SetAside

The employer match is a formula on pay: 50% of the 401(k) deferral, counting deferrals only up to 6% of gross. Dana defers 10% of $6,500 a paycheck, so the match counts $780 of the $1,300 and adds $390 a month.

== 4. Where are we over budget in June?
 envelope  | budget  | actual  | over_by
-----------+---------+---------+---------
 fun       |  150.00 |  460.00 |  310.00
 childcare | 1200.00 | 1420.00 |  220.00
 groceries |  850.00 | 1050.11 |  200.11
 dining    |  250.00 |  309.05 |   59.05
 gifts     |   50.00 |   89.00 |   39.00
 utilities |  480.00 |  503.69 |   23.69

== 6. Income, saving and the savings rate, by month
  month  |  gross   | net_pay  | spending | saved_from_checking | saved_by_payroll | savings_rate_pct | left_over
---------+----------+----------+----------+---------------------+------------------+------------------+-----------
 2026-05 | 22600.00 | 16152.40 |  7907.48 |             4000.00 |          1990.00 |             26.5 |   4244.92
 2026-06 | 20400.00 | 13952.40 |  9455.65 |             4000.00 |          1990.00 |             29.4 |    496.75

== 8. Is enough of the consulting income in the tax reserve?
  month  |   source   |   due   |  moved  | short_by
---------+------------+---------+---------+----------
 2026-05 | sam_design | 1260.00 | 1000.00 |   260.00

June fun is over because of the $412 hotel hold. Groceries include the duplicate charge until it is fixed. Year to date (query 5), fun is $1,440 over, mostly next summer's flights.

Setting budgets

A budget is one row per (month, envelope) in finance.budget. To change one, update the row and the variances follow:

UPDATE finance.budget SET amount = 300 WHERE month = '2026-06' AND envelope_id = 'dining';

A new envelope needs an envelope row and its budget rows. Spending lands in it as soon as txn rows carry its id.

Model 3: net worth (networth)

Question: what do we own minus what do we owe, each month, in dollars?

Each account has exactly one of a ledger balance, holdings or a valuation. A formula over a missing cell has no cell, so the model totals each kind separately and adds the totals:

LedgerValue   = Balance * Fx                         -- euros and yen at the month-end rate
PositionValue = Units * Price                        -- per (Month, Account, Security)
HoldingsValue = SUM(PositionValue OVER Security)     -- 401(k), IRAs, health savings, 529s, brokerage, crypto
OwnedPart     = LedgerValue * (1 + Sign) / 2         -- Sign is 1 (owned) or -1 (owed)
OwedPart      = NEG(LedgerValue) * (1 - Sign) / 2
Cash          = SUM(OwnedPart OVER Account)
Investments   = SUM(HoldingsValue OVER Account)
Property      = SUM(Valuation OVER Account)          -- house and cars
Liabilities   = SUM(OwedPart OVER Account)           -- cards, car loan, mortgage
Assets        = Cash + Investments + Property
NetWorth      = Assets - Liabilities
DebtToAssets  = Liabilities / Assets

Crypto is just another holding: BTC and ETH units times their month-end price. The mortgage balance falls by each payment's principal (a transfer from checking). Interest and escrow are spending in the housing envelope.

== 9. Net worth trend (USD)
  month  | cash  | investments | property | liabilities | net_worth | change | debt_to_assets_pct
---------+-------+-------------+----------+-------------+-----------+--------+--------------------
 2026-01 | 50765 |      403326 |   586800 |      337733 |    703158 |        |               32.4
 2026-02 | 52969 |      412645 |   587800 |      336384 |    717030 |  13871 |               31.9
 2026-03 | 59195 |      409315 |   588800 |      335185 |    722124 |   5094 |               31.7
 2026-04 | 61837 |      427766 |   591300 |      333925 |    746978 |  24854 |               30.9
 2026-05 | 68524 |      443452 |   593300 |      334084 |    771191 |  24213 |               30.2
 2026-06 | 69278 |      455097 |   594300 |      333594 |    785081 |  13890 |               29.8

(The change column is SQL's lag() over the result table. Improv has no previous-period reference, but a result table is an ordinary table.)

Model 4: planning (plan)

Question: at today's pace, will each goal be met, and if not, how much more a month would it take?

There are seven goals in savings_goal, each with a target date on a June 30:

GoalFunded byTarget
Retirement (Dana at 62, 2048)401(k), traditional IRA, Roth IRA$2,500,000
College for Maya (2034) and Leo (2037)each child's 529$120,000 each
Rainy day (2027)high-yield savings6 months of essential expenses
Summer 2027 trip50% of joint savings$9,500
Replace the sedan (2030)30% of joint savings$24,000
New roof (2028)20% of joint savings$8,000

current_balance is the goal's share of its accounts on June 30. model.sql reads it back from the net-worth model's result tables with an ordinary UPDATE … FROM improv_networth.holdingsvalue.

goal_horizon holds, for each goal and each plan anniversary up to its target date, Growth = (1 + r/12)^n and Annuity = ((1 + r/12)^n − 1) / (r/12) (monthly compounding, end-of-month contributions), and IsTargetYear (1 on the target date). SQL computes these; today (1 + Rate/12)^N in a formula does it too.

EssentialPart     = Budget * IsEssential
EssentialBudget   = SUM(EssentialPart OVER Envelope)       -- per Month
WeightedEssential = EssentialBudget * Weight               -- Weight = 1/6 per month
MonthlyEssentials = SUM(WeightedEssential OVER Month)      -- the average, per Goal
Target            = TargetAmount + MonthsOfCover * MonthlyEssentials

Payroll           = DeferralRate * Salary / 12             -- 401(k) deferrals
EmployerMatch     = MIN2(DeferralRate, MatchCap) * MatchRate * Salary / 12
MonthlySaving     = Contribution + Payroll + EmployerMatch

Projected         = Current * Growth + MonthlySaving * Annuity   -- per (Goal, Year)
ProjectedAtTarget = SUM(TargetPart OVER Year)              -- TargetPart = Projected * IsTargetYear
AnnuityAtTarget   = SUM(AnnuityPart OVER Year)
Shortfall         = MAX2(Target - ProjectedAtTarget, 0)
OnTrack           = ProjectedAtTarget >= Target
ExtraMonthly      = Shortfall / AnnuityAtTarget            -- the saving that closes the gap
RequiredMonthly   = MonthlySaving + ExtraMonthly
Progress          = Projected / Target

The rainy-day target is a formula over the budget: six times the average monthly essential budget (housing, utilities, groceries, transport, childcare, healthcare, insurance and the car payment), $5,503.30, so $33,019.80. Raise childcare's budget and the target moves. IsTargetYear picks the target year's projection out of the series without an IF. MAX2(…, 0) floors the shortfall.

== 11. Are we on track for each goal?
      goal       | target_date | today  | monthly | target  | projected | on_track | shortfall
-----------------+-------------+--------+---------+---------+-----------+----------+-----------
 rainy_day       | 2027-06-30  |  24839 |  500.00 |   33020 |     31962 | f        |      1057
 vacation        | 2027-06-30  |   5706 |  250.00 |    9500 |      8706 | f        |       794
 house_projects  | 2028-06-30  |   2282 |   50.00 |    8000 |      3482 | f        |      4518
 car_replacement | 2030-06-30  |   3424 |  100.00 |   24000 |      8224 | f        |     15776
 college_maya    | 2034-06-30  |  35980 |  250.00 |  120000 |     83066 | f        |     36934
 college_leo     | 2037-06-30  |  18766 |  250.00 |  120000 |     76365 | f        |     43635
 retirement      | 2048-06-30  | 306515 | 2190.00 | 2500000 |   2339882 | f        |    160118

== 12. How much more to save each month to close each shortfall?
      goal       | saving_now | add_monthly | required_monthly
-----------------+------------+-------------+------------------
 car_replacement |     100.00 |      328.68 |           428.68
 college_maya    |     250.00 |      313.69 |           563.69
 retirement      |    2190.00 |      293.14 |          2483.14
 college_leo     |     250.00 |      248.63 |           498.63
 house_projects  |      50.00 |      188.23 |           238.23
 rainy_day       |     500.00 |       86.51 |           586.51
 vacation        |     250.00 |       66.17 |           316.17

Reading the planning tables

  • improv_plan.projected (Goal, Year): the balance at each anniversary. Query 13 lists Maya's 529 year by year, reaching 69% of its target by 2034.
  • improv_plan.shortfall and improv_plan.ontrack (Goal): the gap at the target date.
  • improv_plan.extramonthly (Goal): how much more to save each month, starting now, to close it. The sedan fund needs the most: $328.68 more a month.

The vacation line checks by hand: $5,705.98 today + 12 × $250 = $8,705.98, $794.02 short, closed by $794.02 / 12 = $66.17 more a month.

Changing goals

Goals are rows. Change a target, contribution or return in savings_goal and the projections follow. Changing a return or a target date changes the growth factors, so run SELECT finance.refresh_goal_horizon() afterwards.

What-if

improv.what_if evaluates the model with some inputs changed, in memory, and returns only the derived cells that would differ. It writes nothing.

SELECT measure, coord ->> 'Goal' AS goal, value
  FROM improv.what_if('plan',
       '[{"measure": "DeferralRate", "coord": {"Goal": "retirement"}, "value": 0.15}]')
 WHERE measure IN ('Payroll', 'EmployerMatch', 'MonthlySaving',
                   'ProjectedAtTarget', 'Shortfall', 'ExtraMonthly', 'OnTrack');
== 14. What if Dana raises the 401(k) deferral from 10% to 15%? (writes nothing)
      measure      |    goal    |  would_be
-------------------+------------+------------
 ExtraMonthly      | retirement | 0.00
 MonthlySaving     | retirement | 2840.00
 OnTrack           | retirement | true
 Payroll           | retirement | 1950.00
 ProjectedAtTarget | retirement | 2694928.57
 Shortfall         | retirement | 0.00

EmployerMatch is missing from the answer because it does not change: the match stops at 6% of pay. The extra $650 a month closes the whole $160,118 retirement gap.

Cutting dining out by $100 a month and putting it toward the trip is a change to the vacation goal's contribution (the plan model does not see dining):

== 15. What if we cut dining out by $100 a month and save it for the trip?
      measure      |   goal   | would_be
-------------------+----------+----------
 ExtraMonthly      | vacation | 0.00
 MonthlySaving     | vacation | 350.00
 OnTrack           | vacation | true
 ProjectedAtTarget | vacation | 9905.98
 Shortfall         | vacation | 0.00

what_if returns jsonb values, so OnTrack comes back as true, not a number. Cast with care (value::numeric fails on a boolean).

Keeping it current

model.sql builds each model in manual mode and runs improv.recalc once, so the results are complete when the script returns. Its last statement switches every model to logical. From then on the background worker keeps them current from committed changes to the bound tables. The test measures 0.1 to 0.2 s from commit to visible result.

Things to know

  • Results are double precision. A difference of 1524.12 may read 1524.1200000000001. Round for display (round(value::numeric, 2)), and compare with a tolerance, as Reconciled does.
  • Only derived measures get result tables. Read an input (a bound column such as Budget) from its own table.
  • Fill zeros, don't leave cells out. savings_goal has every column for every goal (0 where it does not apply), because Contribution + Payroll has no cell for a goal with no Payroll.

Files

FileWhat
schema.sqlSchema finance: tables, keys, checks, comments, the ledger_month and goal_horizon refreshers.
data.sqlSix months of books, deterministic, with the five planted problems.
model.sqlThe four models.
queries.sqlFifteen questions answered from the result tables, the last two of them what-ifs.
tests/finance.shRuns everything on a scratch cluster and checks 49 values, including the logical-sync fix-up.

Improv in DuckDB

The improv DuckDB extension brings Improv's formula language and its multidimensional models to DuckDB: evaluate any built-in function from SQL, look functions up, and run a model over a table or a query, getting back one row per computed cell.

Where pg_improv keeps a model in Postgres and keeps its results current as the data changes, the DuckDB extension is stateless. improv(source, model) reads the source, computes, and returns rows, the way an analytical query does. Nothing is stored and there is nothing to keep in sync.

The DuckDB v1.5.6 CLI with the extension loaded runs the tutorial's queries, the model a little shorter: improv_calc, the Parquet file, the model, a PIVOT over its result, and a query as the source.

Install

INSTALL improv FROM community;   -- once it is in the community registry
LOAD improv;

A local build (see crates/duckdb_improv/README.md) is unsigned:

duckdb -unsigned -c "LOAD 'crates/duckdb_improv/build/release/improv.duckdb_extension'; ..."

One binary loads into DuckDB v1.5.6 and later, v2.0 included.

Formulas: improv_calc

SELECT improv_calc('ROUND(PMT(rate/12, n, -pv), 2)',
                   json_object('rate', 0.06, 'n', 360, 'pv', 200000));
-- 1199.1

SELECT loan_id,
       improv_calc('ROUND(PMT(rate/12, years*12, -principal), 2)',
                   json_object('rate', rate, 'years', years, 'principal', principal)) AS payment
FROM loans;

improv_calc(formula [, inputs]) evaluates one formula in Improv's formula language: operators, IF and its family, LET, LAMBDA, and the scalar forms of the built-in functions (math, rounding, statistics, financial, text, dates, engineering). An aggregation over a category (SUM(x OVER Time)) needs a model; use improv(...) for that.

  • inputs is a JSON object: json_object('x', col, ...) or a literal like '{"x": 2}'. Each key is a name the formula can use. Its JSON type is the input's type: number, boolean or text (DuckDB's json_object writes a DATE as text). A JSON null is a missing input, and a result that depends on it is NULL: improv_calc('x + 1', '{"x": null}') is NULL, while IF(TRUE, 5, x) is still 5.
  • The result is a DOUBLE: a number; a boolean as 1 or 0; a date as its spreadsheet serial number (days since 1899-12-30). Text and error values (1/0 is #DIV/0!) are NULL.
  • A formula that does not parse or type-check, or inputs that are not a JSON object, fail the query with the reason: improv_calc: parse error at 2: unexpected end of input.
  • A leading = is allowed ('=ROUND(2.675, 2)').
  • Each formula is compiled once per shape of inputs (names and types) and cached, so running one formula over a million rows parses it once.

improv_calc_text(formula [, inputs]) is the same but returns VARCHAR: text results as they are, numbers to 15 significant digits, dates in RFC 3339, and errors as their codes.

SELECT improv_calc_text('1/0');                                     -- #DIV/0!
SELECT improv_calc_text('UPPER(name) & "!"', json_object('name', 'ada'));  -- ADA!
SELECT improv_calc_text('TEXT(EDATE(DATE(2024, 1, 31), 1), "yyyy-mm-dd")'); -- 2024-02-29

Function help: improv_functions

SELECT name, signature, description FROM improv_functions() WHERE category = 'financial';
SELECT name, signature FROM improv_functions(query := 'payment');

One row per built-in function (681): name, category (math, financial, text, datetime, …), signature (PMT(rate, nper, pv, [fv=0], [type=0])), returns (number | boolean | text | date | any), description and aliases (other spellings, or NULL). With query :=, only the functions whose name or description matches, best match first.

Models: improv(source, model)

CREATE TABLE sales(year INTEGER, product VARCHAR, price DECIMAL(10,2), qty INTEGER);
INSERT INTO sales VALUES
  (2024, 'WidgetA', 10, 100), (2024, 'WidgetB', 20, 50),
  (2025, 'WidgetA', 11, 70), (2025, 'WidgetA', 11, 50), (2025, 'WidgetB', 20, 40);

SELECT * FROM improv('sales', '
  category Time = year
  category Product = product
  input Price = price max
  input Quantity = qty sum
  Revenue = Price * Quantity
  Share = Revenue / SUM(Revenue OVER Product)
  Growth = Revenue - PREV(Revenue, Time, 1, 0)
');
measureTimeProductvaluevalue_text
Revenue2024WidgetA1000.01000
Revenue2024WidgetB1000.01000
Revenue2025WidgetA1320.01320
Revenue2025WidgetB800.0800
Share2024WidgetA0.50.5
Share2025WidgetA0.62264150943396220.622641509433962
…
Growth2025WidgetB-200.0-200

These are the values improv eval gives for the same model (the extension's test suite checks that).

source is a table or view name, or a query: anything starting with SELECT, WITH, FROM or VALUES, or in parentheses.

SELECT * FROM improv('SELECT * FROM sales WHERE year >= 2025', '...');
SELECT * FROM improv('read_csv(''sales.csv'')', '...');  -- not a query: use FROM
SELECT * FROM improv('FROM read_csv(''sales.csv'')', '...');

model has one item per line. Blank lines and lines starting with # or -- are ignored, and keywords are case-insensitive.

category <Name> = <column>
input    <Name> = <column> [sum | avg | min | max | count]
<Name> = <formula>
  • category makes a dimension from a column. Its items are the column's distinct non-NULL values in the column's own order: numbers numerically, dates chronologically, text alphabetically. PREV and NEXT follow that order. Each category becomes a result column of that name.
  • input is a measure read from a column, over every category. Two source rows on the same coordinate are an error unless the line names an aggregation, which then combines them (qty sum above adds 2025's two WidgetA rows). Numeric columns of any type are numbers, BOOLEAN is a boolean and VARCHAR is text; count counts any type.
  • Name = formula is a derived measure: any formula over the inputs, the derived measures above it, and itself through PREV (a running total is Balance = PREV(Balance, Time, 1, 0) + Deposits). Aggregations across a category (SUM(Revenue OVER Product)), RANK, running forms and the rest of the formula language all work.
  • A column name with spaces or capitals goes in double quotes: category Time = "Fiscal Year". DuckDB matches column names case-insensitively.
  • A source row with a NULL category value is skipped; a NULL input value is no cell.

The result has one row per derived cell: measures in declaration order, each measure's cells in item order. Its columns are measure, then one VARCHAR column per category (NULL where the measure does not range over that category: SUM(x OVER Product) has no Product), then value DOUBLE (NULL for text, booleans and errors) and value_text (every value as text; errors as #DIV/0!, …). It is an ordinary table expression, so you can filter, join and pivot it:

PIVOT (SELECT * FROM improv('sales', '...') WHERE measure = 'Revenue')
  ON "Time" USING first(value) GROUP BY "Product";

Errors fail the query and name the line:

improv: model line 2: Quantity: two source rows have the coordinate (2025, WidgetA); add an aggregation (sum, avg, min, max, count or count_distinct) to the input line
improv: model line 1: the source has no column "yr" (it has: year, product, price, qty)
improv: model line 7: definition: parse error at 9: unknown measure: Revnue

Notes

  • The source is read through the extension's own connections to the same database (a small pool, IMPROV_DUCKDB_POOL, default one per core up to 8). It sees committed data: not rows the calling transaction has written but not committed, and not the caller's TEMP tables. Materialize those into a regular table first.
  • The whole result is computed at bind time and written out a chunk at a time, so it suits models up to a few million cells: 2.5M distinct cells take about 5 s and 1.5 GB. For a model that stays live as its data changes, use pg_improv or improv stream.
  • Enum and date inputs are not supported in models yet. A date column works as a category.

The HTTP Server

improv-server serves a JSON HTTP API over one model store:

improv-server model.db 127.0.0.1:3000   # or IMPROV_ADDR=...; model defaults to improv.db
improv-server 'postgres://me@127.0.0.1/sales?sslmode=disable&model=plan'

improv-server on the sample model: a request without the token refused, /v1/structure, a window of Revenue cells, then a cell edit that the /v1/changes stream in the background delivers with every cell it moved, and the audit log.

Endpoints

The API is versioned: every route is served under /v1, the path the 1.x releases keep stable. The same routes without the prefix are aliases kept for older clients. docs/openapi.json is the OpenAPI 3.1 description, and the server serves it at /v1/openapi.json. A test fails when the document and the routes disagree.

MethodPathScopeBodyNotes
GET/v1/healthpublicLiveness probe.
GET/v1/openapi.jsonpublicThe OpenAPI document.
GET/v1/modelreadThe whole model. Refused (403) for a model with access policies.
GET/v1/measuresreadId, name, kind, categories.
GET/v1/measures/:id/valuesreadStored inputs, or computed values.
POST/v1/measures/:id/evalread; write to persist{"edits": [{"measure": 101, "coord": [[1, 10], [2, 20]], "value": 90}], "persist": false}What-if edits through the live engine; "persist": true writes them. Ids are numeric; "value": null clears a cell. The answer names coordinates by category and item name.
POST/v1/measures/:id/cellswrite{"coord": {"dims": {"1": 10, "2": 20}}, "value": 90}Set one input cell (category id → item id).
POST/v1/nl/parseread{"text": "revenue is price times quantity"}Controlled English to a formula.
POST/v1/nl/describeread{"formula": …}A formula (as /nl/parse returns it) to controlled English.
GET/v1/scheduler/statusreadRefresh scheduler state.

Values written through these routes are numbers. The routes below are what a GUI drives (The Web GUI uses them); they take and return typed values, and answer with only what the caller may see.

MethodPathScopeBodyNotes
GET/v1/capabilitiesreadWhat the caller may do: the model-wide actions, each visible measure's define and cells (all, some, none), and the items it may rename or delete. Hints for a GUI; every request is still checked.
GET/v1/structurereadCategories with their items in grid order, measures (with formulas as typed), LAMBDAs, views, and the version. The stable shape, in place of /v1/model.
POST/v1/measures/:id/windowread{"at": {"1": [10, 11]}}The cells at these items (per category id; a category left out: all its items), computed by the server.
POST/v1/cellswrite{"edits": [{"measure": 101, "at": [[1, 10], [2, 20]], "value": 150}]}Set or clear ("value": null) cells, all or none. A refusal says which edit (index).
POST/v1/measureswrite{"definition": "Tax = Revenue * 0.1"} or {"name": "Notes", "categories": [2], "type": "Text"}Define (or redefine) a derived measure or a LAMBDA, or add an input measure.
PUT/v1/measures/:idwrite{"formula": "Revenue * 0.2", "name": "Duty", "format": {"decimals": 2}}Any of them, as one step.
DELETE/v1/measures/:idwriteRefused while a formula reads it.
POST/v1/categorieswrite{"name": "Region"}
PUT, DELETE/v1/categories/:idwrite{"name": …}Rename; delete (with its items; refused while a measure uses it).
POST/v1/categories/:id/itemswrite{"name": "North"}
PUT, DELETE/v1/items/:idwrite{"name": …}Rename; delete (with its cells).
POST/v1/viewswrite{"name": "By product", "matrices": [{"measure": 102, "axis_order": [2, 1]}]}Save a view.
PUT, DELETE/v1/views/:idwrite{"name": …, "matrices": …}
POST/v1/undo, /v1/redowriteThe session's last change.
GET/v1/changesreadServer-Sent Events: what changed (see below).

A value is a JSON number, boolean or string, or {"date": "2025-01-31T00:00:00+00:00"} or {"error": "#DIV/0!"} (a computed error). A coordinate (at) is [category id, item id] pairs. A refused request gets {"error": …, "index": n, "diagnostic": {"span": [6, 12], "message": …, "hint": …}}: index names the edit of a batch that failed, and diagnostic places a formula error in the text sent (byte offsets), as the desktop's formula editor underlines it.

Versions ("version" in every answer and event) are opaque strings: compare them for equality only. A cell edit never conflicts: when another writer saved first, the server reloads, checks the edits again, and applies them. A structural change that races another writer's gets 409.

Undo is per session: send x-improv-session: <any id> (one per window, up to 64 characters) with each write; without it a token's writes share one stack. Undo writes back the cells an edit replaced (each checked as a new edit), or restores the structure and the cells a structural change dropped.

Authentication

Once any token is configured, every route except the public ones needs Authorization: Bearer <secret>. Each token has a name and a scope: a read token may call the read routes, a write token every route. A missing or unknown token gets 401; a read token on a write route (or "persist": true) gets 403. Secrets are compared in constant time and never logged; the audit log and the rate limiter use the token's name.

VariableMeaning
IMPROV_API_TOKENOne write token, named IMPROV_API_TOKEN.
IMPROV_API_TOKENSWrite tokens, comma-separated, named IMPROV_API_TOKENS#1, #2, …
IMPROV_API_TOKENS_RORead tokens, comma-separated, named IMPROV_API_TOKENS_RO#1, …
IMPROV_API_TOKEN_FILEA file of tokens, so secrets stay out of the environment (below).
IMPROV_ALLOW_OPEN=1Allow open mode (no tokens) on a non-loopback address. Without it the server refuses to start.

The token file has one name:scope:secret per line, scope being read or write; the secret may contain :. Blank lines and # comments are skipped:

# /etc/improv/tokens, mode 600
dashboard:read:9f2c…
loader:write:b71e…

The server refuses to start if the file is unreadable or malformed, or if two tokens share a name or a secret, and warns if the file is readable by other users. All the sources combine. Generate secrets with openssl rand -hex 32.

In open mode (no tokens) every caller has write access and the audit log names it anonymous.

Access policies

A model with access policies (improv policy set) is served under them, to every route. The caller is the Cedar user named by its token (dashboard, loader, …; anonymous in open mode), with no roles; groups come from the model's policy document. A token's scope stays an outer limit: a read token never writes, whatever the policies allow.

  • Hidden is absent. A measure, item or cell a caller may not read is missing from every answer: lists, cells, windows, what-if results, /nl/parse's names, the change stream, /v1/scheduler/status. A route about a hidden measure answers exactly as for a measure that does not exist (the same status and message). An edit of a cell the caller may not edit answers as an edit of a cell that does not exist.
  • Totals are the model's. Derived values are computed over all the data, hidden cells included, and then filtered. See Totals and what they reveal.
  • /v1/model is refused (403) for a model with policies, to every caller: it is the whole model, unfiltered. Read the model through /v1/structure and the measure routes.
  • Changes take effect at once. The server reads the policies' version on every request, so a set, a clear or a change of groups is seen by the next request, with no restart. Policies that no longer validate refuse every request.
  • Refusals are audited like any write: who, the route and the status (see Audit log).
  • The scheduler's errors are generic. Under policies, /v1/scheduler/status reports a failed refresh as "a refresh failed; the server's log says why", since the error may name a hidden measure; the server's log has the full text.

Writes

A write must name an existing input measure and a coordinate with exactly one item for each of the measure's categories; values must be finite. Anything else is a 400. Writes are serialized, so concurrent writers do not lose updates. The server caches the loaded model, and before every request it checks the store's high-water mark (one cheap query: Mentat's newest transaction, or a Postgres model's improv.model_version). When another process (the GUI, the CLI, SQL on a Postgres model) has saved since, it reloads, so the next read shows that change and the next write builds on it. A write that races such a save (it lands between the server's load and its save) is refused with 409 Conflict, writing nothing, and the cache is dropped, so a retry reloads and succeeds.

Limits

LimitDefaultVariable
Request body1 MiB (413 above)IMPROV_MAX_BODY_BYTES
Requests a minute, per caller600 (429 above, with Retry-After)IMPROV_RATE_LIMIT (0 turns it off)
Edits per /eval10,000 (400 above)
Request time30 s (408), including time queued for a slot
Requests in flight64; the rest queue
Header read10 sIMPROV_HEADER_TIMEOUT_MS
Change streams open (/v1/changes)256 in all, 8 per caller (429 above)IMPROV_MAX_STREAMS (the total)

The rate limit is a token bucket per token name. A request without a valid token (and every request in open mode) is counted against the client's IP address instead. Behind a reverse proxy every client has the proxy's address, so in open mode set the limit in the proxy. Public routes are not limited.

A change stream is long-lived: it is not bound by the request time and takes no in-flight slot, so open streams never hold up other requests. The stream caps bound them instead, counted per principal (a token's name). However many are open, the server reads the store's high-water mark for other writers' changes once every 0.5 s, from one task, and wakes the streams when it moves.

The server speaks HTTP/1.1 only.

Internal errors return {"error": "internal error", "request_id": N}; the detail is logged to stderr under the same id.

Audit log

Every write is logged as one JSON object per line: POST /cells, and /eval with "persist": true. Refused writes are logged too, with the status they got (401, 403, 400, 409, 408, …):

{"ts":"2026-10-22T09:14:03.512Z","audit":"write","who":"loader","route":"POST /v1/measures/100/cells","model":"postgres://me@db/sales?model=plan","status":200}

who is the token's name (unauthenticated for a write without a valid token, anonymous in open mode); model is the model path or URL with any password removed. The log goes to stderr, or is appended to the file named by IMPROV_AUDIT_LOG. Scheduler refreshes are not API writes and are logged as plain lines.

Deployment

In a container. Each release from 0.12 publishes ghcr.io/gburd/improv:<version> (and :latest, amd64): improv-server and the improv CLI on Debian trixie-slim, running as uid 10001 in /data, listening on port 3000. It refuses to start without a token:

podman run -d -p 127.0.0.1:3000:3000 -v "$PWD:/data" \
  -e IMPROV_API_TOKEN_FILE=/data/tokens ghcr.io/gburd/improv /data/sales.db
podman run --rm -v "$PWD:/data" --entrypoint improv ghcr.io/gburd/improv list /data/sales.db

The directory must be writable by uid 10001. Build it yourself with podman build -f Containerfile . from the repository.

The server stops on SIGTERM or Ctrl-C, at once: docker stop, systemctl stop and a terminal's Ctrl-C need no kill timeout. A request still running is cut off; a write in it is one store transaction, so it is saved whole or not at all.

improv-server speaks plain HTTP; it has no TLS of its own. To serve it beyond the machine, bind it to loopback and put a reverse proxy in front that terminates TLS:

IMPROV_API_TOKEN_FILE=/etc/improv/tokens IMPROV_AUDIT_LOG=/var/log/improv/audit.log \
  improv-server /srv/improv/sales.db 127.0.0.1:3000

Caddy (it fetches and renews the certificate itself):

improv.example.com {
	reverse_proxy 127.0.0.1:3000
	request_body {
		max_size 1MB
	}
}

nginx:

server {
    listen 443 ssl;
    server_name improv.example.com;
    ssl_certificate     /etc/letsencrypt/live/improv.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/improv.example.com/privkey.pem;
    client_max_body_size 1m;

    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_http_version 1.1;
        proxy_read_timeout 35s;
    }
}

Keep the proxy's body limit at or below IMPROV_MAX_BODY_BYTES, and its read timeout above the server's 30 s request time. Bearer tokens travel in a header, so never expose the plain-HTTP port itself: the server refuses to listen on a non-loopback address without tokens (unless IMPROV_ALLOW_OPEN=1), but with tokens set it will, and the tokens would then cross the network in clear text.

A web front end

The web GUI (The Web GUI) is served by --static, and the routes above are what it drives. They are there for anyone building another front end too.

Static files. --static DIR serves the files under DIR at /, beside the API: / and a directory are their index.html, .wasm is application/wasm, and a path outside DIR (.., a symlink out) is a 404. The files are public, like /health; the API calls the page makes still need their tokens. Same-origin, the page needs no CORS.

IMPROV_API_TOKEN_FILE=/etc/improv/tokens improv-server sales.db 127.0.0.1:3000 --static ./web/dist

CORS is off by default: without it a browser lets only same-origin pages call the API. To serve the page from elsewhere (a development server, another host), list its origins, matched exactly:

IMPROV_CORS_ORIGINS=http://localhost:8080,https://ui.example.com improv-server sales.db

An allowed origin's preflight (OPTIONS) gets 204 with GET, POST, PUT, DELETE and the authorization, content-type, x-improv-session and last-event-id headers; its responses carry Access-Control-Allow-Origin. Other origins get no CORS headers, so the browser blocks them. * is refused, because a page from any site could then use a visitor's token.

Seeing changes. GET /v1/changes is a Server-Sent Events stream. Its first event is the current version, {"version": "…"}; after that, one event per change the caller may see, carrying the changed cells (inputs and the computed cells they moved) as the server computed them:

id: 268435470
data: {"version":"268435470","cells":[{"measure":101,"at":[[1,10],[2,20]],"value":150},{"measure":102,"at":[[1,10],[2,20]],"value":1800}]}

A structural change, or another program's save, sends {"version": "…", "reload": true}: re-read the structure and what is on screen. A change the caller may see none of sends nothing. To resume after a dropped connection, reconnect with ?since=<the last version> (or Last-Event-ID): the server sends what changed since, or a reload when it no longer has the gap. Each request also checks the store's high-water mark (see Writes), so a client without the stream sees other writers on its next request. A browser's EventSource cannot send the Authorization header: read the stream with fetch instead, as the web GUI does.

Access. Every GUI route asks one policy hook in improv_service, for each measure, item and cell it touches; today it allows everything the token's scope allows. A hidden measure, item or cell is absent from every answer, and is refused exactly as one that does not exist. Cedar policies (the security design, docs/reviews/2026-11-02-cedar-policies.md) plug in there.

Refresh scheduler

The scheduler refreshes CALL (external-function) measures in the background. Refreshing runs code stored in the model, so it is off by default.

VariableMeaning
IMPROV_SCHEDULER=1Enable the scheduler.
IMPROV_EXTFN_ALLOWPath to the allowlist file.
IMPROV_SCHEDULER_TICK_SECSTick period (default 5).

The scheduler runs a function only if its digest is listed in the allowlist file, one lowercase hex digest per line (# comments allowed). Other functions are skipped, and a warning is logged. The digest is the SHA-256 of the function name, a NUL byte and the body:

printf '%s\0%s' double 'result = args[0] * 2' | sha256sum

Scheduler refreshes always run in the Restricted sandbox, whatever the function's pure flag says.

Access Policies

A model can carry access policies: rules, written in Cedar, that say who may see and who may change which parts of it. A model with no policies is unrestricted, as before. Once a model has policies, everything they do not permit is denied, and a forbid always wins over a permit.

The policies are stored with the model and enforced where the model is served: by pg_improv, in the database, for every Postgres client (see Improv in Postgres); by improv-server, on every route (see The HTTP Server); and by improv policy check for testing. A local model file has no protection of its own: whoever can read the file can read all of it, whatever its policies say. The design is in the design note.

The policies enforced by pg_improv: the owner sets policies and grants ann; as ann, the result table and improv.cells lack Falcon, a hidden item answers as a missing one, a Price edit is refused and a Quantity edit written; the owner sees why a cell is hidden, and the audit log.

A first policy

Start from a template. improv policy template prints policy text that you can store as it is or edit first:

improv policy template sales.db viewer --group staff > policies.cedar
improv policy template sales.db analyst --user ann --item Product=Falcon >> policies.cedar
improv policy template sales.db editor --user ed --measure Price >> policies.cedar
echo '{"staff": {"users": ["vic", "ann"]}}' > groups.json
improv policy validate sales.db policies.cedar --groups groups.json
improv policy set sales.db policies.cedar --groups groups.json

validate checks the text against Improv's schema and the model, and stores nothing. set does the same and stores the policies, replacing any stored before. Each set and each clear moves the policies' version on.

improv policy show sales.db            # the stored text, with its version
improv policy show sales.db --groups   # the stored groups
improv policy clear sales.db           # unrestricted again

Asking a question

improv policy check asks whether a user may do an action and names the policies that decided. It exits 0 on allow and 1 on deny, so scripts can test a policy set:

$ improv policy check sales.db --user ann ReadCell --measure Quantity --at Time=2025 Product=Falcon
deny: ann ReadCell cell measure Quantity (101)[Time=2025, Product=Falcon]
  allow ViewModel the model by viewer:group:staff
  allow ReadMeasure measure Quantity (101) by viewer:group:staff
  allow ReadItem item 2025 (10) by viewer:group:staff
  deny  ReadItem item Falcon (21) by analyst:user:ann

The resource is the model (no flag), --measure, --item Cat=Item, --category, --view, or a cell (--measure with --at). --role gives the user a role, and --policies FILE checks a file instead of the stored policies.

What the actions allow

ActionOnAllows
ViewModelthe modelOpening it: its category names and view names. Every other action needs it too.
ReadMeasurea measureIts name, type and dimensions. Its formula too, when every measure the formula reads is readable.
ReadIteman itemIts name as a row or column, and its place in its category.
ReadCella cellIts value.
EditCella cellSetting or clearing an input cell.
DefineMeasurethe model, or a measureAdding, redefining, formatting or dropping measures.
EditStructurethe model, a category or an itemAdding, renaming, reordering and removing categories and items.
ManageViewsthe model, or a viewSaving, changing and dropping views.
Adminthe modelSetting its policies and groups.

Read groups the four read actions, Write holds EditCell, and Build groups the three structure actions, so a policy can say action in Improv::Action::"Read".

The rules apply together. A cell is visible only when its measure, every item of its coordinate and the cell itself are readable. A cell is editable only when it is visible, its measure is an input, and EditCell allows it. A derived measure's cells are never edited.

Writing policies

Policies name the model's objects by id, the numbers improv list prints: Improv::Measure::"101", Improv::Item::"21", Improv::Category::"2", Improv::View::"1". The model is always Improv::Model::"model". Ids do not change when a measure is renamed, so a forbid stays on what it named. validate and set warn when a policy names an id the model lacks, which usually means a name was written where an id belongs.

// Everyone in "finance", and every user with the role "auditor", reads it all.
permit (principal in Improv::Group::"finance", action in Improv::Action::"Read", resource);
permit (principal in Improv::Role::"auditor", action in Improv::Action::"Read", resource);

// Nobody but the treasurer sees Salary (measure 105) or its cells.
forbid (principal, action in Improv::Action::"Read", resource in Improv::Measure::"105")
unless { principal == Improv::User::"treasurer" };

// Input measures only, and only through the server.
permit (principal, action == Improv::Action::"ReadMeasure", resource)
when { resource.kind == "input" && context.channel == "server" };

A cell is in its measure and in each of its items, so resource in Improv::Measure::"105" covers the measure and all its cells. A list (resource in [...]) holds entities of one type: forbid an item and a measure in two policies. A measure has a kind, "input" or "derived". context.channel is "local", "server" or "postgres". A policy may not name a cell directly, or use template slots (?principal).

Users, roles and groups. A user is the name the user signs in with. Roles come from the identity source: Postgres role memberships, or later a sign-in token's claims. Groups are stored with the policies, in a JSON file that set --groups takes. A group lists its users and the groups inside it:

{"finance": {"users": ["fay"], "groups": ["treasury"]},
 "treasury": {"users": ["tom"]}}

An evaluation error, such as an integer overflow in a when clause, denies the request even when the failing policy is a forbid.

Templates

TemplateTakesGives
viewerEvery read action on everything.
editor--measure M…viewer, plus editing the cells of those input measures.
analyst--item Cat=Item…viewer, except those items: their rows and cells are absent. Totals over them stay.
hide-measures--measure M…A forbid on reading those measures and their cells. Add it to another template.
adminEvery action.

Each takes --user U or --group G, and each policy's @id names the template and the principal (analyst:user:ann), which is what check prints.

Totals and what they reveal

A total is computed over all of its items, hidden ones included, and is shown with that value or not at all. It is never recomputed over the items a user can see.

  • Under analyst, totals over the hidden items stay visible, with their full values. The hidden items' rows and cells are absent.
  • Under hide-measures, a derived measure that reads a hidden measure stays visible, without its formula.
  • To hide a total too, forbid its measure or its cells.

So a user who sees a total and all but one of its parts can work out the last part. improv policy lint lists, for one user, each readable measure that reads something hidden from them:

$ improv policy lint sales.db --user ann
measure Total (103) totals over category Product (2), including Falcon, hidden from ann: the total less the visible items is their sum

In Postgres

A Postgres model's policies live in pg_improv's improv.policy table. improv policy set postgres://…?model=plan stores them through improv.set_policies, which checks them again and audits the change; in SQL:

SELECT improv.set_policies('plan', $$ permit (principal in Improv::Role::"staff",
  action in Improv::Action::"Read", resource); $$, '{"staff": {"users": ["ann"]}}');
SELECT version, set_by, set_at FROM improv.policies('plan');
SELECT * FROM improv.explain_access('plan', 'ReadCell',
  '{"measure": "Revenue", "at": {"Time": "Q1", "Product": "Falcon"}}', 'ann');
SELECT improv.set_policies('plan', NULL);   -- clear

The Cedar user is the Postgres role (current_user), and its roles are every role whose privileges it has. The model's owner, roles that may act as the owner, and superusers are never restricted, so a policy cannot lock the owner out. A policy may allow Admin to others, who may then set the policies too.

Everyone else reads the model through what the policies allow:

  • SELECT on a result table returns only the rows it may read (row-level security, on every sync mode);
  • improv.categories, improv.items, improv.measures and improv.cells list only what it may read, and a hidden measure or item answers exactly as one that does not exist;
  • the catalog tables (improv.measure and the rest) show it nothing.

It changes the model where EditCell and DefineMeasure allow: improv.set_cells edits input cells, and improv.define and improv.drop_measure define, redefine and drop measures, all run as the owner. A definition cannot read a measure the role may not. Each change adds a row to improv.policy_audit; a refusal is logged by the server as one pg_improv audit: line. A change to the policies, the groups or a role's memberships applies from another session's next statement.

A restricted role needs improv_reader, a role the extension makes (GRANT improv_reader TO ann, as a superuser or an improv_admin): it may call the filtered functions and read model names, and nothing else in schema improv. To query a result table it needs the owner's grant too (GRANT USAGE ON SCHEMA improv_plan TO ann; GRANT SELECT ON improv_plan.revenue TO ann); that grant alone is enough for SELECT, which the policies still filter.

Not covered: the source tables (a role that may read sales reads it, whatever the model's policies say), and the timing of changes (improv.model_version and NOTIFY are global).

Performance

Measured in release builds (rustc 1.98, x86_64 Linux), 100 policies:

WhatMeasured
One raw authorize (uncached, the canonical model)142 µs
One question of a new, uncached session21 µs
One cell check from a session's cache334 ns
A filtered read of a 1M-cell measure through a session326 ms
SELECT of a 1M-row result table in Postgres, as a restricted role allowed everything / with one hidden item / checked row by row (the owner: 64 ms)88 / 115 / 160 ms

A session caches its decisions per class (a measure, an item a policy names, the rest of a category's items), so a read costs per cell, not per policy. In Postgres the row-level security qual decides once per statement whether every row, no row, the rows without one or two hidden names, or each row on its own is shown; a row checked on its own costs about 100 ns. The fast answers need the result rows to name only the model's items: after an item is renamed or deleted, rows are checked one by one until the next recalc.

Compatibility

The policies live in the model file beside the model, not in it. A model save does not touch them. Releases before 0.13 open a file with policies, ignore them, and keep them when they save. pg_improv before 0.13 keeps none; improv policy set on such a database says to update the extension.

Controlled Natural Language

improv_nl_formula translates between formulas and a controlled natural language: a small, fixed, deterministic grammar — not open-English NLP. There are no LLMs and no external services. The same grammar parses a sentence into a formula and renders a formula back into a sentence.

Two functions form the surface:

  • parse_nl_formula(ctx, text) → Formula
  • describe_formula(ctx, formula) → String

Both take an NlContext built from a Model, which resolves measure and category names (case-insensitively) to ids.

The grammar

sentence   = [ subject copula ] expr [ "." ]
subject    = measure-name          (* parsed, then discarded *)
copula     = "equals" | "is"

expr       = term { ("plus" | "+" | "minus" | "-") term }
term       = factor { ("times" | "*" | "divided" "by" | "/") factor }
factor     = number                (* 42, 2.5, 1e-10, as in a formula *)
           | agg-call
           | measure-ref
           | "(" expr ")"

agg-call   = ["the"] ("sum" | "average" | "min" | "max") "of" measure-ref
measure-ref= measure-name { dim-phrase }
dim-phrase = "over" cat-list                 (* aggregate over  -> DimensionSpec.over *)
           | ("by" | "for" "each") cat-list  (* keep / group by -> DimensionSpec.by   *)
cat-list   = category-name { "and" category-name }

Subject and copula are discarded

A sentence may open with <measure> equals or <measure> is, but the parser strips it: the returned Formula is only the right-hand-side expression. The target measure is a property of where the formula is stored, not of the expression tree. So both of these parse to the same formula:

Revenue equals price times quantity.
price times quantity

The copula is only stripped when one actually follows the first word, so a bare expression like price times quantity (no copula) still parses correctly.

Operators

PhraseSymbolOperation
plus+addition
minus-subtraction
times*multiplication
divided by/division

Precedence is the usual arithmetic one: times/divided by bind tighter than plus/minus. So price times quantity plus revenue parses as (price * quantity) + revenue. Parentheses override precedence.

Aggregation phrases

An aggregation reads as the <func> of <measure-ref> (the the is optional). The function words map to the same function ids as the formula language:

PhraseFuncId
sum of1
average of2
min of3
max of4

Dimension phrases

A dimension phrase binds to the nearest preceding measure reference and fills in that reference's DimensionSpec:

  • over <categories> sets over — the categories an enclosing aggregation collapses.
  • by <categories> or for each <categories> sets by — the categories to keep / group by.

Categories in a list are joined with and, e.g. over time and region.

The except field of a DimensionSpec is not expressible in this grammar.

A full example

the sum of revenue over time for each product

parses to a SUM call over a Revenue reference whose over = [Time] and by = [Product] — i.e. total revenue per product, summed across years.

Round-trip and rendering

describe_formula is the inverse rendering. It uses a fixed vocabulary:

  • Operators render as their words (plus, minus, times, divided by).
  • Aggregations render as the <func> of ....
  • A reference's over renders as over ...; its by renders as for each ... (not by).

So the example above renders back as:

the sum of Revenue over Time for each Product

Because describe uses for each for the by list and the grammar accepts both by and for each, describe → parse is a stable round trip for the supported constructs. Comparison and logical operators have best-effort English renderings (is greater than, and, or, ...) so describe never fails, but they are outside the parseable surface. The same holds for two more renderings: unary minus describes as negative X, and a non-aggregating function call as itself (ROUND(Price, 2), IF(…)); neither parses back, so write those in the formula DSL.

Monitoring

This page is for whoever runs a Postgres database with pg_improv in it, and for anyone running improv-server. It covers what to watch, what the signals mean, and when to page someone. It describes pg_improv 0.11.0, the version on main. Operations runbook has what to do when an alert fires.

Ready-made files:

Both were checked against a PG 18.6 cluster running pg_improv 0.11.0 built from main, with postgres_exporter 0.17.1.

What to watch

flowchart LR
  W[writers] -->|commit| WAL[(WAL)]
  WAL -->|decoded each poll| S[slot improv_db]
  S --> K["pg_improv sync worker<br/>(one per server)"]
  K -->|result rows| R[(improv_‹model›.*)]
  K -->|counters, last_error| ST[improv.sync_state]
  ST --> V["improv.status(model)"]
  S --> RS[pg_replication_slots]
  K --> PA[pg_stat_activity]
  K --> LOG[server log]

Only logical-mode models have a worker, a slot and lag. trigger and commit models fail inside the writer's transaction, so the writer sees the error. A manual model changes only when someone calls improv.recalc().

improv.status(model)

One row per model, SECURITY INVOKER, readable by anyone with USAGE on schema improv and SELECT on its tables (row-level security hides only a model's input cells from roles that may not act as its owner).

SELECT m.name, s.*
  FROM improv.model m, improv.status(m.name) s;
ColumnTypeMeaningHealthy
sync_modetextlogical, trigger, commit or manual.what you set
slottextimprov_db in logical mode (the slot every logical model of the database shares); NULL otherwise.improv_db
lag_bytesbigintpg_current_wal_lsn() − confirmed_flush_lsn of the slot: WAL the worker has not confirmed yet. It is the slot's lag, so every logical model of the database shows the same number. NULL when the slot does not exist (not yet created, or dropped).small and not growing; it rises to about 16 MB while the bound tables are idle and then drops, because the worker advances an idle slot once it lags 16 MB
confirmed_lsntextThe slot's confirmed_flush_lsn.moving
last_applied_attimestamptzWhen the worker last applied a batch to this model, or rebuilt it. It does not move while the model's tables are idle. NULL before the first catch-up, and after a new slot resets progress.recent if the tables are being written
rows_appliedbigintResult rows the worker has written for this model (inserted, updated or deleted), in total.rising with writes
last_errortextWhy the worker's last attempt at this model failed; NULL after a success. While set, the model is retried with backoff (0.5 s, doubling, up to 60 s), and every retry is a full rebuild.NULL
incremental_appliesbigintBatches the worker fed to the live engine (the cheap path).rising with writes
rebuildsbigintFull reloads and recomputes. The first catch-up counts one; so does each worker restart, structural change (define, a new binding), and batch that needs one (Concepts lists the triggers).flat between deploys and restarts
fold_bytesbigintEstimated heap of the model's fold state in the worker: what its aggregated bindings (agg => …) keep per coordinate. A count_distinct, min or max binding keeps its values too, so it grows with their number. 0 without aggregated bindings. Measured after each rebuild, and at most once a second while the model applies batches; NULL while the worker holds no live state for the model (before its first change, or after it failed).stable for a stable model
engine_bytesbigintEstimated heap of the model's live engine and input cells in the worker, as of the same moment. fold_bytes + engine_bytes is what improv.max_model_memory caps.stable for a stable model; below the cap

lag_bytes is measured against the shared slot, so it does not tell you which model is slow. Compare last_applied_at and the counters across models for that.

improv.status does not report the slot's wal_status. A lost slot (see below) leaves last_error NULL on 0.11.0 and earlier, so watch pg_replication_slots as well. D11 in the road to 1.0 makes the worker report and repair it.

The memory columns are estimates of the worker's heap. They come from the sizes of the structures the worker holds, within about 10 % of the live heap measured on the shapes in the tests (maps, joins, SUM, count, sum, count_distinct, min). They do not count the shared buffers the worker reads through. To find the models that use the most memory:

SELECT m.name, pg_size_pretty(s.fold_bytes + s.engine_bytes) AS live
  FROM improv.model m, improv.status(m.name) s
 WHERE s.fold_bytes IS NOT NULL
 ORDER BY s.fold_bytes + s.engine_bytes DESC;

Capping a model's memory

improv.max_model_memory (MB, default 0 = no cap, reloadable) caps each model's live state. The worker checks it whenever it measures the model (after each rebuild, and at most once a second as it applies), and checks the loaded inputs before it builds an engine. A model over the cap is refused: the worker drops its live state, logs pg_improv sync: model <m>: the live state needs about N MB (fold state F MB, engine E MB), over improv.max_model_memory = C MB, and sets that text as the model's last_error. It retries with backoff (each retry is a rebuild), and other models are not held back. The model's result tables keep their last values. Set the cap below what the server can spare for the worker divided by the number of large models, so one model that grows fails alone rather than getting the backend OOM-killed and taking every model down with it.

pg_replication_slots

SELECT slot_name, active, active_pid, wal_status, safe_wal_size,
       pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn))         AS retained,
       pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), confirmed_flush_lsn)) AS unconfirmed
  FROM pg_replication_slots
 WHERE slot_name = 'improv_db';
  • retained (pg_current_wal_lsn() − restart_lsn) is what the slot keeps on disk in pg_wal. This is the number that fills disks.
  • unconfirmed is lag_bytes from improv.status.
  • active is true only while the worker is decoding (during a poll), so it flickers; active_pid is the worker's pid then.
  • wal_status is reserved or extended while the slot is healthy. unreserved means it is past max_wal_size and about to exceed max_slot_wal_keep_size. lost means Postgres removed WAL the slot needed: the slot is dead, results no longer follow writes, and on 0.11.0 and earlier the worker does not recover by itself (runbook).
  • safe_wal_size is how much more WAL may be written before the slot is lost (NULL when max_slot_wal_keep_size is unlimited, which is the Postgres default; set it).

With no logical-mode model left, the worker drops the slot. A database whose models are all trigger, commit or manual has no improv_db row.

The worker in pg_stat_activity

SELECT pid, datname, backend_start, state, wait_event_type, wait_event
  FROM pg_stat_activity
 WHERE backend_type = 'pg_improv sync';
  • There is one worker per server, serving the database named by improv.database (default postgres). It exists only when pg_improv is in shared_preload_libraries.
  • No row means the worker is not running. Without the preload there is never one; with it, the postmaster restarts a dead worker 5 s after it exits.
  • backend_start keeps resetting when the worker is crash-looping.
  • Between polls it waits on the latch: wait_event_type = 'Extension', wait_event = 'Extension'.
  • datname is the database it serves. Logical-mode models in any other database are never applied.

The worker's log lines

The worker logs at LOG level into the server log. Every line starts with pg_improv sync. Here is each line in crates/pg_improv/src/worker.rs:

LineMeaningAction
pg_improv sync worker started on database "<db>"The worker connected. Once at server start, and after each restart.none; frequent restarts mean a crash loop
FATAL: terminating background worker "pg_improv sync" due to administrator commandIt received SIGTERM (shutdown, or pg_terminate_backend) and stopped at its next interrupt check, mid-poll if need be. It exits with status 1, so the postmaster starts it again 5 s later and it resumes from the slot position.none
pg_improv sync worker stoppingThe postmaster died.see why the server went down
pg_improv sync: listing models: <error>It could not read the catalog this poll.check the error; it retries next poll
pg_improv sync: dropping improv_db: <error>No logical model is left, and dropping the slot failed.drop it by hand if it stays
pg_improv sync: creating the slot improv_db: <error>Slot creation failed, usually max_replication_slots reached or wal_level not logical. No logical model is updated until it succeeds.fix the setting and restart
pg_improv sync: creating the publication improv_db: <error>The publication was missing (dropped by hand) and recreating it failed.run SELECT improv.sync_publication() and read its error
pg_improv sync: resetting progress: <error>A new slot was created, and resetting the models' recorded positions failed.check the error
pg_improv sync: reading improv_db: <error>Decoding the slot failed, so no model was updated this poll. Repeated every poll with can no longer access replication slot "improv_db" and invalidated due to "wal_removed" in the detail, it means the slot is lost.runbook
pg_improv sync: model <name>: <error>That model's apply failed. The same text is in its last_error, and it is retried with backoff. The other models are not held back.runbook
pg_improv sync: model <name>: rebuilding (model changed)Its structure changed (define, bind_*), so it is rebuilt from its tables.none; expected after a deploy
pg_improv sync: model <name>: rebuilding (<reason>)The batch could not be applied incrementally. The reasons are listed below.if it repeats, see rebuild loop
pg_improv sync: advancing improv_db: <error>The slot could not be moved forward. The models' results are already written, but WAL is retained until the next successful advance.check the error
pg_improv sync: dropping queued slots: <error>An old per-model slot (improv_<model>, from 0.10.0) left by the upgrade could not be dropped.drop it by hand

Rebuild reasons (in crates/pg_model/src/live.rs and worker.rs):

ReasonCause
model changedmodel_version moved while the batch waited for the model's lock
no live statefirst batch after a restart or a failure
new item in a category a formula enumerates / new itema new dimension value in a category whose item list a formula reads (POSITION, PREV, RANK, FILL, …)
two rows on one coordinatea measure bound without agg got a second row for one coordinate; bind it with agg
min or max of texta text min/max binding whose value column has no collation changed (rare: a text column always has one)
nondeterministic collationa text min, max or count_distinct binding over a column with a nondeterministic collation (deterministic = false) changed: only Postgres can tell which texts are equal
truncateTRUNCATE of a bound table
old row not replicated, unchanged TOAST value, bound column missingan UPDATE or DELETE whose old row the decoder did not carry; the table needs REPLICA IDENTITY FULL (the worker sets it on tables without a primary key)
value the loader would not read, a fold went out of step, fold not seeded, unknown binding, unknown measure, undescribed relation, not an aggregated binding, no rowinternal consistency checks; the rebuild makes the result exact again. If one repeats, report it with the model's definition

Log volume on 0.11.0 and earlier. Every poll decodes the slot, and Postgres itself logs two LOG lines per decoding call, each with a DETAIL and a CONTEXT line: starting logical decoding for slot "improv_db" and logical decoding found consistent point at …. It does this even when nothing has changed. Measured on PG 18.6 (both PG 17 and 18 log these at LOG): about 3.6 KB/s of server log at the default improv.poll_ms = 200 (about 310 MB a day), and 13.5 KB/s at poll_ms = 50. Rotate the server log (log_rotation_size, log_rotation_age, or logrotate), and do not lower poll_ms below what you need. log_min_messages cannot hide these lines without hiding the worker's own LOG lines as well. D8 in the road to 1.0 skips the decode when there is no new WAL and quiets it, fixing this in 0.11.

Changing improv.poll_ms / improv.max_changes. Both take effect on pg_reload_conf() in 0.11 (D9). On 0.10.0 and earlier, and on main before D9 lands, the running worker keeps its old values until it restarts: SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE backend_type = 'pg_improv sync' (it is back 5 s later, and loses nothing).

Alerts

Thresholds are starting points for a database like the capacity planning example (one poll is 200 ms). Tune them to your write rate.

AlertConditionForSeverityWhy
Worker downno pg_stat_activity row with backend_type = 'pg_improv sync', with the preload configured1 minpageno logical model is updated; WAL accumulates
Worker crash loopworker backend_start younger than 60 s, three times in 10 min10 minpagesomething kills it every poll; read the server log
Slot about to be lostwal_status = 'unreserved' for improv_db0pagethe next checkpoint may invalidate it
Slot lostwal_status = 'lost' for improv_db0pageresults have stopped; status stays clean. This is the only signal on 0.11.0 and earlier
Retained WAL highretained bytes > 50 % of max_slot_wal_keep_size (or of free space on the pg_wal volume if unset)10 minwarnthe worker is behind or stopped
Lag growinglag_bytes > 64 MB and rising15 minwarnan idle slot stays at or below 16 MB; more than that, rising, means the worker is not keeping up
Model failinglast_error IS NOT NULL5 minwarn (page if it is a business-critical model)the model's results are stale and every retry is a full rebuild
Rebuilds risingrebuilds increases by more than 3 in 15 min outside a deploy15 minwarna rebuild loop: each costs a full recompute
Stale modellast_applied_at older than 10 min while its bound tables were written (n_tup_ins + n_tup_upd + n_tup_del in pg_stat_user_tables moved)10 minwarnthe worker is not reaching this model
Commit/trigger failuresthe server log shows improv: model … could not recomputeanywarnwriters' transactions are being rolled back

As PromQL over the queries file (metric names are <query>_<column>):

groups:
- name: pg_improv
  rules:
  - alert: ImprovWorkerDown
    expr: pg_improv_worker_running == 0
    for: 1m
    labels: {severity: page}
  - alert: ImprovSlotLost        # wal_status unreserved or lost
    expr: pg_improv_slot_at_risk == 1
    labels: {severity: page}
  - alert: ImprovRetainedWalHigh
    expr: pg_improv_slot_retained_bytes > 2 * 1024^3   # half of a 4 GB max_slot_wal_keep_size
    for: 10m
    labels: {severity: warn}
  - alert: ImprovLagGrowing
    expr: pg_improv_status_lag_bytes{sync_mode="logical"} > 64 * 1024^2
          and deriv(pg_improv_status_lag_bytes{sync_mode="logical"}[15m]) > 0
    for: 15m
    labels: {severity: warn}
  - alert: ImprovModelFailing
    expr: pg_improv_status_last_error == 1
    for: 5m
    labels: {severity: warn}
  - alert: ImprovRebuildsRising
    expr: increase(pg_improv_status_rebuilds[15m]) > 3
    labels: {severity: warn}

Run postgres_exporter against the database named by improv.database, with --extend.query-path=postgres_exporter-queries.yaml, and as a role that has USAGE on schema improv, SELECT on its tables, and pg_monitor.

The HTTP server

improv-server (The HTTP Server) serves one model store.

  • Health: GET /health returns 200 ok without a token. It says the process is up and accepting requests. It does not open the store, so pair it with a periodic authenticated GET /measures if you need to know the model loads.
  • Scheduler: GET /scheduler/status (token required) returns {"enabled", "tick_secs", "last_tick_refreshed", "last_error"} when IMPROV_SCHEDULER=1. Alert on a non-null last_error.
  • Logs: plain lines on stderr, with no timestamps, so capture stderr with your supervisor (systemd's journal adds the time):
LineMeaning
improv-server listening on <addr>started
auth disabled: set IMPROV_API_TOKEN to require a bearer tokenopen mode (loopback, or IMPROV_ALLOW_OPEN=1)
improv-server: <error>startup failed (bad address, refused open mode); it exits
accept: <error>a connection could not be accepted (often file descriptors exhausted)
request <id>: internal error: <detail>a 500; the client got {"error": "internal error", "request_id": <id>} with the same id
scheduler disabled (set IMPROV_SCHEDULER=1 to enable)the default
scheduler: refreshing due CALL measures every <n>sscheduler on
scheduler: IMPROV_EXTFN_ALLOW unset; no function will run / cannot read IMPROV_EXTFN_ALLOW …scheduler on but nothing allowed
scheduler: WARNING skipping measure <id>: its function is not in the IMPROV_EXTFN_ALLOW allowlista function's digest is not allowed
scheduler: [<t>s] refreshed measure <id> (<n> cells)a refresh ran
scheduler: measure <id> refresh failed: <error> / scheduler: tick error (continuing): <error>a refresh failed; the server keeps running
  • Signals in responses: 409 means another writer saved since the server loaded (the next request reloads). 408 and 413 mean the request limits were hit. A rising 409 rate means two writers are fighting over one model.

Capacity Planning

This page turns measured costs into sizing formulas. It is for whoever decides how much memory a Postgres server or a desktop needs for a model, which sync mode to use, and how much disk a stopped worker can fill.

Every number links to where it was measured:

Where main changed a cost, the post-fix number is used. These are measurements of particular models. Treat a formula as an estimate within a factor of about two, and measure your own model before you buy hardware.

The costs

CostValueSource
Engine memory per cellabout 0.3 kB in the live engine (5M-cell Price * Quantity grid: 269 B per cell); evaluate with its model about 0.5 kB (1M cells: 0.54 GB peak; 5M: 2.35 GB); 20k measures × 100 items: 1.17 GBchangelog (B7: no collapse after a join)
Engine evaluateabout 0.9 µs per cell on one worker (1M cells 0.87 s, 5M 4.5 s); 0.22 µs on 8 (1M cells 0.22 s, 2M 0.45 s), using 15–20 % more memorychangelog (B7, evaluate on several workers)
One-cell edit56 µs at 100k cells, independent of size; plus a per-measure round cost (fan of 20k measures: 129 ms per edit)changelog
Logical worker memory, fold state per fact row, count + count_distinct bindingsabout 120 B (derived: 444 MB private for 2.5M rows, less the engine's 4 × 44,750 cells at 0.8 kB)bench §1, here
Logical worker memory per small modelabout 0.6 MB (1,000 models of 1,000 rows: 575–602 MB)here
FIXPOINT memory per edgeabout 0.4 kB in the live engine (10M edges: 390 B per edge, 8.2 GB peak); the tagged 1.5k and 10k-node tests together peak at 1.5 GBchangelog (B8), qual
Worker CPU per 1,000-row batchabout 20–25 ms above idlehere
Worker idle CPU0.08 core at poll_ms = 50 with one large model; 0.06 core at 200 models, 0.11 at 1,000here
Initial build (or rebuild) per million fact rowsabout 2.1–2.6 s (2.5M rows: 5.3–6.5 s)here
improv.recalc per million fact rowsabout 0.9–1.1 s (2.5M rows: 2.2–2.8 s)here
Logical apply latency, 1,000-row batch86–130 ms commit → visible at poll_ms = 50 (at the default 200, add up to a poll)bench §1, here
Trigger mode, per write statement, 2.5M-row model380–390 ms for 1,000 rows; 3.1 s for 10 one-row statements in one transactionbench §3e, here
Commit mode, per transaction, 2.5M-row model2.2 schangelog, here
improv.what_if, one cell, element-wise chain0.28 s on 2.5M rowschangelog, here
WAL per bound-table row (2.5M-row table, REPLICA IDENTITY FULL)INSERT 190–230 B, UPDATE 240–700 B, DELETE about 360 Bhere
Store file (Mentat) on diskabout 1.2 kB per input cell (100k cells: 120 MB; 1M: 1.2 GB)bench §3g, qual
Store file import (import-csv)linear: 1M rows in 74–78 s, 585 MB peakqual
DuckDB improv()2.5M fact rows folded to 44,750 cells: 0.3–0.35 s, 500–640 MB (more with more DuckDB threads); 2.5M distinct cells: 4.1 s, 1.7 GBqual

Memory

A model in the GUI, TUI, CLI or server holds every cell in the engine:

RAM ≈ cells × 0.5 kB + store overhead

A 1M-cell model needs about 0.5 GB. "Cells" means input cells plus every derived cell, so a model with ten derived measures over the same grid as its inputs has about eleven times the input count.

The logical worker (one Postgres backend) holds, for each logical-mode model, its fold state and its live engine:

worker RAM ≈ Σ over models ( fact rows × 120 B  +  cells × 0.8 kB ) + 0.6 MB per model

"Cells" counts the model's input and derived cells. The 120 B per row is derived from one measurement: the worker's 444 MB with a count and a count_distinct binding, less its engine cells (the benchmark's "180 B per fact row" is the total, engine included). count_distinct keeps every distinct value per coordinate, and min/max keep a count per value, so these grow with the data's cardinality. sum, avg and count keep a few numbers per coordinate and cost less (not measured separately). The worker also reads the tables through shared buffers. That shows up in its RSS as shared memory (about 300 MB in the example) but is not extra memory.

FIXPOINT models need about edges × 0.4 kB on top, and more at peak while they build: ten million edges peaked at 8.2 GB.

improv.max_cells (default 5,000,000 bound input cells per model) refuses recalc, trigger and commit recomputes and the worker's apply above it. Raise it only after sizing the memory.

improv.status reports what each logical model holds in the worker, as fold_bytes and engine_bytes, and improv.max_model_memory caps their sum per model (monitoring). Measured on 0.11.0 (estimate = live heap): a fold state takes 533 B per coordinate for count or a numeric sum, 837 B for a float sum, and about 1 kB plus 40–60 B per kept value for count_distinct, min and max. A model's input cells take about 226 B each, and its engine 120–450 B per cell (input plus derived): a map of an input is the low end, a join or a reduction the high end.

CPU and time

initial build / rebuild ≈ 2.1–2.6 s per million fact rows
recalc / commit-mode transaction ≈ 0.9 s per million fact rows of the written tables
logical worker ≈ 20–25 ms CPU per 1,000 changed rows + idle polling

The worker is one process. Each model's engine computes on a thread of its own, so models whose formulas take long compute at the same time, on as many cores. The decode, the fold of aggregated bindings, and the SPI writes of the results stay on the worker's one thread. That is the 20–25 ms per 1,000 changed rows, and the share every model's batches take turns on:

worker utilization ≈ (changed rows/s ÷ 1,000) × 25 ms  +  idle cost

At 10,000 changed rows per second that is about a quarter of a core. Engine time is not in it: a model whose apply takes 1 s in its formulas (a large MEDIAN, a FIXPOINT) uses 1 s of its own core and delays only its own results. Beside four such models a fifth model's change was visible in 40–100 ms here. A rebuild still blocks the other models for its whole duration, since it loads and writes on the worker's thread: a 6 s rebuild delays every other model's results by 6 s. Count your expected rebuilds (restarts, deploys, new items in categories a formula reads the item list of) as well as your batches.

WAL retained while the worker is down

The slot improv_db keeps all WAL the server writes from its restart_lsn on, not only the bound tables' WAL. So, while the worker is stopped (or stuck):

retained WAL per hour ≈ server WAL rate (bytes/s) × 3600

The server's WAL rate is pg_stat_wal.wal_bytes sampled twice, divided by the interval. Measure it; it is the right number. If you only know the bound tables' write rate, a lower bound is:

bound-table WAL per hour ≈ rows written/s × WAL per row × 3600

The WAL per row was measured on the 2.5M-row example table (rows of about 86 B, REPLICA IDENTITY FULL). It was 190–230 B per inserted row, about 360 B per DELETE, and 240 B (single row) to 700 B (bulk, after a checkpoint) per UPDATE, because REPLICA IDENTITY FULL logs the whole old row. Wider rows cost proportionally more, and full-page images after each checkpoint add to it.

Example: 1,000 updated rows per second at 700 B is 2.5 GB per hour. max_slot_wal_keep_size = 10GB then gives about four hours before the slot is lost and every model needs a rebuild. Size max_slot_wal_keep_size for the longest outage you want to survive without a rebuild, and keep the pg_wal volume larger than that. Monitoring has the alerts.

Models per database

  • One logical database per server. The worker serves the database named by improv.database. Models in other databases of the same server can use trigger, commit or manual mode, but logical-mode models there are never applied.
  • Many models in one database. All logical models share one slot, so the decoding cost does not grow with the model count. On main, 1,000 small models built in 0.8 s after their switch to logical mode, a one-row change showed up in 54–146 ms, and a transaction writing every model's table showed up everywhere within 2.6 s here. At v0.10.0, with a slot per model, the same took up to 120 s and 201 s (bench §3f).
  • The limit is the worker's one thread. The models' engines compute at once, but their decodes, folds, writes and rebuilds run one after the other. So a change may wait for the sum of the other models' writes and rebuilds, but not for their engine time. Rebuilds and write-heavy models in their own processes (background workers per busy model) are not built; see B1 in the road to 1.0.

Choosing a sync mode by write rate and model size

Trigger and commit modes lock the model's catalog row for the recompute. Writers to one model's tables therefore take turns, and a mode's cost per write also caps the write rate:

ModeCost to the writerWrite rate it sustains per model
logicalnonebounded by the worker: about 40,000 changed rows/s of worker time at 25 ms per 1,000
triggerone scoped recompute per statement: 0.38 s on the 2.5M-row model; 30–170 ms at 10k cells (pg_improv README benchmarks)about 1 / cost statements per second: 2–3 statements/s on the example
commitone full recompute of the written tables' dependents per transaction: 2.2 s on the example; 77–82 ms at 10k cellsabout 1 / cost transactions per second: 0.45/s on the example
manualnoneany; results are as fresh as your last recalc
flowchart TD
  A{"Must a writer read its own<br/>results in the same transaction?"}
  A -- no --> L["logical<br/>(add manual + recalc for bulk loads)"]
  A -- yes --> B{"recompute time × write statements/s<br/>well under 1?"}
  B -- yes --> C{"many statements<br/>per transaction?"}
  C -- no --> T[trigger]
  C -- yes --> M[commit]
  B -- no --> R["logical, and improv.recalc()<br/>in the transactions that need it"]

Rules of thumb:

  • Under about 100k cells and a few writes per second: any mode works. Pick by consistency (Concepts).
  • Millions of fact rows, or more than one write per second: logical.
  • Bulk loads and migrations: switch to manual, load, recalc once, switch back. Leaving logical and entering it again costs one rebuild.

Worked example: 2.5M rows, 44,750 cells

The model from benchmark §1: a contribution_rows table of 2.5M rows (person, year, release, scope, commit sha), bound as agg => 'count' and agg => 'count_distinct' into Person × Year × Release × Scope (1,790 × 15 × 4 × 3, 44,750 coordinates), with two derived measures. Assume writers add 1,000 rows a minute in 1,000-row batches, and the server writes no other WAL.

QuestionEstimateMeasured on main here
Worker memory2.5M × 120 B = 300 MB, plus 4 × 44,750 cells (2 input, 2 derived measures) × 0.8 kB = 143 MB: 443 MB (the per-row figure was derived from this model)444 MB private (plus 316 MB of shared buffers)
Initial build2.5 × 2.1–2.6 s = 5–6.5 s5.3–6.5 s
Rebuild after a restart or definethe same5.4 s
recalc2.5 × 0.9–1.1 s2.2–2.8 s
A 1,000-row batchone or two polls (50 ms in the test; 200 ms by default), plus apply86–130 ms commit → visible at poll_ms = 50
Worker CPU1 batch/min × 25 ms: negligible next to idle polling0.08 core at poll_ms = 50, mostly idle polling
WAL retained per hour of downtime1,000 rows/min × 230 B × 60 = 14 MB/h from this table, plus all other WAL(derived)
Fits improv.max_cells?2 × 44,750 bound cells ≪ 5,000,000yes
Modelogical: trigger would cost 0.38 s per statement, commit 2.2 s per transaction

With max_slot_wal_keep_size = 10GB this model survives roughly a month of worker downtime from its own writes alone. The rest of the database's WAL decides the real number.

Measurements for this page

Made on 2026-10-21 on EC2 c7i.12xlarge (Intel Xeon, 48 vCPU, 92 GB), Debian 13, PostgreSQL 18.6 (PGDG release build), pg_improv 0.11.0 built from main with cargo pgrx install --release. Nothing else heavy ran on the box.

  • The 2.5M-row model: ROWS=2500000 BATCHES=1000 tests/scale.sh (crates/pg_improv/tests/), twice. Load 6.8–7.0 s, REFRESH MATERIALIZED VIEW CONCURRENTLY 4.9–5.8 s, recalc 2.4–2.8 s, initial build 5.3–6.5 s, six 1,000-row batches visible in 86–130 ms, no rebuild, PASS. Worker RSS sampled every 0.5 s from /proc/<pid>/status: 444 MB anonymous after the build, flat through the batches.
  • Trigger, commit, recalc, what_if: on that model, after the run (KEEP=1). Trigger mode: 379–387 ms per 1,000-row INSERT statement, 3,073 ms for 10 one-row INSERT statements in one transaction. Commit mode: 2,214–2,217 ms per 1,000-row transaction, 2,197 ms for 10 one-row INSERT statements in one transaction. recalc 2,205–2,223 ms. what_if of one cell 281–285 ms. Back to logical: rebuild in 5.4 s.
  • Worker CPU: 20 batches of 1,000 rows, 0.5 s apart, cost 1.40 s of worker CPU over 12.3 s. Idle cost: 0.77 s per 10 s at poll_ms = 50. That leaves about 22 ms per batch (1.40 s − 12.3 s × 0.077, over 20).
  • WAL per row: pg_current_wal_insert_lsn() before and after, on the same table: one 10,000-row INSERT 189 B/row, UPDATE 699 B/row, DELETE 355 B/row (each right after a CHECKPOINT, so with full-page images); ten one-row INSERT transactions 228 B each, ten one-row UPDATE transactions 242 B each.
  • Many models: the v0.10.0 benchmark's pg_many.sh (§3f), unchanged, at 200 and 1,000 models. 200: all built 0.6 s after the last switch, one-row change visible in 53–292 ms, a transaction touching all 200 in 0.56 s, worker 121–128 MB private. 1,000: built 0.8 s after the last switch, 54–146 ms, all 1,000 in 2.6 s, 575–602 MB private, 1.13 s CPU per 10 s idle.
  • Re-measured for the 0.12.0 release (the qualification): scale.sh at 2.5M rows on PG 17 and 18 (recalc 2.3–2.5 s, initial build 5.5–5.6 s, batches visible in 54–113 ms in three runs of four), 1,000 models (all built 22 s after the last switch, a one-row change in 33–124 ms, 322 MB private, 0.12 core idle), FIXPOINT, the engine probes (a RANK edit 1.5 ms at 1M items), the 1M-row import and DuckDB.
  • Re-measured for the 0.11.0 release (the 0.11.0 qualification): scale.sh at 2.5M rows on PG 17 and 18 (recalc 2.3–2.5 s, initial build 5.4–5.6 s, batches visible in 83–145 ms in four runs of five), 1,000 models (all built 21 s after the last switch, a one-row change in 52–182 ms, 426 MB private), FIXPOINT, the engine probes, the 1M-row import and DuckDB.
  • Parallel apply (B1), 2026-10-26, the same box, PG 17.11 (PGDG), release build. Four models of 2,000 items, each with F = FIXPOINT(0, LAMBDA(r, X - r), 1451, 0), which never converges and so runs all its rounds: 1.0–1.06 s of engine time per one-row change. A writer kept all four busy, and a fifth model (W = V * 2, one row) took ten one-row changes. Before B1 each was visible in 5.2–8.3 s (median 7.9 s); after, in 40–103 ms (median 57–71 ms), in three runs (tests/logical.sh §21). In the timings the worker logged before the change, the engine was 96–99 % of a slow apply (745–782 ms of a 767–803 ms apply for a MEDIAN over 1M items, and 1.00–1.04 s of 1.006–1.046 s for the FIXPOINT), and decode, fold and SPI writes were under 1 ms. A batch of 20,000 rows that rewrites 20,000 result rows is the other way around: 42 ms of decode and fold, 25–32 ms of engine, and 126–472 ms of SPI writes, which B1 does not overlap.

Backup and Restore Runbook

This runbook covers procedures for the person who backs up and restores databases and model files that hold Improv models. Each one ends with a verify step: a check that tells you the restore worked, not only that it ran. It describes pg_improv 0.11.0 (main). Where 0.11 changes a step, the step says so.

Tested. The pg_dump/pg_restore procedure (with one model in each sync mode), the base-backup restore, moving a model between databases, and the store-file copies (VACUUM INTO with a writer running, and a plain copy with the app closed) were run on 2026-10-21 against PG 18.6 with pg_improv 0.11.0 built from main, and against the improv CLI built from main. The pg_upgrade and failover sections are short versions of procedures tested separately (D1, D2 in the road to 1.0); they are not tested here.

What is where

HoldsWhereBacked up by
A model's structure (categories, items, measures, formulas, bindings, views) and its unbound cellsthe improv schemapg_dump (the catalog is registered with pg_extension_config_dump), base backups
Bound input datayour own tableswhatever backs them up
Derived resultsone table per measure in improv_<model>pg_dump, base backups (and they can always be recomputed)
The logical worker's positionimprov.sync_state plus the replication slot improv_dbthe table is dumped; the slot is in neither a dump nor a base backup
A store-file modelone SQLite file, model.db, in WAL modea safe file copy (below)

The slot is the one thing that never comes back. After any restore, the worker creates a new slot, resets every logical model's recorded position, and rebuilds each model once from its tables. That costs one full load per model: about 2–3 s per million fact rows (capacity). Nothing is lost by it.

pg_dump and pg_restore

Works for databases with models in any sync mode.

  1. Dump as usual, in the custom format:

    pg_dump -Fc -f shop.dump shop
    
  2. Prepare the target server. Install the same pg_improv version (or newer). For logical and commit models, set shared_preload_libraries = 'pg_improv'; for logical, also wal_level = logical and improv.database = '<the database>'. Restart, then create the empty database.

  3. Restore in one transaction:

    createdb shop
    pg_restore --single-transaction --exit-on-error -d shop shop.dump
    

    Use --single-transaction on every version. It is the safe procedure in any case, since a failed restore leaves nothing half-done. On 0.10.0 and on main it is also required when any model is in commit mode. A restore without it (or psql -f of a plain-format dump) fails with improv: model "<m>" (sync_mode commit) could not recompute before COMMIT, … there is no unique or exclusion constraint matching the ON CONFLICT specification, because the bound table's data commits before the result table's primary key exists. D10 in the road to 1.0 fixes this in 0.11.

  4. What happens next, by mode:

    ModeAfter the restore
    logicalWithin a few seconds the worker creates improv_db, resets the model's position, and rebuilds the model once (rebuilds goes up by one). Then it follows writes.
    triggerThe restore recreates the sync triggers, so writes are recomputed at once.
    commitWorks at once (needs the preload in every writing backend).
    manualResults are as dumped; call improv.recalc() when you want them current.
  5. Verify:

    -- every model: no error; logical ones rebuilt once and on improv_db
    SELECT m.name, s.sync_mode, s.slot, s.rebuilds, s.last_error
      FROM improv.model m, improv.status(m.name) s;
    -- the slot exists and is healthy
    SELECT slot_name, wal_status FROM pg_replication_slots WHERE slot_name = 'improv_db';
    -- no result cell differs from a fresh computation (an empty what_if)
    SELECT m.name, count(w.*) AS stale
      FROM improv.model m LEFT JOIN LATERAL improv.what_if(m.name, '[]') w ON true
     GROUP BY 1;
    

    stale must be 0 for every model. Then write one row into a bound table of a logical model and check that its result follows within a second.

    In the test run, the restored results' sums matched the source for all four models. Every model had 0 stale cells. The worker created the slot and rebuilt the logical model once. A new row then appeared in each mode's results: at once in trigger and commit, within 2 s in logical, and after recalc in manual.

Base backups and point-in-time recovery

pg_basebackup and file-level backups (pgBackRest, Barman, WAL-G) copy the improv catalog and the result tables, which are ordinary tables. They do not copy the replication slot: pg_basebackup leaves pg_replslot empty. A server started from a base backup, or recovered to a point in time, therefore has no improv_db slot.

  1. Restore and start the server as your tool documents. Keep shared_preload_libraries, wal_level = logical and improv.database in its configuration.
  2. Expect one rebuild per logical model. Once the server is out of recovery, the worker creates a new slot, resets every logical model's position and rebuilds it from its tables as they are at the recovery point. Writes between that point and the slot's creation are already in the tables, so the rebuild includes them.
  3. Verify: the same queries as after pg_restore. In the test, pg_replication_slots was empty right after the start and showed improv_db reserved 4 s later, with rebuilds up by one and a new row followed within a second.

A standby that is promoted is the same case; see failover below.

pg_upgrade

pg_upgrade copies logical slots only from a PG 17 or later old cluster, and only when they are caught up. The simple, safe procedure, on every version:

  1. Stop writes to the bound tables, and wait until lag_bytes in improv.status stops falling.

  2. Drop the slot. Stop the worker and drop the slot in quick succession, because the worker holds the slot while it polls:

    SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE backend_type = 'pg_improv sync';
    SELECT pg_drop_replication_slot('improv_db');
    
  3. Install the same pg_improv version for the new major version, run pg_upgrade, and start the new cluster with the same pg_improv settings.

  4. The worker creates a new slot and rebuilds each logical model once. Then upgrade the extension if you are also changing its version (ALTER EXTENSION pg_improv UPDATE).

  5. Verify: as after pg_restore.

The full procedure, tested by tests/pg_upgrade.sh, is task D2 in the road to 1.0. The pg_improv README carries it once it lands.

Failover to a standby

The result tables replicate to physical standbys like any table, so reads on a standby see the results as of its replay position. The worker does not run on a standby. Logical slots are not carried over to a standby unless they are PG 17+ failover slots, which pg_improv does not create yet. After a promotion:

  1. The new primary has no improv_db slot. Once it is out of recovery, the worker (if the preload and improv.database are configured on it) creates one and rebuilds each logical model.
  2. On the old primary, if it comes back, drop its improv_db slot before it rejoins as a standby, or it retains WAL.
  3. Verify: as after pg_restore, on the new primary.

The tested procedure (tests/failover.sh, with failover slots on PG 17+) is task D1 in the road to 1.0, and lands in the pg_improv README.

Moving a model to another database

There is no export function. A model is its catalog rows plus its bound tables, so the move is: copy the tables, then replay the model's definition in the target database.

  1. Copy the bound tables to the target database (any way you like):

    pg_dump -d shop -t sales | psql -d shop2
    
  2. Generate the model's definition from the source catalog. This query prints the calls that rebuild it: create the model in manual mode, bind the categories and measures in their original order, define the named LAMBDAs and derived measures, and set the original mode.

    -- psql -d shop -qAt -v model=plan -f gen_model.sql > plan.sql
    SELECT stmt FROM (
      SELECT 0 AS o, 0 AS k, format('SELECT improv.create_model(%L);', m.name) AS stmt
        FROM improv.model m WHERE m.name = :'model'
      UNION ALL
      SELECT 1, 0, format('SELECT improv.set_sync_mode(%L, ''manual'');', m.name)
        FROM improv.model m WHERE m.name = :'model'
      UNION ALL
      SELECT 2, c.id, format('SELECT improv.bind_category(%L, %L, %L, %L);',
                             m.name, c.name, cb.rel::text, cb.col)
        FROM improv.model m JOIN improv.category c ON c.model_id = m.id
        JOIN improv.category_binding cb ON cb.model_id = m.id AND cb.category_id = c.id
       WHERE m.name = :'model'
      UNION ALL
      SELECT 3, me.id, format('SELECT improv.bind_measure(%L, %L, %L, %L%s);',
                              m.name, me.name, b.rel::text, b.value_col,
                              CASE WHEN b.agg IS NULL THEN '' ELSE format(', agg => %L', b.agg) END)
        FROM improv.model m JOIN improv.measure me ON me.model_id = m.id
        JOIN improv.binding b ON b.model_id = m.id AND b.measure_id = me.id
       WHERE m.name = :'model'
      UNION ALL
      SELECT 4, l.id, format('SELECT improv.define(%L, %L);', m.name, l.definition)
        FROM improv.model m JOIN improv.lambda l ON l.model_id = m.id WHERE m.name = :'model'
      UNION ALL
      SELECT 5, me.id, format('SELECT improv.define(%L, %L);', m.name, me.formula)
        FROM improv.model m JOIN improv.measure me ON me.model_id = m.id
       WHERE m.name = :'model' AND me.kind = 'derived'
      UNION ALL
      SELECT 6, 0, format('SELECT improv.set_sync_mode(%L, %L);', m.name, m.sync_mode)
        FROM improv.model m WHERE m.name = :'model'
    ) s ORDER BY o, k;
    

    It covers bound models. A model with unbound input cells (improv.cell), saved views or scenarios keeps those in catalog rows this query does not replay. For such a model, open it with the CLI and copy the cells, or move the whole database with pg_dump. If one derived measure reads another defined later, reorder the define lines (they are emitted in measure-id order).

  3. Replay it in the target, with the extension installed:

    psql -d shop2 -v ON_ERROR_STOP=1 -f plan.sql
    psql -d shop2 -c "SELECT improv.recalc('plan')"
    
  4. Logical mode only works in the database named by improv.database. One worker serves one database per server. On 0.10.0 and main, set_sync_mode(…, 'logical') succeeds in any other database, and status even shows slot = improv_db with no error, but nothing ever applies its changes. 0.11 refuses it (D12 in the road to 1.0). Moving the logical model to another database of the same server means changing improv.database (a restart). Otherwise use trigger, commit or manual mode there.

  5. Verify: compare every result table between the two databases:

    for t in revenue total; do
      diff <(psql -d shop  -Atc "TABLE improv_plan.$t ORDER BY 1, 2") \
           <(psql -d shop2 -Atc "TABLE improv_plan.$t ORDER BY 1, 2") && echo "$t identical"
    done
    

    Then drop the model in the source with SELECT improv.drop_model('plan'). That removes its catalog rows, result schema and triggers, and takes its tables out of the publication.

In the test the generated script recreated a two-category, four-measure model, and both result tables were identical in the two databases.

Store files (Mentat)

A store file is a SQLite database in WAL mode. While a program has it open there are three files: model.db, model.db-wal and model.db-shm. Recent commits can live only in -wal until a checkpoint copies them back. Copying model.db alone while a program has it open can lose recent changes or produce a broken copy. When every program that had it open has exited cleanly, only model.db remains, and a plain copy is safe.

With the app closed:

  1. Quit the GUI, TUI and server, and wait for any CLI command to finish.

  2. Check that no model.db-wal exists, then copy:

    ls model.db-wal 2>/dev/null && echo "still open somewhere" || cp model.db backup.db
    

While it is in use, with VACUUM INTO: SQLite writes a consistent, compacted copy as of one moment, without stopping writers:

sqlite3 'file:model.db?mode=ro' "VACUUM INTO 'backup-$(date +%F).db'"
# or, without the sqlite3 tool:
python3 -c "import sqlite3; sqlite3.connect('file:model.db?mode=ro', uri=True).execute(\"VACUUM INTO 'backup.db'\")"

The copy is a single file in rollback-journal mode. Improv switches it to WAL the first time it opens it.

Verify either copy:

python3 -c "import sqlite3; print(sqlite3.connect('backup.db').execute('PRAGMA integrity_check').fetchone()[0])"   # ok
improv list backup.db | head
improv eval backup.db <measure-id>

In the test, VACUUM INTO ran while a loop of improv set commands kept writing the store. The copy passed integrity_check, and improv eval read a consistent earlier state from it. The plain copy, made after the last command exited and with no -wal file present, evaluated to the original's values.

Restore by copying the backup over model.db (with every program closed), and delete any stale model.db-wal and model.db-shm next to it first.

Autosave. The GUI writes the model to its store after every change to the model: each cell edit, formula, import, undo or redo, and Save View (a pivot by itself changes the layout, not the model, and is kept only as a saved view). The TUI writes when you save a view, press w, and quit. The CLI writes once per command. The GUI saves in the background; its title has a trailing • until the store has every edit. An autosave that fails is shown in the status line, the edit stays in the window, and the next save (or File ▸ Save) writes it. Your backups are therefore current as of the last edit, not the last explicit save. If another program saved the same store in between, the save is refused with a conflict instead of overwriting it, and the GUI saves nothing more until you reload: use File ▸ Revert to Saved (GUI) or R (TUI), then redo the edit.

Large stores: an edit saves only what it changed (milliseconds for a cell, even at 1M cells), but a full save (an import, a refresh) of a 1M-cell store takes about 8 s. Use VACUUM INTO, which copies at file speed, rather than improv export and re-import for backups.

Operations Runbook

This runbook covers incidents for whoever is on call for a Postgres database with pg_improv in it. Each entry is symptom → cause → diagnosis → fix, and ends with how to check the fix. It describes pg_improv 0.11.0 (main); where a fix in the road to 1.0 changes the procedure, the entry says so. Monitoring has the signals and alerts these entries start from.

Two queries come up in most entries:

-- every model at a glance
SELECT m.name, s.sync_mode, s.lag_bytes, s.last_applied_at, s.rebuilds,
       s.incremental_applies, s.last_error
  FROM improv.model m, improv.status(m.name) s;

-- the slot and the worker
SELECT slot_name, active_pid, wal_status, safe_wal_size,
       pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) AS retained
  FROM pg_replication_slots WHERE slot_name = 'improv_db';
SELECT pid, datname, backend_start FROM pg_stat_activity
 WHERE backend_type = 'pg_improv sync';

Restarting the worker is always safe: it re-applies only what no model has recorded, and the postmaster starts it again 5 s after it exits.

SELECT pg_terminate_backend(pid) FROM pg_stat_activity
 WHERE backend_type = 'pg_improv sync';

The worker stopped

Symptom. Logical-mode results stop following writes. lag_bytes grows for every logical model, and pg_stat_activity has no pg_improv sync row, or its backend_start keeps resetting.

Causes.

  • pg_improv is not in shared_preload_libraries (often after a config rewrite or an upgrade). Without the preload there is no worker at all.
  • improv.database names another database, or one that does not exist. The server log then shows FATAL: database "<name>" does not exist every 5 s.
  • The worker crashes during each poll (a crash loop).
  • max_worker_processes had no room at the last start: see the worker never started.

Diagnosis.

SHOW shared_preload_libraries;      -- must contain pg_improv
SHOW improv.database;               -- must be this database
SELECT current_database();

Then read the server log for the worker's lines (pg_improv sync) and for background worker "pg_improv sync" … exited.

Fix. Set shared_preload_libraries = 'pg_improv' and improv.database = '<db>' in postgresql.conf, then restart Postgres (both settings are read at server start). For a crash loop, the last pg_improv sync: … line before each exit names the model or step: put that model in manual mode (SELECT improv.set_sync_mode('<m>', 'manual')) to get the others going, and see the entries below.

Check. One pg_improv sync row in pg_stat_activity with a stable backend_start, and lag_bytes falling.

The worker never started (max_worker_processes)

Symptom. Logical-mode results stop following writes after a restart. pg_stat_activity has no pg_improv sync row, and every logical model's last_error reads the sync worker is not running: if the server log says "too many background workers", raise max_worker_processes (now N) and restart.

Cause. The worker is a background worker registered at server start, and max_worker_processes had no slot left for it: other extensions' workers, parallel query, and the logical replication launcher share the same pool. The postmaster logs the failure once at start and does not retry, so there is no crash loop and no other log line.

Diagnosis.

SHOW max_worker_processes;
SELECT backend_type, count(*) FROM pg_stat_activity GROUP BY 1;

The server log from the last start has LOG: too many background workers with the hint Consider increasing the configuration parameter "max_worker_processes".

Fix. Raise max_worker_processes (it takes a restart) to cover every registered worker plus max_parallel_workers. Nothing is lost while the worker is away: the slot keeps the WAL, up to max_slot_wal_keep_size (see the slot is lost if it ran past that).

Check. One pg_improv sync row, last_error NULL, and the writes made meanwhile applied.

Disk full while writing results

Symptom. A logical model's last_error reads could not extend file "base/…": No space left on device, and the server log repeats pg_improv sync: model <m>: could not extend file …, further and further apart. In trigger or commit mode, writers to the model's bound tables get the same error and their statements roll back.

Cause. The tablespace holding the model's result tables (improv_<m>.*) is full.

What pg_improv does. The failed apply rolls back: no result row is half-written, and the slot does not move past the batch. The worker keeps running and keeps the models that still fit in sync, and retries the failing model with backoff (0.5 s, doubling to 60 s). A full pg_wal is different: Postgres itself stops (PANIC) until there is room; then recovery runs, and the worker resumes from its slot.

Fix. Free space or grow the volume. To move a model's results elsewhere, put its tables in another tablespace: ALTER TABLE improv_<m>.<measure> SET TABLESPACE <ts> as the model's owner. The next retry (at most 60 s later) rebuilds the model; restart the worker to retry at once.

Check. last_error is NULL and rebuilds went up by one.

wal_keep_size and the slot

wal_keep_size does not limit the slot. A slot keeps the WAL it needs whatever wal_keep_size says (0 included), so lowering it does not make a stopped worker lose changes, and it does not stop the slot from retaining WAL either. The caps are max_slot_wal_keep_size (while the worker is down) and improv.max_slot_lag (while it runs but lags); see slot lag growing.

A model is stuck with last_error

Symptom. improv.status('<m>') shows a non-NULL last_error, and the model's results are stale. The server log repeats pg_improv sync: model <m>: <error>, further and further apart (the retry backs off from 0.5 s to 60 s). Other models are not affected.

Causes. Whatever the error says. The common ones:

  • … bound input cells exceed improv.max_cells = N: the model grew past the cell budget.
  • the live state needs about N MB …, over improv.max_model_memory = C MB: the model's fold state plus engine outgrew the memory cap. Raise the cap (reload) if the server has the memory, or split the model.
  • A permission error on a result table or a bound table (the result table was altered or its grants changed by hand).
  • A result table changed by hand: a CHECK constraint, a dropped column, or a changed value type.
  • A formula that compiles but fails at load: a bound column that was dropped or retyped.

Diagnosis.

SELECT last_error FROM improv.status('<m>');
SELECT improv.recalc('<m>');   -- runs the same load in your session: the error, with context

Fix. Fix the cause, then wait: the next retry (at most 60 s later) rebuilds the model from its tables and clears last_error. To retry at once, restart the worker. For improv.max_cells, size the memory first (capacity), then raise it in postgresql.conf and reload, or split the model. The worker reads it per load, but it must be restarted to see a reload on 0.10.0 and main (D9).

Check. last_error is NULL, rebuilds went up by one, and last_applied_at is recent.

Slot lag growing and the disk filling

Symptom. pg_wal grows. The slot's retained and the models' lag_bytes keep rising, and safe_wal_size falls.

Causes.

  • The worker is stopped (see above) or serves another database.
  • The worker cannot keep up: a slow model, a rebuild loop, or more changed rows per second than one core applies (see slow apply).
  • Every poll fails to read the slot (pg_improv sync: reading improv_db: … in the log).

The slot keeps all of the server's WAL from its restart point, not only the bound tables'. A stopped worker therefore retains WAL at the server's full write rate (capacity).

Diagnosis. The two queries at the top, plus the server log's pg_improv sync: lines from the last minutes.

Fix.

  1. If the worker is stopped, start it (above).

  2. If one model is slow or rebuilding, take it out of logical mode for now with SELECT improv.set_sync_mode('<m>', 'manual'), so the others catch up, and refresh it with improv.recalc('<m>') on a schedule.

  3. If the disk will fill before the worker catches up, give up the slot. Dropping it costs one rebuild per logical model and loses no data:

    SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE backend_type = 'pg_improv sync';
    SELECT pg_drop_replication_slot('improv_db');   -- right after: the worker holds it while polling
    

    If the drop fails with replication slot "improv_db" is active for PID …, the worker restarted in between: run both statements again, together.

  4. Prevent it next time: set max_slot_wal_keep_size (Postgres then invalidates the slot instead of filling the disk; see the next entry) and alert on retained WAL.

Check. retained drops to a few MB and stays there. If you dropped the slot, improv_db comes back within a poll and every logical model shows one more rebuild.

The slot is lost

Symptom. pg_replication_slots.wal_status = 'lost' for improv_db (invalidation_reason = 'wal_removed'). Logical-mode results have stopped following writes. improv.status shows no last_error, and its lag_bytes stays at its last value. The server log repeats, every poll: pg_improv sync: reading improv_db: … can no longer access replication slot "improv_db" with This replication slot has been invalidated due to "wal_removed".

Cause. The worker fell behind, or was down, by more than max_slot_wal_keep_size, and Postgres removed WAL the slot still needed. On 0.10.0 and main the worker does not recover by itself.

Fix (0.10.0 and main). Stop the worker and drop the slot, in that order and at once:

SELECT pg_terminate_backend(pid, 5000) FROM pg_stat_activity
 WHERE backend_type = 'pg_improv sync';
SELECT pg_drop_replication_slot('improv_db');

The restarted worker creates a new slot, resets every logical model's position and rebuilds each from its tables, so the results are exact again. In 0.11, D11 makes this automatic: the worker recreates a lost slot, rebuilds the models and reports it in status.

Check. wal_status = 'reserved', every logical model's rebuilds went up by one, and a test write to a bound table shows up in its results. This was tested on PG 18.6: after the fix, writes made while the slot was lost were in the results, and so were writes made after it.

A rebuild loop

Symptom. rebuilds rises with almost every batch, and incremental_applies stays flat. The log shows pg_improv sync: model <m>: rebuilding (<reason>) again and again. Apply latency equals a full load (seconds on large models), and the other models wait behind it.

Causes, by the reason in the log line (the full list is in Monitoring):

  • new item in a category a formula enumerates: writes keep adding new dimension values (a new day, a new order id) to a category that a PREV, POSITION, RANK, FILL, window or similar formula reads the item list of.
  • two rows on one coordinate: a measure bound without agg gets duplicate keys.
  • nondeterministic collation: a text min, max or count_distinct binding over a column with a nondeterministic (case- or accent-insensitive) collation changes. Bind a deterministic column, or use trigger or commit mode for that model.
  • truncate: the bound table is truncated and reloaded.
  • old row not replicated: UPDATE or DELETE statements on a table without REPLICA IDENTITY FULL (set it).
  • model changed: something keeps calling define or bind_* (a migration in a loop).

Fix. For new items, move the item-list-reading formula to a separate model in manual mode refreshed on a schedule, or bind the fast-growing column to a category that only simple reductions read. For duplicates, rebind with an aggregate: SELECT improv.bind_measure('<m>', '<measure>', '<table>', '<col>', agg => 'sum'). For TRUNCATE and reload, switch to manual, load, recalc, switch back. For text min/max, accept it or bind a numeric column.

Check. Over 15 minutes of normal writes, incremental_applies rises and rebuilds does not.

A slow apply

Symptom. Results lag the commit by seconds rather than a poll. With several models, all of them lag at once.

Causes.

  • One large model rebuilds (above), or its batches write many result rows. The worker loads and writes models one after the other, so every model waits for that. A model whose batches take long in its formulas delays only its own results: each model's engine computes on its own thread (B1).
  • Huge transactions: one transaction changing millions of rows is applied as one batch.
  • A per-item reduction (RANK, SORT) over a category with very many items: one edit re-reads the whole group (seconds at 1M items).
  • improv.poll_ms set high.

Diagnosis. Compare last_applied_at across models: the slow one is recent while the others are stale. The server log's rebuilding lines name rebuilds. For a closer look, time improv.recalc('<m>') in a session, which is the cost of one rebuild.

Fix. Put the slow model in manual mode and refresh it on a schedule, or give it its own database (and server). Break bulk loads into batches of 10k–100k rows. Lower improv.poll_ms if it was raised. The default is 200 ms; in 0.11 a reload applies the change (D9), while on 0.10.0 and main the worker must be restarted for it to take effect.

Check. A 1,000-row batch is visible within about two polls.

Out of memory

Symptom. The server log shows server process (PID …) was terminated by signal 9: Killed for the pg_improv sync worker, or the kernel log shows the OOM killer choosing it. Postgres then restarts every backend (crash recovery), and the worker rebuilds every model, which can be killed again.

Cause. The worker holds every logical model's fold state and engine. For aggregated bindings that is about 180 B per fact row plus 0.8 kB per cell (capacity). A model that grew, or several large models in one database, can exceed the server's memory. Trigger and commit recomputes and recalc load the model in the writer's backend, so those can run out of memory too.

Diagnosis. RssAnon of the worker (grep RssAnon /proc/<pid>/status) against the server's memory, and each model's fold_bytes + engine_bytes in improv.status (monitoring). In-backend recomputes show up as large RssAnon on writers' backends.

Fix.

  1. Stop the loop. Put the largest models in manual mode (from any session: SELECT improv.set_sync_mode('<m>', 'manual')). If Postgres keeps restarting, temporarily set improv.database to a database with no models and restart.
  2. Set improv.max_model_memory (MB) so an oversized model fails with a clear last_error instead of exhausting memory. It caps each model's fold state plus engine, which improv.status reports as fold_bytes and engine_bytes, so it bounds a heavily aggregated binding too. improv.max_cells counts bound input cells (coordinates after aggregation), not fact rows.
  3. Add memory, or split the model, then return it to logical.

Check. The worker's RssAnon is stable through a day of writes.

A stale publication

Symptom. A bound table's writes never reach its logical model: incremental_applies does not move after writes to that table, while other tables work. Or the log shows pg_improv sync: creating the publication improv_db: ….

Cause. The publication improv_db was edited by hand (ALTER PUBLICATION … DROP TABLE, DROP PUBLICATION), or a restore or replication tool rewrote it.

Diagnosis.

SELECT * FROM pg_publication_tables WHERE pubname = 'improv_db';
-- against what the logical models bind
SELECT DISTINCT b.rel FROM improv.binding b JOIN improv.model m ON m.id = b.model_id
 WHERE m.sync_mode = 'logical';

Fix.

SELECT improv.sync_publication();

It sets the publication to exactly the union of the logical models' tables, creating it if it is missing. Changes to a table made while it was out of the publication were never decoded, so rebuild the affected models once: define them again, or switch each to manual and back to logical.

Check. The two queries list the same tables, and a test write moves the model's incremental_applies.

Logical mode in the wrong database

Symptom. A model reports sync_mode = logical and slot = improv_db with no error, but its results never change.

Cause. Its database is not the one in improv.database. One worker serves one database per server. On 0.10.0 and main, set_sync_mode accepts logical anywhere, and status reports the other database's slot. 0.11 refuses it (D12).

Fix. Use trigger, commit or manual in that database, or move the model (runbook).

Permission denied for an improv model

Symptom. A role gets permission denied for improv model "m": only a superuser or a member of its owner, alice, may change it (from define, bind_*, recalc, set_sync_mode, drop_*), or … what_if needs to act as its owner, alice (see Privileges). Or it reads 0 rows from improv.item or improv.cell for a model it can see in improv.model.

Cause. Since 0.11.0 only a role that may act as a model's owner (a superuser, or a member of the owner with SET; any member on PG 15) changes the model, runs what_if on it, or reads its items and cells. Writers to bound tables are unaffected.

Diagnosis.

SELECT owner, improv.may_act_as(owner) FROM improv.model WHERE name = '<m>';

Fix. The model's owner decides. To let a co-owner change the model, GRANT alice TO <role> WITH INHERIT FALSE, SET TRUE (PG 15: GRANT alice TO <role>). To give a read-only analyst what_if on one model and nothing else, the owner creates a SECURITY DEFINER wrapper and grants EXECUTE on it. The text is in the pg_improv README's Privileges. Either way the role sees results computed from what the owner can read.

Check. The diagnosis query returns t for the role (option a), or the role's call to the wrapper returns rows (option b).

An upgrade went wrong

Symptom. After installing a new release: ALTER EXTENSION pg_improv UPDATE fails; or CREATE EXTENSION/the worker complain about a version mismatch; or the worker does nothing.

Causes and fixes.

  • Postgres was not restarted after installing. The preloaded library is still the old one. Restart, then run ALTER EXTENSION pg_improv UPDATE.

  • Mixed versions: the .so is new, the SQL objects old (or the reverse). Check both:

    SELECT extversion FROM pg_extension WHERE extname = 'pg_improv';
    SELECT default_version FROM pg_available_extensions WHERE name = 'pg_improv';
    

    They must match after ALTER EXTENSION … UPDATE. The worker does nothing until the catalog is at 0.11.0 or later (it waits for improv.sync_publication() to exist).

  • The update script failed. It runs in one transaction, so nothing changed. Read the error, fix it (often a hand-made object in the improv schema), and run it again.

  • After 0.10.0 → 0.11.0: the update drops the old improv_<model> publications and queues their slots, the worker drops them and creates improv_db, and every logical model rebuilds once. Until that finishes, results lag. pg_improv sync: dropping queued slots: … in the log means an old slot is still in use; drop it by hand once nothing holds it.

  • Going back: there are no downgrade scripts. Restore the pre-upgrade backup (runbook).

Check. extversion equals default_version, improv.status shows slot = improv_db for every logical model, and no improv_<model> slot remains in pg_replication_slots.

The tested upgrade matrix from every released version is D6 in the plan. The README's upgrade section is in the pg_improv README.

Removing pg_improv cleanly

On every version, drop the models first and the extension second. Tested on 0.11.0, DROP EXTENSION pg_improv CASCADE alone, with a logical model present, left the replication slot improv_db, the publication improv_db, the result schemas improv_<model>, and REPLICA IDENTITY FULL on the bound tables. The slot is the dangerous part: no worker serves it any more, so it retains WAL forever. In 0.11 the worker drops an orphaned improv_db slot and publication once the extension is gone (D13 in the plan). Result schemas stay in every version, because they are your data.

  1. Drop every model, while the extension still works. This removes their result schemas and triggers and empties the publication, and the worker then drops the slot on its next poll:

    SELECT improv.drop_model(name) FROM improv.model;
    
  2. Drop the extension: DROP EXTENSION pg_improv; (no CASCADE needed once the models are gone).

  3. Remove the preload: delete pg_improv from shared_preload_libraries and the improv.* settings from postgresql.conf, then restart. Until then the worker keeps running and idles.

  4. Optionally, reset the replica identity of tables that had no primary key with ALTER TABLE <t> REPLICA IDENTITY DEFAULT. The worker set FULL on bound tables without one.

Check.

SELECT nspname FROM pg_namespace WHERE nspname LIKE 'improv%';             -- none (or only improv, if your own tables live there)
SELECT slot_name FROM pg_replication_slots WHERE slot_name LIKE 'improv%';  -- none
SELECT pubname FROM pg_publication WHERE pubname LIKE 'improv%';           -- none
SELECT lanname FROM pg_language WHERE lanname = 'improv';                  -- none

Your bound tables and their rows are untouched. This procedure was tested on PG 18.6, and every check above returned nothing.

Recovering an orphaned slot (0.10.0 and main). If the extension was dropped first and improv_db (or a pre-0.11 improv_<model> slot) is still in pg_replication_slots, drop it once the worker no longer holds it, and drop the publication. Stopping the worker first makes sure it does not hold the slot:

SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE backend_type = 'pg_improv sync';
SELECT pg_drop_replication_slot(slot_name) FROM pg_replication_slots
 WHERE slot_name = 'improv_db' OR slot_name LIKE 'improv\_%';
DROP PUBLICATION IF EXISTS improv_db;
DROP SCHEMA improv_<model> CASCADE;   -- only if you do not want the old results

Troubleshooting and FAQ

This page is for anyone whose formula, command or model does not do what they expected. Look up the message you got, or the symptom. Messages are quoted as Improv prints them; <…> marks the part that changes.

Formula errors

A formula is checked in two steps. Each has its own kind of message.

  1. Parsing reads the text and resolves every name against the model. Its errors carry a position, a byte offset into the text you typed (counting from 0, the target name included): parse error at 18: unknown measure: Quantty points at the Q. The GUI and TUI underline that spot (The Desktop GUI).
  2. Compiling checks the types and the dimensions of the whole expression. Its errors have no position; they name the measures and categories involved. They start with type mismatch:, dimension mismatch: or unsupported:.

The grammar itself is in The Formula Language.

Parse errors

MessageMeansFix
unknown measure: <name>No measure has that name. Names are case-sensitive (price is not Price). Often a typo, or a measure defined later in a script.Check the spelling with improv list, or define the other measure first.
unknown category: <name>The name after OVER, or a category argument, is not a category.As above.
unknown function: <name>; did you mean <a>, <b>?Not one of the built-in functions or the model's named LAMBDAs.Use a suggested name, or see the Function Reference.
unknown qualifier: <x> (no such matrix; …)X.Name was written; there are no matrix-qualified names.Write the name alone.
expected ')', expected ')' to close function call, expected ']' to close dimension listA bracket is not closed. The position is where the parser gave up, usually the end.Close it. In the GUI, the ( that was never closed is underlined.
unexpected end of inputThe expression stops early: 1 +.Finish it.
unexpected trailing inputSomething follows a complete expression. Common causes are two expressions side by side, a missing operator, or 1e-10 (there are no exponent literals yet).Add the operator, or write 0.0000000001.
unexpected operator: <op>An operator where a value should be: * 2.
unexpected character: <c>A character that is not part of the language.Quote a name with spaces as 'Unit Price'.
expected '=' after target measure name, formula must start with a target measure nameA definition needs Target = expression.improv add-derived takes the expression alone; improv define and the GUI take the whole definition.
unterminated string literal, unterminated quoted name, unterminated date literalA ", ' or # is not closed.
invalid date: "<text>", invalid number: <text>#2025-13-01# is not a date; a number is malformed.Dates are #YYYY-MM-DD#.
expected '(' after function nameA function name without its argument list.
<NAME> takes <n> argument(s), got <m>Wrong argument count for a fixed-arity function. The GUI spells out the parameters.
only one OVER clause per aggregation, only one INTO clause per callSUM(X OVER A OVER B).List several categories in one clause: OVER A, B.
<NAME> does not aggregate OVER a category, <NAME> cannot take a windowOVER given to a function that is not a reduction, or a window to one that cannot take one.
expected FIRST, LAST or THIS in a window, expected '..' in a window: OVER T[FIRST..THIS]A malformed running window.OVER Time[FIRST..THIS].
FIXPOINT needs LAMBDA(r, body), LAMBDA needs at least one parameter, <NAME> needs LAMBDA(row, body)A higher-order function without its LAMBDA.
expression nested too deeplyMore than the parser's nesting limit (320 nested parentheses, calls or unary operators).Split it into intermediate measures, or LET.
formula nests too deeply (N levels; the limit is 256)The formula's tree is deeper than 256 levels: a chain of more than 256 + terms, say, or deep nesting. See Limits.Split it into intermediate measures, or use SUM(...) instead of a long + chain.
formula is too large (more than 100000 terms once LET and LAMBDA are expanded)LET and LAMBDA copy a value at each use, so bindings that each use the previous one twice double the formula.Make the repeated part its own measure.
empty formula, empty expressionNothing to parse.

A model saved before 0.11 can hold a formula past these limits:

SymptomMeansFix
A measure shows #REF! everywhere; its description starts [unreadable formula]Its stored formula is too deep to read back (embedded store). The rest of the model loads.Redefine it: improv add-derived or improv define with the same id.
measure X: formula nests too deeply (N levels; the limit is 256); drop it …A Postgres model's text formula is deeper than the load bound. Nothing that builds the model works until it is fixed.SELECT improv.define('model', 'X = …', replace => true) with a shallower formula, or SELECT improv.drop_measure('model', 'X').

Compile errors

Message (start)MeansFix
dimension mismatch: <A> ranges over [<x>] and <B> over [<y>]: they share no category, so no cell has both …Two operands whose categories are not a subset one of the other: Price[Product] + Headcount[Region]. Improv will not guess how to line them up.Reduce one first (SUM(Headcount OVER Region)), or give both a common category.
dimension mismatch: <M>[…] leaves out category <C>, which only an aggregation can collapse: write SUM(<M> OVER <C>) …A plain reference must keep all of its measure's categories: X = Quantity[Product].Say what to do with the left-out category: SUM(Quantity OVER Time).
dimension mismatch: <F> arguments not broadcastable: one ranges over …, another over …A function's arguments have unrelated categories.As for operands.
dimension mismatch: <F>: the measures reduced together must range over the same categories …A multi-measure reduction (CORREL, SUMPRODUCT, …) over measures with different categories.
dimension mismatch: <F>: the WHERE condition ranges over categories the measure does notSUM(X OVER T WHERE Y > 0) where Y has categories X lacks.
type mismatch: <Op> requires NumberArithmetic on text or booleans: Label * 2.Convert (VALUE(Label)), or check the measure's type with improv list.
type mismatch: IF test must be Boolean, got NumberIF(Price, …).Compare: IF(Price > 0, …).
type mismatch: IF branches must have the same type, got Number and TextOne branch is a number, the other text.Make both the same type (TEXT(Price, "0"), or NA() for "no value").
type mismatch: <F> argument <n> must be <type>, got <type>A function was given the wrong type.
unsupported: <M> refers to itself; only PREV may read its earlier values …Balance = Balance + Flow.Write the recurrence with PREV(Balance, Time, 1, 0) + Flow.
unsupported: <F> returns a list: say where it lands, <F>(… INTO Category)SORT, UNIQUE, FILTER and similar return several values.Add INTO a category for the positions (List results).
unsupported: <F> over a window or per item takes exactly one OVER categoryRANK(X OVER Time, Product).Rank over one category.
unsupported: FIXPOINT must be a measure's whole formula …, FIXPOINT may not read its own measure …FIXPOINT inside a larger expression, or reading its target.Define it as its own measure; use r for the iterate.
unknown measure referenced in formula: MeasureId(<n>)A saved formula refers to a measure that was deleted.Redefine the formula.
formula cycle: <A> → <B> → <A>Measures read each other in a circle (A reads B, B reads A). In 0.11 improv define refuses the definition that closes the cycle (G4), as the GUI and pg_improv's define already do.Break the cycle (use PREV if it is a recurrence). Up to 0.10.0 the CLI saved such a definition, and eval of a measure in the cycle then failed with unsupported plan node in v1 dataflow builder: cyclic measure dependency at MeasureId(<n>).

Errors in values

An error is also a value: a cell can hold #DIV/0!, #NUM!, #VALUE! or #N/A, and it flows through every formula that reads it (Errors). If a total shows #DIV/0!, one of the cells it adds holds it. Find the cell with improv eval, and guard the division (IFERROR(A / B, 0), or IF(B = 0, NA(), A / B)).

Common modeling mistakes

  • Mixing categories that do not belong together. Price[Product] and Headcount[Region] do not combine, because no cell has both. If they should combine, the model is missing a category (Region of a Product) or a mapping measure. Add it, and sum over it.
  • Forgetting that a reduction removes a category. Total = SUM(Revenue OVER Time) has no Time. To show the total next to each year, the formula broadcasts it back: Share = Revenue / SUM(Revenue OVER Time).
  • Expecting a missing cell to be 0. Where an input has no cell, a formula has no cell either, and a reduction skips it. Use COALESCE(X, 0) or FILL(X, 0) when "missing" should count as zero (Missing cells).
  • Two rows for one coordinate in Postgres. A measure bound without agg needs one row per coordinate. A second row is an error (in recalc, trigger and commit modes) or a rebuild (in logical mode). Bind with agg => 'sum' (or count, avg, …).
  • A measure that never converges. FIXPOINT stops after max_iter rounds (default 100) and returns the last iterate. It never hangs, but it reports no error either. A body that grows without bound (r * 2) returns a huge number after max_iter rounds. If a result looks wrong, check that the step is a contraction (PageRank's damping below 1), and raise max_iter or the tolerance only after that. PREV recurrences run once along their category and always finish.
  • Exponent literals. 1e-10 is not a number yet. Write 0.0000000001 or 10^-10.
  • Per-item reductions over huge categories. RANK, SORT and the other per-item reductions re-read the whole group on each edit, so an edit costs seconds over a million items. Keep them on smaller categories, or in a separate model.

CLI errors

MessageMeans
error: no measure with id <n>Commands take measure ids, not names (improv list shows them).
error: measure <n> '<name>' is an input measure; use show to see its cellseval evaluates derived measures.
error: no item named '<item>' in category '<cat>'--at names items that must exist; add them with add-item.
error: measure <n> '<name>' is declared over [<cats>], but --at gave [<cats>] — missing <cat>set needs one item for every category of the measure.
error: value must be a number, got '<v>'set parses the value by the measure's declared type.
error: mentat error: SQL error: unable to open database file: <path> …The store path's directory does not exist, or is not writable.
error: postgres error: a postgres model URL needs ?model=<name> …A Postgres target names one model: postgres://me@db/sales?model=plan.
error: postgres error: postgres connect failed (connection error)The server is unreachable, or refused the connection (host, port, pg_hba.conf, password). The Postgres connection has no TLS yet; use a loopback port or an SSH tunnel.
save failed: … conflict … (GUI, TUI, server: 409)Someone else saved the same model after you loaded it. Your save was refused, not merged. Reload (File ▸ Revert to Saved, R in the TUI) and redo the edit.

Errors are printed on stderr after error:. improv help lists the commands and their arguments.

Why is this slow?

SymptomLikely causeWhat to do
Importing a large CSV (import-csv) or saving a large store file takes minutesBefore Improv 0.11 (Mentat 1.16.0), writing a store file was quadratic: 100k rows 21 s, 200k 91 s. Mentat 1.18.0 made it linear: 100k 7 s, 1M about 105 s. In 0.11 a cell edit saves only that cell (milliseconds at 1M cells), but opening a 1M-cell store still loads it all (about 5 s), and an import or refresh still rewrites the whole store (about 8 s at 1M cells)Upgrade to 0.11. For models of millions of cells that change often, keep the data in Postgres or DuckDB, bound with agg.
Opening a model is slowEvery open loads and evaluates the whole model (about 2–2.5 µs per cell to evaluate, plus the load)Normal for millions of cells; see capacity.
Every edit takes 100 ms or more on a model with thousands of measuresEach edit is one dataflow round that visits every tracked measure (129 ms at 20k simple measures)Split the model, or remove unused measures.
One edit takes secondsA SORT, RANK.AVG, RANK.DENSE, PERCENTRANK or other per-item reduction over a very large category (RANK and SORTBY with constant orders recompute only what moves), or an edit that changes a FIXPOINT's input (it re-solves)Move it to a smaller category or a separate model.
The first open after adding many items is slow, later edits fastA rebuild, because a formula reads the category's item listExpected; see Concepts.
Postgres: writes got slower after set_sync_modetrigger or commit mode makes the writer pay for the recompute (0.4 s per statement / 2.2 s per transaction on 2.5M rows)Use logical (When to use).
Postgres: logical results lag by secondsOne worker loads and writes every model in turn; a rebuild, or a model that writes many rows, delays all (a model slow in its formulas delays only itself)Operations runbook.
Postgres: recalc or a commit-mode commit is slowBoth reload the bound tables in full (about 1 s per million fact rows)Expected; use logical mode for large tables.
DuckDB: improv() is slow on many distinct coordinatesIt builds one engine cell per distinct coordinate (2.5M distinct cells: 4.5 s)Bind with an aggregate so DuckDB folds rows first (2.5M rows into 44,750 cells: 0.4 s).

Function Reference

Every built-in function, by category. Names are case-insensitive; [x] is optional ([x=1]: 1 if omitted), … repeats the arguments before it, x OVER T is reduced over a category and INTO K lays a list result along one. Positions are 1-based. An error argument (#DIV/0!, #N/A, …) makes the result that error, except in the functions that test for errors. See The Formula Language for operators, types and dimensions.

Aggregations

Written F(Measure OVER Category): collapse one category. Each also has a scalar form over its arguments, listed under its category.

FunctionReturnsDescription
SUM(values OVER T)numberthe sum over a category (also DSUM)
AVERAGE(values OVER T)numberthe mean over a category (also AVG, DAVERAGE)
MIN(values OVER T)numberthe smallest value over a category (also DMIN)
MAX(values OVER T)numberthe largest value over a category (also DMAX)
PRODUCT(values OVER T)numberthe product over a category (also DPRODUCT)
SUMSQ(values OVER T)numberthe sum of squares over a category
AND(values OVER T)booleanwhether every value over a category is true
OR(values OVER T)booleanwhether any value over a category is true
XOR(values OVER T)booleanwhether an odd number of values over a category are true
FIRST(values OVER T)the branches' typethe value at the first item (in category order) that has one
LAST(values OVER T)the branches' typethe value at the last item that has one
S(values OVER T)textthe first value, as text (Quantrix)
TEXTJOIN(delimiter, ignore_empty, values OVER T)textthe values in item order joined by the delimiter (skipping empty text when ignore_empty is TRUE)

Logical

IF and the functions built on it evaluate only the branch they choose, so an error or missing cell in the other branch does not matter.

FunctionReturnsDescription
AND(logical1, …)booleanwhether every argument is true
OR(logical1, …)booleanwhether any argument is true
XOR(logical1, …)booleanwhether an odd number of arguments are true
IF(logical_test, value_if_true, [value_if_false])the branches' typethen where the test is true, else (or no cell) where it is false
IFS(logical_test1, value_if_true1, …)the branches' typethe value paired with the first true test
SWITCH(expression, value1, result1, …, [default])the branches' typethe result paired with the first value equal to the expression, else the default
CHOOSE(index_num, value1, …)the branches' typethe index_num-th value (1-based)
IFERROR(value, value_if_error)the branches' typethe value, or the alternative where it is an error
IFNA(value, value_if_na)the branches' typethe value, or the alternative where it is #N/A
CLEARERROR(value, [alternative])the branches' typethe value, or the alternative (or no cell) where it is an error
CLEARZERO(value, [alternative])numberthe value, or the alternative (or no cell) where it is zero
COALESCE(value1, …, default)the branches' typea cell wherever any argument that reads a measure has one: the first argument with a cell, else the last (the default)
BETWEEN(x, low, high, [inclusive])booleanwhether low ≤ x ≤ high (strict when inclusive is FALSE)
TRUE()booleanTRUE
FALSE()booleanFALSE
SCAN(initial_value, array OVER T, lambda)the branches' typeSCAN(initial_value, array OVER T, LAMBDA(acc, v, body)): the running fold along T, one value per item
REDUCE(initial_value, array OVER T, lambda)the branches' typeREDUCE(initial_value, array OVER T, LAMBDA(acc, v, body)): the fold's last value
LET(name, value, …, body)the branches' typeLET(name, value, …, body): the body with each name bound to its value
LAMBDA(p, …, body)the branches' typeLAMBDA(p, …, body): a function of its parameters, called on the spot or passed to MAP, REDUCE or SCAN
MAKEARRAY(rows, cols, lambda)the branches' typeMAKEARRAY(rows, cols, LAMBDA(r, c, body)): the body over the categories rows × cols, with r and c the item positions
BYROW(array OVER C, lambda)the branches' typeBYROW(array OVER C, LAMBDA(row, body)): the body per item of array's other categories, row being the values along C (the body reduces it: SUM(row), …) (also BYCOL)
MAP(array1, …, lambda)the branches' typeMAP(array1, …, LAMBDA(p, …, body)): the body applied element by element

Information and errors

FunctionReturnsDescription
ISERROR(value)booleanwhether the value is any error
ISERR(value)booleanwhether the value is an error other than #N/A
ISNA(value)booleanwhether the value is #N/A
NA()numberthe #N/A error
ERROR(name)numberthe error a code names ("#DIV/0!")
ERROR.TYPE(error_val)number1 #NULL!, 2 #DIV/0!, 3 #VALUE!, 4 #REF!, 5 #NAME?, 6 #NUM!, 7 #N/A; #N/A for a non-error
ISBLANK(value)booleanwhether the value is blank: always FALSE for a value, since a missing cell has none (ISBLANK("") is FALSE) (also ISEMPTY)
ISNUMBER(value)booleanwhether the value is a number; a date is one, as in Excel
ISTEXT(value)booleanwhether the value is text
ISNONTEXT(value)booleanwhether the value is not text (TRUE for an error)
ISLOGICAL(value)booleanwhether the value is a boolean
ISDATE(value)booleanwhether the value is a date
ISNUMBERORDATE(value)booleanwhether the value is a number or a date
ISEVEN(number)booleanwhether the integer part is even (also ISEVEN_ADD)
ISODD(number)booleanwhether the integer part is odd (also ISODD_ADD)
N(value)numberthe value as a number: a date's serial number, TRUE 1, FALSE and text 0
T(value)textthe value if it is text, else ""
TYPE(value)number1 number (or date), 2 text, 4 boolean, 16 error

Math and trigonometry

Angles are in radians.

FunctionReturnsDescription
SUM(number1, …)numberthe sum of the arguments
AVERAGE(number1, …)numberthe mean of the arguments
MIN(number1, …)numberthe smallest argument (also MIN2)
MAX(number1, …)numberthe largest argument (also MAX2)
PRODUCT(number1, …)numberthe product of the arguments
SUMSQ(number1, …)numberthe sum of the squares of the arguments
ABS(number)numberabsolute value
NEG(number)numbernegation
SIGN(number)number−1, 0 or 1
SQRT(number)numbersquare root (#NUM! below zero)
SQRTPI(number)number√(x·π)
EXP(number)numbere to the power x
EXPM1(x)numbereˣ − 1, accurate near 0
LN(number)numbernatural logarithm
LN1P(x)numberln(1 + x), accurate near 0
LOG(number, [base=10])numberlogarithm to a base (default 10)
LOG10(number)numberbase-10 logarithm
LOG2(x)numberbase-2 logarithm
POWER(number, power)numbernumber raised to power (same as ^)
MOD(number, divisor)numberremainder, with the divisor's sign
QUOTIENT(numerator, denominator)numberinteger part of a quotient
PI()numberπ
DEGREES(angle)numberradians to degrees
RADIANS(angle)numberdegrees to radians
SIN(number)numbersine (radians)
COS(number)numbercosine
TAN(number)numbertangent
ASIN(number)numberarcsine
ACOS(number)numberarccosine
ATAN(number)numberarctangent
ATAN2(x_num, y_num)numberangle of the point (x, y)
SINH(number)numberhyperbolic sine
COSH(number)numberhyperbolic cosine
TANH(number)numberhyperbolic tangent
ASINH(number)numberinverse hyperbolic sine
ACOSH(number)numberinverse hyperbolic cosine
ATANH(number)numberinverse hyperbolic tangent
SEC(number)numbersecant
CSC(number)numbercosecant
COT(number)numbercotangent
SECH(number)numberhyperbolic secant
CSCH(number)numberhyperbolic cosecant
COTH(number)numberhyperbolic cotangent
ACOT(number)numberinverse cotangent
ACOTH(number)numberinverse hyperbolic cotangent
SINPI(x)numbersin(πx), exact at integers
COSPI(x)numbercos(πx), exact at integers
TANPI(x)numbertan(πx), exact at integers
COTPI(x)numbercot(πx), exact at integers
HYPOT(number1, …)number√(Σ xᵢ²) without overflow
FACT(number)numberfactorial
FACTDOUBLE(number)numberdouble factorial n!!
COMBIN(number, number_chosen)numbercombinations of number items taken number_chosen at a time
COMBINA(number, number_chosen)numbercombinations with repetition
PERMUT(number, number_chosen)numberpermutations of number items taken number_chosen at a time
PERMUTATIONA(number, number_chosen)numberpermutations with repetition
GCD(number1, …)numbergreatest common divisor
LCM(number1, …)numberleast common multiple
MULTINOMIAL(number1, …)number(Σ n)! / Π n!
RAWSUBTRACT(number1, …)numberthe first argument minus the rest
INVSUMINV(number1, …)number1 / Σ(1/xᵢ)
GAMMA(number)numberthe gamma function Γ(x)
GAMMALN(x)numberln Γ(x), for x > 0 (also GAMMALN.PRECISE)
BETA(x, y)numberthe Euler beta function B(a, b)
BETALN(x, y)numberln
DIGAMMA(x)numberthe digamma function ψ(x)
IGAMMA(a, x, [lower=TRUE], [regularize=TRUE], [real=TRUE])numberthe incomplete gamma function of a and x: lower (default) or upper, regularized (default) or not; the imaginary part (real = FALSE) is 0
POCHHAMMER(x, n)numberthe rising factorial Γ(x + n) / Γ(x)
ERF(lower_limit, [upper_limit])numberthe error function erf(x), or erf(upper) − erf(lower)
ERF.PRECISE(x)numberthe error function erf(x)
ERFC(x)numberthe complementary error function 1 − erf(x) (also ERFC.PRECISE)
SUMA(values OVER T)numberthe sum, counting TRUE as 1 and text as 0
SUMPRODUCT(array1, … OVER T)numberΣ xᵢ·yᵢ·… over the rows where every measure has a cell
SUMX2MY2(array_x, array_y OVER T)numberΣ(x² − y²)
SUMX2PY2(array_x, array_y OVER T)numberΣ(x² + y²)
SUMXMY2(array_x, array_y OVER T)numberΣ(x − y)²
SERIESSUM(x, n, m, coefficients OVER T)numberΣ cᵢ·x^(n + i·m), the coefficients c in item order (i from 0)
POLYNOMIAL(x, coefficients OVER T)numberΣ cᵢ·xⁱ, the coefficients c in item order (the constant c₀ first)
PERCENTOF(data_subset, data_all OVER T)numberΣ subset / Σ all
LAMBERTW(x, [k=0])numberthe Lambert W function: the w with w·eʷ = x, on branch k 0 (the default, x ≥ −1/e) or −1 (−1/e ≤ x < 0)
AGM(a, b)numberthe arithmetic-geometric mean of a, b ≥ 0
GD(x)numberthe Gudermannian function: 2·atan(tanh(x/2))
ILOG(x, [base=10])numberthe integer logarithm: the largest k with baseᵏ ≤ x, for x > 0 and an integer base ≥ 2 (default 10)
REDUCEPI(x, e, [q])numberx reduced modulo π/2ᵉ as if π were exact: the xr with x = xr + j·π/2ᵉ and
FIB(n)numberthe n-th Fibonacci number, n ≥ 1 (truncated); #NUM! past n = 1476, where it overflows
ISPRIME(n)booleanwhether n is prime (FALSE below 2)
ITHPRIME(i)numberthe i-th prime, i from 1 to 10⁷ (Gnumeric: 10⁸)
PFACTOR(n)numberthe smallest prime factor of n ≥ 2 (#VALUE! below 2)
NT_D(n)numberthe number of divisors of n ≥ 1
NT_SIGMA(n)numberthe sum of the divisors of n ≥ 1
NT_PHI(n)numberEuler's totient: how many of 1…n are coprime to n ≥ 1
NT_MU(n)numberthe Möbius function of n ≥ 1: 0 if a square divides n, else (−1)^(number of prime factors)
NT_OMEGA(n)numberthe number of distinct prime factors of n ≥ 1
NT_PI(n)numberhow many primes are ≤ n (0 below 2; n up to 179 424 673, the 10⁷-th prime)
NT_RADICAL(n)numberthe product of the distinct prime factors of n ≥ 1
PARTITIONS(n)numberthe number of ways to write n ≥ 0 as a sum of positive integers (n up to 4000)
FLT.MAX()numberthe largest finite double, 1.7976931348623157e308
FLT.MIN()numberthe smallest positive normal double, 2.2250738585072014e-308
FLT.RADIX()numberthe floating-point base, 2
FLT.NEXTAFTER(x, y)numberthe next double after x toward y ("+" or "-" for the infinities); y itself if y = x
MDETERM(A OVER R, C)numberMDETERM(A OVER R, C): the determinant of the square matrix A (rows along R, columns along C); 0 if singular
LOGMDETERM(A OVER R, C)numberLOGMDETERM(A OVER R, C): ln
MINVERSE(A OVER R, C INTO R2, C2)numberMINVERSE(A OVER R, C INTO R2, C2): the inverse of the square matrix A, row by row; #NUM! if singular
MPSEUDOINVERSE(A OVER R, C, [threshold] INTO C2, R2)numberMPSEUDOINVERSE(A OVER R, C, [threshold] INTO C2, R2): the Moore–Penrose pseudo-inverse (C × R, row by row); singular values up to threshold (default 256 ε) times the largest count as zero
CHOLESKY(A OVER R, C INTO R2, C2)numberCHOLESKY(A OVER R, C INTO R2, C2): the lower-triangular L with L·Lᵀ = A for a symmetric positive-definite A (asymmetric pairs averaged), row by row; #NUM! where A is not positive definite
EIGEN(A OVER R, C INTO R2, C2)numberEIGEN(A OVER R, C INTO R2, C2): for a symmetric A (asymmetric pairs averaged), its eigenvalues largest magnitude first, then the matrix of their unit eigenvectors as columns: (n + 1) × n values, row by row
FOURIER(y OVER T, [inverse] INTO K)textFOURIER(y OVER T, [inverse] INTO K): Gnumeric's discrete Fourier transform (scaled by 1/n, zero-padded to a power of two), each value as complex text "a+bi"

Rounding

Rounding is decimal: ROUND(2.675, 2) is 2.68.

FunctionReturnsDescription
ROUND(number, [num_digits=0])numberto num_digits decimal places, halves away from zero
ROUNDUP(number, [num_digits=0])numberaway from zero to num_digits places
ROUNDDOWN(number, [num_digits=0])numbertoward zero to num_digits places
ROUNDSIG(value, digits)numberto digits significant digits
TRUNC(number, [num_digits=0])numbertruncate to num_digits places
INT(number)numberdown to an integer
FLOOR(number, [significance=1])numberdown to a multiple of significance (default 1)
CEIL(x)numberup to an integer
CEILING(number, [significance=1])numberup to a multiple of significance (default 1)
FLOOR.MATH(number, [significance=1], [mode=0])numberdown to a multiple; mode ≠ 0 rounds negatives toward zero
CEILING.MATH(number, [significance=1], [mode=0])numberup to a multiple; mode ≠ 0 rounds negatives away from zero
FLOOR.PRECISE(number, [significance=1])numberdown to a multiple, ignoring the multiple's sign
CEILING.PRECISE(number, [significance=1])numberup to a multiple, ignoring the multiple's sign
ISO.CEILING(number, [significance=1])numbersame as CEILING.PRECISE
MROUND(number, multiple)numberto the nearest multiple
EVEN(number)numberaway from zero to an even integer
ODD(number)numberaway from zero to an odd integer

Text

Lengths and positions count characters, not bytes.

FunctionReturnsDescription
CHAR(number)textthe character with code n (1–255)
UNICHAR(number)textthe Unicode character n
CODE(text)numberthe code of the first character
UNICODE(text)numberthe code point of the first character
CLEAN(text)textremove non-printing characters
CONCAT(text1, …)textjoin values as text (same as &)
CONCATENATE(text1, …)textjoin values as text
EXACT(text1, text2)booleancase-sensitive equality
FIND(find_text, within_text, [start_num=1])number1-based position of find_text in within_text, case-sensitive
SEARCH(find_text, within_text, [start_num=1])number1-based position, case-insensitive, with * and ? wildcards
LEFT(text, [num_chars=1])textthe first num_chars characters (default 1)
RIGHT(text, [num_chars=1])textthe last num_chars characters (default 1)
MID(text, start_num, num_chars)textnum_chars characters from a 1-based start_num
LEN(text)numberthe number of characters
LOWER(text)textlowercase
UPPER(text)textuppercase
PROPER(text)textcapitalize each word
REPLACE(old_text, start_num, num_chars, new_text)textreplace num_chars characters from a 1-based start_num
REPT(text, number_times)textrepeat text number_times times
SUBSTITUTE(text, old_text, new_text, [instance_num])textreplace every (or the instance_num-th) occurrence of old_text
TRIM(text)textremove leading, trailing and repeated spaces
VALUE(text)numbertext as a number
TEXTBEFORE(text, delimiter, [instance_num=1], [match_mode=0], [match_end=0], [if_not_found])texttext before the instance_num-th delimiter
TEXTAFTER(text, delimiter, [instance_num=1], [match_mode=0], [match_end=0], [if_not_found])texttext after the instance_num-th delimiter
TEXTBETWEEN(text, start_delimiter, end_delimiter)texttext between the first start delimiter and the next end delimiter
COUNTMATCHES(text, search)numberhow many times search occurs in text
TEXT(value, format_text)textformat with an Excel number-format code: 0 # ? . , % E+ E- "text" \c _c *c, General, ; sections (positive;negative;zero;text with @), colors; dates y m d h s AM/PM A/P. Unsupported (#VALUE!): conditions, locales, [h] elapsed time, fractional seconds, fractions, eras
FIXED(number, [decimals=2], [no_commas=FALSE])textrounded to decimals places (default 2) as text, with thousands commas unless no_commas
DOLLAR(number, [decimals=2])textas en-US currency text: $1,234.57, negatives in parentheses, decimals default 2
NUMBERVALUE(text, [decimal_separator="."], [group_separator=","])numbertext as a number with explicit decimal (default .) and group (default ,) separators
VALUETOTEXT(value, [format=0])texta value as text; format 1 quotes text
REGEX(text, expression, [replacement], [flags])textthe first match (#N/A if none), or with a replacement the text with the first match replaced; the fourth argument is "g" (replace all) or the occurrence to replace. Patterns use the Rust regex syntax, not ICU's
REGEXTEST(text, pattern, [case_sensitivity=0])booleanwhether the pattern matches; case_sensitivity 1 ignores case. Rust regex syntax
REGEXEXTRACT(text, pattern, [return_mode=0], [case_sensitivity=0])textthe first match (#N/A if none); only return mode 0, modes 1 and 2 (arrays) are #VALUE!. Rust regex syntax (also REGEX.EXTRACT)
REGEXREPLACE(text, pattern, replacement, [occurrence=0], [case_sensitivity=0])textreplace every match (or the occurrence-th, negative from the end) with $n-style replacement text. Rust regex syntax
TEXTSPLIT(text OVER T, col_delimiter, [row_delimiter=""], [ignore_empty=FALSE], [match_mode=0], [pad_with] INTO K)textthe parts of the text between col_delimiter matches (case-sensitive), in order; written without OVER, each cell splits on its own: TEXTSPLIT(Text, "," INTO Part). row_delimiter must be "" (splitting into rows is not supported yet); ignore_empty drops empty parts; match_mode 1 matches the delimiter ignoring case; pad_with is accepted (it pads only a 2-D split); empty text is #VALUE!
ARRAYTOTEXT(array OVER T, [format=0])textthe values as text in item order: format 0 "1, 2, a", format 1 {1,2,"a"}
ASC(text)textfull-width ASCII and katakana as half-width, as LibreOffice's ASC (a voiced kana becomes its letter and a sound mark)
JIS(text)texthalf-width ASCII and katakana as full-width, as LibreOffice's JIS (a letter and its sound mark join) (also DBCS)
BAHTTEXT(number)texta number as Thai baht and satang in words, rounded to the satang
ROT13(text)textASCII letters rotated 13 places; anything else unchanged
ENCODEURL(text)textUTF-8 percent-encoding of every byte but A–Z a–z 0–9 - _ . ~ (#VALUE! for empty text)
ROMAN(number, [form=0])text0–3999 in Roman numerals; form 0 classic (or TRUE) to 4 most concise (or FALSE)
ARABIC(text)numberRoman numerals (0–3999) as a number; case and surrounding spaces ignored, a leading - negates, "" is 0

Date and time

Dates are date-time values (UTC, millisecond precision). A number given where a date is wanted is a spreadsheet serial date, as in LibreOffice: 61 is 1900-03-01, and 1 is 1899-12-31 (Excel's 1 is 1900-01-01, because it counts a fictitious 1900-02-29).

FunctionReturnsDescription
DATE(year, month, day)datea date; out-of-range months and days roll over, years 0–1899 add 1900
DATEVALUE(date_text)dateparse a date: 2025-01-31, 2025-01-31T09:30:00Z (the time is dropped) or 1/31/2025
TIME(hour, minute, second)datea time of day on serial day 0 (1899-12-30), wrapping at 24 hours
TIMEVALUE(time_text)numberparse a time (09:30, 9:30 PM, 2025-01-31T09:30:00Z) as a fraction of a day
YEAR(serial_number)numberthe year
MONTH(serial_number)numberthe month, 1–12
DAY(serial_number)numberthe day of the month
HOUR(serial_number)numberthe hour, 0–23
MINUTE(serial_number)numberthe minute
SECOND(serial_number)numberthe second, rounded
WEEKDAY(serial_number, [return_type=1])numberday of the week: type 1 Sunday=1 (default), 2 Monday=1, 3 Monday=0, 11–17 day 1 is Monday…Sunday
WEEKNUM(serial_number, [return_type=1])numberweek of the year (the week of January 1 is 1), weeks starting on type's day as in WEEKDAY (1, 2, 11–17); type 21 is the ISO week (also WEEKNUM_EXCEL2003)
ISOWEEKNUM(date)numberthe ISO 8601 week number
ISOYEAR(date)numberthe ISO 8601 week-numbering year
DAYOFYEAR(date)numberthe day of the year, 1–366
DAYNAME(date)textthe English weekday name of a date, or of a day number 1–7 (1 is Sunday)
MONTHNAME(month)textthe English name of month 1–12
DAYS(end_date, start_date)numberdays from start to end (end − start, times included)
DAYS360(start_date, end_date, [method=FALSE])numberdays between on a 360-day year, US (NASD) method or European when TRUE
DATEDIF(start_date, end_date, unit)numbercomplete "Y" years, "M" months or "D" days between; "YM", "YD", "MD" ignore the larger units
EDATE(start_date, months)datethe same day n months later (clamped to the month's end)
EOMONTH(start_date, months)datethe last day of the month n months later
YEARFRAC(start_date, end_date, [basis=0])numberthe fraction of a year between: basis 0 US 30/360 (default), 1 actual/actual, 2 actual/360, 3 actual/365, 4 European 30/360
NETWORKDAYS(start_date, end_date)numberworking days (Monday–Friday) from start to end inclusive; no holidays argument yet (it needs an aggregation) (also NETWORKDAYS_EXCEL2003)
NETWORKDAYS.INTL(start_date, end_date, [weekend=1])numberworking days with a weekend of 1–7 (two days), 11–17 (one day) or a "0000011" Monday-first mask; no holidays argument yet
WORKDAY(start_date, days)datethe date n working days (Monday–Friday) after start; no holidays argument yet
WORKDAY.INTL(start_date, days, [weekend=1])dateWORKDAY with a weekend as in NETWORKDAYS.INTL; no holidays argument yet
NOW()datethe current date and time (UTC); re-evaluated when the model is recalculated
TODAY()datethe current date (UTC midnight); re-evaluated when the model is recalculated
DAYSINMONTH(date)numberthe number of days in the date's month
DAYSINYEAR(date)numberthe number of days in the date's year
WEEKSINYEAR(date)numberthe number of ISO weeks (52 or 53) in the date's year
ISLEAPYEAR(date)booleanwhether the date's year is a leap year
MONTHS(start_date, end_date, type)numbermonths between: type 0 complete months, 1 calendar months
WEEKS(start_date, end_date, type)numberweeks between: type 0 complete weeks, 1 calendar (Monday) weeks
YEARS(start_date, end_date, type)numberyears between: type 0 complete years, 1 calendar years
UNIX2DATE(t)datethe date of a Unix time in seconds
DATE2UNIX(d)numbera date as Unix time in seconds
DUR2DAYS(duration)numbera duration (a number of days) in days
DUR2HOURS(duration)numbera duration in days as hours
DUR2MINUTES(duration)numbera duration in days as minutes
DUR2SECONDS(duration)numbera duration in days as seconds
DUR2MILLISECONDS(duration)numbera duration in days as milliseconds
DUR2WEEKS(duration)numbera duration in days as weeks
STRIPDURATION(duration)numberthe value (durations are already a number of days)
EASTERSUNDAY(year)dateEaster Sunday (Gregorian) of a year 1583–9956; 0–29 mean 2000–2029, 30–99 mean 1930–1999
ASCENSIONTHURSDAY(year)dateAscension Thursday, 39 days after Easter Sunday
ASHWEDNESDAY(year)dateAsh Wednesday, 46 days before Easter Sunday
GOODFRIDAY(year)dateGood Friday, 2 days before Easter Sunday
PENTECOSTSUNDAY(year)datePentecost Sunday, 49 days after Easter Sunday
DATE2JULIAN(date)numberthe Julian day number of a date
HDATE_JULIAN(year, month, day)numberthe Julian day number of Gregorian year, month, day (out-of-range days and months roll over)
HDATE(year, month, day)textthe Hebrew date of Gregorian year, month, day, as "20 Tebet 5784" (#VALUE! for a month outside 1–12 or a day outside 1–31)
HDATE_HEB(year, month, day)textthe Hebrew date of Gregorian year, month, day in Hebrew, as "כ׳ בְּטֵבֵת התשפ״ד"
HDATE_DAY(year, month, day)numberthe day of the Hebrew month of Gregorian year, month, day
HDATE_MONTH(year, month, day)numberthe Hebrew month of Gregorian year, month, day: 0 Tishri … 11 Elul, 12 Adar I, 13 Adar II
HDATE_YEAR(year, month, day)numberthe Hebrew year of Gregorian year, month, day
DATE2HDATE(date)textthe Hebrew date of a date, as "20 Tebet 5784"
DATE2HDATE_HEB(date)textthe Hebrew date of a date in Hebrew

Dimensional

Functions of a cell's position in a category, and the ordered (previous/next, running) forms.

FunctionReturnsDescription
POSITION(category)number1-based position of this cell's item along the category
@ITEM(category)textthe name of this cell's item along the category
@ID(category)textthe item name (Improv item names are unique within a category)
@ITEMCOUNT(category)numberthe number of items in the category
PREV(x, category, [n=1], [default])the branches' typethe value at the n-th previous item along the category (n = 1); off the end, the default, else no cell
NEXT(x, category, [n=1], [default])the branches' typethe value at the n-th next item along the category (n = 1); off the end, the default, else no cell
SEQUENCE(T, [start=1], [step=1])the branches' typeSEQUENCE(T, [start=1], [step=1]): start, start + step, … along T's items, (POSITION(T) - 1) * step + start
RELABEL(x, from_category, to_category)the branches' typex read with category From replaced by To, each item mapped to To's item of the same name (items with no namesake are dropped)
SWAP(x, category_a, category_b)the branches' typex read with categories A and B exchanged, items matched by name (W at Src = a, Dst = b is SWAP(W, Src, Dst) at Src = b, Dst = a)
FIXPOINT(init, lambda, [max_iter=100], [tolerance=1e-10])the branches' typeFIXPOINT(init, LAMBDA(r, body), [max_iter=100], [tolerance=1e-10]): r = init, then r = body(r) until the cells change by at most tolerance in total (Σ
FILL(x, default)the branches' typea cell at every item combination of x's categories: x where it has a cell, else the default
SORT(array OVER T, [sort_order=1] INTO K)the branches' typethe values in ascending order (descending when sort_order is -1)
UNIQUE(array OVER T, [exactly_once=FALSE] INTO K)the branches' typeeach distinct value once (text ignoring case, in its first spelling), in item order (only values that occur once when exactly_once is TRUE)
FILTER(array, include OVER T, [if_empty] INTO K)the branches' typethe values of array whose include is TRUE, in item order; if none, if_empty (else #N/A: Excel's #CALC!)
SORTBY(array, by_array1 OVER T, [sort_order1], … INTO K)the branches' typeSORTBY(array, by_array1 OVER T, [sort_order1], [by_array2, sort_order2], …): the values of array sorted by by_array1, ties by by_array2, … (stable; a key descends when its order is -1)
TAKE(array OVER T, rows INTO K)the branches' typethe first rows values in item order (the last -rows when rows is negative)
DROP(array OVER T, rows INTO K)the branches' typethe values TAKE leaves out: all but the first rows (the last -rows when rows is negative), in item order
SELECTS(values, tests OVER T, condition INTO K)the branches' typeQuantrix: the values whose test meets the condition (a criterion like ">5" or "a*", as in SUMIF), in item order
XLOOKUP(lookup_value, lookup_array OVER T, return_array, [if_not_found=NA()], [match_mode=0], [search_mode=1])the values' typereturn_array at the item where lookup_array matches lookup_value (match_mode 0 exact, -1 next smaller, 1 next larger, 2 wildcard; search_mode 1 first to last, -1 last to first, ±2 the same as ±1); if_not_found (else #N/A) when none does
XMATCH(lookup_value, lookup_array OVER T, [match_mode=0], [search_mode=1])numberthe 1-based item position along the category where lookup_array matches lookup_value (XLOOKUP's modes); #N/A when none does
MATCH(lookup_value, lookup_array OVER T, [match_type=1])numberthe 1-based item position of lookup_value: match_type 1 (default) the largest ≤ it, 0 the first equal (text with * and ? wildcards), -1 the smallest ≥ it; #N/A when none
LOOKUP(lookup_value, lookup_vector OVER T, result_vector)the values' typeresult_vector at the largest lookup_vector ≤ lookup_value (ascending); #N/A when none
INDEX(array OVER T, row_num)the branches' typethe value at the row_num-th item (1-based); #REF! out of range, #N/A where that item has no cell (also VALUEAT)
SELECT(values, keys OVER T, lookup)the branches' typevalues at the first item (in item order) whose key equals lookup; #N/A when none (SELECTLIST: a lookup over its own category gives one result per lookup) (also SELECTLIST)
SELECTBETWEEN(values, keys OVER T, low, high, [inclusive])the branches' typevalues at the first item whose key is between low and high (strictly when inclusive is FALSE); #N/A when none
SELECTGREATERTHAN(values, keys OVER T, lookup, [inclusive])the branches' typevalues at the first item whose key is > lookup (≥ when inclusive is TRUE); #N/A when none
SELECTLESSTHAN(values, keys OVER T, lookup, [inclusive])the branches' typevalues at the first item whose key is < lookup (≤ when inclusive is TRUE); #N/A when none

Statistical

FunctionReturnsDescription
MODE.MULT(values OVER T INTO K)numberevery most frequent value, in order of first occurrence (#N/A if none repeats)
LINEST(known_ys, known_xs1, … OVER T, [const=TRUE], [stats=FALSE] INTO K)numberLINEST(known_ys, known_xs1, [known_xs2, …] OVER T, [const], [stats]): the least-squares fit y = m1·x1 + … + b: mk, …, m1, b (const = FALSE: b = 0); an x collinear with those before it (or with the constant) is dropped, m = 0, as Excel; with stats, Excel's 5×(k+1) block row by row (one x: m, b, se_m, se_b, r², se_y, F, df, ss_reg, ss_resid); INTO R, C lays it out as the block
LOGEST(known_ys, known_xs1, … OVER T, [const=TRUE], [stats=FALSE] INTO K)numberLOGEST(known_ys, known_xs1, [known_xs2, …] OVER T, [const], [stats]): y = b·m1^x1·…, fitted to ln y: mk, …, m1, b (const = FALSE: b = 1); with stats LINEST's block, for ln y
FREQUENCY(data_array OVER T, bin1, … INTO K)numbercounts of x in the bins given as numbers b1, b2, …: ≤ b1, (b1, b2], …, > bn (n + 1 counts; Excel takes the bins as a range)
BETA.DIST(x, alpha, beta, cumulative, [a=0], [b=1])numberthe beta distribution of x on [A, B] (default [0, 1]): density, or cumulative
BETADIST(x, alpha, beta, [a=0], [b=1])numberthe cumulative beta distribution of x on [A, B] (default [0, 1])
BETA.INV(probability, alpha, beta, [a=0], [b=1])numberthe beta quantile on [A, B] (default [0, 1]) (also BETAINV)
BINOM.DIST(number_s, trials, probability_s, cumulative)numberthe binomial probability of k successes in n trials: P(K = k), or P(K ≤ k) (also BINOMDIST)
BINOM.INV(trials, probability_s, alpha)numberthe smallest k with binomial P(K ≤ k) ≥ alpha, for n trials of probability p (also CRITBINOM)
BINOM.DIST.RANGE(trials, probability_s, number_s, [number_s2])numberthe binomial P(k1 ≤ K ≤ k2) for n trials of probability p (k2 defaults to k1) (also B)
CHISQ.DIST(x, deg_freedom, cumulative)numberthe chi-square distribution: density, or left tail (also CHISQDIST)
CHISQ.DIST.RT(x, deg_freedom)numberthe chi-square right tail (also CHIDIST)
CHISQ.INV(probability, deg_freedom)numberthe chi-square left-tail quantile (also CHISQINV)
CHISQ.INV.RT(probability, deg_freedom)numberthe chi-square right-tail quantile (also CHIINV)
EXPON.DIST(x, lambda, cumulative)numberthe exponential distribution of rate λ: density, or cumulative (also EXPONDIST)
F.DIST(x, deg_freedom1, deg_freedom2, cumulative)numberthe F distribution: density, or left tail
F.DIST.RT(x, deg_freedom1, deg_freedom2)numberthe F right tail (also FDIST)
F.INV(probability, deg_freedom1, deg_freedom2)numberthe F left-tail quantile
F.INV.RT(probability, deg_freedom1, deg_freedom2)numberthe F right-tail quantile (also FINV)
GAMMA.DIST(x, alpha, beta, cumulative)numberthe gamma distribution of shape α and scale β: density, or cumulative (also GAMMADIST)
GAMMA.INV(probability, alpha, beta)numberthe gamma quantile (also GAMMAINV)
GAUSS(z)numberΦ(z) − 0.5: the standard normal probability between 0 and z
HYPGEOM.DIST(sample_s, number_sample, population_s, number_pop, cumulative)numberthe hypergeometric probability of k successes in a sample of n from N holding K: P(X = k), or P(X ≤ k)
HYPGEOMDIST(sample_s, number_sample, population_s, number_pop)numberthe hypergeometric probability P(X = k)
LOGNORM.DIST(x, mean, standard_dev, cumulative)numberthe log-normal distribution: density, or cumulative
LOGNORMDIST(x, mean, standard_dev)numberthe cumulative log-normal distribution
LOGNORM.INV(probability, mean, standard_dev)numberthe log-normal quantile (also LOGINV)
NEGBINOM.DIST(number_f, number_s, probability_s, cumulative)numberthe negative binomial probability of f failures before the s-th success: P(F = f), or P(F ≤ f)
NEGBINOMDIST(number_f, number_s, probability_s)numberthe negative binomial probability P(F = f)
NORM.DIST(x, mean, standard_dev, cumulative)numberthe normal distribution: density, or cumulative (also NORMDIST)
NORM.INV(probability, mean, standard_dev)numberthe normal quantile (also NORMINV)
NORM.S.DIST(z, cumulative)numberthe standard normal distribution: density, or cumulative
NORMSDIST(z)numberthe cumulative standard normal distribution Φ(z)
NORM.S.INV(probability)numberthe standard normal quantile (also NORMSINV)
PHI(x)numberthe standard normal density
POISSON.DIST(x, mean, cumulative)numberthe Poisson probability of k events at mean λ: P(X = k), or P(X ≤ k) (also POISSON)
T.DIST(x, deg_freedom, cumulative)numberStudent's t distribution: density, or left tail
T.DIST.RT(x, deg_freedom)numberStudent's t right tail
T.DIST.2T(x, deg_freedom)numberStudent's t two-tailed probability
TDIST(x, deg_freedom, tails)numberStudent's t right tail (tails = 1) or two-tailed probability (tails = 2), for x ≥ 0
T.INV(probability, deg_freedom)numberStudent's t left-tail quantile
T.INV.2T(probability, deg_freedom)numberStudent's t two-tailed quantile (also TINV)
WEIBULL.DIST(x, alpha, beta, cumulative)numberthe Weibull distribution of shape α and scale β: density, or cumulative (also WEIBULL)
FISHER(x)numberthe Fisher transformation atanh(x)
FISHERINV(y)numberthe inverse Fisher transformation tanh(y)
CONFIDENCE.NORM(alpha, standard_dev, size)numberthe half-width of a normal confidence interval at significance alpha, for sd and sample size n (also CONFIDENCE)
CONFIDENCE.T(alpha, standard_dev, size)numberthe half-width of a Student's t confidence interval at significance alpha, for sd and sample size n
STANDARDIZE(x, mean, standard_dev)numberthe z-score (x − mean) / sd
AVERAGEA(values OVER T)numberthe mean, counting TRUE as 1 and text and FALSE as 0
AVERAGEIF(range OVER T, criteria, [average_range])numberthe mean of average_range (else range) where range meets the criteria
AVERAGEIFS(average_range, criteria_range1 OVER T, criteria1, …)numberthe mean of x where every criteria measure meets its criterion
AVEDEV(values OVER T)numberthe mean absolute deviation from the mean
COUNT(values OVER T)numberthe number of numbers (and dates) (also DCOUNT)
COUNTA(values OVER T)numberthe number of cells (errors included) (also DCOUNTA)
COUNTUNIQUE(values OVER T)numberthe number of distinct values, SQL's count(DISTINCT …) (text compares case-sensitively; an error among them is the result)
COUNTBLANK(range OVER T)numberthe number of items with no cell (or empty text)
COUNTIF(range OVER T, criteria)numberthe number of cells meeting the criterion (">5", "<>x", "a*", 3)
COUNTIFS(criteria_range1 OVER T, criteria1, …)numberthe number of rows where every criteria measure meets its criterion
SUMIF(range OVER T, criteria, [sum_range])numberthe sum of sum_range (else range) where range meets the criteria
SUMIFS(sum_range, criteria_range1 OVER T, criteria1, …)numberthe sum of x where every criteria measure meets its criterion
MAXA(values OVER T)numberthe largest value, counting TRUE as 1 and text and FALSE as 0
MAXIFS(max_range, criteria_range1 OVER T, criteria1, …)numberthe largest x where every criteria measure meets its criterion (0 if none)
MINA(values OVER T)numberthe smallest value, counting TRUE as 1 and text and FALSE as 0
MINIFS(min_range, criteria_range1 OVER T, criteria1, …)numberthe smallest x where every criteria measure meets its criterion (0 if none)
MEDIAN(values OVER T)numberthe median
MODE(values OVER T)numberthe most frequent value (the first in item order on a tie; #N/A if none repeats) (also MODE.SNGL)
GEOMEAN(values OVER T)numberthe geometric mean (#NUM! for a value ≤ 0)
HARMEAN(values OVER T)numberthe harmonic mean (#NUM! for a value ≤ 0)
TRIMMEAN(array OVER T, percent)numberthe mean without the fraction of values at the tails (rounded down to an even count)
DEVSQ(values OVER T)numberΣ(x − mean)²
STDEV(values OVER T)numberthe sample standard deviation (also STDEV.S, DSTDEV)
STDEVP(values OVER T)numberthe population standard deviation (also STDEV.P, DSTDEVP)
STDEVA(values OVER T)numberthe sample standard deviation, counting TRUE as 1 and text and FALSE as 0
STDEVPA(values OVER T)numberthe population standard deviation, counting TRUE as 1 and text and FALSE as 0
VAR(values OVER T)numberthe sample variance (also VAR.S, DVAR)
VARP(values OVER T)numberthe population variance (also VAR.P, DVARP)
VARA(values OVER T)numberthe sample variance, counting TRUE as 1 and text and FALSE as 0
VARPA(values OVER T)numberthe population variance, counting TRUE as 1 and text and FALSE as 0
KURT(values OVER T)numberthe sample excess kurtosis
KURTP(values OVER T)numberthe population excess kurtosis
SKEW(values OVER T)numberthe sample skewness
SKEWP(values OVER T)numberthe population skewness (also SKEW.P)
LARGE(array OVER T, k)numberthe k-th largest value
SMALL(array OVER T, k)numberthe k-th smallest value
PERCENTILE(array OVER T, k)numberthe p-th percentile, interpolated, 0 ≤ p ≤ 1 (also PERCENTILE.INC)
PERCENTILE.EXC(array OVER T, k)numberthe p-th percentile, exclusive of 0 and 1
QUARTILE(array OVER T, quart)numberthe q-th quartile (0 min … 4 max) (also QUARTILE.INC)
QUARTILE.EXC(array OVER T, quart)numberthe q-th quartile (1 … 3), exclusive
PROB(x_range, prob_range OVER T, lower_limit, [upper_limit])numberΣ p over the values x in [low, high] (x = low without high); #NUM! unless every 0 < p ≤ 1 and Σ p = 1
SUBTOTAL(function_num, values OVER T)numberthe reduction a code picks: 1 AVERAGE, 2 COUNT, 3 COUNTA, 4 MAX, 5 MIN, 6 PRODUCT, 7 STDEV, 8 STDEVP, 9 SUM, 10 VAR, 11 VARP (101–111 the same)
AGGREGATE(function_num, options, array OVER T, [k])numberSUBTOTAL's codes and 12 MEDIAN, 13 MODE, 14 LARGE, 15 SMALL, 16 PERCENTILE, 17 QUARTILE, 18 PERCENTILE.EXC, 19 QUARTILE.EXC; options 2, 3, 6, 7 skip errors
RANK(ref OVER T, [order=0])numbereach item's rank among the values (order 0, the default, ranks the largest 1) (also RANK.EQ)
RANK.AVG(ref OVER T, [order=0])numbereach item's rank, ties sharing their mean rank
PERCENTRANK(array OVER T, [x], [significance=3])numbereach item's (or x's) rank as a fraction 0 … 1, to significance (3) significant digits (also PERCENTRANK.INC)
RANK.DENSE(ref OVER T, [order=0])numbereach item's dense rank: tied values share a rank and the next value ranks one after them, SQL's dense_rank() (order 0, the default, ranks the largest 1)
PERCENTRANK.EXC(array OVER T, [x], [significance=3])numbereach item's (or x's) rank as a fraction, exclusive of 0 and 1
TREND(known_ys, known_xs OVER T, [const=TRUE])numbereach item's value on the least-squares line of y on x, at its own x (through 0 if const is FALSE)
GROWTH(known_ys, known_xs OVER T, [const=TRUE])numbereach item's value on the least-squares curve y = b·mˣ (fitting ln y; b = 1 if const is FALSE)
CORREL(array1, array2 OVER T)numberthe Pearson correlation of x and y (also PEARSON)
RSQ(known_ys, known_xs OVER T)numberthe square of the Pearson correlation
COVAR(array1, array2 OVER T)numberthe population covariance (also COVARIANCE.P)
COVARIANCE.S(array1, array2 OVER T)numberthe sample covariance
SLOPE(known_ys, known_xs OVER T)numberthe least-squares slope of y on x
INTERCEPT(known_ys, known_xs OVER T)numberthe least-squares intercept of y on x
STEYX(known_ys, known_xs OVER T)numberthe standard error of the predicted y
FORECAST(x, known_ys, known_xs OVER T)numberthe least-squares line of y on x at x0 (also FORECAST.LINEAR)
EXPA(known_ys, known_xs OVER T, [simple])numberA of the fit y = A·e^(Bx): least squares of ln y weighted by y (simple = TRUE: unweighted, as LOGEST)
EXPB(known_ys, known_xs OVER T, [simple])numberB of the fit y = A·e^(Bx)
EXPFORECAST(x, known_ys, known_xs OVER T, [simple])numberthe fit y = A·e^(Bx) at x0
CHITEST(actual_range, expected_range OVER T)numberthe χ² test p-value of actual against expected (also CHISQ.TEST)
FTEST(array1, array2 OVER T)numberthe two-tailed F-test p-value that a and b have the same variance (also F.TEST)
TTEST(array1, array2 OVER T, tails, type)numberthe t-test p-value (tails 1 or 2; type 1 paired, 2 equal variance, 3 unequal) (also T.TEST)
ZTEST(array OVER T, x, [sigma])numberthe one-tailed z-test p-value of the mean against μ0 (σ defaults to the sample's) (also Z.TEST)
AUTOCORREL(values OVER T)numberthe lag-1 autocorrelation in item order (GSL) (also GSL_STATS_LAG1_AUTOCORRELATION)
DGET(values OVER T)the branches' typethe single value (with WHERE, the single match); #NUM! when more than one (a WHERE that keeps none leaves no cell)
PROBBLOCK(traffic, circuits)numberthe Erlang-B probability that a call is blocked when traffic erlangs load circuits (1 to 10⁶; truncated below 100)
OFFTRAF(traffic, circuits)numberthe offered traffic that carries traffic erlangs on circuits (#VALUE! if circuits cannot carry it)
DIMCIRC(traffic, gos)numberthe fewest circuits (up to 10⁶) that carry traffic erlangs with blocking at most gos, 0 < gos ≤ 1
OFFCAP(circuits, gos)numberthe traffic circuits carry with blocking gos, 0 < gos < 1
BERNOULLI(k, p)numberthe Bernoulli probability of k (0 or 1) for success probability p
CAUCHY(x, a, cumulative)numberthe Cauchy distribution of scale a at x: density, or (as Gnumeric) the right tail P(X > x)
EXPPOWDIST(x, a, b)numberthe exponential-power density of scale a and exponent b at x
GEOMDIST(k, p, cumulative)numberthe geometric probability of k failures before the first success: P(K = k), or P(K ≤ k)
LANDAU(x)numberthe Landau density at x (Kölbig and Schorr's approximation, about 9 digits)
LAPLACE(x, a)numberthe Laplace density of width a at x
LOGISTIC(x, a)numberthe logistic density of scale a at x
PARETO(x, a, b)numberthe Pareto density of exponent a and scale b at x
RAYLEIGH(x, sigma)numberthe Rayleigh density of scale σ at x
RAYLEIGHTAIL(x, a, sigma)numberthe Rayleigh tail density (lower limit a, scale σ) at x
SNORM.DIST.RANGE(x1, x2)numberΦ(x2) − Φ(x1): the standard normal probability between x1 and x2
OWENT(h, a)numberOwen's T function T(h, a)
CUM_BIV_NORM_DIST(a, b, rho)numberthe standard bivariate normal P(X ≤ a, Y ≤ b) with correlation ρ,
R.DBETA(x, shape1, shape2, [give_log=FALSE])numberthe density at x of the beta distribution of shapes shape1 and shape2, or its logarithm (give_log)
R.PBETA(x, shape1, shape2, [lower_tail=TRUE], [log_p=FALSE])numberP(X ≤ x) for the beta distribution of shapes shape1 and shape2, or P(X > x) (lower_tail = FALSE), or its logarithm (log_p)
R.QBETA(p, shape1, shape2, [lower_tail=TRUE], [log_p=FALSE])numberthe quantile of the beta distribution of shapes shape1 and shape2: the x with P(X ≤ x) = p, or of P(X > x) (lower_tail = FALSE), p may be a logarithm (log_p)
R.DBINOM(x, size, prob, [give_log=FALSE])numberthe probability mass at x of the binomial distribution of size trials of success probability prob, or its logarithm (give_log)
R.PBINOM(x, size, prob, [lower_tail=TRUE], [log_p=FALSE])numberP(X ≤ x) for the binomial distribution of size trials of success probability prob, or P(X > x) (lower_tail = FALSE), or its logarithm (log_p)
R.QBINOM(p, size, prob, [lower_tail=TRUE], [log_p=FALSE])numberthe quantile of the binomial distribution of size trials of success probability prob: the smallest x with P(X ≤ x) ≥ p, or of P(X > x) (lower_tail = FALSE), p may be a logarithm (log_p)
R.DCAUCHY(x, location, scale, [give_log=FALSE])numberthe density at x of the Cauchy distribution of location and scale, or its logarithm (give_log)
R.PCAUCHY(x, location, scale, [lower_tail=TRUE], [log_p=FALSE])numberP(X ≤ x) for the Cauchy distribution of location and scale, or P(X > x) (lower_tail = FALSE), or its logarithm (log_p)
R.QCAUCHY(p, location, scale, [lower_tail=TRUE], [log_p=FALSE])numberthe quantile of the Cauchy distribution of location and scale: the x with P(X ≤ x) = p, or of P(X > x) (lower_tail = FALSE), p may be a logarithm (log_p)
R.DCHISQ(x, df, [give_log=FALSE])numberthe density at x of the chi-square distribution of df degrees of freedom, or its logarithm (give_log)
R.PCHISQ(x, df, [lower_tail=TRUE], [log_p=FALSE])numberP(X ≤ x) for the chi-square distribution of df degrees of freedom, or P(X > x) (lower_tail = FALSE), or its logarithm (log_p)
R.QCHISQ(p, df, [lower_tail=TRUE], [log_p=FALSE])numberthe quantile of the chi-square distribution of df degrees of freedom: the x with P(X ≤ x) = p, or of P(X > x) (lower_tail = FALSE), p may be a logarithm (log_p)
R.DEXP(x, scale, [give_log=FALSE])numberthe density at x of the exponential distribution of the given scale (mean), or its logarithm (give_log)
R.PEXP(x, scale, [lower_tail=TRUE], [log_p=FALSE])numberP(X ≤ x) for the exponential distribution of the given scale (mean), or P(X > x) (lower_tail = FALSE), or its logarithm (log_p)
R.QEXP(p, scale, [lower_tail=TRUE], [log_p=FALSE])numberthe quantile of the exponential distribution of the given scale (mean): the x with P(X ≤ x) = p, or of P(X > x) (lower_tail = FALSE), p may be a logarithm (log_p)
R.DF(x, df1, df2, [give_log=FALSE])numberthe density at x of the F distribution of df1 and df2 degrees of freedom, or its logarithm (give_log)
R.PF(x, df1, df2, [lower_tail=TRUE], [log_p=FALSE])numberP(X ≤ x) for the F distribution of df1 and df2 degrees of freedom, or P(X > x) (lower_tail = FALSE), or its logarithm (log_p)
R.QF(p, df1, df2, [lower_tail=TRUE], [log_p=FALSE])numberthe quantile of the F distribution of df1 and df2 degrees of freedom: the x with P(X ≤ x) = p, or of P(X > x) (lower_tail = FALSE), p may be a logarithm (log_p)
R.DGAMMA(x, shape, scale, [give_log=FALSE])numberthe density at x of the gamma distribution of shape and scale, or its logarithm (give_log)
R.PGAMMA(x, shape, scale, [lower_tail=TRUE], [log_p=FALSE])numberP(X ≤ x) for the gamma distribution of shape and scale, or P(X > x) (lower_tail = FALSE), or its logarithm (log_p)
R.QGAMMA(p, shape, scale, [lower_tail=TRUE], [log_p=FALSE])numberthe quantile of the gamma distribution of shape and scale: the x with P(X ≤ x) = p, or of P(X > x) (lower_tail = FALSE), p may be a logarithm (log_p)
R.DGEOM(x, prob, [give_log=FALSE])numberthe probability mass at x of the geometric distribution (failures before the first success) of success probability prob, or its logarithm (give_log)
R.PGEOM(x, prob, [lower_tail=TRUE], [log_p=FALSE])numberP(X ≤ x) for the geometric distribution (failures before the first success) of success probability prob, or P(X > x) (lower_tail = FALSE), or its logarithm (log_p)
R.QGEOM(p, prob, [lower_tail=TRUE], [log_p=FALSE])numberthe quantile of the geometric distribution (failures before the first success) of success probability prob: the smallest x with P(X ≤ x) ≥ p, or of P(X > x) (lower_tail = FALSE), p may be a logarithm (log_p)
R.DGUMBEL(x, mu, beta, [give_log=FALSE])numberthe density at x of the Gumbel distribution of location μ and scale β, or its logarithm (give_log)
R.PGUMBEL(x, mu, beta, [lower_tail=TRUE], [log_p=FALSE])numberP(X ≤ x) for the Gumbel distribution of location μ and scale β, or P(X > x) (lower_tail = FALSE), or its logarithm (log_p)
R.QGUMBEL(p, mu, beta, [lower_tail=TRUE], [log_p=FALSE])numberthe quantile of the Gumbel distribution of location μ and scale β: the x with P(X ≤ x) = p, or of P(X > x) (lower_tail = FALSE), p may be a logarithm (log_p)
R.DHYPER(x, m, n, k, [give_log=FALSE])numberthe probability mass at x of the hypergeometric distribution of the white balls among k drawn from m white and n black, or its logarithm (give_log)
R.PHYPER(x, m, n, k, [lower_tail=TRUE], [log_p=FALSE])numberP(X ≤ x) for the hypergeometric distribution of the white balls among k drawn from m white and n black, or P(X > x) (lower_tail = FALSE), or its logarithm (log_p)
R.QHYPER(p, m, n, k, [lower_tail=TRUE], [log_p=FALSE])numberthe quantile of the hypergeometric distribution of the white balls among k drawn from m white and n black: the smallest x with P(X ≤ x) ≥ p, or of P(X > x) (lower_tail = FALSE), p may be a logarithm (log_p)
R.DLNORM(x, meanlog, sdlog, [give_log=FALSE])numberthe density at x of the log-normal distribution of log-mean and log-sd, or its logarithm (give_log)
R.PLNORM(x, meanlog, sdlog, [lower_tail=TRUE], [log_p=FALSE])numberP(X ≤ x) for the log-normal distribution of log-mean and log-sd, or P(X > x) (lower_tail = FALSE), or its logarithm (log_p)
R.QLNORM(p, meanlog, sdlog, [lower_tail=TRUE], [log_p=FALSE])numberthe quantile of the log-normal distribution of log-mean and log-sd: the x with P(X ≤ x) = p, or of P(X > x) (lower_tail = FALSE), p may be a logarithm (log_p)
R.DNBINOM(x, size, prob, [give_log=FALSE])numberthe probability mass at x of the negative binomial distribution (failures before the size-th success) of success probability prob, or its logarithm (give_log)
R.PNBINOM(x, size, prob, [lower_tail=TRUE], [log_p=FALSE])numberP(X ≤ x) for the negative binomial distribution (failures before the size-th success) of success probability prob, or P(X > x) (lower_tail = FALSE), or its logarithm (log_p)
R.QNBINOM(p, size, prob, [lower_tail=TRUE], [log_p=FALSE])numberthe quantile of the negative binomial distribution (failures before the size-th success) of success probability prob: the smallest x with P(X ≤ x) ≥ p, or of P(X > x) (lower_tail = FALSE), p may be a logarithm (log_p)
R.DNORM(x, mean, sd, [give_log=FALSE])numberthe density at x of the normal distribution of mean μ and standard deviation σ, or its logarithm (give_log)
R.PNORM(x, mean, sd, [lower_tail=TRUE], [log_p=FALSE])numberP(X ≤ x) for the normal distribution of mean μ and standard deviation σ, or P(X > x) (lower_tail = FALSE), or its logarithm (log_p)
R.QNORM(p, mean, sd, [lower_tail=TRUE], [log_p=FALSE])numberthe quantile of the normal distribution of mean μ and standard deviation σ: the x with P(X ≤ x) = p, or of P(X > x) (lower_tail = FALSE), p may be a logarithm (log_p)
R.DPOIS(x, lambda, [give_log=FALSE])numberthe probability mass at x of the Poisson distribution of mean λ, or its logarithm (give_log)
R.PPOIS(x, lambda, [lower_tail=TRUE], [log_p=FALSE])numberP(X ≤ x) for the Poisson distribution of mean λ, or P(X > x) (lower_tail = FALSE), or its logarithm (log_p)
R.QPOIS(p, lambda, [lower_tail=TRUE], [log_p=FALSE])numberthe quantile of the Poisson distribution of mean λ: the smallest x with P(X ≤ x) ≥ p, or of P(X > x) (lower_tail = FALSE), p may be a logarithm (log_p)
R.DRAYLEIGH(x, scale, [give_log=FALSE])numberthe density at x of the Rayleigh distribution of the given scale, or its logarithm (give_log)
R.PRAYLEIGH(x, scale, [lower_tail=TRUE], [log_p=FALSE])numberP(X ≤ x) for the Rayleigh distribution of the given scale, or P(X > x) (lower_tail = FALSE), or its logarithm (log_p)
R.QRAYLEIGH(p, scale, [lower_tail=TRUE], [log_p=FALSE])numberthe quantile of the Rayleigh distribution of the given scale: the x with P(X ≤ x) = p, or of P(X > x) (lower_tail = FALSE), p may be a logarithm (log_p)
R.DSNORM(x, shape, location, scale, [give_log=FALSE])numberthe density at x of the skew-normal distribution of shape, location and scale, or its logarithm (give_log)
R.PSNORM(x, shape, location, scale, [lower_tail=TRUE], [log_p=FALSE])numberP(X ≤ x) for the skew-normal distribution of shape, location and scale, or P(X > x) (lower_tail = FALSE), or its logarithm (log_p)
R.QSNORM(p, shape, location, scale, [lower_tail=TRUE], [log_p=FALSE])numberthe quantile of the skew-normal distribution of shape, location and scale: the x with P(X ≤ x) = p, or of P(X > x) (lower_tail = FALSE), p may be a logarithm (log_p)
R.DST(x, df, shape, [give_log=FALSE])numberthe density at x of the skew-t distribution of df degrees of freedom and the given shape, or its logarithm (give_log)
R.PST(x, df, shape, [lower_tail=TRUE], [log_p=FALSE])numberP(X ≤ x) for the skew-t distribution of df degrees of freedom and the given shape, or P(X > x) (lower_tail = FALSE), or its logarithm (log_p)
R.QST(p, df, shape, [lower_tail=TRUE], [log_p=FALSE])numberthe quantile of the skew-t distribution of df degrees of freedom and the given shape: the x with P(X ≤ x) = p, or of P(X > x) (lower_tail = FALSE), p may be a logarithm (log_p)
R.DT(x, df, [give_log=FALSE])numberthe density at x of the Student t distribution of df degrees of freedom, or its logarithm (give_log)
R.PT(x, df, [lower_tail=TRUE], [log_p=FALSE])numberP(X ≤ x) for the Student t distribution of df degrees of freedom, or P(X > x) (lower_tail = FALSE), or its logarithm (log_p)
R.QT(p, df, [lower_tail=TRUE], [log_p=FALSE])numberthe quantile of the Student t distribution of df degrees of freedom: the x with P(X ≤ x) = p, or of P(X > x) (lower_tail = FALSE), p may be a logarithm (log_p)
R.DWEIBULL(x, shape, scale, [give_log=FALSE])numberthe density at x of the Weibull distribution of shape and scale, or its logarithm (give_log)
R.PWEIBULL(x, shape, scale, [lower_tail=TRUE], [log_p=FALSE])numberP(X ≤ x) for the Weibull distribution of shape and scale, or P(X > x) (lower_tail = FALSE), or its logarithm (log_p)
R.QWEIBULL(p, shape, scale, [lower_tail=TRUE], [log_p=FALSE])numberthe quantile of the Weibull distribution of shape and scale: the x with P(X ≤ x) = p, or of P(X > x) (lower_tail = FALSE), p may be a logarithm (log_p)
R.PTUKEY(x, nmeans, df, [nranges=1], [lower_tail=TRUE], [log_p=FALSE])numberP(Q ≤ x) for the largest of nranges (default 1) studentized ranges of nmeans means with df degrees of freedom, or P(Q > x) (lower_tail = FALSE), or its logarithm (log_p)
R.QTUKEY(p, nmeans, df, [nranges=1], [lower_tail=TRUE], [log_p=FALSE])numberthe quantile of the studentized range of nmeans means with df degrees of freedom, the largest of nranges (default 1): the x with P(Q ≤ x) = p, or of P(Q > x) (lower_tail = FALSE), p may be a logarithm (log_p)
SSMEDIAN(array OVER T, [interval=1])numberthe median of grouped data (Gnumeric): each value the midpoint of an interval of width interval (default 1), interpolated within the median's interval
INTERPOLATION(xs, ys OVER T, target, [method=0], [next])numberINTERPOLATION(xs, ys OVER T, target, [method], [next]): ys interpolated at target (Gnumeric): method 0 linear, 2 staircase, 4 natural cubic spline; 1, 3, 5 the same averaged over [target, next]
HPFILTER(values OVER T, [lambda=1600])numbereach item's trend under the Hodrick–Prescott filter with smoothing λ (default 1600); the cycle is y − trend; needs 6 values
ADTEST(values OVER T)numberthe p-value of the Anderson–Darling test of normality (Gnumeric; 8 values or more)
CVMTEST(values OVER T)numberthe p-value of the Cramér–von Mises test of normality (Gnumeric; 8 values or more)
LKSTEST(values OVER T)numberthe p-value of the Lilliefors (Kolmogorov–Smirnov) test of normality (Gnumeric; 5 values or more)
SFTEST(values OVER T)numberthe p-value of the Shapiro–Francia test of normality (Gnumeric; 5 to 5000 values)
ADTEST.STAT(values OVER T)numberthe Anderson–Darling statistic A² (adjusted for n), Gnumeric's ADTEST second value
CVMTEST.STAT(values OVER T)numberthe Cramér–von Mises statistic W², Gnumeric's CVMTEST second value
LKSTEST.STAT(values OVER T)numberthe Lilliefors statistic D, Gnumeric's LKSTEST second value
SFTEST.STAT(values OVER T)numberthe Shapiro–Francia statistic W', Gnumeric's SFTEST second value
LOGREG(known_ys, known_xs OVER T, [affine=TRUE], [stats=FALSE] INTO K)numberLOGREG(known_ys, known_xs OVER T, [affine], [stats] INTO K): the least-squares fit y = m·ln x + b (Gnumeric): m, b (affine = FALSE: b = 0); with stats LINEST's 5×2 block for ln x, row by row
LOGFIT(known_ys, known_xs OVER T INTO K)numberLOGFIT(known_ys, known_xs OVER T INTO K): the fit y = a + b·ln(sign·(x − c)) by Gnumeric's trial-and-error search: sign, a, b, c and the sum of squared residuals; #NUM! if the points are not logarithmic enough
PERIODOGRAM(y OVER T, [filter] INTO K)numberPERIODOGRAM(y OVER T, [filter] INTO K): the magnitudes of the first half of the Fourier transform (Gnumeric), after a window: 0 none, 1 Bartlett, 2 Hann, 3 Welch
CRONBACH(x1, x2, … OVER T)numberCRONBACH(x1, x2, … OVER T): Cronbach's α of the items x1, x2, … (one row per respondent; population variances, as Gnumeric)
FORECAST.ETS(target_date, values, timeline OVER T, [seasonality=1], [data_completion=1], [aggregation=1])numberFORECAST.ETS(target_date, values, timeline OVER T, [seasonality], [data_completion], [aggregation]): the additive Holt–Winters (triple exponential smoothing) forecast at target_date, LibreOffice's algorithm; seasonality 1 detects the season, 0 none; a target_date before the timeline's end is #NUM! (also FORECAST.ETS.ADD)
FORECAST.ETS.MULT(target_date, values, timeline OVER T, [seasonality=1], [data_completion=1], [aggregation=1])numberFORECAST.ETS.MULT(target_date, values, timeline OVER T, …): FORECAST.ETS with multiplicative seasons (LibreOffice)
FORECAST.ETS.CONFINT(target_date, values, timeline OVER T, [confidence_level=0.95], [seasonality=1], [data_completion=1], [aggregation=1])numberFORECAST.ETS.CONFINT(target_date, values, timeline OVER T, [confidence_level], [seasonality], …): the half-width of the prediction interval (default confidence_level 0.95); only for seasonality 0 (LibreOffice simulates seasonal intervals randomly): otherwise #N/A (also FORECAST.ETS.PI.ADD)
FORECAST.ETS.PI.MULT(target_date, values, timeline OVER T, [confidence_level=0.95], [seasonality=1], [data_completion=1], [aggregation=1])numberFORECAST.ETS.PI.MULT(target_date, values, timeline OVER T, …): FORECAST.ETS.CONFINT for the multiplicative model (the same for seasonality 0, the only one supported)
FORECAST.ETS.STAT(values, timeline OVER T, statistic_type, [seasonality=1], [data_completion=1], [aggregation=1])numberFORECAST.ETS.STAT(values, timeline OVER T, statistic_type, …): a statistic of FORECAST.ETS's fit: 1 α, 2 β (trend), 3 γ (season), 4 MASE, 5 SMAPE, 6 MAE, 7 RMSE, 8 step, 9 seasonality (also FORECAST.ETS.STAT.ADD)
FORECAST.ETS.STAT.MULT(values, timeline OVER T, statistic_type, [seasonality=1], [data_completion=1], [aggregation=1])numberFORECAST.ETS.STAT.MULT(values, timeline OVER T, statistic_type, …): FORECAST.ETS.STAT of the multiplicative model
FORECAST.ETS.SEASONALITY(values, timeline OVER T, [data_completion=1], [aggregation=1])numberFORECAST.ETS.SEASONALITY(values, timeline OVER T, [data_completion], [aggregation]): the season length FORECAST.ETS detects (1: none)
LEVERAGE(A OVER R, C INTO K)numberLEVERAGE(A OVER R, C INTO K): the regression leverages, the diagonal of A·(AᵀA)⁻¹·Aᵀ, one per row of A (Gnumeric); #NUM! if A's columns are dependent

Financial

Rates are per period; cash flows are in item order along their OVER category.

FunctionReturnsDescription
FV(rate, nper, pmt, [pv=0], [type=0])numberfuture value: FV(rate, nper, pmt, [pv], [type])
PV(rate, nper, pmt, [fv=0], [type=0])numberpresent value: PV(rate, nper, pmt, [fv], [type])
PMT(rate, nper, pv, [fv=0], [type=0])numberpayment per period: PMT(rate, nper, pv, [fv], [type])
IPMT(rate, per, nper, pv, [fv=0], [type=0])numberinterest part of payment per: IPMT(rate, per, nper, pv, [fv], [type])
PPMT(rate, per, nper, pv, [fv=0], [type=0])numberprincipal part of payment per: PPMT(rate, per, nper, pv, [fv], [type])
NPER(rate, pmt, pv, [fv=0], [type=0])numbernumber of periods: NPER(rate, pmt, pv, [fv], [type])
RATE(nper, pmt, pv, [fv=0], [type=0], [guess=0.1])numberrate per period (iterative): RATE(nper, pmt, pv, [fv], [type], [guess])
CUMIPMT(rate, nper, pv, start_period, end_period, type)numberinterest paid from period start to end: CUMIPMT(rate, nper, pv, start_period, end_period, type) (also CUMIPMT_ADD)
CUMPRINC(rate, nper, pv, start_period, end_period, type)numberprincipal paid from period start to end: CUMPRINC(rate, nper, pv, start_period, end_period, type) (also CUMPRINC_ADD)
ISPMT(rate, per, nper, pv)numberinterest of period per with straight-line principal: ISPMT(rate, per, nper, pv)
EFFECT(nominal_rate, npery)numbereffective annual rate of a nominal rate compounded npery times (also EFFECT_ADD)
NOMINAL(effect_rate, npery)numbernominal annual rate of an effective rate compounded npery times (also NOMINAL_ADD)
PDURATION(rate, pv, fv)numberperiods for pv to grow to fv at rate: PDURATION(rate, pv, fv) (also G_DURATION)
RRI(nper, pv, fv)numberequivalent growth rate per period: RRI(nper, pv, fv)
DOLLARDE(fractional_dollar, fraction)numbera fractional dollar price (1.02 with fraction 16 is 1 and 2/16) as a decimal
DOLLARFR(decimal_dollar, fraction)numbera decimal dollar price as a fraction (in the integer part's units)
SLN(cost, salvage, life)numberstraight-line depreciation per period: SLN(cost, salvage, life)
SYD(cost, salvage, life, per)numbersum-of-years'-digits depreciation: SYD(cost, salvage, life, per)
DB(cost, salvage, life, period, [month=12])numberfixed declining balance: DB(cost, salvage, life, period, [month=12])
DDB(cost, salvage, life, period, [factor=2])numberdouble declining balance: DDB(cost, salvage, life, period, [factor=2])
VDB(cost, salvage, life, start_period, end_period, [factor=2], [no_switch])numberdeclining balance between two periods: VDB(cost, salvage, life, start_period, end_period, [factor=2], [no_switch])
AMORDEGRC(cost, date_purchased, first_period, salvage, period, rate, [basis])numberFrench degressive depreciation: AMORDEGRC(cost, date_purchased, first_period, salvage, period, rate, [basis])
AMORLINC(cost, date_purchased, first_period, salvage, period, rate, [basis])numberFrench linear depreciation: AMORLINC(cost, date_purchased, first_period, salvage, period, rate, [basis])
ACCRINT(issue, first_interest, settlement, rate, par, frequency, [basis=0], [calc_method=TRUE])numberaccrued interest of a periodic-coupon security: ACCRINT(issue, first_interest, settlement, rate, par, frequency, [basis], [calc_method])
ACCRINTM(issue, settlement, rate, [par=1000], [basis])numberaccrued interest paid at maturity: ACCRINTM(issue, settlement, rate, [par=1000], [basis])
COUPDAYBS(settlement, maturity, frequency, [basis])numberdays from the coupon period's start to settlement
COUPDAYS(settlement, maturity, frequency, [basis])numberdays in the coupon period holding settlement
COUPDAYSNC(settlement, maturity, frequency, [basis])numberdays from settlement to the next coupon
COUPNCD(settlement, maturity, frequency, [basis])datethe next coupon date after settlement
COUPNUM(settlement, maturity, frequency, [basis])numbercoupons payable between settlement and maturity
COUPPCD(settlement, maturity, frequency, [basis])datethe coupon date on or before settlement
DISC(settlement, maturity, pr, redemption, [basis])numberdiscount rate: DISC(settlement, maturity, pr, redemption, [basis])
DURATION(settlement, maturity, coupon, yld, frequency, [basis])numberMacaulay duration: DURATION(settlement, maturity, coupon, yld, frequency, [basis]) (also BONDDURATION)
MDURATION(settlement, maturity, coupon, yld, frequency, [basis])numbermodified duration: MDURATION(settlement, maturity, coupon, yld, frequency, [basis]) (also BONDMDURATION)
INTRATE(settlement, maturity, investment, redemption, [basis])numberinterest rate of a fully invested security: INTRATE(settlement, maturity, investment, redemption, [basis])
ODDFPRICE(settlement, maturity, issue, first_coupon, rate, yld, redemption, frequency, [basis])numberprice with an odd first period: ODDFPRICE(settlement, maturity, issue, first_coupon, rate, yld, redemption, frequency, [basis])
ODDFYIELD(settlement, maturity, issue, first_coupon, rate, pr, redemption, frequency, [basis])numberyield with an odd first period: ODDFYIELD(settlement, maturity, issue, first_coupon, rate, pr, redemption, frequency, [basis])
ODDLPRICE(settlement, maturity, last_interest, rate, yld, redemption, frequency, [basis])numberprice with an odd last period: ODDLPRICE(settlement, maturity, last_interest, rate, yld, redemption, frequency, [basis])
ODDLYIELD(settlement, maturity, last_interest, rate, pr, redemption, frequency, [basis])numberyield with an odd last period: ODDLYIELD(settlement, maturity, last_interest, rate, pr, redemption, frequency, [basis])
PRICE(settlement, maturity, rate, yld, redemption, frequency, [basis])numberprice per 100 face value: PRICE(settlement, maturity, rate, yld, redemption, frequency, [basis])
PRICEDISC(settlement, maturity, discount, redemption, [basis])numberprice of a discounted security: PRICEDISC(settlement, maturity, discount, redemption, [basis])
PRICEMAT(settlement, maturity, issue, rate, yld, [basis])numberprice of a security paying interest at maturity: PRICEMAT(settlement, maturity, issue, rate, yld, [basis])
RECEIVED(settlement, maturity, investment, discount, [basis])numberamount at maturity of a fully invested security: RECEIVED(settlement, maturity, investment, discount, [basis])
TBILLEQ(settlement, maturity, discount)numberbond-equivalent yield of a Treasury bill: TBILLEQ(settlement, maturity, discount)
TBILLPRICE(settlement, maturity, discount)numberprice per 100 face of a Treasury bill: TBILLPRICE(settlement, maturity, discount)
TBILLYIELD(settlement, maturity, pr)numberyield of a Treasury bill: TBILLYIELD(settlement, maturity, pr)
YIELD(settlement, maturity, rate, pr, redemption, frequency, [basis])numberyield of a periodic-coupon security (iterative): YIELD(settlement, maturity, rate, pr, redemption, frequency, [basis])
YIELDDISC(settlement, maturity, pr, redemption, [basis])numberannual yield of a discounted security: YIELDDISC(settlement, maturity, pr, redemption, [basis])
YIELDMAT(settlement, maturity, issue, rate, pr, [basis])numberannual yield of a security paying interest at maturity: YIELDMAT(settlement, maturity, issue, rate, pr, [basis])
NPV(rate, values OVER T)numbernet present value of the flows in item order, the first discounted one period (a missing item is skipped, not zero): NPV(rate, values OVER T)
XNPV(rate, values, dates OVER T)numbernet present value of flows at dates, discounted from the first date (365-day years): XNPV(rate, values, dates OVER T)
IRR(values OVER T, [guess=0.1])numberinternal rate of return of the flows in item order (iterative): IRR(values OVER T, [guess=0.1])
XIRR(values, dates OVER T, [guess=0.1])numberinternal rate of return of flows at dates (iterative): XIRR(values, dates OVER T, [guess=0.1])
MIRR(values OVER T, finance_rate, reinvest_rate)numbermodified internal rate of return, outflows financed and inflows reinvested: MIRR(values OVER T, finance_rate, reinvest_rate)
FMRR(values OVER T, safe_rate, reinvest_rate, reinvest_min)numberfinancial management rate of return (GNU Oleo): outflows pulled back at the safe rate, inflows of at least reinvest_min pushed forward at the reinvestment rate: FMRR(values OVER T, safe_rate, reinvest_rate, reinvest_min)
FVSCHEDULE(principal, schedule OVER T)numberprincipal compounded over the rates in item order: FVSCHEDULE(principal, schedule OVER T)
OPT_BS(call_put, spot, strike, time, rate, volatility, [cost_of_carry])numberBlack-Scholes price of a European option: OPT_BS(call_put, spot, strike, time, rate, volatility, [cost_of_carry])
OPT_BS_DELTA(call_put, spot, strike, time, rate, volatility, [cost_of_carry])numberBlack-Scholes delta: OPT_BS_DELTA(call_put, spot, strike, time, rate, volatility, [cost_of_carry])
OPT_BS_GAMMA(spot, strike, time, rate, volatility, [cost_of_carry])numberBlack-Scholes gamma (calls and puts alike): OPT_BS_GAMMA(spot, strike, time, rate, volatility, [cost_of_carry])
OPT_BS_RHO(call_put, spot, strike, time, rate, volatility, [cost_of_carry])numberBlack-Scholes rho: OPT_BS_RHO(call_put, spot, strike, time, rate, volatility, [cost_of_carry])
OPT_BS_THETA(call_put, spot, strike, time, rate, volatility, [cost_of_carry])numberBlack-Scholes theta: OPT_BS_THETA(call_put, spot, strike, time, rate, volatility, [cost_of_carry])
OPT_BS_VEGA(spot, strike, time, rate, volatility, [cost_of_carry])numberBlack-Scholes vega (calls and puts alike): OPT_BS_VEGA(spot, strike, time, rate, volatility, [cost_of_carry])
OPT_BS_CARRYCOST(call_put, spot, strike, time, rate, volatility, [cost_of_carry])numberBlack-Scholes sensitivity to the cost of carry: OPT_BS_CARRYCOST(call_put, spot, strike, time, rate, volatility, [cost_of_carry])
OPT_GARMAN_KOHLHAGEN(call_put, spot, strike, time, domestic_rate, foreign_rate, volatility)numbercurrency option: OPT_GARMAN_KOHLHAGEN(call_put, spot, strike, time, domestic_rate, foreign_rate, volatility)
OPT_FRENCH(call_put, spot, strike, trading_time, calendar_time, rate, volatility, cost_of_carry)numberBlack-Scholes with trading-day volatility: OPT_FRENCH(call_put, spot, strike, trading_time, calendar_time, rate, volatility, cost_of_carry)
OPT_JUMP_DIFF(call_put, spot, strike, time, rate, volatility, lambda, gamma)numberMerton jump diffusion: OPT_JUMP_DIFF(call_put, spot, strike, time, rate, volatility, lambda, gamma)
OPT_MILTERSEN_SCHWARTZ(call_put, p_t, f_t, strike, t1, t2, v_s, v_e, v_f, rho_se, rho_sf, rho_ef, kappa_e, kappa_f)numbercommodity futures option: OPT_MILTERSEN_SCHWARTZ(call_put, p_t, f_t, strike, t1, t2, v_s, v_e, v_f, rho_se, rho_sf, rho_ef, kappa_e, kappa_f)
OPT_EXEC(call_put, spot, strike, time, rate, volatility, cost_of_carry, lambda)numberexecutive stock option: OPT_EXEC(call_put, spot, strike, time, rate, volatility, cost_of_carry, lambda)
OPT_FORWARD_START(call_put, spot, alpha, time_start, time, rate, volatility, cost_of_carry)numberforward start option: OPT_FORWARD_START(call_put, spot, alpha, time_start, time, rate, volatility, cost_of_carry)
OPT_TIME_SWITCH(call_put, spot, strike, a, time, m, dt, rate, cost_of_carry, volatility)numberdiscrete time switch option: OPT_TIME_SWITCH(call_put, spot, strike, a, time, m, dt, rate, cost_of_carry, volatility)
OPT_SIMPLE_CHOOSER(spot, strike, time1, time2, rate, cost_of_carry, volatility)numbersimple chooser option: OPT_SIMPLE_CHOOSER(spot, strike, time1, time2, rate, cost_of_carry, volatility)
OPT_BAW_AMER(call_put, spot, strike, time, rate, volatility, cost_of_carry)numberBarone-Adesi-Whaley American approximation: OPT_BAW_AMER(call_put, spot, strike, time, rate, volatility, cost_of_carry)
OPT_BJER_STENS(call_put, spot, strike, time, rate, volatility, cost_of_carry)numberBjerksund-Stensland American approximation: OPT_BJER_STENS(call_put, spot, strike, time, rate, volatility, cost_of_carry)
OPT_RGW(spot, strike, time_payout, time_exp, rate, d, volatility)numberRoll-Geske-Whaley American call with one known dividend: OPT_RGW(spot, strike, time_payout, time_exp, rate, d, volatility)
OPT_BINOMIAL(amer_euro, call_put, steps, spot, strike, time, rate, volatility, [cost_of_carry])numberCox-Ross-Rubinstein binomial tree: OPT_BINOMIAL(amer_euro, call_put, steps, spot, strike, time, rate, volatility, [cost_of_carry])
OPT_COMPLEX_CHOOSER(spot, strike_call, strike_put, time, time_call, time_put, rate, cost_of_carry, volatility)numbercomplex chooser option: OPT_COMPLEX_CHOOSER(spot, strike_call, strike_put, time, time_call, time_put, rate, cost_of_carry, volatility)
OPT_ON_OPTIONS(type, spot, strike1, strike2, time1, time2, rate, cost_of_carry, volatility)numberoption on an option ("cc", "cp", "pc", "pp"): OPT_ON_OPTIONS(type, spot, strike1, strike2, time1, time2, rate, cost_of_carry, volatility)
OPT_EXTENDIBLE_WRITER(call_put, spot, strike1, strike2, time1, time2, rate, cost_of_carry, volatility)numberwriter-extendible option: OPT_EXTENDIBLE_WRITER(call_put, spot, strike1, strike2, time1, time2, rate, cost_of_carry, volatility)
OPT_2_ASSET_CORRELATION(call_put, spot1, spot2, strike1, strike2, time, cost_of_carry1, cost_of_carry2, rate, volatility1, volatility2, rho)numbertwo-asset correlation option: OPT_2_ASSET_CORRELATION(call_put, spot1, spot2, strike1, strike2, time, cost_of_carry1, cost_of_carry2, rate, volatility1, volatility2, rho)
OPT_EURO_EXCHANGE(spot1, spot2, qty1, qty2, time, rate, cost_of_carry1, cost_of_carry2, volatility1, volatility2, rho)numberEuropean option to exchange asset 2 for asset 1: OPT_EURO_EXCHANGE(spot1, spot2, qty1, qty2, time, rate, cost_of_carry1, cost_of_carry2, volatility1, volatility2, rho)
OPT_AMER_EXCHANGE(spot1, spot2, qty1, qty2, time, rate, cost_of_carry1, cost_of_carry2, volatility1, volatility2, rho)numberAmerican option to exchange asset 2 for asset 1: OPT_AMER_EXCHANGE(spot1, spot2, qty1, qty2, time, rate, cost_of_carry1, cost_of_carry2, volatility1, volatility2, rho)
OPT_SPREAD_APPROX(call_put, fut_price1, fut_price2, strike, time, rate, volatility1, volatility2, rho)numberKirk's futures spread option approximation: OPT_SPREAD_APPROX(call_put, fut_price1, fut_price2, strike, time, rate, volatility1, volatility2, rho)
OPT_FIXED_STRK_LKBK(call_put, spot, spot_min, spot_max, strike, time, rate, cost_of_carry, volatility)numberfixed-strike lookback: OPT_FIXED_STRK_LKBK(call_put, spot, spot_min, spot_max, strike, time, rate, cost_of_carry, volatility)
OPT_FLOAT_STRK_LKBK(call_put, spot, spot_min, spot_max, time, rate, cost_of_carry, volatility)numberfloating-strike lookback: OPT_FLOAT_STRK_LKBK(call_put, spot, spot_min, spot_max, time, rate, cost_of_carry, volatility)
OPT_BARRIER(spot, vol, r, rf, maturity, strike, lower, upper, rebate, put_call, in_out, continuous_or_end, [greek])numberbarrier option: OPT_BARRIER(spot, vol, r, rf, maturity, strike, lower, upper, rebate, put_call, in_out, continuous_or_end, [greek])
OPT_TOUCH(spot, vol, r, rf, maturity, lower, upper, foreign_domestic, in_out, continuous_or_end, [greek])numberone/no-touch option: OPT_TOUCH(spot, vol, r, rf, maturity, lower, upper, foreign_domestic, in_out, continuous_or_end, [greek])
OPT_PROB_HIT(spot, vol, mu, maturity, lower, upper)numberprobability of touching a barrier: OPT_PROB_HIT(spot, vol, mu, maturity, lower, upper)
OPT_PROB_INMONEY(spot, vol, mu, maturity, lower, upper, [strike], [put_call])numberprobability of ending between the barriers (and in the money): OPT_PROB_INMONEY(spot, vol, mu, maturity, lower, upper, [strike], [put_call])

Engineering

Complex numbers are text, "3+4i" (suffix i or j); base conversions use 10-digit two's complement for negatives.

FunctionReturnsDescription
BIN2DEC(number)numberbinary text as a number
BIN2HEX(number, [places])textbinary text as hexadecimal, zero-padded to places
BIN2OCT(number, [places])textbinary text as octal, zero-padded to places
DEC2BIN(number, [places])textan integer in −512…511 as binary text
DEC2HEX(number, [places])textan integer in −2³⁹…2³⁹−1 as hexadecimal text
DEC2OCT(number, [places])textan integer in −2²⁹…2²⁹−1 as octal text
HEX2BIN(number, [places])texthexadecimal text as binary
HEX2DEC(number)numberhexadecimal text as a number
HEX2OCT(number, [places])texthexadecimal text as octal
OCT2BIN(number, [places])textoctal text as binary
OCT2DEC(number)numberoctal text as a number
OCT2HEX(number, [places])textoctal text as hexadecimal
BASE(number, radix, [min_length])textan integer in 0…2⁵³−1 as text in a radix 2…36, zero-padded to min_length (also NUMTOBASE)
DECIMAL(text, radix)numbertext in a radix 2…36 as a number (also BASETONUM)
HEXREP(x)textthe bytes of a number's IEEE double, little-endian, in hexadecimal
BITAND(number1, number2)numberbitwise and
BITOR(number1, number2)numberbitwise or
BITXOR(number1, number2)numberbitwise exclusive or
BITLSHIFT(number, shift_amount)numbershifted left by shift_amount bits (right if negative), at most 53 either way
BITRSHIFT(number, shift_amount)numbershifted right by shift_amount bits (left if negative), at most 53 either way
CONVERT(number, from_unit, to_unit)numbera measurement converted between units of Excel's table (SI and binary prefixes allowed); #N/A for unknown or mismatched units
DELTA(number1, [number2=0])number1 if the numbers are equal (number2 defaults to 0), else 0
GESTEP(number, [step=0])number1 if number ≥ step (default 0), else 0
COMPLEX(real_num, i_num, [suffix="i"])textthe complex number re + im·i as text, with suffix "i" (default) or "j"
IMREAL(inumber)numbera complex number's real part
IMAGINARY(inumber)numbera complex number's imaginary part
IMABS(inumber)numbera complex number's modulus
IMARGUMENT(inumber)numbera complex number's angle in radians, −π…π (#NUM! at 0)
IMCONJUGATE(inumber)textthe complex conjugate
IMNEG(inumber)text−z
IMINV(inumber)text1/z
IMSUM(inumber1, …)textthe sum of complex numbers
IMPRODUCT(inumber1, …)textthe product of complex numbers
IMSUB(inumber1, inumber2)textz1 − z2
IMDIV(inumber1, inumber2)textz1 / z2
IMPOWER(inumber, number)textz raised to a real power
IMSQRT(inumber)textthe principal square root
IMEXP(inumber)texte^z
IMLN(inumber)textthe principal natural logarithm
IMLOG10(inumber)textthe principal base-10 logarithm
IMLOG2(inumber)textthe principal base-2 logarithm
IMSIN(inumber)textthe complex sine
IMCOS(inumber)textthe complex cosine
IMTAN(inumber)textthe complex tangent
IMSEC(inumber)textthe complex secant
IMCSC(inumber)textthe complex cosecant
IMCOT(inumber)textthe complex cotangent
IMSINH(inumber)textthe complex hyperbolic sine
IMCOSH(inumber)textthe complex hyperbolic cosine
IMTANH(inumber)textthe complex hyperbolic tangent
IMSECH(inumber)textthe complex hyperbolic secant
IMCSCH(inumber)textthe complex hyperbolic cosecant
IMCOTH(inumber)textthe complex hyperbolic cotangent
IMARCSIN(inumber)textthe complex arcsine (principal branch)
IMARCCOS(inumber)textthe complex arccosine
IMARCTAN(inumber)textthe complex arctangent
IMARCSEC(inumber)textthe complex arcsecant
IMARCCSC(inumber)textthe complex arccosecant
IMARCCOT(inumber)textthe complex arccotangent
IMARCSINH(inumber)textthe complex inverse hyperbolic sine
IMARCCOSH(inumber)textthe complex inverse hyperbolic cosine
IMARCTANH(inumber)textthe complex inverse hyperbolic tangent
IMARCSECH(inumber)textthe complex inverse hyperbolic secant
IMARCCSCH(inumber)textthe complex inverse hyperbolic cosecant
IMARCCOTH(inumber)textthe complex inverse hyperbolic cotangent
IMFACT(inumber)textthe complex factorial z! = Γ(z + 1)
IMGAMMA(inumber)textthe complex gamma function Γ(z)
BESSELI(x, n)numberthe modified Bessel function Iₙ(x)
BESSELJ(x, n)numberthe Bessel function Jₙ(x)
BESSELK(x, n)numberthe modified Bessel function Kₙ(x), x > 0
BESSELY(x, n)numberthe Bessel function Yₙ(x), x > 0
IMIGAMMA(a, inumber, [lower=TRUE], [regularize=TRUE])textthe complex incomplete gamma function of a and z: lower (default) or upper, regularized (default) or not

pg_improv SQL reference

Every function, setting and status column of pg_improv 0.13.0, read from the extension's catalog. Every function is in schema improv and runs SECURITY INVOKER; a function on a model acts as the model's owner (see Privileges). Improv in Postgres explains how they fit together, and Compatibility which of them are stable.

Functions

bind_category

improv.bind_category(model text, category text, rel regclass, col text) → void

Creates the category if missing and records that rel.col supplies its items.

bind_measure

improv.bind_measure(model text, measure text, rel regclass, value_col text, agg text DEFAULT NULL::text) → void

Creates an input measure read from rel.value_col. Its dimensions are the categories already bound on rel, in category-id order. Two rows on one coordinate are an error unless agg (sum, avg, min, max, count) folds them; an aggregated measure is read-only in the GUI.

categories

improv.categories(model text) → TABLE(id bigint, name text)

The model's categories, for a role its policies let open it (ViewModel), and for the owner.

cells

improv.cells(model text, measure text) → TABLE(coord jsonb, value jsonb)

The cells of one measure the caller may read (ReadCell): an input's from its table, a derived measure's from its result table, read as the owner. A hidden measure answers as one that does not exist.

create_model

improv.create_model(name text) → bigint

Creates the model and its result schema improv_<lower(name)>.

define

improv.define(model text, definition text, replace boolean DEFAULT false) → bigint

Adds a derived measure from Target = expr and creates its result table, or a named LAMBDA from Name = LAMBDA(p, …, body) (see the README). SQL(...) and CALL(...) are rejected. An existing name is an ERROR unless replace => true, which redefines the derived measure (see the README). Returns the measure's (or lambda's) id.

drop_measure

improv.drop_measure(model text, measure text) → void

Drops a measure: a derived one's result table, an input's binding and stored cells, and its catalog row; or a named LAMBDA. An ERROR names the measures (and lambdas) that still reference it.

drop_model

improv.drop_model(name text) → void

Drops the catalog rows, the result schema and the triggers, and takes relations no other logical-mode model binds out of improv_db.

enable_logical

improv.enable_logical(model text) → void

Adds the model's bound relations to the database's publication improv_db and gives PK-less ones REPLICA IDENTITY FULL. Called for you by bind_measure and set_sync_mode(…, 'logical'). The worker creates the slot.

explain_access

improv.explain_access(model text, action text, resource jsonb DEFAULT NULL::jsonb, role text DEFAULT NULL::text) → TABLE(step integer, action text, resource text, allowed boolean, policies text[], errors text[])

Each question the policy rules ask for role (the caller when NULL) doing action on resource (NULL: the model; {"measure": M}, {"measure": M, "at": {"Category": "Item"}}, {"category": C}, {"category": C, "item": I}, {"view": V}), with the deciding policies, to the first denial. Only the owner's side and Admins ask about others or see the policies; a role asking about itself gets one row, allowed or not.

items

improv.items(model text) → TABLE(category text, id bigint, name text)

The items the caller may read (ReadItem).

measures

improv.measures(model text) → TABLE(id bigint, name text, kind text, value_type text, categories text[], formula text)

The measures the caller may read (ReadMeasure); formula is NULL unless every measure it reads is readable too.

policies

improv.policies(model text) → TABLE(version bigint, policies text, groups text, set_by text, set_at timestamp with time zone)

The stored policies: no row if never set, a NULL policies after a clear. For the owner's side and Admins.

recalc (1 arguments)

improv.recalc(model text) → bigint

Recomputes every derived measure in the caller's transaction and returns the number of result rows inserted, updated or deleted.

recalc (2 arguments)

improv.recalc(model text, measures text[]) → bigint

Recomputes only the named measures (input or derived, case-insensitive) and every derived measure that depends on them. NULL means all.

set_cells

improv.set_cells(model text, edits jsonb) → bigint

Sets (null: clears) input cells, as what_if's edits name them, writing the bound table (or improv.cell) as the owner and recomputing. Each cell must pass EditCell; one that does not refuses the call. Returns the cells written. Audited.

set_policies

improv.set_policies(model text, policies text, groups text DEFAULT NULL::text) → bigint

Stores the model's access policies (Cedar text, groups JSON), validated as improv policy set validates them; NULL policies clears them. Returns the new version. For the owner, a role that may act as it, or one the policies allow Admin. Audited. See Access policies.

set_sync_mode

improv.set_sync_mode(model text, mode text) → void

trigger: installs the sync triggers on every bound relation and recomputes once (re-run it after binding a new relation). commit: recomputes once, then once per writing transaction before it commits; needs the preload. logical/manual: removes the triggers.

status

improv.status(model text) → TABLE(sync_mode text, slot text, lag_bytes bigint, confirmed_lsn text, last_applied_at timestamp with time zone, rows_applied bigint, last_error text, incremental_applies bigint, rebuilds bigint, fold_bytes bigint, engine_bytes bigint)

How the model is kept current, how far the logical worker is behind, and how it applied its batches: incremental_applies to the live engine, rebuilds full loads (the first catch-up, structural changes, and what it could not apply incrementally).

sync_publication

improv.sync_publication() → void

Sets improv_db to the union of the relations every logical-mode model binds (creating it when missing). Called for you by every function that changes that set; run it by hand to repair a publication edited by hand.

what_if

improv.what_if(model text, edits jsonb) → TABLE(measure text, coord jsonb, value jsonb)

Evaluates the model with edits applied in memory and returns the derived cells that differ from the stored results (value NULL: the cell would vanish). Writes nothing. When every edit has the same categories and the measures they feed are element-wise, it loads and compares only the edited coordinates, as trigger mode does. Only a role that may act as the model's owner may call it, and it reads as the owner (see Privileges, which shows how to give it to other roles).

Internal functions

The extension calls these itself (as triggers, as the LANGUAGE improv handler, or from its row-level security policies). Do not call them.

FunctionReturnsWhat it is
cell_name(model bigint, measure bigint, dim integer, slot integer)textRow-level security on a result table, under cell_rule 2: the slotth name of dimension dim the caller may not read (NULL past the last).
cell_rule(model bigint, measure bigint)integerRow-level security on a result table of a model with access policies, once per statement (an InitPlan): 0 shows every row, 1 none (the stored policies cannot be used, or nothing of the measure is readable), 2 compares each row's names with cell_name's (only while improv.stale vouches that every result row names the model's items), 3 checks each row with row_visible.
cell_visible(model bigint, measure bigint, dims text[])booleanWhether the caller may read the cell of measure at dims (item names in the measure's category order), as the result tables' row-level security decides it: true without policies and for the owner's side; false for a hidden cell, a name the model lacks, and every cell when the stored policies cannot be used. The check of a result table without dimensions.
check_owner()triggerTrigger on improv.model: only a role that may act as both the current and the new owner may set or change a model's owner.
commit_capture()triggerCommit mode's row-capture statement trigger (improv.commit_capture = 'rows'): notes the coordinates a statement touched for the pre-commit recompute.
commit_catalog_changed()triggerStatement trigger on improv.model and improv.binding: invalidates every backend's cache of the commit-mode relations.
item_changed()triggerStatement trigger on improv.item: an item renamed or deleted marks its model's result rows stale (improv.stale), so the result tables' qual checks them row by row until a recalc.
may_act_as(r regrole)booleanWhether the caller may act as role r: a superuser, or a member with the right to SET ROLE to it (any member on PG 15). The row-level security policies on the catalog call it.
mint_items(p_model bigint, p_cats bigint[], p_names text[])TABLE(category_id bigint, name text, id bigint)Assigns ids to item names it has not seen, in lexical order, never reusing one. Shared with the postgres:// model store.
on_change()triggerTrigger mode's sync trigger: recomputes the changed inputs' dependents in the writer's transaction, as the model's owner.
plimprov_call_handler()language_handlerThe LANGUAGE improv call handler.
plimprov_validator(oid)voidThe LANGUAGE improv validator: checks the signature, and the body when check_function_bodies is on.
result_written()triggerStatement trigger on a filtered result table: a write marks the model's result rows stale (improv.stale) until a recalc checks them.
row_visible(model bigint, measure bigint, VARIADIC dims "any")booleanRow-level security on a result table, per row under cell_rule 3: cell_visible's answer for the row's dimension values (text, in the measure's category order), from a decision table kept for the query.
unrestricted(model bigint)booleanRow-level security on the catalog: whether the caller may read model model's measures, bindings, views and lambdas. True without access policies (0.12's rule) and for the owner's side.

Settings (GUCs)

Set in is the GUC's context: where a change takes effect.

GUCTypeDefaultRangeSet inDescription
improv.commit_captureenumrelationsrelations, rowsany session (SET)What entering commit sync mode installs on the bound tables. relations (the default): nothing, and each COMMIT recomputes the written tables' dependents in full; rows: statement triggers that capture the touched coordinates, so COMMIT recomputes only those. Read by improv.set_sync_mode.
improv.databasestringpostgrespostgresql.conf, restartDatabase the pg_improv sync worker connects to. The logical-decoding worker serves the Improv models of this one database.
improv.max_cellsinteger50000000–2147483647any session (SET)Maximum bound input cells per Improv model. Every load of a model (recalc, define, a trigger-mode or commit-mode recompute, the sync worker's rebuild and apply) refuses a model with more bound input cells.
improv.max_changesinteger100001–2147483647postgresql.conf, reloadMost decoded changes one poll of the sync worker reads. Bounds the work (and memory) of one poll.
improv.max_model_memoryinteger0 MB0–2147483647 MBpostgresql.conf, reloadMost memory (MB) one model's live state may hold in the sync worker. A model whose fold state plus engine (as improv.status estimates them) would exceed it is refused: the worker logs why, sets its last_error, and retries it with backoff instead of growing until the backend is killed; 0 is no cap.
improv.max_slot_laginteger4096 MB0–2147483647 MBpostgresql.conf, reloadWAL (MB) the sync worker's slot may lag before it is dropped and remade. Past it the worker drops the slot and rebuilds each model from its tables, rather than retain more WAL; 0 never drops it. A cap that also holds while the worker is down is max_slot_wal_keep_size.
improv.poll_msinteger20010–60000postgresql.conf, reloadHow often the pg_improv sync worker polls its slot, in ms. Lower is fresher results; higher is fewer idle wakeups.
improv.raise_errorsbooloffany session (SET)Raise a LANGUAGE improv error value instead of returning NULL. When on, a LANGUAGE improv function whose result is an error value (#DIV/0!, #NUM!, #N/A, ...) raises an ERROR naming it; when off it returns NULL.

improv.database exists only when pg_improv is in shared_preload_libraries.

improv.status(model) columns

One row per call; Monitoring says what a healthy value looks like and which to alert on.

ColumnTypeMeaning
sync_modetextlogical, trigger, commit or manual.
slottextimprov_db in logical mode (the slot every logical model of the database shares); NULL otherwise.
lag_bytesbigintpg_current_wal_lsn() − confirmed_flush_lsn of the slot: WAL the worker has not confirmed yet. It is the slot's lag, so every logical model of the database shows the same number. NULL when the slot does not exist (not yet created, or dropped).
confirmed_lsntextThe slot's confirmed_flush_lsn.
last_applied_attimestamptzWhen the worker last applied a batch to this model, or rebuilt it. It does not move while the model's tables are idle. NULL before the first catch-up, and after a new slot resets progress.
rows_appliedbigintResult rows the worker has written for this model (inserted, updated or deleted), in total.
last_errortextWhy the worker's last attempt at this model failed; NULL after a success. While set, the model is retried with backoff (0.5 s, doubling, up to 60 s), and every retry is a full rebuild.
incremental_appliesbigintBatches the worker fed to the live engine (the cheap path).
rebuildsbigintFull reloads and recomputes. The first catch-up counts one; so does each worker restart, structural change (define, a new binding), and batch that needs one (Concepts lists the triggers).
fold_bytesbigintEstimated heap of the model's fold state in the worker: what its aggregated bindings (agg => …) keep per coordinate. A count_distinct, min or max binding keeps its values too, so it grows with their number. 0 without aggregated bindings. Measured after each rebuild, and at most once a second while the model applies batches; NULL while the worker holds no live state for the model (before its first change, or after it failed).
engine_bytesbigintEstimated heap of the model's live engine and input cells in the worker, as of the same moment. fold_bytes + engine_bytes is what improv.max_model_memory caps.

improv.models columns

A view of every model, for anyone who may read the catalog.

ColumnTypeMeaning
nametextThe model's name.
ownerregroleThe role the model reads its tables and writes its results as.
sync_modetextlogical, trigger, commit or manual.
may_changebooleanWhether the caller may act as the owner: change the model, read its items and cells, what_if it.
result_schematextThe schema of its result tables, improv_<lower(name)>.

Command-line reference

Every command and flag of the four binaries, as --help prints them. The same text is in the man pages: man improv, man improv-set, and so on. Every command also takes -h (a summary) and --help, and each binary -V/--version. Running Improv shows which binary to use when.

improv

Build, edit and evaluate Improv models from the shell. Each command opens a model store, reads or changes the model, and saves it back. Run 'improv help COMMAND' for one command.

Usage: improv [COMMAND]

improv init

Create or open a store and install the schema.

An existing model is kept. An empty string is an in-memory store.

Usage: improv init <db>
ArgumentDescription
<db>The model store: a file, or postgres://USER@HOST/DB?model=NAME

improv add-category

Add a category (a dimension, such as Time)

Usage: improv add-category <db> <id> <name>
ArgumentDescription
<db>The model store: a file, or postgres://USER@HOST/DB?model=NAME
<id>The category's numeric id
<name>The category's name

improv add-item

Add an item (a member of a category).

The category must exist.

Usage: improv add-item <db> <id> <category-id> <name>
ArgumentDescription
<db>The model store: a file, or postgres://USER@HOST/DB?model=NAME
<id>The item's numeric id
<category-id>The id of the item's category
<name>The item's name

improv add-measure

Add an input measure.

Its type says how set parses its values. The word input is required, after the type and before the categories it ranges over, which follow by name: add-measure m.db 101 Quantity number input Time Product.

Usage: improv add-measure <db> <id> <name> <type> <input> [category]...
ArgumentDescription
<db>The model store: a file, or postgres://USER@HOST/DB?model=NAME
<id>The measure's numeric id
<name>The measure's name
<type>number, boolean or text
<input>The word input
<category>The categories the measure ranges over, by name

improv add-derived

Add a derived (formula) measure.

The formula is the right-hand side only, e.g. "Price * Quantity" or "SUM(Revenue OVER Time)", with names resolved against the model. The measure's categories come from the measures it references. A formula cycle is refused.

Usage: improv add-derived <db> <id> <name> <formula>
ArgumentDescription
<db>The model store: a file, or postgres://USER@HOST/DB?model=NAME
<id>The measure's numeric id
<name>The measure's name
<formula>The formula text (in IMPROV_LOCALE's spelling)

improv define

Create a measure or LAMBDA from a definition, "Target = ...".

Three forms: a formula, "Revenue = Price * Quantity"; an external call, "H = CALL(hypot, Price, Quantity)", which refresh-ext populates; or a named LAMBDA, "Margin = LAMBDA(p, c, p - c)", which formulas then call as Margin(Price, Cost). The id names a LAMBDA, and redefining one keeps its first id. The SQL(...) form needs a column-to-dimension map: use import-sql. A formula cycle is refused.

Usage: improv define [OPTIONS] <db> <id> <definition>
ArgumentDescription
<db>The model store: a file, or postgres://USER@HOST/DB?model=NAME
<id>The measure's (or LAMBDA's) numeric id
<definition>The definition: Target = formula, CALL(...) or LAMBDA(...)
--refresh <policy>When serve-refresh re-runs it: manual, on-load or interval:SECS (default: manual)

improv register-ext

Register a Python external function.

Number arguments and a Number result: the body reads the list args and sets result, e.g. register-ext m.db hypot 2 "result = (args[0]**2 + args[1]**2) ** 0.5".

Usage: improv register-ext <db> <name> <arity> <python-body>
ArgumentDescription
<db>The model store: a file, or postgres://USER@HOST/DB?model=NAME
<name>The function's name, as CALL(...) names it
<arity>How many arguments it takes
<python-body>The Python body

improv refresh-ext

Run a CALL(...) measure's function and store its cells.

The function runs host-side, over its argument measures; external calls stay off the dataflow engine.

Usage: improv refresh-ext <db> <measure>
ArgumentDescription
<db>The model store: a file, or postgres://USER@HOST/DB?model=NAME
<measure>A measure: its numeric id, or its name (all digits is an id)

improv set

Set an input cell.

The value is parsed by the measure's type: a number, true or false, or verbatim text. --at maps category names to item names; omit it for a scalar cell. Pairs may be comma-joined (--at Time=Q1,Product=A), space-separated (--at Time=Q1 Product=A) or in repeated flags; they are merged, and a category may appear only once.

Usage: improv set [OPTIONS] <db> <measure> <value>
ArgumentDescription
<db>The model store: a file, or postgres://USER@HOST/DB?model=NAME
<measure>A measure: its numeric id, or its name (all digits is an id)
<value>The cell's value
--at <Cat=Item>The cell's coordinate: Category=Item pairs, comma-joined, space-separated, or in repeated --at flags

improv list

Print the categories, items, measures, views and input cells

Usage: improv list <db>
ArgumentDescription
<db>The model store: a file, or postgres://USER@HOST/DB?model=NAME

improv save-view

Save a named view of a measure, as the GUI does.

--rows and --cols stack category names outer to inner; each defaults to the next unused category of the measure. The other categories are pages, pinned to their first item. A view with the same id is replaced.

Usage: improv save-view [OPTIONS] <db> <view-id> <name> <measure>
ArgumentDescription
<db>The model store: a file, or postgres://USER@HOST/DB?model=NAME
<view-id>The view's numeric id
<name>The view's name
<measure>The measure, by id or name
--rows <Cat,...>The row categories, comma-separated, outer first
--cols <Cat,...>The column categories, comma-separated, outer first

improv format

Set how a measure's numbers are shown.

The format is general (as many digits as the value needs) or a count of decimals, 0 to 15, then grouped for thousands separators: format m.db Revenue 2 grouped. Decimals round half away from zero; the separators follow IMPROV_LOCALE. show, eval and stream print the measure's cells in it, and the GUI and TUI show it; the values, list and the exports are untouched.

Usage: improv format <db> <measure> <format>...
ArgumentDescription
<db>The model store: a file, or postgres://USER@HOST/DB?model=NAME
<measure>A measure: its numeric id, or its name (all digits is an id)
<format>general, or 0 to 15 decimals, then grouped

improv show

Print one measure and its input cells

Usage: improv show <db> <measure>
ArgumentDescription
<db>The model store: a file, or postgres://USER@HOST/DB?model=NAME
<measure>A measure: its numeric id, or its name (all digits is an id)

improv eval

Compute a derived measure and print its cells.

With --scenario, under that what-if scenario's overrides.

Usage: improv eval [OPTIONS] <db> <measure>
ArgumentDescription
<db>The model store: a file, or postgres://USER@HOST/DB?model=NAME
<measure>A measure: its numeric id, or its name (all digits is an id)
--scenario <name>The scenario to evaluate under

improv scenario

Add an input-cell override to a what-if scenario.

The scenario is created if it is new. The base model is untouched; evaluate under it with eval ... --scenario NAME. --at takes the same forms as for set.

Usage: improv scenario [OPTIONS] <db> <scenario-name> <measure> <value>
ArgumentDescription
<db>The model store: a file, or postgres://USER@HOST/DB?model=NAME
<scenario-name>The scenario's name
<measure>A measure: its numeric id, or its name (all digits is an id)
<value>The overriding value
--at <Cat=Item>The cell's coordinate: Category=Item pairs, comma-joined, space-separated, or in repeated --at flags

improv export

Print the whole model as JSON

Usage: improv export <db>
ArgumentDescription
<db>The model store: a file, or postgres://USER@HOST/DB?model=NAME

improv import-sql

Import a SQLite query into a new SQL-backed input measure.

Each dimension spec maps a result column to a category (its distinct values become items); the value column holds the numbers. Re-run the query with refresh-sql. Example: improv import-sql m.db sales.db 100 Revenue "SELECT t,p,r FROM sales" r t:1:Time p:2:Product

Usage: improv import-sql [OPTIONS] <db> <source.sqlite> <measure-id> <measure-name> <SELECT> <value-col> <dim-col:cat-id:cat-name>...
ArgumentDescription
<db>The model store: a file, or postgres://USER@HOST/DB?model=NAME
<source.sqlite>The SQLite database to query
<measure-id>The new measure's numeric id
<measure-name>The new measure's name
<SELECT>The query
<value-col>The result column holding the values
<dim-col:cat-id:cat-name>COLUMN:CATEGORY-ID:CATEGORY-NAME: a column, and the category its distinct values become items of
--refresh <policy>When serve-refresh re-runs it: manual, on-load or interval:SECS (default: manual)

improv refresh-sql

Re-run an SQL-backed measure's query and replace its cells.

New dimension values become new items.

Usage: improv refresh-sql <db> <source.sqlite> <measure>
ArgumentDescription
<db>The model store: a file, or postgres://USER@HOST/DB?model=NAME
<source.sqlite>The SQLite database to query
<measure>A measure: its numeric id, or its name (all digits is an id)

improv refresh-all

Refresh every external measure now.

Every CALL(...) measure, and every SQL-backed measure when a source is given. Each measure's refresh policy is reported, not applied.

Usage: improv refresh-all <db> [source.sqlite]
ArgumentDescription
<db>The model store: a file, or postgres://USER@HOST/DB?model=NAME
<source.sqlite>The SQLite database the SQL-backed measures query

improv serve-refresh

Refresh measures as their refresh policies fall due, until interrupted.

On every tick: on-load measures once, interval:N measures every N seconds. SQL-backed measures refresh only when a source is given.

Usage: improv serve-refresh [OPTIONS] <db> [source.sqlite]
ArgumentDescription
<db>The model store: a file, or postgres://USER@HOST/DB?model=NAME
<source.sqlite>The SQLite database the SQL-backed measures query
--tick <SECS>Seconds between ticks (default: 5)

improv export-sql

Write a measure's input cells to a SQLite table.

One column per dimension category, then the value column; the table is created if absent. Identifiers are validated and values bound as parameters.

Usage: improv export-sql <db> <target.sqlite> <measure> <table> <value-col>
ArgumentDescription
<db>The model store: a file, or postgres://USER@HOST/DB?model=NAME
<target.sqlite>The SQLite database to write
<measure>A measure: its numeric id, or its name (all digits is an id)
<table>The table
<value-col>The value column's name

improv import-csv

Import a CSV or TSV file into a new input measure.

Columns are header names, or 0-based indices with --no-header. The delimiter is a comma unless --tsv is given or the file ends in .tsv. Example: improv import-csv m.db sales.csv 100 Revenue r t:1:Time p:2:Product

Usage: improv import-csv [OPTIONS] <db> <file.csv> <measure-id> <measure-name> <value-col> <dim-col:cat-id:cat-name>...
ArgumentDescription
<db>The model store: a file, or postgres://USER@HOST/DB?model=NAME
<file.csv>The file to read
<measure-id>The new measure's numeric id
<measure-name>The new measure's name
<value-col>The column holding the values
<dim-col:cat-id:cat-name>COLUMN:CATEGORY-ID:CATEGORY-NAME: a column, and the category its distinct values become items of
--tsv <TSV>Tab-separated
--no-header <NO_HEADER>The file has no header row: columns are 0-based indices

improv export-csv

Write a measure's cells to a CSV or TSV file.

An input measure's stored cells or a derived measure's computed ones: one column per dimension category, then the value; header row first. Text a spreadsheet would run as a formula is prefixed with a quote.

Usage: improv export-csv [OPTIONS] <db> <target.csv> <measure>
ArgumentDescription
<db>The model store: a file, or postgres://USER@HOST/DB?model=NAME
<target.csv>The file to write (tab-separated if it ends in .tsv)
<measure>A measure: its numeric id, or its name (all digits is an id)
--tsv <TSV>Tab-separated

improv stream

Apply input edits from stdin and print the cells they change.

One edit per line, MEASURE VALUE [Cat=Item,...] (the measure by id or name; no coordinate for a scalar measure). Each applies to a live incremental engine, and every changed cell of a target measure prints as MEASURE Cat=Item,... = VALUE. A malformed line is reported on stderr and skipped. At end of input the model is saved. Example: printf 'Price 12 Product=WidgetA\n' | improv stream m.db Revenue

Usage: improv stream <db> <target-measure>...
ArgumentDescription
<db>The model store: a file, or postgres://USER@HOST/DB?model=NAME
<target-measure>The measures whose changes to print, by id or name

improv policy

Manage a model's access policies (Cedar).

A model with no policies is unrestricted. With policies, a user may do only what a policy permits, and a forbid wins. Policies name measures, items, categories and views by id. See improv-policy-* and the guide's Access Policies chapter.

Usage: improv policy <COMMAND>

improv-gui

Open a model in a NeXTSTEP-style workspace.

Usage: improv-gui [model]
ArgumentDescription
<model>The model: a store file, or postgres://USER@HOST/DB?model=NAME. Without it the model is in memory only

improv-cosmic

Open a model in a COSMIC (libcosmic) window that follows the desktop's theme.

Usage: improv-cosmic [model]
ArgumentDescription
<model>The model: a store file, or postgres://USER@HOST/DB?model=NAME. Without it the model is in memory only

improv-tui

Show one measure of a model as a pivot grid in the terminal.

Usage: improv-tui <model>
ArgumentDescription
<model>The model: a store file (a new one opens empty), or postgres://USER@HOST/DB?model=NAME

improv-server

Serve one model over HTTP/1.1 as JSON.

Usage: improv-server [OPTIONS] [model] [addr]
ArgumentDescription
<model>The model: a store file, or postgres://USER@HOST/DB?model=NAME (default: improv.db)
<addr>The address to listen on (default: 127.0.0.1:3000) (env: IMPROV_ADDR)
--static <DIR>Also serve the files in DIR (a web front end's build) at /, beside the API; off by default

HTTP API reference

JSON HTTP API over one Improv model. Every path is also served without the /v1 prefix (an alias kept for older clients). x-improv-scope names the token scope a route needs: public (no token), read, or write. A missing or unknown token gets 401, a read token on a write route 403, an over-limit body 413, a caller over its rate limit 429.

The server serves this document at /v1/openapi.json. Point any OpenAPI viewer at that URL, or at docs/openapi.json, for an interactive page. The HTTP Server covers running, tokens and limits.

MethodPathScopeSummary
GET/v1/capabilitiesreadWhat the caller may do
POST/v1/categorieswriteAdd a category
DELETE/v1/categories/{id}writeDelete a category
PUT/v1/categories/{id}writeRename a category
POST/v1/categories/{id}/itemswriteAdd an item
POST/v1/cellswriteEdit cells
GET/v1/changesreadChanges, as Server-Sent Events
GET/v1/healthpublicLiveness probe
DELETE/v1/items/{id}writeDelete an item
PUT/v1/items/{id}writeRename an item
GET/v1/measuresreadList the measures
POST/v1/measureswriteDefine a measure
DELETE/v1/measures/{id}writeDelete a measure
PUT/v1/measures/{id}writeChange a measure
POST/v1/measures/{id}/cellswriteSet one input cell
POST/v1/measures/{id}/evalreadWhat-if evaluation
GET/v1/measures/{id}/valuesreadA measure's values
POST/v1/measures/{id}/windowreadA window of a measure's cells
GET/v1/modelreadThe whole model
POST/v1/nl/describereadA formula to controlled English
POST/v1/nl/parsereadControlled English to a formula
GET/v1/openapi.jsonpublicThis document
POST/v1/redowriteRedo
GET/v1/scheduler/statusreadRefresh scheduler state
GET/v1/structurereadWhat the caller may see of the model
POST/v1/undowriteUndo
POST/v1/viewswriteSave a view
DELETE/v1/views/{id}writeDelete a view
PUT/v1/views/{id}writeChange a view

GET /v1/capabilities

What the caller may do Scope: read.

Hints for a GUI to grey out what the caller cannot do, from the model's access policies: the model-wide actions, for each visible measure whether it may be redefined and which of its cells may be edited, and the visible items that may be renamed or deleted. Every request is still checked. Without policies, everything the token's scope allows.

StatusResponse
200The caller's capabilities. Body: Capabilities.
401No token, or an unknown one. Body: Error.
403Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
429The caller is over IMPROV_RATE_LIMIT requests a minute. Body: Error.
500Internal error; the detail is in the server log under request_id. Body: Error.

POST /v1/categories

Add a category Scope: write.

  • Path parameter x-improv-session: {"maxLength":64,"type":"string"}.

Request body: Name.

StatusResponse
200Done. Body: Done.
400Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
401No token, or an unknown one. Body: Error.
403Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
404Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
409Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
413The body is over IMPROV_MAX_BODY_BYTES.
429The caller is over IMPROV_RATE_LIMIT requests a minute. Body: Error.
500Internal error; the detail is in the server log under request_id. Body: Error.

DELETE /v1/categories/

Delete a category Scope: write.

With its items. Refused while a measure uses it.

  • Path parameter id: {"minimum":0,"type":"integer"}.

  • Path parameter x-improv-session: {"maxLength":64,"type":"string"}.

StatusResponse
200Done. Body: Done.
400Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
401No token, or an unknown one. Body: Error.
403Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
404Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
409Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
429The caller is over IMPROV_RATE_LIMIT requests a minute. Body: Error.
500Internal error; the detail is in the server log under request_id. Body: Error.

PUT /v1/categories/

Rename a category Scope: write.

  • Path parameter id: {"minimum":0,"type":"integer"}.

  • Path parameter x-improv-session: {"maxLength":64,"type":"string"}.

Request body: Name.

StatusResponse
200Done. Body: Done.
400Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
401No token, or an unknown one. Body: Error.
403Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
404Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
409Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
413The body is over IMPROV_MAX_BODY_BYTES.
429The caller is over IMPROV_RATE_LIMIT requests a minute. Body: Error.
500Internal error; the detail is in the server log under request_id. Body: Error.

POST /v1/categories/{id}/items

Add an item Scope: write.

  • Path parameter id: {"minimum":0,"type":"integer"}.

  • Path parameter x-improv-session: {"maxLength":64,"type":"string"}.

Request body: Name.

StatusResponse
200Done. Body: Done.
400Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
401No token, or an unknown one. Body: Error.
403Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
404Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
409Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
413The body is over IMPROV_MAX_BODY_BYTES.
429The caller is over IMPROV_RATE_LIMIT requests a minute. Body: Error.
500Internal error; the detail is in the server log under request_id. Body: Error.

POST /v1/cells

Edit cells Scope: write.

Set or clear input cells, all or none. A refusal names the failing edit (index); a hidden cell is refused as one that does not exist. Never a conflict: when another writer moved the model, the server reloads, checks the batch again and applies it.

  • Path parameter x-improv-session: {"maxLength":64,"type":"string"}.

Request body: EditBatch.

StatusResponse
200Done. Body: Done.
400Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
401No token, or an unknown one. Body: Error.
403Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
404Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
409Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
413The body is over IMPROV_MAX_BODY_BYTES.
429The caller is over IMPROV_RATE_LIMIT requests a minute. Body: Error.
500Internal error; the detail is in the server log under request_id. Body: Error.

GET /v1/changes

Changes, as Server-Sent Events Scope: read.

A text/event-stream. The first event carries the current version, or what changed since since. Then one event per change the caller may see: the changed cells, filtered for the caller, or reload. A change the caller may see none of sends nothing. Each event's id is its version; reconnect with ?since= (or Last-Event-ID) to resume. A stream is not bound by the request time limit and takes no in-flight slot; at most IMPROV_MAX_STREAMS (default 256) are open at once, 8 per caller, with 429 past either.

  • Path parameter since: {"$ref":"#/components/schemas/Version"}.
StatusResponse
200The event stream; each data: line is a ChangeEvent.
401No token, or an unknown one. Body: Error.
429Over the rate limit, or too many change streams open (in all, or for this caller). Body: Failure.
500Internal error; the detail is in the server log under request_id. Body: Error.

GET /v1/health

Liveness probe Scope: public.

StatusResponse
200The text ok.

DELETE /v1/items/

Delete an item Scope: write.

With its cells.

  • Path parameter id: {"minimum":0,"type":"integer"}.

  • Path parameter x-improv-session: {"maxLength":64,"type":"string"}.

StatusResponse
200Done. Body: Done.
400Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
401No token, or an unknown one. Body: Error.
403Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
404Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
409Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
429The caller is over IMPROV_RATE_LIMIT requests a minute. Body: Error.
500Internal error; the detail is in the server log under request_id. Body: Error.

PUT /v1/items/

Rename an item Scope: write.

  • Path parameter id: {"minimum":0,"type":"integer"}.

  • Path parameter x-improv-session: {"maxLength":64,"type":"string"}.

Request body: Name.

StatusResponse
200Done. Body: Done.
400Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
401No token, or an unknown one. Body: Error.
403Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
404Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
409Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
413The body is over IMPROV_MAX_BODY_BYTES.
429The caller is over IMPROV_RATE_LIMIT requests a minute. Body: Error.
500Internal error; the detail is in the server log under request_id. Body: Error.

GET /v1/measures

List the measures Scope: read.

StatusResponse
200Measures, sorted by id. Body: array of MeasureSummary.
401No token, or an unknown one. Body: Error.
429The caller is over IMPROV_RATE_LIMIT requests a minute. Body: Error.
500Internal error; the detail is in the server log under request_id. Body: Error.

POST /v1/measures

Define a measure Scope: write.

A derived measure or LAMBDA from a definition, or a new input measure. A formula error is located in the text (diagnostic).

  • Path parameter x-improv-session: {"maxLength":64,"type":"string"}.

Request body: Define.

StatusResponse
200Done. Body: Done.
400Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
401No token, or an unknown one. Body: Error.
403Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
404Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
409Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
413The body is over IMPROV_MAX_BODY_BYTES.
429The caller is over IMPROV_RATE_LIMIT requests a minute. Body: Error.
500Internal error; the detail is in the server log under request_id. Body: Error.

DELETE /v1/measures/

Delete a measure Scope: write.

Refused while a formula reads it.

  • Path parameter id: {"minimum":0,"type":"integer"}.

  • Path parameter x-improv-session: {"maxLength":64,"type":"string"}.

StatusResponse
200Done. Body: Done.
400Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
401No token, or an unknown one. Body: Error.
403Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
404Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
409Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
429The caller is over IMPROV_RATE_LIMIT requests a minute. Body: Error.
500Internal error; the detail is in the server log under request_id. Body: Error.

PUT /v1/measures/

Change a measure Scope: write.

A new formula (an error located in it), name or number format.

  • Path parameter id: {"minimum":0,"type":"integer"}.

  • Path parameter x-improv-session: {"maxLength":64,"type":"string"}.

Request body: UpdateMeasure.

StatusResponse
200Done. Body: Done.
400Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
401No token, or an unknown one. Body: Error.
403Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
404Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
409Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
413The body is over IMPROV_MAX_BODY_BYTES.
429The caller is over IMPROV_RATE_LIMIT requests a minute. Body: Error.
500Internal error; the detail is in the server log under request_id. Body: Error.

POST /v1/measures/{id}/cells

Set one input cell Scope: write.

  • Path parameter id: {"minimum":0,"type":"integer"}.

Request body: SetCellRequest.

Example:

{"coord":{"dims":{"1":10,"2":20}},"value":90}
StatusResponse
200Written. Body: {"properties":{"ok":{"const":true}},"type":"object"}.
400The request was refused. Body: Error.
401No token, or an unknown one. Body: Error.
403The request was refused. Body: Error.
404The request was refused. Body: Error.
409The request was refused. Body: Error.
413The body is over IMPROV_MAX_BODY_BYTES.
429The caller is over IMPROV_RATE_LIMIT requests a minute. Body: Error.
500Internal error; the detail is in the server log under request_id. Body: Error.

POST /v1/measures/{id}/eval

What-if evaluation Scope: read.

Apply edits through the live engine and return derived measure id. A read token may evaluate; "persist": true writes the edits and needs a write token (403 otherwise). A persisting request is audited.

  • Path parameter id: {"minimum":0,"type":"integer"}.

Request body: EvalRequest.

Example:

{"edits":[{"coord":[[1,10],[2,20]],"measure":101,"value":90}],"persist":false}
StatusResponse
200Cells, coordinates named by category and item. Body: array of Cell.
400The request was refused. Body: Error.
401No token, or an unknown one. Body: Error.
403The request was refused. Body: Error.
404The request was refused. Body: Error.
409The request was refused. Body: Error.
413The body is over IMPROV_MAX_BODY_BYTES.
429The caller is over IMPROV_RATE_LIMIT requests a minute. Body: Error.
500Internal error; the detail is in the server log under request_id. Body: Error.

GET /v1/measures/{id}/values

A measure's values Scope: read.

The stored cells of an input measure, or the computed cells of a derived one.

  • Path parameter id: {"minimum":0,"type":"integer"}.
StatusResponse
200Cells, coordinates named by category and item. Body: array of Cell.
401No token, or an unknown one. Body: Error.
404The request was refused. Body: Error.
429The caller is over IMPROV_RATE_LIMIT requests a minute. Body: Error.
500Internal error; the detail is in the server log under request_id. Body: Error.

POST /v1/measures/{id}/window

A window of a measure's cells Scope: read.

The visible cells of the measure at the given items. Derived cells are computed by the server's engine over every cell, hidden ones included.

  • Path parameter id: {"minimum":0,"type":"integer"}.

Request body: Window.

StatusResponse
200The window's visible cells. Body: Cells.
400Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
401No token, or an unknown one. Body: Error.
403Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
404Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
413The body is over IMPROV_MAX_BODY_BYTES.
429The caller is over IMPROV_RATE_LIMIT requests a minute. Body: Error.
500Internal error; the detail is in the server log under request_id. Body: Error.

GET /v1/model

The whole model Scope: read. Unstable: not covered by the compatibility promise.

Unstable: the body is the store's internal serialization of the model (ids, expression trees, function ids as numbers) and may change in any release. Not covered by the /v1 compatibility promise; use /v1/measures and /v1/measures/{id}/values for a stable view. Refused (403) for a model with access policies, whoever asks: it is everything, unfiltered.

StatusResponse
200The model, as the store serializes it. Body: {"type":"object"}.
401No token, or an unknown one. Body: Error.
403The request was refused. Body: Error.
429The caller is over IMPROV_RATE_LIMIT requests a minute. Body: Error.
500Internal error; the detail is in the server log under request_id. Body: Error.

POST /v1/nl/describe

A formula to controlled English Scope: read.

Request body:

{
  "properties": {
    "formula": {
      "description": "A formula as /v1/nl/parse returns it.",
      "type": "object"
    }
  },
  "required": [
    "formula"
  ],
  "type": "object"
}
StatusResponse
200The text. Body: {"properties":{"text":{"type":"string"}},"type":"object"}.
400The request was refused. Body: Error.
401No token, or an unknown one. Body: Error.
413The body is over IMPROV_MAX_BODY_BYTES.
429The caller is over IMPROV_RATE_LIMIT requests a minute. Body: Error.

POST /v1/nl/parse

Controlled English to a formula Scope: read.

Request body:

{
  "properties": {
    "text": {
      "type": "string"
    }
  },
  "required": [
    "text"
  ],
  "type": "object"
}

Example:

{"text":"revenue is price times quantity"}
StatusResponse
200The formula. Body: {"type":"object"}.
400The request was refused. Body: Error.
401No token, or an unknown one. Body: Error.
413The body is over IMPROV_MAX_BODY_BYTES.
429The caller is over IMPROV_RATE_LIMIT requests a minute. Body: Error.

GET /v1/openapi.json

This document Scope: public.

StatusResponse
200The OpenAPI document. Body: {"type":"object"}.

POST /v1/redo

Redo Scope: write.

The session's last undone change.

  • Path parameter x-improv-session: {"maxLength":64,"type":"string"}.
StatusResponse
200Done. Body: Done.
400Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
401No token, or an unknown one. Body: Error.
403Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
404Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
409Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
429The caller is over IMPROV_RATE_LIMIT requests a minute. Body: Error.
500Internal error; the detail is in the server log under request_id. Body: Error.

GET /v1/scheduler/status

Refresh scheduler state Scope: read.

StatusResponse
200enabled false, or the tick period and the last tick's outcome. Body: {"properties":{"enabled":{"type":"boolean"},"last_error":{"type":["string","null"]},"last_tick_refreshed":{"items":{"type":"integer"},"type":"array"},"tick_secs":{"type":"integer"}},"required":["enabled"],"type":"object"}.
401No token, or an unknown one. Body: Error.
429The caller is over IMPROV_RATE_LIMIT requests a minute. Body: Error.

GET /v1/structure

What the caller may see of the model Scope: read.

Categories with their visible items, visible measures with formulas when shown, LAMBDAs and views. The stable shape a GUI reads, in place of /v1/model.

StatusResponse
200The visible structure. Body: Structure.
400Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
401No token, or an unknown one. Body: Error.
429The caller is over IMPROV_RATE_LIMIT requests a minute. Body: Error.
500Internal error; the detail is in the server log under request_id. Body: Error.

POST /v1/undo

Undo Scope: write.

The session's last change (an edit batch, or a structural change with the cells it dropped). Cells written back are checked as new edits.

  • Path parameter x-improv-session: {"maxLength":64,"type":"string"}.
StatusResponse
200Done. Body: Done.
400Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
401No token, or an unknown one. Body: Error.
403Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
404Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
409Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
429The caller is over IMPROV_RATE_LIMIT requests a minute. Body: Error.
500Internal error; the detail is in the server log under request_id. Body: Error.

POST /v1/views

Save a view Scope: write.

  • Path parameter x-improv-session: {"maxLength":64,"type":"string"}.

Request body: ViewBody.

StatusResponse
200Done. Body: Done.
400Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
401No token, or an unknown one. Body: Error.
403Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
404Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
409Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
413The body is over IMPROV_MAX_BODY_BYTES.
429The caller is over IMPROV_RATE_LIMIT requests a minute. Body: Error.
500Internal error; the detail is in the server log under request_id. Body: Error.

DELETE /v1/views/

Delete a view Scope: write.

  • Path parameter id: {"minimum":0,"type":"integer"}.

  • Path parameter x-improv-session: {"maxLength":64,"type":"string"}.

StatusResponse
200Done. Body: Done.
400Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
401No token, or an unknown one. Body: Error.
403Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
404Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
409Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
429The caller is over IMPROV_RATE_LIMIT requests a minute. Body: Error.
500Internal error; the detail is in the server log under request_id. Body: Error.

PUT /v1/views/

Change a view Scope: write.

Its name, its matrices, or both.

  • Path parameter id: {"minimum":0,"type":"integer"}.

  • Path parameter x-improv-session: {"maxLength":64,"type":"string"}.

Request body: ViewBody.

StatusResponse
200Done. Body: Done.
400Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
401No token, or an unknown one. Body: Error.
403Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
404Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
409Refused: a bad request (400), a write with a read token (403), not there or not visible (404), another writer's structural change (409). Body: Failure.
413The body is over IMPROV_MAX_BODY_BYTES.
429The caller is over IMPROV_RATE_LIMIT requests a minute. Body: Error.
500Internal error; the detail is in the server log under request_id. Body: Error.

Schemas

At

{
  "description": "A coordinate: [category id, item id] pairs, sorted by category id.",
  "items": {
    "maxItems": 2,
    "minItems": 2,
    "prefixItems": [
      {
        "type": "integer"
      },
      {
        "type": "integer"
      }
    ],
    "type": "array"
  },
  "type": "array"
}

Capabilities

{
  "properties": {
    "add_measure": {
      "type": "boolean"
    },
    "admin": {
      "description": "May set the model's policies.",
      "type": "boolean"
    },
    "edit_items": {
      "description": "The visible items the caller may rename or delete.",
      "items": {
        "type": "integer"
      },
      "type": "array"
    },
    "edit_structure": {
      "description": "May add, rename or remove categories and items.",
      "type": "boolean"
    },
    "manage_views": {
      "type": "boolean"
    },
    "measures": {
      "description": "Each visible measure, in id order.",
      "items": {
        "properties": {
          "cells": {
            "description": "Which of its visible cells may be edited.",
            "enum": [
              "all",
              "some",
              "none"
            ]
          },
          "define": {
            "description": "May redefine, format or drop it.",
            "type": "boolean"
          },
          "id": {
            "type": "integer"
          }
        },
        "required": [
          "id",
          "define",
          "cells"
        ],
        "type": "object"
      },
      "type": "array"
    },
    "restricted": {
      "description": "Whether the model has access policies.",
      "type": "boolean"
    },
    "version": {
      "description": "The model's version: opaque, compare for equality only.",
      "type": "string"
    }
  },
  "required": [
    "version",
    "restricted",
    "admin",
    "add_measure",
    "edit_structure",
    "manage_views",
    "measures",
    "edit_items"
  ],
  "type": "object"
}

Cell

{
  "properties": {
    "coord": {
      "description": "[category name, item name] pairs, sorted.",
      "items": {
        "items": {
          "type": "string"
        },
        "maxItems": 2,
        "minItems": 2,
        "type": "array"
      },
      "type": "array"
    },
    "value": {
      "type": "number"
    }
  },
  "required": [
    "coord",
    "value"
  ],
  "type": "object"
}

Cells

{
  "description": "The window's visible cells, as the server computed them. A cell absent here is blank: empty, or not visible to the caller.",
  "properties": {
    "cells": {
      "items": {
        "properties": {
          "at": {
            "$ref": "#/components/schemas/At"
          },
          "value": {
            "$ref": "#/components/schemas/Value"
          }
        },
        "required": [
          "at",
          "value"
        ],
        "type": "object"
      },
      "type": "array"
    },
    "measure": {
      "type": "integer"
    },
    "version": {
      "$ref": "#/components/schemas/Version"
    }
  },
  "required": [
    "version",
    "measure",
    "cells"
  ],
  "type": "object"
}

ChangeEvent

{
  "properties": {
    "cells": {
      "description": "The cells that changed, and only those the subscriber may see.",
      "items": {
        "properties": {
          "at": {
            "$ref": "#/components/schemas/At"
          },
          "measure": {
            "type": "integer"
          },
          "value": {
            "oneOf": [
              {
                "$ref": "#/components/schemas/Value"
              },
              {
                "type": "null"
              }
            ]
          }
        },
        "type": "object"
      },
      "type": "array"
    },
    "reload": {
      "description": "The structure changed, or the gap since `since` is too old: re-read everything.",
      "type": "boolean"
    },
    "version": {
      "$ref": "#/components/schemas/Version"
    }
  },
  "required": [
    "version"
  ],
  "type": "object"
}

Define

{
  "description": "A definition (`Revenue = Price * Quantity` defines or redefines a derived measure, `Half = LAMBDA(x, x / 2)` a LAMBDA), or a name for a new input measure.",
  "properties": {
    "categories": {
      "description": "An input measure's categories (default: all).",
      "items": {
        "type": "integer"
      },
      "type": "array"
    },
    "definition": {
      "type": "string"
    },
    "name": {
      "type": "string"
    },
    "type": {
      "enum": [
        "Number",
        "Boolean",
        "Text",
        "DateTime"
      ]
    }
  },
  "type": "object"
}

Done

{
  "properties": {
    "id": {
      "description": "The id of what it made.",
      "type": "integer"
    },
    "message": {
      "type": "string"
    },
    "version": {
      "$ref": "#/components/schemas/Version"
    }
  },
  "required": [
    "version",
    "message"
  ],
  "type": "object"
}

EditBatch

{
  "properties": {
    "edits": {
      "items": {
        "properties": {
          "at": {
            "$ref": "#/components/schemas/At"
          },
          "measure": {
            "type": "integer"
          },
          "value": {
            "description": "The new value; null or absent clears the cell.",
            "oneOf": [
              {
                "$ref": "#/components/schemas/Value"
              },
              {
                "type": "null"
              }
            ]
          }
        },
        "required": [
          "measure",
          "at"
        ],
        "type": "object"
      },
      "maxItems": 10000,
      "type": "array"
    }
  },
  "required": [
    "edits"
  ],
  "type": "object"
}

Error

{
  "properties": {
    "error": {
      "type": "string"
    },
    "request_id": {
      "description": "On a 500: the id the server logged the detail under.",
      "type": "integer"
    }
  },
  "required": [
    "error"
  ],
  "type": "object"
}

EvalRequest

{
  "properties": {
    "edits": {
      "items": {
        "properties": {
          "coord": {
            "description": "[category id, item id] pairs.",
            "items": {
              "items": {
                "type": "integer"
              },
              "maxItems": 2,
              "minItems": 2,
              "type": "array"
            },
            "type": "array"
          },
          "measure": {
            "type": "integer"
          },
          "value": {
            "description": "null clears the cell.",
            "type": [
              "number",
              "null"
            ]
          }
        },
        "required": [
          "measure",
          "coord",
          "value"
        ],
        "type": "object"
      },
      "maxItems": 10000,
      "type": "array"
    },
    "persist": {
      "default": false,
      "type": "boolean"
    }
  },
  "type": "object"
}

Failure

{
  "description": "A refused request. A hidden thing is refused exactly as a missing one.",
  "properties": {
    "diagnostic": {
      "description": "Where in the formula text the error is (byte offsets).",
      "properties": {
        "hint": {
          "type": "string"
        },
        "message": {
          "type": "string"
        },
        "span": {
          "prefixItems": [
            {
              "type": "integer"
            },
            {
              "type": "integer"
            }
          ],
          "type": "array"
        }
      },
      "type": "object"
    },
    "error": {
      "type": "string"
    },
    "index": {
      "description": "The edit of a batch that failed.",
      "type": "integer"
    }
  },
  "required": [
    "error"
  ],
  "type": "object"
}

MeasureSummary

{
  "properties": {
    "categories": {
      "items": {
        "type": "string"
      },
      "type": "array"
    },
    "id": {
      "type": "integer"
    },
    "kind": {
      "enum": [
        "input",
        "derived"
      ]
    },
    "name": {
      "type": "string"
    }
  },
  "required": [
    "id",
    "name",
    "kind",
    "categories"
  ],
  "type": "object"
}

Name

{
  "properties": {
    "name": {
      "type": "string"
    }
  },
  "required": [
    "name"
  ],
  "type": "object"
}

NumberFormat

{
  "properties": {
    "decimals": {
      "maximum": 15,
      "minimum": 0,
      "type": [
        "integer",
        "null"
      ]
    },
    "grouping": {
      "type": "boolean"
    }
  },
  "type": [
    "object",
    "null"
  ]
}

SetCellRequest

{
  "properties": {
    "coord": {
      "properties": {
        "dims": {
          "additionalProperties": {
            "type": "integer"
          },
          "description": "Category id to item id.",
          "type": "object"
        }
      },
      "required": [
        "dims"
      ],
      "type": "object"
    },
    "value": {
      "type": "number"
    }
  },
  "required": [
    "coord",
    "value"
  ],
  "type": "object"
}

Structure

{
  "description": "What the caller may see of the model. Hidden measures and items are absent.",
  "properties": {
    "categories": {
      "items": {
        "properties": {
          "id": {
            "type": "integer"
          },
          "items": {
            "description": "Visible items, in grid order.",
            "items": {
              "properties": {
                "id": {
                  "type": "integer"
                },
                "name": {
                  "type": "string"
                }
              },
              "type": "object"
            },
            "type": "array"
          },
          "name": {
            "type": "string"
          }
        },
        "type": "object"
      },
      "type": "array"
    },
    "lambdas": {
      "items": {
        "properties": {
          "id": {
            "type": "integer"
          },
          "name": {
            "type": "string"
          },
          "params": {
            "items": {
              "type": "string"
            },
            "type": "array"
          }
        },
        "type": "object"
      },
      "type": "array"
    },
    "measures": {
      "items": {
        "properties": {
          "categories": {
            "items": {
              "type": "integer"
            },
            "type": "array"
          },
          "editable": {
            "description": "A hint; every edit is still checked.",
            "type": "boolean"
          },
          "error": {
            "description": "Why the formula does not build.",
            "type": "string"
          },
          "format": {
            "$ref": "#/components/schemas/NumberFormat"
          },
          "formula": {
            "description": "As typed (the DSL), or controlled English; absent when the formula reads a hidden measure.",
            "type": "string"
          },
          "id": {
            "type": "integer"
          },
          "kind": {
            "enum": [
              "input",
              "derived"
            ]
          },
          "name": {
            "type": "string"
          },
          "type": {
            "enum": [
              "Number",
              "Boolean",
              "Text",
              "DateTime",
              "Enum"
            ]
          }
        },
        "type": "object"
      },
      "type": "array"
    },
    "version": {
      "$ref": "#/components/schemas/Version"
    },
    "views": {
      "items": {
        "description": "A saved view, as the model stores it, with only visible matrices, filters and pages.",
        "type": "object"
      },
      "type": "array"
    }
  },
  "required": [
    "version",
    "categories",
    "measures"
  ],
  "type": "object"
}

UpdateMeasure

{
  "description": "Any of a new formula, name and format, as one step.",
  "properties": {
    "format": {
      "$ref": "#/components/schemas/NumberFormat"
    },
    "formula": {
      "type": "string"
    },
    "name": {
      "type": "string"
    }
  },
  "type": "object"
}

Value

{
  "description": "A cell value: a number, boolean or string, or an object for a date or an error value.",
  "oneOf": [
    {
      "type": "number"
    },
    {
      "type": "boolean"
    },
    {
      "type": "string"
    },
    {
      "properties": {
        "date": {
          "format": "date-time",
          "type": "string"
        }
      },
      "required": [
        "date"
      ],
      "type": "object"
    },
    {
      "properties": {
        "error": {
          "examples": [
            "#DIV/0!"
          ],
          "type": "string"
        }
      },
      "required": [
        "error"
      ],
      "type": "object"
    }
  ]
}

Version

{
  "description": "The model's version: opaque, compare for equality only.",
  "type": "string"
}

ViewBody

{
  "properties": {
    "matrices": {
      "description": "The view's matrices, the primary first (as the model stores a view's placements).",
      "items": {
        "type": "object"
      },
      "type": "array"
    },
    "name": {
      "type": "string"
    }
  },
  "type": "object"
}

Window

{
  "properties": {
    "at": {
      "additionalProperties": {
        "items": {
          "type": "integer"
        },
        "type": "array"
      },
      "description": "Item ids to read, per category id; a category left out reads all its visible items.",
      "type": "object"
    }
  },
  "type": "object"
}

Compatibility

From 1.0.0 Improv follows Semantic Versioning. A 1.x release (a minor, 1.y, or a patch, 1.y.z) does not break what this page calls stable. Anything that would break it waits for 2.0.

Each section below lists, for one surface, what is stable, what a 1.x minor may add, and what is not covered. What it does not list is not promised.

The rules for every surface

  • A minor may add: new functions, commands, flags, endpoints, columns, GUCs and optional arguments. An omitted new argument keeps today's behavior. Read results by name, not by position, wherever a list can grow (JSON fields, SELECT * columns, improv_functions rows).
  • A patch only fixes bugs and documents. A behavior that contradicts this guide is a bug; its fix goes under Fixed in the CHANGELOG, with the old and the new behavior.
  • Deprecation. Nothing stable is removed in 1.x. To retire something, a minor marks it deprecated: the CHANGELOG and the page that documents it name the replacement. It keeps working, unchanged, for the rest of 1.x. Where the surface has a channel for it, using it warns: a NOTICE in Postgres, a line on stderr from a command, a Deprecation header over HTTP. 2.0 may remove it.
  • Upgrades go forward. Data written by 1.y opens in every later 1.x. Opening it with an older release is not supported.

Formulas

The formula language has its own promise, in The Formula Language: Language stability: which formulas stay valid, what their results may and may not do across 1.x, how a bug fix is listed, and how a function is deprecated. It covers every place a formula is written: models, improv define, the GUI and TUI editors, LANGUAGE improv function bodies, improv.define, and DuckDB's improv_calc and improv(source, model).

pg_improv

The extension lives in the schema improv (relocatable = false).

Stable: the functions. Their names, argument names, argument order and types, defaults and return types:

FunctionReturns
improv.create_model(name text)bigint, the model's id
improv.drop_model(name text)void
improv.bind_category(model text, category text, rel regclass, col text)void
improv.bind_measure(model text, measure text, rel regclass, value_col text, agg text DEFAULT NULL)void
improv.define(model text, definition text, replace boolean DEFAULT false)bigint, the measure's or LAMBDA's id
improv.drop_measure(model text, measure text)void
improv.recalc(model text)bigint
improv.recalc(model text, measures text[])bigint
improv.set_sync_mode(model text, mode text)void
improv.enable_logical(model text)void
improv.sync_publication()void
improv.what_if(model text, edits jsonb)TABLE(measure text, coord jsonb, value jsonb)
improv.status(model text)one row; columns below

Also stable: the agg values (sum, avg, min, max, count, count_distinct), the sync modes (logical, trigger, commit, manual), the edits JSON of what_if (see Improv in Postgres), and LANGUAGE improv: a CREATE FUNCTION … LANGUAGE improv that works in 1.0 works in every 1.x. Every function runs as its caller (SECURITY INVOKER) and acts on a model as the model's owner; that privilege model (see Privileges) is stable too.

Not stable yet: the access-policy functions (0.13): set_policies, policies, explain_access, categories, items, measures, cells and set_cells. They become stable when 1.0 lists them here. The Cedar schema they enforce is improv_policy::SCHEMA.

Stable: the GUCs. Their names, types, units, contexts and defaults:

GUCTypeDefaultSet in
improv.max_cellsinteger5000000any session
improv.raise_errorsbooleanoffany session
improv.commit_captureenum: relations, rowsrelationsany session; read by set_sync_mode
improv.databasestringpostgresql.conf, restart; only with shared_preload_libraries
improv.poll_msinteger, ms (10–60000)200postgresql.conf, reload
improv.max_slot_laginteger, MB (0 = never)4096postgresql.conf, reload
improv.max_changesinteger10000postgresql.conf, reload
improv.max_model_memoryinteger, MB (0 = no cap)0postgresql.conf, reload

A minor may add GUCs. It does not change a default in a way that changes results; a default that only tunes performance (poll_ms, max_changes) may change, and the CHANGELOG says so.

Stable: the result tables. A derived measure's results are the table improv_<model>.<measure>, both names lower-cased. It has one text NOT NULL column per category of the measure, named by the category lower-cased, in the measure's category order, then value: double precision, boolean, text or timestamp with time zone, after the measure's type. The primary key is the category columns. A measure with no categories has just value and at most one row. You may index, GRANT and query these tables; the extension owns their rows.

Stable: improv.status. Its columns, in this order, with these types: sync_mode text, slot text, lag_bytes bigint, confirmed_lsn text, last_applied_at timestamptz, rows_applied bigint, last_error text, incremental_applies bigint, rebuilds bigint, fold_bytes bigint, engine_bytes bigint (the last two added in 0.11.0). Monitoring says what each means. A minor may append columns. The logical worker's slot and publication are named improv_db.

Not stable: the catalog tables. improv.model, improv.category, improv.item, improv.measure, improv.binding, improv.category_binding, improv.cell, improv.view, improv.meta, improv.lambda, improv.model_version, improv.sync_state, improv.slot_to_drop, improv.policy and improv.policy_audit are internal. Change models through the functions, never by writing these tables. A minor may change them, with an update script. One exception, for monitoring queries like the ones in this guide: improv.model's id, name, sync_mode and owner columns stay readable.

Upgrades. Every 1.x release ships an update script from each earlier 1.x, so ALTER EXTENSION pg_improv UPDATE (after installing the new release and restarting) moves any 1.x database forward with its models and results. tests/upgrade.sh checks this against the released tags. There are no downgrade scripts. A minor may support a new Postgres major; it drops one only after PGDG ends its support, and says so in the CHANGELOG.

Model files

A model file is a Mentat store: a SQLite database holding datoms. Its schema is the attributes in crates/storage_mentat/src/schema.rs (:category/*, :item/*, :measure/*, :cell/*, :view/*, :meta/*). Views, scenarios, named LAMBDAs and external functions are JSON values inside it.

Stable: a file saved by 1.0 opens in every 1.x, with the same model. The same holds for a Postgres model saved through the CLI, TUI, GUI or server.

How the schema changes. There is no schema version number and no separate migration step. Every open installs the schema, which is idempotent: an attribute that exists is unchanged and a new one is added. So a minor may only:

  • add attributes, which an older file simply lacks (a new reader treats a missing one as its default; see the tests store_without_category_order_still_loads and measure_format_round_trips_and_old_stores_load);
  • add fields to the JSON values, with defaults, so an older value still reads;
  • read an older shape and write the new one on the next save (the views did this when one view became a canvas of several worksheets).

It does not rename, retype or remove an attribute, or change what a stored value means. The mentatdb version is pinned exactly; a bump that changes Mentat's own on-disk format must open older files unchanged, and the CHANGELOG records it.

Not stable: opening a file with an older release than the one that last saved it. It may load, but a save then drops whatever the older release does not know. An added attribute usually survives: a release ignores an attribute it does not know and its saves keep it (the test a_later_releases_attribute_is_ignored_and_kept). So 0.11 opens a file with 0.12's number formats, shows its numbers in the General form, and keeps the formats when it saves; the same holds for a Postgres model, whose improv.measure.format column 0.11 neither reads nor writes.

The command line

improv, improv-tui, improv-gui, improv-server and their man pages describe one surface.

Stable:

  • the subcommands, their positional arguments and order, their flags, and the environment variables the man pages list (IMPROV_LOCALE, IMPROV_EXTFN_TRUSTED, IMPROV_EXTFN_ALLOW_UNSANDBOXED, the server's IMPROV_ADDR and token variables);
  • the exit status of improv: 0 success, 1 the command failed (the reason is on stderr after error:), 2 the arguments were wrong (a usage error); --help and --version exit 0;
  • stdout of the commands scripts read: what crates/cli/tests/compat.rs records. That test runs every invocation from the tests, the man pages' EXAMPLES, this guide and the smoke scripts, and checks its stdout byte for byte. A change that breaks it is a breaking change.

A minor may add subcommands, flags, and fields to the JSON of improv export.

Not stable: the wording of error messages and --help text, and the layout of the TUI and GUI.

The HTTP API

improv-server serves its API under the versioned path /v1/. Within 1.x:

Stable: every /v1 endpoint's method and path; its request fields and their meaning; its response fields, their types and their meaning; its status codes (400 a bad request, 401 no token, 403 a token that may not do this, 404 no such measure, 409 a conflicting write, 413 a body over the limit, 408 a timeout); bearer-token authentication, and what a read-only token may do. /health stays public. The HTTP Server lists the endpoints.

A minor may add: endpoints, optional request fields, and response fields. Clients must ignore fields they do not know. A minor may tighten a limit (body size, rate, concurrency) only to fix a security or stability problem, and says so.

Breaking changes go under a new prefix, /v2/. When it ships, /v1 keeps being served for the rest of 1.x. A deprecated /v1 endpoint answers with a Deprecation header and keeps working.

Paths outside /v1/ (other than /health) are not covered, nor is any endpoint the OpenAPI document marks x-improv-unstable. Today that is GET /v1/model: it returns the store's internal serialization of the model, which follows the Rust types (see "Rust crates" below) and may change in any release. Read measures and values through /v1/measures.

DuckDB

The extension improv (INSTALL improv FROM community; LOAD improv;).

Stable:

FunctionArgumentsResult
improv_calc(formula VARCHAR), (formula VARCHAR, inputs VARCHAR)DOUBLE
improv_calc_textthe sameVARCHAR
improv_functions(), or (query := VARCHAR)table: name, category, signature, returns, description, aliases, all VARCHAR
improv(source VARCHAR, model VARCHAR)table: measure VARCHAR, one VARCHAR column per category of the model, value DOUBLE, value_text VARCHAR

inputs is a JSON object of names to values (json_object(…)). The model text is the definition language Improv in DuckDB documents, with formulas under the formula language's promise.

The DuckDB version floor. The extension is built against DuckDB's stable C API with the floor v1.5.6, so one binary loads into DuckDB 1.5.6 and every later release that keeps that API, including 2.0. CI loads it into both. A 1.x minor may raise the floor only when a DuckDB release makes keeping it impossible, and the CHANGELOG says so first.

A minor may add functions, optional named parameters, and improv_functions rows as the language grows.

The Rust crates

The crates are not a stable API in 1.x. improv_core_model, improv_engine and the storage crates are the internals of the programs above, not a library: they are not published to crates.io, and a 1.x minor may change any of their items.

The reason is improv_core_model::Model. It exposes ten pub fields (categories, items, measures, inputs, sql_sources, views, external_fns, external_calls, scenarios, lambdas), all plain maps. Any caller can change them behind the model's back, which is how the name-index compromise of 0.11 came about. Freezing that would freeze the internals with it. Hiding them behind methods first is the road-to-1.0 task J2; once that lands, a later minor may declare a smaller API stable.

To build on Improv, use a stable surface: the CLI (scripts), the /v1 HTTP API (programs), pg_improv (SQL over Postgres) or the DuckDB extension. Each of them reads and writes the same model.

Architecture & Design

Improv is a small Cargo workspace. Each crate has one job and depends only on the ones below it.

Crate layout

CratePackagePurpose
core_modelimprov_core_modelCategories, items, measures, coordinates, formulas, values, and the formula text parser. No GUI or storage code.
engineimprov_engineFormula compiler and differential-dataflow evaluation: one-shot evaluate and the live session::Engine.
verifiedimprov_verifiedSmall integer kernels the engine calls, with Verus specifications and machine-checked proofs (see Formal verification).
nl_formulaimprov_nl_formulaControlled natural language ⇄ formula translation.
storage_mentatimprov_storage_mentatModel ⇄ datoms in an embedded, SQLite-backed Mentat file.
storage_pgimprov_storage_pgModel ⇄ the improv.* catalog in Postgres, with bound measures read from and written to their fact tables.
storeimprov_storeStore: one store type over both backends, picked by Store::open from the target (path or postgres://…?model=).
storage_sqlimprov_storage_sqlImport SQL query results into a model, export a measure to a table, refresh. SQLite, PostgreSQL, DuckDB.
storage_csvimprov_storage_csvImport a CSV/TSV file into a model; export a measure's cells (input or computed) to CSV/TSV.
data_sourceimprov_data_sourceThe import bookkeeping shared by storage_sql and storage_csv: create categories and the measure, intern dimension values as items.
extfnimprov_extfnExternal functions. Python, R, Julia and Pure run in a sandboxed subprocess (bwrap on Linux); Wasm runs in-process on wasmi with fuel and memory limits.
cliimprov_cliThe improv command-line tool.
tuiimprov_tuiimprov-tui, a VisiCalc-style terminal pivot grid.
guiimprov_guiimprov-gui, the desktop GUI (egui/eframe).
clientimprov_clientWhat the front ends share without the engine or a store: located formula errors, autocomplete, function help, the formula printer. Builds for wasm32-unknown-unknown.
serviceimprov_serviceThe authority a GUI drives: one model, its live engine and the /v1 operations, each checked by a policy hook and answered with only what the caller may see. improv-server serves it.
serverimprov_serverimprov-server, a JSON HTTP API over a model store.
pg_modelimprov_pg_modelThe Postgres-free core of pg_improv: catalog rows → Model, bound rows → cells, engine results → SQL.
pg_improvpg_improvThe Postgres extension (pgrx): Improv models over Postgres tables. A thin shell over SPI and pg_model.

The computation pipeline

A derived measure's formula is compiled through a typed intermediate form into an operator plan, which is then built into a differential-dataflow graph and run. Input cells are fed as data; computed values come back out.

graph TD
    A["Model<br/>(measures + input cells)"] --> B["Formula (AST)"]
    B --> C["infer<br/>type + dimension inference"]
    C --> D["TypedExpr"]
    D --> E["build_plan<br/>insert Join / Aggregate"]
    E --> F["PlanNode graph"]
    F --> G["dataflow builder"]
    G --> H["differential-dataflow<br/>InputSession -> operators -> reduce"]
    A -. "typed input cells" .-> H
    H --> I["computed values<br/>measure -> (coord -> CellValue)"]

The two compiler passes (infer, build_plan) live in engine::compiler; the plan node types in engine::plan; the dataflow builder and the one-shot evaluate entry point in engine::dataflow.

PlanNode kinds map onto differential-dataflow operators:

PlanNodeKindDataflow operator
InputMeasurean InputSession collection (or an already built derived measure)
Literala one-cell collection at the empty coordinate; as a MapBinary operand it is folded into the map closure instead
MapUnarymap
MapBinaryjoin on the shared categories, then map element-wise
Joinre-key both sides to shared categories, join, rebuild the union key
Aggregatere-key to the group-by coordinate, then reduce (SUM/AVG/MIN/MAX)
FuncCalla scalar function (ABS, ROUND, …): map for one argument, join then map for two

A final reduce collapses each key to a single value before results are captured. Derived measures are built in dependency order, so one derived measure can feed another; a cycle is rejected.

Why differential dataflow

Differential dataflow is a hard requirement of the design: the engine computes incrementally, so an edit propagates as a delta and only the affected cells recompute. The engine's spike (dd_revenue_is_incremental) proves this: after computing Revenue = Price * Quantity, it changes one Quantity cell and confirms the matching Revenue cell updates while an unaffected cell does not recompute.

The version pin is deliberate and delicate — differential-dataflow = "=0.13.0" with timely = "=0.13.0". Newer DD pulls a timely line that does not compile on the project's rustc; an older DD compiles but aborts on a merge_batcher bug under debug assertions. 0.13.0 is the pair that both compiles and runs. Do not bump it without re-validating.

The live engine

evaluate runs a model once and returns. Interactive users need more: change one cell and see what it affects, without a rebuild. That is engine::session::Engine.

Engine::new(model, targets) compiles the plans for the target derived measures, then starts a dataflow on its own thread (timely's execute_directly, one worker; a batch evaluate uses several, see Running Improv). Every input measure gets an InputSession. The model's input cells are fed in at time 0. new returns the handle and the first Snapshot.

After that the engine is fed edits:

#![allow(unused)]
fn main() {
pub struct Edit {
    pub measure: MeasureId,
    pub coord: CoordKey,
    pub value: Option<CellValue>, // None removes the cell
}
}

apply(edits) sends a batch over a channel. The worker retracts each cell's old value, inserts the new one, advances time by one, and steps the dataflow until the probe passes that time. Measures fall into components by what they read; a round advances only the input sessions of the components its edits reach and waits only for their outputs, so an edit costs what it touches, not the size of the model. Only the deltas flow, so only the affected cells recompute. set and clear are one-edit shortcuts. The reply is the new Snapshot. apply_delta(edits) applies a batch the same way but replies with what the round changed: per measure, each changed cell's coordinate, old value and new value (Changes). snapshot() returns the current snapshot.

A Snapshot is Arc<HashMap<MeasureId, Arc<MeasureValues>>>, where MeasureValues is HashMap<CoordKey, CellValue>. It is copy-on-write: cloning one is a reference-count bump, and measures an edit did not change are shared with the previous snapshot. A changed measure is copied whole only while a caller still holds the old snapshot (52 ms for one edit at 1M cells, against 0.1 ms without), so a caller that keeps a view drops its snapshot before the next edit, or keeps its own view and applies apply_delta's changes to it.

The structure is fixed when the engine is built. Changing a formula or adding a measure means building a new Engine. Dropping the handle stops the thread.

session::input_cell(type, value) is the one rule for which model values are engine cells. A value counts only when it matches its measure's declared type: Number, Boolean, Text or DateTime. Text in a number measure, or an error value, is no cell. Engine::new uses it to pick the seed cells, and the GUI uses it to turn a cell edit into an Edit, so an edit and a rebuild agree.

Users of the live engine:

UserHow
TUI (improv-tui)one engine per session; a numeric edit is Engine::set, any other value rebuilds the engine
GUI (improv-gui)one engine per session; edits go through input_cell and apply, its snapshot dropped first; rebuilt on structural changes
improv streamedits read from stdin, changed cells written to stdout
server POST /measures/:id/evala short-lived engine per request, for what-if edits
pg_improv's logical workerone engine per model in logical mode, fed the row changes of each batch through apply_delta; it writes the changed rows

The coordinate / value encoding for dataflow

Timely 0.13 needs dataflow data to be Clone + 'static, and data that crosses an exchange channel to also be Send + Sync and serde Serialize + Deserialize. Differential dataflow adds Ord + Debug, and keys must be hashable. The model's Coordinate is a dynamic-arity BTreeMap and Value holds an f64, which is neither Ord nor Hash. The engine encodes at the dataflow boundary:

  • Key — a coordinate becomes a sorted list of (category_id, item_id) pairs (CoordKey, a SmallVec<[(u32, u32); 3]>: up to three pairs inline, no heap allocation per cell). The BTreeMap already iterates in sorted order, so the encoding is deterministic and Ord + Hash. encode_coord / decode_coord convert at the edge; project_key narrows a key to a subset of categories (used for joins and group-bys).

  • Value — the CellValue enum:

    VariantHolds
    Num(u64)an f64 as f64::to_bits(); decoded with f64::from_bits
    Bool(bool)a boolean
    Text(String)text
    Date(i64)a UTC timestamp, milliseconds since the Unix epoch
    Err(u8)an error, by kind, so errors propagate through operators

    CellValue::from_model_value converts a model Value; Enum becomes a Num. Arithmetic happens after decoding, inside map and reduce closures.

  • Diff — the differential multiplicity R stays isize.

This encoding is what cleared the project's Phase 1 viability gate.

Stores and front ends

Every front end opens a model through improv_store::Store::open. A path opens a Mentat file; a postgres://…?model=<name> URL opens that model in Postgres. Both backends have the same methods and the same conflict error, so the GUI, TUI, CLI and server work on either without knowing which. See Storage & Persistence.

pg_improv runs the same engine inside Postgres. A model's categories and measures are bound to columns of ordinary tables, and each derived measure is written to a result table (improv_<model>.<measure>) that any SQL client can read. Three sync modes keep the results current: logical (the default; a background worker follows the commit through logical decoding), trigger (statement triggers recompute inside the writer's transaction), and manual (results change when you call improv.recalc). See Improv in Postgres.

Determinism

The core engine is deterministic and unit/property tested. The Time × Product revenue model (with results 1000 / 1000 / 1200 / 1600) is the canonical fixture checked by engine's tests, and each crate carries its own test module.

Formal verification

A few integer kernels of the engine are proven correct with Verus, not just tested. They live in crates/verified inside verus! { ... } blocks: a spec fn states what the kernel means and the executable function ensures it. Under plain cargo the specs are erased, and the engine calls these functions, so the proven code is the code that runs. scripts/verify.sh (and a CI job) checks the proofs with the pinned Verus release.

What is proven:

KernelUsed byProven
gcd::gcdGCD, LCM, the number-theory functionsThe result is Euclid's gcd: it divides both arguments, every common divisor divides it, and gcd(a, 0) = a.
gcd::lcm_belowLCMThe result is a positive common multiple, a / gcd(a, b) · b; it is None exactly when that reaches the cap (2⁵³), so the overflow check neither misses nor over-rejects.
radix::encode / decodeDEC2BIN, BIN2DEC, … (radix 2, 8, 16)decode(encode(v)) = v for every v in [−r¹⁰/2, r¹⁰/2); encode is None exactly outside that range; its digits are each below the radix, at most 10, and 10 for a negative v. decode rejects more than 10 digits or a digit not below the radix, and otherwise means exactly 10-digit two's complement.
radix::to_digitsBASE, and the aboveThe digits (radix 2–36) are each below the radix, have no leading zero, and are worth exactly the input.
bits::and / or / xor / shl / shrBITAND, BITOR, BITXOR, BITLSHIFT, BITRSHIFTFor operands below 2⁴⁸: every result stays below 2⁴⁸; and is at most either operand, or at least; shl is exactly x · 2ⁿ (below 2¹⁰¹, no overflow) and shr exactly ⌊x / 2ⁿ⌋ for shifts up to 53.
graph::build_orderthe derived-measure build order (derived_build_order)The depth-first post-order from the targets holds exactly the measures reachable from them, each once and after every measure it depends on; it fails exactly when a dependency cycle is reachable. So building a model's dataflow always terminates, and a cyclic model is always rejected.
take::rangeTAKE, DROPThe kept index range is in bounds (from ≤ to ≤ len) and holds m values for TAKE, len − m for DROP; TAKE and DROP of one count partition the list.
keys::projectevery join key and group-by (project_key)Exactly the pairs whose category is kept, in their order; a sorted key projects to a sorted key.
keys::union_keysevery dimensional joinA merge of two sorted keys: sorted with no category twice, contains every pair of both when they agree on shared categories, and nothing else.

What is tested instead: everything with floating point. Verus does not reason about f64 arithmetic, so the kernels take and return integers and the engine does the float range checks and truncation before calling them. The numeric functions are checked against LibreOffice and Gnumeric goldens (crates/engine/tests/data), and invariants (parse ⇄ print, save ⇄ load, key encoding) by property tests.

Storage & Persistence

improv_storage_mentat persists a Model to an embedded, SQLite-backed Mentat store — a Datomic-style datom database. Categories, items, measures, and input cells are stored as first-class entities, so the model is queryable, not an opaque blob.

ModelStore::open(path) opens (or creates) a store; pass "" for an in-memory database. Opening transacts the schema (a no-op after the first time). save_model writes the model; load_model rebuilds it by querying.

Front ends do not use ModelStore directly. They open improv_store::Store, which can also open a model kept in Postgres (see The Postgres store).

The datom schema

The schema is defined as an EDN transaction in improv_storage_mentat::schema::SCHEMA_EDN. It declares these attributes.

Category

AttributeValue typeCardinalityNotes
:category/idlongoneunique/identity, indexed
:category/namestringone

Item

AttributeValue typeCardinalityNotes
:item/idlongoneunique/identity, indexed
:item/namestringone
:item/categoryrefonereference to a category entity

Measure

AttributeValue typeCardinalityNotes
:measure/idlongoneunique/identity, indexed
:measure/namestringone
:measure/value-typestringonethe declared value type
:measure/categoriesrefmanythe measure's tensor dimensions (a set)
:measure/category-orderstringoneJSON array of category ids: the order of the set above. Coordinates and SQL/CSV columns depend on it. Absent in older stores, which load sorted by id.
:measure/kindstringone"input" or "derived"
:measure/descriptionstringoneoptional
:measure/formulastringoneJSON-serialized Formula, on derived measures
:measure/sql-sourcestringoneJSON SqlSource (query, dimension columns, value column, refresh policy), on SQL-backed measures
:measure/formatstringoneJSON NumberFormat ({"decimals":2,"grouping":true}): how its numbers are shown. Absent for the General form, and in older stores, which load as General.

Cell (an input value)

AttributeValue typeCardinalityNotes
:cell/keystringoneunique/identity, indexed — synthetic measure::coord key
:cell/measurerefonereference to the owning measure
:cell/coordstringoneJSON-serialized Coordinate
:cell/value-numberdoubleonepresent for numeric cells
:cell/value-booleanbooleanonepresent for boolean cells
:cell/value-textstringonepresent for text cells

View (a saved pivot layout)

AttributeValue typeCardinalityNotes
:view/idlongoneunique/identity, indexed
:view/jsonstringonethe whole view, as JSON

Meta (one entity per store)

Maps with no natural per-entity shape are stored as JSON on a singleton.

AttributeValue typeCardinalityNotes
:meta/singletonlongoneunique/identity, indexed; always the same value
:meta/external-fnsstringoneJSON: external function definitions
:meta/external-callsstringoneJSON: CALL(...) measures and their arguments
:meta/scenariosstringoneJSON: scenarios

How a model maps to datoms

  • Native attributes. Ids, names, kinds, and value types map straight to native datom value types (long, string, boolean, double, ref).

  • Formulas and coordinates are JSON. A Formula AST and a Coordinate are serialized with serde to JSON strings and stored in :measure/formula and :cell/coord. This is why a derived measure's formula survives a round trip even though the datom layer has no notion of an expression tree. Views, the SQL source of a measure, and the meta maps are JSON too.

  • Number format. A measure set back to General has no format, and the save retracts its stored :measure/format.

  • Category order. :measure/categories is a set, so the store loses its order. :measure/category-order keeps it. On load the categories are sorted by that list. A category the list does not name sorts after those it does.

  • Typed cell values. A cell writes exactly one of the three typed value attributes, chosen by the value's type:

    ValueAttribute
    Number, Enum:cell/value-number
    Boolean:cell/value-boolean
    Text, DateTime (RFC 3339 text):cell/value-text

    An Error value cannot be saved as an input; the save fails with Integrity.

  • Cell identity. Each cell is keyed by a synthetic string "<measure-id>::<coord-json>" on :cell/key, which is unique/identity. Re-saving the same measure+coordinate updates the cell in place.

Save

save_model is one SQLite transaction. It calls Store::begin_transaction once, makes several transact calls inside it, and calls commit once at the end. Later steps can use lookup-refs (for example :item/category, :measure/categories, :cell/measure) to entities that earlier steps wrote but have not committed yet. If any step fails, the transaction is dropped without a commit and nothing is written.

save_changes(model, cells, structure) is the incremental save, with the same transaction and conflict check. It writes only the named cells, each read by an index seek on its :cell/key and then upserted, or retracted if the model no longer holds it. With structure it also runs steps 1–3 and 5–6, and it retracts a dropped measure's cells by seeking on their :cell/measure. It never runs the pass over every stored cell (step 4 below) unless more than 4,096 cells are named, where one pass is cheaper. The caller names everything it changed. save_cells is save_changes without structure. On a 1M-cell store one cell saves in 4–8 ms, against about 8 s for save_model.

open transacts the schema only when an attribute is missing. Re-transacting an installed schema writes nothing, but Mentat still scans the log for metadata changes: 0.2 s per open of a 1M-cell store.

The steps run in this order:

StepWhat is transacted
1categories
2items
3measures
4cell retractions
5cells
6views
7meta (only if the model has external functions, external calls, or scenarios)

Each step is split into transact calls of at most MAX_DATOMS_PER_TRANSACT (2000) datoms. Mentat aborts the process (a hard assert!, not an error) on a transact carrying 5461 or more datoms for one attribute queue. The chunks share the one transaction, so the save is still all-or-nothing.

A single entity cannot be split. A measure carries one :measure/categories datom per category, so a measure with more than 5460 categories is refused up front with StoreError::Integrity, before anything is written.

Cells are diffed

Before writing cells, the save reads every stored cell and compares:

  • a cell whose stored value is unchanged is skipped (no datoms);
  • a cell whose value changed is re-asserted;
  • a value left under another type's attribute (the cell held text and now holds a number, say) is retracted;
  • a stored cell the model no longer has is retracted whole.

After a save, the store's cells are exactly model.inputs.

What is not retracted

Only cells are diffed. Categories, items, measures and views that the model no longer has are not retracted; they stay in the store and come back on the next load. Stale :measure/categories refs are not retracted either: re-save a measure with a changed category set and the store keeps the union. A loaded model can therefore grow past the 5460-category limit without any single save having been that wide. The source marks this as a known bug (see the comments in save_model).

Optimistic concurrency

load_model records the store's high-water transaction, read live from SQLite by TX_HIGH_WATER_SQL. It is the newest transaction in the log that changed anything other than :db/txInstant, so the schema transact every open performs does not count as a write.

save_model re-reads the high-water inside its transaction. If another writer has committed since this handle loaded (or last saved), the save returns StoreError::Conflict and writes nothing. A handle that never loaded saves unconditionally. loaded_tx and set_loaded_tx carry the token between handles, for callers that open the store fresh for each save.

To recover from a conflict, read the model again. reload_model does that; it is the same as load_model. The GUI's File ▸ Revert to Saved and the TUI's R key do the same thing: they open the store, load the model with a fresh token, and rebuild the engine. The conflicting edit is lost; the other writer's changes are picked up.

Load

load_model runs Datalog queries and rebuilds the Model:

  • categories, then items (each relinked to its category);
  • measures: one query for the required fields, then per measure one query each for the formula (derived measures only), description, categories, category order, number format, and SQL source. A format this release cannot read (one a later release wrote) loads as General;
  • cells: one query per typed value attribute (three in all), each returning (measure id, coord, value) rows. The value is decoded by the owning measure's declared type. If an old store holds a cell under more than one attribute, the attribute matching the declared type wins;
  • views and the meta singleton.

load_partial(measure_ids) loads the same structure, views and meta, but only the cells of measure_ids and their dependency closure (every measure reached through a derived formula or an external call's arguments). The filter is in the query. The handle remembers that closure, and its next save retracts only the closure's missing cells, so a partial model saves safely: cells of measures it never loaded stay as they are. A full load lifts the limit again.

The Postgres store

improv_store::Store is the one store type the GUI, TUI, CLI and server use. Store::open(target) looks at the target:

TargetBackend
starts with postgres:// or postgresql://improv_storage_pg::PgModelStore
anything else (a path; "" for in-memory)improv_storage_mentat::ModelStore

Both backends have the same methods: load_model, load_partial, save_model, save_changes, save_cells, reload_model, tx_high_water, loaded_tx, set_loaded_tx. A conflict from either backend becomes improv_store::StoreError::Conflict.

Store::save_changes(model, &ChangeSet) is the incremental save every front end uses for edits. A ChangeSet lists the cells (measure, coordinate) that were set or cleared, and whether anything else changed (structure). The front ends say what they edited. ChangeSet::between(old, new) computes the set from two models in memory, for callers that hold the model as it was. A handle with no save token (it has loaded or saved nothing) falls back to save_model. take_save_token and adopt_save_token carry the token from one handle to the next without copying the Postgres snapshot.

A Postgres target names one model: postgres://me@db/sales?model=plan. split_model_url removes the model parameter and passes the rest to the driver. ?model= is required; without it open fails. Opening a model name that does not exist yet creates it.

The catalog

The model is stored normalized in the improv schema. The DDL is CATALOG_SQL in crates/storage_pg/src/lib.rs:

TableHolds
improv.modelone row per model: name (unique), sync_mode (logical, trigger, commit, manual), slot_name
improv.categorycategories, keyed by (model_id, id)
improv.itemitems, with category_id
improv.measurename, value_type, kind, formula, description, categories bigint[], format jsonb (the number format; NULL is General)
improv.bindinga measure bound to a fact table: rel, value_col, dim_cols (category name → column), optional agg (sum, avg, min, max, count, count_distinct)
improv.cellunbound input cells: coord jsonb, value jsonb
improv.viewsaved views, layout jsonb
improv.metaone blob jsonb per model: external functions, external calls, scenarios, SQL sources
improv.model_versionone tx counter per model: the conflict token

CATALOG_SQL also creates the unique index item_name_uniq on (model_id, category_id, name) and the function improv.mint_items, which assigns ids to item names it has not seen. The pg_improv extension uses the same function.

open creates the catalog, under an advisory lock, when improv.mint_items does not exist. When the pg_improv extension is installed the function exists, so the client runs no DDL and the extension owns the tables. The extension's catalog is the same plus improv.category_binding, which records the column that supplies a bound category.

improv.measure.format came with pg_improv 0.12.0. open adds it to a plain catalog that lacks it (CATALOG_SQL runs again), but it leaves an older extension's catalog alone: there every measure loads as General, and a save of a model with a number format fails, naming the update to run (ALTER EXTENSION pg_improv UPDATE).

Formulas are written as JSON of the Formula AST. On load, a formula that is not JSON is parsed as formula text (Target = expr), which is what the extension's improv.define writes. Cell values are JSON scalars; dates are RFC 3339 strings.

Bound and unbound cells

A measure with a binding row lives in its fact table. Load runs SELECT dims…, value FROM rel (with GROUP BY when the binding has an agg). Dimension values map to items by name; names with no item are minted by improv.mint_items. A row with a NULL value is no cell; a row with a NULL dimension is ignored. Two rows on one coordinate of an unaggregated binding are an Integrity error. Cells of unbound measures come from improv.cell.

Load reads in one REPEATABLE READ, read-only transaction. Item minting runs after it closes, read-committed, so it sees items other clients minted. The handle keeps a snapshot of what it loaded.

Save

save_model is one transaction. It locks the model's model_version row and returns Conflict if tx moved since this handle loaded. Then it writes the diff against the snapshot:

  • categories, items, measures and views are upserted; only rows the snapshot held but the model dropped are deleted, so rows another client added survive;
  • bound cells that were added, changed or removed are written to the fact table with a guarded UPDATE … WHERE <dims> AND value IS NOT DISTINCT FROM <loaded value>. A removed cell sets the value column to NULL and keeps the row. An added cell with no row is INSERTed. If a guard matches no row, or several, SQL changed that cell since the load, and the save fails with Conflict. The save never runs DDL and never deletes a fact-table row;
  • an aggregated measure is read-only: a save that changes one of its cells fails with Integrity;
  • save_changes(model, cells, structure) writes only the named cells and, with structure, the catalog rows, and updates the snapshot in place. It never walks every cell or rebuilds the snapshot. On a 1M-cell model one cell saves in 2–11 ms and a structural change in 40 ms, against 1.6–1.9 s for save_model;
  • unbound cells that changed are upserted into improv.cell, and removed ones are deleted;
  • the meta blob is replaced, and model_version.tx is incremented.

A handle with no snapshot (it never loaded) writes the whole model unchecked and deletes rows the model lacks. As with the Mentat store, a partial model from load_partial saves safely through the handle that loaded it, since the diff only touches what it loaded.

Store::save_token carries both the version and the snapshot to a later handle, for callers that reopen the store per save.

Transport

This build has no TLS. open refuses:

  • sslmode=require, which cannot be honoured (use an SSH tunnel to a loopback port);
  • any host that is not localhost, a loopback address, or a Unix socket, unless the URL sets sslmode=disable explicitly, since the password would cross the network in cleartext.

A connect error that is not from the database is reported without the connection string, so a password in the URL is not echoed.

For the extension itself (binding tables, result tables, sync modes) see Improv in Postgres (pg_improv).