Nanuq dev log · OpenSpec · updated 19 November 2026

Specs and changes

Watch out where the queries go, and process well that rusty data.

Living page, rebuilt when openspec/ changes · at dae8ec2 Merge pull request #75 from pietroppeter/claude/project-thread-mv5eg2 · rendered with tools/specview.nim and nimib

The code this page talks about is folded under Source files, at the end.

Nanuq plans its work with OpenSpec. The specs in openspec/specs/ describe how Nanuq behaves today: one per capability, each requirement with a Nim example, its output and the scenarios it must pass. A change proposes new behavior: a proposal (with its differences from Polars), spec deltas, sometimes a design, and tasks. Once implemented, it is archived and its deltas are merged into the specs. The README explains the process.

Below, first the changes (open ones first; tick the box to see the archived ones, each with its proposal, spec deltas and revisions), then every spec in full. Ideas not yet picked up wait in BACKLOG.md. The page is rendered by tools/specview.nim.

Changes

ChangeStageTasksSpecs
add-api-polishArchived11/11data-types ~1
dataframe-api +3 ~2
expressions +1
frame-verbs ~1
missing-values ~4
native-bridge ~1
add-arraymancer-interopArchived3/3arraymancer-interop +2
add-arrow-c-dataArchived3/3arrow-interop +3
add-binary-decimal-bitwiseArchived3/3binary-decimal +4
add-book-port-needsArchived7/7dataframe-api ~1
expressions +1
frame-verbs +1
missing-values +1
add-book-port-needs-0-5Archived6/6expressions +2
frame-verbs +2
list-functions +1
series +3
struct-functions +1
add-book-port-needs-0-6Archived4/4column-selectors +1
expressions +1
frame-verbs +4
inspection +1
add-categoricalsArchived8/8categoricals +3
data-types ~2
native-bridge ~1
add-cloud-storageArchived4/4cloud-storage +3
add-column-access-and-nullsArchived12/12dataframe-api ~1
missing-values +7
native-bridge +1
add-column-selectorsArchived10/10column-selectors +5
native-bridge ~1
add-coverage-easy-wins-0-6Archived5/5csv-io +1
excel-io +1
expressions +2
frame-utilities +5
inspection +1
parquet-ipc +2
series +1
strings +1
temporal +2
add-csv-options-and-scanArchived9/9csv-io +3
native-bridge ~1
add-cumulative-and-shiftArchived4/4cumulative-functions +4
expressions +1
add-database-ioArchived2/2database-io +2
add-datamancer-interopArchived6/6datamancer-interop +4
add-datatype-and-castArchived10/10data-types +4
native-bridge ~1
add-devlog-indexArchived7/7ci ~1
dev-log +2
add-dynamic-group-byArchived4/4temporal-grouping +3
add-excel-ioArchived3/3excel-io +2
add-explainer-needs-0-5Archived4/4frame-verbs +2
missing-values +1
add-explainer-needs-0-6Archived3/3binary-decimal +2
csv-io +1
data-types +1
add-expr-essentialsArchived13/13expressions +8
native-bridge ~1
add-expr-filterArchived3/3column-selectors ~1
expressions +1
add-expr-mathArchived4/4math-functions +5
add-expression-pluginsArchived7/7expression-plugins +1
add-frame-utilitiesArchived3/3frame-utilities +4
add-frame-utilities-0-6Archived3/3frame-utilities +7
add-frame-verbsArchived13/13frame-verbs +6
native-bridge ~1
add-horizontal-and-rangesArchived4/4horizontal-functions +3
add-html-tablesArchived6/6dataframe-api +1
native-bridge +1
add-inspection-and-configArchived6/6inspection +4
add-joins-and-concatArchived10/10api-conventions +2
combining-frames +3
data-types ~2
native-bridge ~1
add-json-ioArchived3/3json-io +3
add-list-namespaceArchived3/3list-functions +4
add-nested-dtypesArchived5/5data-types ~1
nested-data +4
add-nested-stringsArchived3/3strings +3
add-nim-callbacksArchived3/3callbacks +4
add-openspec-pageArchived4/4ci ~2
dev-log +1
add-parameter-type-conventionArchived1/1api-conventions +1
add-parquet-ipcArchived7/7csv-io +1
native-bridge ~1
parquet-ipc +4
add-plan-serializationArchived3/3plan-serialization +3
add-polars-coverage-pageArchived3/3dev-log +1
add-repeat-by-and-seedsArchived3/3list-functions +2
add-reshapingArchived4/4reshaping +5
add-review-modeArchived6/6dev-log +2
add-rolling-and-ewmArchived5/5missing-values +1
rolling-windows +3
add-row-objectsArchived3/3row-objects +2
add-sample-datasetsArchived5/5datasets +3
add-series-apiArchived4/4series +4
add-spec-examplesArchived7/7ci ~2
spec-examples +3
add-specview-full-specsArchived3/3spec-review +2
add-sqlArchived3/3sql +3
add-streaming-and-sinksArchived3/3streaming +4
add-string-expressionsArchived7/7native-bridge ~1
strings +6
add-struct-namespaceArchived3/3struct-functions +5
add-temporal-typesArchived10/10csv-io ~1
data-types ~3
native-bridge ~1
temporal +7
add-testing-helpersArchived2/2testing-helpers +2
add-top-k-rows-and-date-partsArchived10/10dataframe-api ~1
inspection ~2
temporal +1
temporal-grouping ~1
value-functions +1
add-typed-errorsArchived7/7combining-frames ~3
csv-io ~1
data-types ~1
dataframe-api +1 ~2 −1
datamancer-interop ~1
frame-verbs ~3
inspection ~1
missing-values ~1
native-bridge ~2
add-value-functionsArchived6/6value-functions +6
build-lib-with-nightlyArchived5/5binary-distribution +1
strings +1
one-program-buildsArchived7/7ci +1 ~1
spec-examples ~1
pin-polars-to-py-releaseArchived3/3categoricals ~1
native-bridge +1
streaming −1
print-dtypes-as-nanuq-codeArchived3/3data-types ~2
nested-data ~1
refine-book-needs-0-6Archived3/3excel-io ~1
temporal-grouping +1
ship-prebuilt-binariesArchived11/11binary-distribution +6
ci +1 ~1
native-bridge +1 ~1
use-how-for-method-paramsArchived3/3api-conventions +1
expressions ~1
horizontal-functions ~1
missing-values ~1

No active changes.

add-api-polish Archived

openspec/changes/archive/2026-10-31-add-api-polish
  1. Proposal
  2. Specs
  3. Design
  4. Tasks
  5. Implement 11/11
  6. Archive
Proposal

Why

The 0.3 explainer ("Aged 19") and the Nanuq Book ports keep tripping over small things in the 0.2 API: toSeq clashes with sequtils.toSeq, col("a") / col("b") silently truncates integers, every tiny frame repeats series(...) for each column, col("race") is noisy next to Python's pl.col.race, there is no way to count nulls inside a query, and shared places in a ranking need rank. None of them is big, and all of them change how the rest of 0.3 reads, so they land first.

This change takes up the BACKLOG.md entries "Block syntax for building a dataframe", "/ on two integer columns: open design question" and "toSeq clashes with sequtils.toSeq". It is the first change of the 0.3 release. The API choices were made by Pietro on 2026-10-31 in the 0.3 design discussion (dev log "Designing Nanuq 0.3", section 7, and the decisions that followed it): true division for / because Nim's / is closer to Python than to Rust, col.name shorthand, string keys and nil in the block syntax, Expr.nullCount, and rank with ties.

What Changes

  • BREAKING: toSeq is renamed toList (Polars' to_list), for plain and Option types. toSeq(walkFiles("*.csv")) compiles again with Nanuq imported.
  • BREAKING: / is true division. col("a") / col("b") on integers gives f64, as in Python Polars and Nim (7 / 2 == 3.5); a division by zero gives inf or NaN. div stays Polars' floor division.
  • col.name shorthand: col.race is col("race"), as Python's pl.col.race. col becomes a constant whose call operator keeps every existing form working: col("a"), col("a", "b"), col(SomeNumber), col(float, int).
  • Block syntax for newDataFrame:
  let df = newDataFrame:
    rider: ["Pogačar", "Seixas"]
    wins: [22, nil]          # nil is a missing value
    "nrs + 5": [1, 2]        # string keys for names that aren't identifiers

Each line becomes series(name, values). A bracket holding nil becomes an Option column typed from its other values. newDataFrame() with no columns stays valid.

  • Expr.nullCount: the number of nulls as an aggregation, col.a.nullCount.
  • rank(rankMethod = Average, descending = false, seed = none(int)) with a pure enum RankMethod (Average, Min, Max, Dense, Ordinal, Random). Written positionally, rank(Min, descending = true), because method is a Nim keyword.
  • Polars feature rank is compiled in. The crate version becomes 0.3.0-dev.

Capabilities

New Capabilities

None.

Modified Capabilities
  • dataframe-api: toList, the block syntax, the col.name shorthand and true division.
  • missing-values: toList in the null reads, and Expr.nullCount.
  • data-types: toList in the casting scenario.
  • frame-verbs: toList in the row window example.
  • expressions: rank and RankMethod.
  • native-bridge: NqRankMethod joins the enums kept in the same order.

Differences from Polars

Expected differences from Polars' Rust and Python APIs:

  • / matches Python Polars (truediv), not Rust Polars' / operator, which truncates integer division and gives null for a division by zero. This is the one operator where Nanuq picks Python over Rust, because Nim's own / does the same.
  • col.name works for any column name that is a Nim identifier, keywords such as end included. A few names are taken by Nim before the shorthand sees them: type, and procs from system that accept anything, such as repr and sizeof. Those columns need col("type"). Python's pl.col.name has similar gaps (methods of pl.col), different ones.
  • Block syntax has no Polars counterpart: Python writes a dict (pl.DataFrame({"a": [...]})), Rust the df! macro (df!("a" => [...])). Missing values are nil where Python writes None.
  • rank's method is a positional argument: Python's keyword method= can't be a Nim named argument because method is a keyword. The parameter is named rankMethod. The default is Average, as in Python (Rust has no default). seed applies only to Random.
  • toList takes the Nim element type: df.toList("a", int). Python's Series.to_list() infers it.
  • Names follow Polars in camelCase: null_count → nullCount, to_list → toList.

Impact

  • src/rust/src/lib.rs: NqBinOp gains TrueDiv and / maps to it; new nq_expr_rank with NqRankMethod; NqUnary gains NullCount. Cargo.toml adds the rank feature and moves to 0.3.0-dev.
  • src/nanuq/ffi.nim and src/nanuq.nim: the declarations, toList, ColNs with call and dot operators, the newDataFrame macro, nullCount, rank.
  • src/nanuq/datamancer.nim, tests, README, dev log posts and examples move from toSeq to toList.
  • tests/test_basic.nim and tests/test_expressions.nim cover the new API.
Spec changesdata-types ~1 · dataframe-api +3 ~2 · expressions +1 · frame-verbs ~1 · missing-values ~4 · native-bridge ~1

data-types modified ~1

MODIFIED
Casting
The API SHALL cast expressions (`e.cast(target, strict = true)`), all columns of a DataFrame or LazyFrame (`cast(target, strict = true)`), where `target` is a Nim type or a `DataType`, and named columns (`cast({"a": Int32}, strict = true)`) with `DataType` values. Temporal Nim targets (`Date`, `DateTime`, `Duration`, `TimeOfDay`) SHALL take `timeUnit = Microseconds` and, for `DateTime`, `timeZone = ""`. A strict cast SHALL raise `PolarsError``NanuqError` (when the query runs) if a value cannot be converted; a non-strict cast SHALL turn such values into nulls. Casting to a `DataTypeKind.Other` dtype SHALL raise `PolarsError`.`NanuqError`. ```nim let df = newDataFrame(series("a", [1, 2]), series("s", ["1", "x"])) echo df.cast({"a": Int32}).dtype("a") echo df.select(col("a").cast(float32)).dtype("a") echo df.select(col("s").cast(Int64, strict = false)) echo df.select(col("a").cast(DateTime, timeUnit = Milliseconds, timeZone = "UTC")).dtype("a") ``` ```text Int32i32 Float32f32 shape: (2, 1) ┌──────┐ │ s │ │ --- │ │ i64 │ ╞══════╡ │ 1 │ │ null │ └──────┘ DateTime(Milliseconds, "UTC") ``` Scenario: Narrow an integer column - **WHEN** `df.cast({"a": Int32})` runs on an i64 column - **THEN** `dtype("a") == Int32` and `toList(df, "a", int)` returns the same values Scenario: Nim type as target - **WHEN** `col("a").cast(float32)` is selected from an i64 column - **THEN** the result column has dtype `Float32` Scenario: Strict failure - **WHEN** a string column holding "1" and "x" is cast to `Int64` with `strict = true` - **THEN** `PolarsError``NanuqError` is raised Scenario: Non-strict cast - **WHEN** the same column is cast with `strict = false` - **THEN** the result is 1 and null Scenario: Integers to dates - **WHEN** a column of microseconds `[0, 86_400_000_000]` is cast to `DateTime` and then to `Date` - **THEN** the result is 1970-01-01 and 1970-01-02

Unchanged in this spec: DataType values, DataType constants and predicates, Schemas, Nim types map to DataType, Full-range UInt64

dataframe-api modified +3 ~2

MODIFIED
Building and reading data
The API SHALL build a DataFrame from Nim arrays of int, float, bool and string (`series`, `newDataFrame`), read and write CSV with a header row, and expose `shape`, `columns`, `dtype`, `head`, `$` (Polars' table format), single cells and whole columns (`toList`). ```nim let df = newDataFrame(series("bear", ["Nanuq", "Ursa"]), series("weight", [410.5, 380.0])) echo df echo df.shape, " ", df.columns, " ", df["bear", 0, string], " ", df.toList("weight", float) ``` ```text shape: (2, 2) ┌───────┬────────┐ │ bear ┆ weight │ │ --- ┆ --- │ │ str ┆ f64 │ ╞═══════╪════════╡ │ Nanuq ┆ 410.5 │ │ Ursa ┆ 380.0 │ └───────┴────────┘ (2, 2) @["bear", "weight"] Nanuq @[410.5, 380.0] ``` Scenario: Columns of different lengths - **WHEN** `newDataFrame` gets series of different lengths - **THEN** `PolarsError``NanuqError` is raised Scenario: No clash with sequtils - **WHEN** a module imports `nanuq` and `std/[os, sequtils]` and calls `toSeq(walkFiles("*.csv"))` - **THEN** it compiles and returns the matching paths
MODIFIED
Reading columns by type
Reading as `float` SHALL accept any integer or float column; as `string`, any column, formatted as Polars does; as `int`, only integer columns; as `bool`, only boolean columns. A dtype that does not match SHALL raise `PolarsError`.`NanuqError`. ```nim let df = newDataFrame(series("a", [1, 2])) echo df.toList("a", float) # integers widen to float echo df.toList("a", string) # any column formats as text ``` ```text @[1.0, 2.0] @["1", "2"] ``` Scenario: Integers read as floats - **WHEN** an i64 column holding 1, 2 is read with `toList(df, "a", float)` - **THEN** the result is `@[1.0, 2.0]` Scenario: Floats are not truncated to int - **WHEN** an f64 column is read with `toList(df, "a", int)` - **THEN** `PolarsError``NanuqError` is raised Scenario: Bool column - **WHEN** a bool column is read with `toList(df, "d", bool)` - **THEN** the result holds the column's values
ADDED
Block syntax for building a DataFrame

newDataFrame SHALL accept a block of name: [values] lines and build one column per line, in order, as series(name, values) would. A name SHALL be a Nim identifier or a string literal. A nil inside the brackets SHALL be a missing value, and the column SHALL then have the type of its other values. newDataFrame SHALL keep accepting series (newDataFrame(series(...), ...), a seq of series, or none at all).

let df = newDataFrame:
  rider: ["Pogačar", "Seixas", "Vingegaard"]
  wins: [22, 8, nil]
  "win %": [0.31, 0.12, 0.05]
echo df
shape: (3, 3)
┌────────────┬──────┬───────┐
│ rider      ┆ wins ┆ win % │
│ ---        ┆ ---  ┆ ---   │
│ str        ┆ i64  ┆ f64   │
╞════════════╪══════╪═══════╡
│ Pogačar    ┆ 22   ┆ 0.31  │
│ Seixas     ┆ 8    ┆ 0.12  │
│ Vingegaard ┆ null ┆ 0.05  │
└────────────┴──────┴───────┘
Scenario: Same frame as series
  • WHEN a frame is built with the block syntax and the same frame with series calls
  • THEN both have the same columns, dtypes and values
Scenario: nil is a null
  • WHEN a line reads wins: [22, nil]
  • THEN column "wins" is i64 with values 22 and null
Scenario: Only nil
  • WHEN a line reads wins: [nil, nil]
  • THEN the program fails to compile
Scenario: Empty frame
  • WHEN newDataFrame() is called
  • THEN the result has shape (0, 0)
ADDED
Column shorthand

col.name SHALL be the same expression as col("name") for any column name that is a Nim identifier and not taken by Nim first (type, and generic system procs such as repr). Every other form of col SHALL keep working: col("a"), col("a", "b"), col(SomeNumber) and col(float, int). User code SHALL need no pragma to use them.

let df = newDataFrame:
  race: ["Sanremo", "Lombardia"]
  "end": [1, 2]
echo df.select(col.race, col.end, col("race", "end").count.name.suffix("_n"))
shape: (2, 4)
┌───────────┬─────┬────────┬───────┐
│ race      ┆ end ┆ race_n ┆ end_n │
│ ---       ┆ --- ┆ ---    ┆ ---   │
│ str       ┆ i64 ┆ u32    ┆ u32   │
╞═══════════╪═════╪════════╪═══════╡
│ Sanremo   ┆ 1   ┆ 2      ┆ 2     │
│ Lombardia ┆ 2   ┆ 2      ┆ 2     │
└───────────┴─────┴────────┴───────┘
Scenario: Same plan
  • WHEN $col.race and $col("race") are compared
  • THEN they are equal
Scenario: Names that are procs
  • WHEN col.len and col.min are used
  • THEN they select the columns "len" and "min"
ADDED
True division

/ on expressions SHALL be Polars' true division: the result SHALL be a float column even when both sides are integers, and a division by zero SHALL give inf or NaN, not null. div SHALL stay floor division.

let df = newDataFrame:
  seconds: [7200, 5400, 0]
echo df.select(col.seconds, (col.seconds / 3600).alias("hours"),
               (col.seconds div 3600).alias("whole"), (col.seconds / 0).alias("by_zero"))
shape: (3, 4)
┌─────────┬───────┬───────┬─────────┐
│ seconds ┆ hours ┆ whole ┆ by_zero │
│ ---     ┆ ---   ┆ ---   ┆ ---     │
│ i64     ┆ f64   ┆ i64   ┆ f64     │
╞═════════╪═══════╪═══════╪═════════╡
│ 7200    ┆ 2.0   ┆ 2     ┆ inf     │
│ 5400    ┆ 1.5   ┆ 1     ┆ inf     │
│ 0       ┆ 0.0   ┆ 0     ┆ NaN     │
└─────────┴───────┴───────┴─────────┘
Scenario: Integers divide to a float
  • WHEN lit(7) / 2 is evaluated
  • THEN the result is 3.5 with dtype f64
Scenario: Floor division unchanged
  • WHEN lit(7) div 2 is evaluated
  • THEN the result is 3 with dtype i64

Unchanged in this spec: Automatic memory management, Expressions and lazy queries, HTML tables, Errors as PolarsError

expressions modified +1

ADDED
Ranking

Expr SHALL support rank(rankMethod = Average, descending = false, seed = none(int)) with a pure enum RankMethod (Average, Min, Max, Dense, Ordinal, Random), giving each value its rank from 1. Ties SHALL be handled as Polars does: Average gives tied values the mean of their ranks (f64), Min and Max the lowest or highest (u32), Dense leaves no gaps after ties, and Ordinal breaks ties by position. seed SHALL make Random repeatable. Nulls SHALL stay null.

let roll = newDataFrame:
  rider: ["Merckx", "Pogačar", "De Vlaeminck", "Van Looy", "Kelly"]
  monuments: [19, 13, 11, 8, 9]
echo roll.select(col.rider, col.monuments,
                 col.monuments.rank(Min, descending = true).alias("place"),
                 col.monuments.rank.alias("avg"))
shape: (5, 4)
┌──────────────┬───────────┬───────┬─────┐
│ rider        ┆ monuments ┆ place ┆ avg │
│ ---          ┆ ---       ┆ ---   ┆ --- │
│ str          ┆ i64       ┆ u32   ┆ f64 │
╞══════════════╪═══════════╪═══════╪═════╡
│ Merckx       ┆ 19        ┆ 1     ┆ 5.0 │
│ Pogačar      ┆ 13        ┆ 2     ┆ 4.0 │
│ De Vlaeminck ┆ 11        ┆ 3     ┆ 3.0 │
│ Van Looy     ┆ 8         ┆ 5     ┆ 1.0 │
│ Kelly        ┆ 9         ┆ 4     ┆ 2.0 │
└──────────────┴───────────┴───────┴─────┘
Scenario: Shared places
  • WHEN rank(Min, descending = true) runs over 9, 9, 7
  • THEN the result is 1, 1, 3
Scenario: Dense
  • WHEN rank(Dense) runs over 9, 9, 7
  • THEN the result is 2, 2, 1
Scenario: Average
  • WHEN rank() runs over 9, 9, 7
  • THEN the result is 2.5, 2.5, 1.0 with dtype f64

Unchanged in this spec: Conditional expressions, choose macro, Membership and ranges, Arithmetic operators, Rounding, More aggregations, Null fill strategies, Window expressions, Filtering inside expressions, Shape and position aggregations, Boolean aggregations, Entropy, Row count expression, Several window keys and selector concatenation, Null-aware comparisons and closeness, More expression functions

frame-verbs modified ~1

MODIFIED
Row windows
LazyFrame and DataFrame SHALL support `head(n = 5)`, `tail(n = 5)`, `slice(offset)` and `slice(offset, length)`. A negative offset SHALL count from the end. `reverse()` SHALL reverse the row order. ```nim let df = newDataFrame(series("n", [1, 2, 3, 4, 5])) echo df.tail(2).toList("n", int) echo df.slice(-3, 2).toList("n", int) # negative offset counts from the end echo df.slice(1).toList("n", int) # to the end echo df.reverse.toList("n", int) ``` ```text @[4, 5] @[3, 4] @[2, 3, 4, 5] @[5, 4, 3, 2, 1] ``` Scenario: Tail - **WHEN** `tail(2)` runs on rows 1 to 5 - **THEN** the result is rows 4 and 5 Scenario: Slice from the end - **WHEN** `slice(-3, 2)` runs on rows 1 to 5 - **THEN** the result is rows 3 and 4 Scenario: Slice to the end - **WHEN** `slice(1)` runs on rows 1 to 5 - **THEN** the result is rows 2 to 5

Unchanged in this spec: Dropping and renaming columns, Unique rows, Row index, Sorting by several keys, Sampling rows, Every n-th row, Frame interpolation, Casting by data type, Several filter predicates, Group order parameter, Frame aggregations, Group-by shortcuts, Iterating over groups, Frame fillNan and select without a frame

missing-values modified ~4

MODIFIED
Nulls are read as Option
Reading a column or a cell with the type `Option[T]` SHALL return `none(T)` for each null and `some(value)` otherwise, for T in int, float, bool and string. ```nim let df = newDataFrame(series("a", [some(1), none(int), some(3)])) echo df.toList("a", Option[int]) echo df["a", 1, Option[int]] ``` ```text @[some(1), none(int), some(3)] none(int) ``` Scenario: Column with gaps - **WHEN** a column holds 1, null, 3 and is read with `toList(df, "a", Option[int])` - **THEN** the result is `@[some(1), none(int), some(3)]` Scenario: Single cell - **WHEN** the null cell is read with `df["a", 1, Option[int]]` - **THEN** the result is `none(int)`
MODIFIED
Plain reads refuse nulls
Reading a column or a cell with a plain type T SHALL raise `InvalidOperationError``NanuqError` if the values read include a null, and the message SHALL name the column. ```nim let df = newDataFrame(series("a", [some(1), none(int)])) try: discard df.toList("a", int) except PolarsErrorNanuqError as e: echo e.name"NanuqError" ``` ```text InvalidOperationErrorNanuqError ``` Scenario: Column with a null read as int - **WHEN** a column with one null is read with `toList(df, "a", int)` - **THEN** `InvalidOperationError``NanuqError` is raised before any value is returned, naming column "a"
MODIFIED
Inspecting nulls
The API SHALL report the number of nulls in a column and whether it has any, and SHALL provide `nullCount` on expressions as an aggregation (u32), usable in `select` and `agg`. ```nim let df = newDataFrame(series("a", [some(1), none(int), some(3)])) echo df.nullCount("a"), " ", df.hasNulls("a") echo df.select(col.a.nullCount.alias("missing")) ``` ```text 1 true shape: (1, 1) ┌─────────┐ │ missing │ │ --- │ │ u32 │ ╞═════════╡ │ 1 │ └─────────┘ ``` Scenario: Counting - **WHEN** a column of 3 values has 1 null - **THEN** `nullCount(df, "a")` is 1 and `hasNulls(df, "a")` is true Scenario: No nulls - **WHEN** a column has no nulls - **THEN** `nullCount` is 0 and `hasNulls` is false Scenario: Null count per group - **WHEN** `groupBy(col.g).agg(col.a.nullCount)` runs on groups with 1 and 0 nulls - **THEN** the result has 1 and 0 for those groups
MODIFIED
Null expressions
The API SHALL provide `isNull` and `isNotNull` on expressions (giving booleans), and `fillNull` replacing nulls with a literal or an expression. ```nim let df = newDataFrame(series("a", [some(1), none(int), some(3)])) echo df.select(col("a").isNull.alias("missing"), col("a").fillNull(0).alias("filled")) echo df.filter(col("a").isNotNull).toList("a", int) ``` ```text shape: (3, 2) ┌─────────┬────────┐ │ missing ┆ filled │ │ --- ┆ --- │ │ bool ┆ i64 │ ╞═════════╪════════╡ │ false ┆ 1 │ │ true ┆ 0 │ │ false ┆ 3 │ └─────────┴────────┘ @[1, 3] ``` Scenario: Filter out nulls - **WHEN** a LazyFrame is filtered with `col("a").isNotNull` and collected - **THEN** the result has no nulls in column "a" Scenario: Fill nulls - **WHEN** `withColumns(col("a").fillNull(0))` is applied to a column 1, null, 3 - **THEN** column "a" becomes 1, 0, 3

Unchanged in this spec: Building columns with nulls, CSV null markers, Dropping rows with nulls, Interpolation, Null literal, Filling nulls in whole frames

native-bridge modified ~1

MODIFIED
Nim declarations mirror the C ABI
`src/nanuq/ffi.nim` SHALL declare every exported function with matching signatures, and the enums `NqBinOp`, `NqUnary`, `NqDtype`, `NqDtypeClass`, `NqJoinType`, `NqJoinValidation`, `NqMaintainOrderJoin`, `NqConcat`, `NqUniqueKeepStrategy`, `NqClosedInterval`, `NqQuantileMethod`, `NqFillNullStrategy`, `NqRoundMode`, `NqQuoteStyle`,`NqQuoteStyle` `NqRankMethod`,and `NqErrorKind`, `NqStrOp`,`NqRankMethod` `NqTimeUnit`, `NqClosedWindow`, `NqDtOp`, `NqCatOp`, `NqParquetCompression` and `NqIpcCompression` SHALL keep the same order as in Rust. `NqDtype` SHALL also keep the order of of `DataTypeKind`, and the option enums the order of their Nim API enums. Data types SHALL cross the ABI as an `NqDtypeSpec` struct (code, time unit, time zone, categories) with the same field order on both sides. Scenario: ABI change - **WHEN** a function is added or changed in `rust/src/lib.rs` - **THEN** `src/nanuq/ffi.nim` is updated in the same change

Unchanged in this spec: C ABI over Polars with opaque handles, Errors and panics never cross the boundary, Linking the static library, Columns cross in bulk, Library version check, Formatted cells, Polars version matches a py-polars release

Design

Design

Context

col is a proc today, plus a macro (col(SomeNumber)) and a proc with two or more names returning a Selector. Python Polars' pl.col is an object with a __call__ and a __getattr__, so pl.col("a") and pl.col.a both work. newDataFrame is a proc over varargs[Series]. Polars 0.55 has Expr::true_div, Expr::null_count and Expr::rank(RankOptions { method, descending }, seed) (feature rank).

Decisions

col is a constant with call and dot operators

const col* = ColNs() with () overloads for every existing form (one name, several names, the type selector macro), and a . template that turns col.race into col("race"). The experimental callOperator and dotOperators features only need to be enabled where the operators are declared, so user code needs no pragma (checked with Nim 2.2.4). The dot template only fires when nothing else matches, so col.len is a column but col.repr is system.repr.

Alternative considered: a col macro taking an untyped dot expression. It can't tell col.a from col(a) where a is a variable, and macros can't be overloaded on untyped arguments cleanly.

newDataFrame is a macro over varargs[untyped]

A macro with one untyped parameter and a proc over varargs[Series] don't overload: the block form gets sem-checked against the proc and fails. So newDataFrame becomes a single macro. With one block argument it rewrites each name: [values] line to series("name", values); with anything else it forwards the arguments unchanged to the old proc (now private), so newDataFrame(series(...), series(...)), newDataFrame(someSeq) and newDataFrame() keep working.

nil inside a bracket turns the bracket into [some(a), none(typeof(a)), ...], with the type taken from the first non-nil value. A bracket of only nil fails to compile: there is no type to infer.

True division through NqBinOp

NqBinOp.Div now maps to Expr::true_div. Rust's truncating / is not exposed (div already gives floor division, which is what integer code wants). No new ABI function.

rank

nq_expr_rank(e, NqRankMethod, descending, has_seed, seed). Polars returns f64 for Average and u32 otherwise; Nanuq passes that through.

Risks / Trade-offs

  • col as a constant: code that took col as a proc value (names.map(col)) breaks; names.mapIt(col(it)) works. Nothing in the repo does that.
  • Changing / silently changes results of 0.2 code. Nanuq has no users yet, and the CHANGELOG says so under "Changed".
Tasks11 of 11 done

1. Bridge 4/4

  • 1.1Add the Polars feature rank and move the crate to 0.3.0-dev
  • 1.2Map NqBinOp::Div to true_div; add NqUnary::NullCount
  • 1.3Add nq_expr_rank with NqRankMethod
  • 1.4Mirror everything in ffi.nim; verify that cargo build --release passes

2. Nim API 5/5

  • 2.1Rename toSeq to toList everywhere (library, Datamancer module, tests, README, dev log posts, examples)
  • 2.2Turn col into a ColNs constant with call operators for every existing form and a dot template
  • 2.3Turn newDataFrame into a macro with the block syntax (nil as missing, string keys) that forwards other calls to the series form
  • 2.4Add Expr.nullCount and rank with RankMethod
  • 2.5Tests: toSeq(walkFiles(...)) compiles with Nanuq imported, col.name gives the same plan as col("name"), the block syntax (nil, string keys, compile failure for only nil), true division and division by zero, nullCount in agg, every RankMethod

3. Docs and integration 2/2

  • 3.1README: toList, col.name, the block syntax and true division; verify that nimble test, nimble example and nimble specexamples pass
  • 3.2Archive the change: remove the three BACKLOG entries, add CHANGELOG lines (Changed for / and toList), update spec example outputs with --update
Revisions1 revision
r1 b925875 2026-10-31 Implement and archive add-api-polish

First version: design.md, proposal.md, specs/data-types/spec.md, specs/dataframe-api/spec.md, specs/expressions/spec.md, specs/frame-verbs/spec.md, specs/missing-values/spec.md, specs/native-bridge/spec.md, tasks.md

add-arraymancer-interop Archived

openspec/changes/archive/2026-11-01-add-arraymancer-interop
  1. Proposal
  2. Specs
  3. Tasks
  4. Implement 3/3
  5. Archive
Proposal

Why

Numerical work in Nim (linear algebra, statistics, machine learning with Flambeau or Arraymancer's own layers) happens on Arraymancer tensors, the way Python moves from Polars to NumPy with to_numpy. BACKLOG.md lists "Arraymancer tensors (S): copy numeric columns to and from Tensor[T]", and the coverage map puts it in 0.4.

It is the ninth change of the 0.4 release, from the BACKLOG.md entry "Arraymancer tensors".

What Changes

  • An optional module nanuq/arraymancer, like nanuq/datamancer: only it imports Arraymancer.
  • toTensor(series, T), toTensor(df, column, T) and toTensor(df, T, columns) (a 2-D tensor, one row per row), for T in int, float and bool; nulls become NaN in float tensors and raise InvalidOperationError otherwise.
  • toSeries(tensor, name) for 1-D tensors and toDataFrame(tensor, columns) for 2-D tensors.
  • CI already installs Datamancer, which depends on Arraymancer, so the new test runs there.

Capabilities

New Capabilities
  • arraymancer-interop: copying numeric columns to and from Arraymancer tensors.

Differences from Polars

  • Python's to_numpy can be zero-copy; Nanuq copies (zero-copy needs the Arrow C Data Interface, a backlog item).
  • The element type is given (toTensor(float)); Python infers the NumPy dtype.
  • toDataFrame takes a 2-D tensor only (Python's from_numpy also takes 1-D arrays and an orient).

Impact

  • New src/nanuq/arraymancer.nim and tests/test_arraymancer.nim; nanuq.nimble test list; a comment in .github/workflows/ci.yml; BACKLOG.md entry removed.
Spec changesarraymancer-interop +2

arraymancer-interop modified +2

ADDED
Columns to tensors

The optional module nanuq/arraymancer SHALL provide toTensor(series, T), toTensor(df, column, T) and toTensor(df, T, columns), copying values into an Arraymancer Tensor[T] for T in int, float and bool; the frame version SHALL give a 2-D tensor with one row per row of the frame. Nulls SHALL become NaN in float tensors and SHALL raise InvalidOperationError for int and bool.

import pkg/arraymancer, nanuq/arraymancer
let df = newDataFrame:
  oni: [2.4, 2.6, 2.0]
  temp: [14.7, 15.0, 15.2]
let t = df.toTensor(float)
echo t.shape[0], "x", t.shape[1], " ", t[1, 0]
TBD
Scenario: Nulls in a float tensor
  • WHEN a float column with a null is copied with toTensor("a", float)
  • THEN the tensor holds NaN at that position
ADDED
Tensors to columns

toSeries(tensor, name) SHALL copy a 1-D tensor into a Series, and toDataFrame(tensor, columns) SHALL copy a 2-D tensor into a frame with one column per tensor column, named columns or column_0, column_1, ...

import pkg/arraymancer, nanuq/arraymancer
echo [[1.0, 2.0], [3.0, 4.0]].toTensor.toDataFrame(["a", "b"])
TBD
Scenario: Wrong rank
  • WHEN toSeries is called on a 2-D tensor
  • THEN ValueError is raised
Tasks3 of 3 done

1. Implementation 3/3

  • 1.1nanuq/arraymancer with toTensor, toSeries, toDataFrame
  • 1.2Tests in tests/test_arraymancer.nim, run by nimble test and CI
  • 1.3BACKLOG.md entry removed; CHANGELOG
Revisions1 revision
r1 46ae6c2 2026-11-01 Nanuq 0.4, changes 8-10: Series API, Arraymancer tensors, row objects

First version: proposal.md, specs/arraymancer-interop/spec.md, tasks.md

add-arrow-c-data Archived

openspec/changes/archive/2026-11-01-add-arrow-c-data
  1. Proposal
  2. Specs
  3. Tasks
  4. Implement 3/3
  5. Archive
Proposal

Why

The Arrow C Data Interface is the standard way to hand columns between libraries in one process without copying: DuckDB, Arrow C++/GLib, nanoarrow and any Arrow-aware C library read and write it. It is how Python Polars talks to PyArrow, pandas and DuckDB (to_arrow, from_arrow, __arrow_c_stream__), and the 0.6 book map counts 7 sections using it. It also gives Nim code zero-copy access to Polars' buffers, which is what the BACKLOG.md entry "Zero-copy columns through the Arrow C Data Interface" asks for, to make mapElements faster.

It is the fourth change of the 0.6 release and takes that BACKLOG.md entry.

What Changes

  • Nim objects with the standard layouts: ArrowSchema, ArrowArray, ArrowArrayStream, and release for each.
  • s.toArrow: ArrowExport (schema + array, released when it goes away unless a consumer took them over) and fromArrow(schema, array, name) / fromArrow(export) for Series; df.toArrow: ArrowArrayStream and fromArrow(stream) for frames (record batches as struct arrays).
  • s.view(T) / df.view(column, T): a ColumnView[T] reading a numeric column without nulls in place (v[i], v.len, items, v.toOpenArray).
  • mapElements on numeric columns without nulls reads each batch through a view instead of copying it into a seq first.

Capabilities

New Capabilities
  • arrow-interop: exchanging columns and frames through the Arrow C Data Interface, and zero-copy views.

Differences from Polars

  • Python returns PyArrow objects (pa.Array, pa.Table); Nanuq hands out the C structs themselves, which is what a Nim program passes to a C library. There is no compat_level argument: Nanuq always exports the newest layout (string views).
  • fromArrow takes over the array (Arrow's move semantics); Python copies or shares through PyArrow.
  • view has no Python counterpart besides to_numpy(allow_copy = False), which it mirrors for numeric columns; it refuses columns with nulls instead of copying.

Impact

  • src/rust/Cargo.toml: polars-arrow (for its ffi module).
  • src/rust/src/lib.rs, src/nanuq/ffi.nim: nq_series_to_arrow, nq_series_from_arrow, nq_df_to_arrow_stream, nq_df_from_arrow_stream, and the struct layouts.
  • src/nanuq.nim: the API above and the mapElements fast path.
  • New tests/test_arrow.nim; benchmarks/map_elements rerun.
Spec changesarrow-interop +3

arrow-interop modified +3

ADDED
Series through the Arrow C Data Interface

s.toArrow SHALL export a Series as an ArrowExport holding the standard ArrowSchema and ArrowArray C structs, without copying the values. Whatever a consumer did not take over SHALL be released when the export goes away. fromArrow(schema, array, name = "") SHALL import a Series from such structs, taking over the array.

var ex = series("kg", @[410, 380]).toArrow
echo ex.schema.format, " ", ex.array.length
let back = fromArrow(ex, name = "mass")
echo back
TBD
Scenario: Taken over
  • WHEN an export's array is imported with fromArrow
  • THEN the export's array.release is nil and the Series reads the same values
ADDED
Frames through the Arrow C stream interface

df.toArrow SHALL export a frame as an ArrowArrayStream of record batches (struct arrays), and fromArrow(stream) SHALL read a whole stream into a frame and release it.

let df = newDataFrame(series("bear", @["Ada", "Bo"]), series("kg", @[410.0, 380.5]))
var stream = df.toArrow
echo fromArrow(stream)
TBD
Scenario: Nested and temporal columns
  • WHEN a frame with List, Struct and Datetime columns goes through toArrow and fromArrow
  • THEN the result equals the frame
ADDED
Zero-copy views

s.view(T) and df.view(column, T) SHALL give a ColumnView[T] over a numeric column's values without copying, with [], len, items and toOpenArray. T SHALL match the column's type exactly and the column SHALL have no nulls, else InvalidOperationError.

import std/math
let df = newDataFrame(series("kg", @[410.0, 380.5, 455.0]))
let v = df.view("kg", float)
echo v.len, " ", v[1], " ", sum(v.toOpenArray)
TBD
Scenario: Wrong type
  • WHEN an Int64 column is viewed as float
  • THEN InvalidOperationError is raised
Scenario: Nulls
  • WHEN a column with a null is viewed
  • THEN InvalidOperationError is raised
Tasks3 of 3 done

1. Implementation 3/3

  • 1.1Crate: polars-arrow ffi; Series export/import; frame stream export/import
  • 1.2Nim struct layouts, toArrow, fromArrow, ArrowExport, ColumnView, view; mapElements fast path
  • 1.3Tests in tests/test_arrow.nim; benchmark rerun; nimble test and nimble specexamples pass; CHANGELOG; BACKLOG entry removed
Revisions1 revision
r1 4ea5dad 2026-11-01 0.6: archive the 9 changes, fill spec example outputs, map_elements benchmark, dev log Designing Nanuq 0.6

First version: proposal.md, specs/arrow-interop/spec.md, tasks.md

add-binary-decimal-bitwise Archived

openspec/changes/archive/2026-11-01-add-binary-decimal-bitwise
  1. Proposal
  2. Specs
  3. Tasks
  4. Implement 3/3
  5. Archive
Proposal

Why

Binary and Decimal are the two Polars data types Nanuq still shows as Other. Decimal matters for money and for data read from databases and Parquet files that store exact numbers; Binary for raw bytes (hashes, images, encoded payloads) and is the one blocker of the user guide's lazy/gpu page. Bitwise operations come with them in the roadmap's 0.6 line "Binary, Decimal dtypes; bitwise ops". It takes the BACKLOG.md entry "More dtypes".

It is the third change of the 0.6 release.

What Changes

  • DataTypeKind gains Binary and Decimal; constants Binary and Decimal(precision = 38, scale = 0); tables print binary and decimal[p,s], $ prints Binary and Decimal(p, s).
  • series(name, strings, dtype): with Binary the strings are raw bytes (any bytes); other dtypes cast the strings (Decimal(5, 2) parses them).
  • Reading back: Binary columns read as string (raw bytes); Decimal columns as string (exact) or float.
  • bin namespace: contains, startsWith, endsWith, encode(Hex | Base64), decode(Hex | Base64), size(unit).
  • str.encode(Hex | Base64), str.toDecimal(scale).
  • Bitwise expressions: bitwiseCountOnes, bitwiseCountZeros, bitwiseLeadingOnes, bitwiseLeadingZeros, bitwiseTrailingOnes, bitwiseTrailingZeros, and the aggregations bitwiseAnd, bitwiseOr, bitwiseXor. (and, or, xor between integer expressions already work bitwise, as in Polars.)

Capabilities

New Capabilities
  • binary-decimal: Binary and Decimal data and their functions, bitwise operations.

Differences from Polars

  • Nim has no bytes type: Binary values are Nim strings holding raw bytes, built with series(name, strings, Binary) (Python pl.Series([b"..."])).
  • Nim has no decimal type in the standard library: Decimal values are read as strings (exact) or floats, and written from strings (Python uses decimal.Decimal).
  • encode/decode take a BinaryEncoding enum (Python "hex"/"base64" strings); decode is always strict.
  • str.toDecimal takes the scale; Python 2.x infers it from the first rows (inference_length).

Impact

  • src/rust/Cargo.toml: Polars features binary_encoding, bitwise, string_encoding.
  • src/rust/src/lib.rs, src/nanuq/ffi.nim: dtype codes, nq_dtype_decimal, nq_series_new_binary, nq_expr_bin, nq_expr_str_codec, nq_expr_bitwise; string reads accept Binary columns, float reads Decimal ones.
  • New tests/test_binary_decimal.nim.
Spec changesbinary-decimal +4

binary-decimal modified +4

ADDED
Binary data

Binary SHALL be a data type of raw bytes. series(name, strings, Binary) SHALL build a Binary column whose values are the strings' bytes (any bytes), and toList(column, string) SHALL read them back unchanged.

let s = series("sig", ["\x00\xff", "bear"], Binary)
echo s.dtype
let df = newDataFrame(s)
echo df
echo df.toList("sig", string) == @["\x00\xff", "bear"]
TBD
Scenario: Cast from strings
  • WHEN a String column is cast to Binary
  • THEN its values read back as the same strings
ADDED
Decimal data

Decimal(precision = 38, scale = 0) SHALL be the exact decimal type, with precision 1 to 38 and scale 0 to precision (else ValueError). Strings SHALL become decimals with series(name, strings, Decimal(p, s)) or str.toDecimal(scale), and Decimal columns SHALL read back as string (exact) or float.

let df = newDataFrame(series("price", ["1.25", "10.50", "0.10"], Decimal(10, 2)))
echo df
echo df.select(col("price").sum)
echo df.toList("price", float)
TBD
Scenario: Bad precision
  • WHEN Decimal(40, 2) is called
  • THEN ValueError is raised
ADDED
Binary functions

e.bin SHALL provide contains, startsWith, endsWith (with a string of bytes or an expression), encode(BinaryEncoding) (hex or base64 text), decode(BinaryEncoding) and size(unit = SizeUnit.Bytes); str.encode(BinaryEncoding) SHALL encode strings' UTF-8 bytes.

let df = newDataFrame(series("b", ["bear", "cub"], Binary))
echo df.select(col("b").bin.encode(BinaryEncoding.Hex).alias("hex"),
               col("b").bin.startsWith("be").alias("be"), col("b").bin.size.alias("n"))
echo newDataFrame(series("s", @["hi"])).select(col("s").str.encode(BinaryEncoding.Base64))
TBD
Scenario: Round trip
  • WHEN a Binary column is encoded to hex, cast to Binary and decoded from hex
  • THEN the values equal the original
ADDED
Bitwise operations

Integer expressions SHALL provide bitwiseCountOnes, bitwiseCountZeros, bitwiseLeadingOnes, bitwiseLeadingZeros, bitwiseTrailingOnes, bitwiseTrailingZeros (per value) and bitwiseAnd, bitwiseOr, bitwiseXor (aggregations).

let df = newDataFrame(series("flags", @[0b0110'u8, 0b0011'u8]))
echo df.select(col("flags").bitwiseCountOnes.alias("ones"),
               col("flags").bitwiseTrailingZeros.alias("tz"))
echo df.select(col("flags").bitwiseAnd.alias("and"), col("flags").bitwiseOr.alias("or"))
TBD
Scenario: Not integers
  • WHEN bitwiseCountOnes is applied to a String column
  • THEN PolarsError is raised

Unchanged in this spec: Binary slicing and bytes, Strings to integers

Tasks3 of 3 done

1. Implementation 3/3

  • 1.1Crate: features; Binary/Decimal dtype codes, constructors, reads; bin, str codec, bitwise
  • 1.2Binary, Decimal, series(..., dtype), bin.*, str.encode, str.toDecimal, bitwise*
  • 1.3Tests in tests/test_binary_decimal.nim; nimble test and nimble specexamples pass; CHANGELOG
Revisions1 revision
r1 4ea5dad 2026-11-01 0.6: archive the 9 changes, fill spec example outputs, map_elements benchmark, dev log Designing Nanuq 0.6

First version: proposal.md, specs/binary-decimal/spec.md, tasks.md

add-book-port-needs Archived

openspec/changes/archive/2026-11-01-add-book-port-needs
  1. Proposal
  2. Specs
  3. Tasks
  4. Implement 7/7
  5. Archive
Proposal

Why

Porting the Nanuq Book chapters to 0.4 (nanuq-book#6) worked, and every Nim frame matched Python, but the port worked around a few gaps that are small to close: any/all aggregations (the book used min/max on booleans), a null literal (fill_nan(None)), groupBy with column names, and frame gatherEvery. It also found that eager df.groupBy(...).agg(...) returned a LazyFrame, unlike Python.

It is the thirteenth change of the 0.4 release (#51). The larger items from the same list go to BACKLOG.md.

What Changes

  • Expr.any(ignoreNulls) and Expr.all(ignoreNulls) aggregations (also on Series).
  • lit(nil) null literal and fillNan(nil).
  • groupBy("a", "b") and select("a", "b") with column names, on DataFrame and LazyFrame (select from the explainer port).
  • gatherEvery(n, offset) on DataFrame and LazyFrame.
  • BREAKING On a DataFrame, groupBy, groupByDynamic and rolling return a GroupBy whose agg returns a DataFrame, as in Python (it returned a LazyFrame, so eager code needed .collect). LazyFrame keeps LazyGroupBy.

Capabilities

Modified Capabilities
  • expressions: boolean aggregations.
  • missing-values: null literal.
  • dataframe-api: groupBy by name; eager agg returns a DataFrame.
  • frame-verbs: every n-th row.

Differences from Polars

  • Python writes pl.lit(None) and fill_nan(None); Nanuq writes lit(nil) and fillNan(nil).
  • any and all on a Series return a one-value Series (s.all.item(bool)), as other Series aggregations do; Python returns a bool.
  • all() with no argument stays the column selector, as Python's pl.all().

Impact

  • Rust: nq_expr_lit_null, nq_expr_any_all.
  • src/nanuq.nim: lit(nil), fillNan(nil), any, all, groupBy(varargs[string]), frame gatherEvery, the GroupBy type.
  • Tests in tests/test_expressions.nim, tests/test_nulls.nim, tests/test_verbs.nim.
Spec changesdataframe-api ~1 · expressions +1 · frame-verbs +1 · missing-values +1

dataframe-api modified ~1

MODIFIED
Expressions and lazy queries
The API SHALL provide `col`, `lit`, arithmetic, comparison and boolean operators on `Expr` (lifting Nim literals automatically), the aggregations sum, mean, min, max, count, first, last, nUnique and std, and `alias`. LazyFrame SHALL support select, withColumns, filter, groupBy/agg, sort, limit, explain and collect. `select` and `groupBy` SHALL take expressions or column names (`select("a", "b")`, `groupBy("species")`); `groupBy` SHALL keep the groups in the order their keys first appear (Python's `maintain_order=True`, always on). On a DataFrame, `groupBy`, `groupByDynamic` and `rolling` followed by `agg` SHALL return a DataFrame, as in Python; on a LazyFrame they return a LazyFrame. DataFrame SHALL offer eager shortcuts for select, withColumns, filter and sort. ```nim let query = penguins().lazy .filter(col("body_mass_g").isNotNull) .groupBy(col("species")) .agg(col("body_mass_g").mean.alias("mass"), col("species").count.alias("n")) .sort("mass", descending = true) echo query.collect # nothing runs before collect ``` ```text shape: (3, 3) ┌───────────┬─────────────┬─────┐ │ species ┆ mass ┆ n │ │ --- ┆ --- ┆ --- │ │ str ┆ f64 ┆ u32 │ ╞═══════════╪═════════════╪═════╡ │ Gentoo ┆ 5076.01626 ┆ 123 │ │ Chinstrap ┆ 3733.088235 ┆ 68 │ │ Adelie ┆ 3700.662252 ┆ 151 │ └───────────┴─────────────┴─────┘ ``` Scenario: Eager group by - **WHEN** `df.groupBy("a").agg(col.v.sum)` runs on a DataFrame - **THEN** the result is a DataFrame, with no `collect` needed Scenario: Select by name - **WHEN** `df.select("c", "a")` runs - **THEN** the result has columns c and a, in that order Scenario: Keys by name - **WHEN** `df.groupBy("a", "b")` is followed by `agg` - **THEN** it groups as `df.groupBy(col.a, col.b)` does Scenario: Group order - **WHEN** a frame with keys b, a, b, c is grouped by the key - **THEN** the groups come out as b, a, c Scenario: Lazy group by - **WHEN** a LazyFrame is filtered, grouped, aggregated and sorted - **THEN** nothing runs until `collect`, which returns the resulting DataFrame

Unchanged in this spec: Automatic memory management, Building and reading data, Reading columns by type, HTML tables, Block syntax for building a DataFrame, Column shorthand, True division, Errors as PolarsError

expressions modified +1

ADDED
Boolean aggregations

Expr SHALL support any(ignoreNulls = true) and all(ignoreNulls = true) on boolean columns, as aggregations: whether any value, or every value, is true. With ignoreNulls = false they SHALL follow Kleene logic: any is null when there are nulls and no true value, all is null when there are nulls and no false value. The all() selector (no arguments) SHALL keep working.

let df = newDataFrame:
  team: ["a", "a", "b", "b"]
  won: [true, false, true, true]
echo df.groupBy("team").agg(col.won.all.alias("always"), col.won.any.alias("ever"))
Scenario: Kleene logic
  • WHEN any(ignoreNulls = false) runs on false and null
  • THEN the result is null

Unchanged in this spec: Conditional expressions, choose macro, Membership and ranges, Arithmetic operators, Rounding, More aggregations, Null fill strategies, Window expressions, Ranking, Filtering inside expressions, Shape and position aggregations, Entropy, Row count expression, Several window keys and selector concatenation, Null-aware comparisons and closeness, More expression functions

frame-verbs modified +1

ADDED
Every n-th row

LazyFrame and DataFrame SHALL support gatherEvery(n, offset = 0), keeping rows offset, offset + n, offset + 2n, ... (Python's gather_every).

let df = newDataFrame:
  month: [1, 2, 3, 4, 5, 6]
echo df.gatherEvery(3, offset = 2)
Scenario: Offset past the end
  • WHEN gatherEvery(2, offset = 10) runs on 6 rows
  • THEN the result has no rows

Unchanged in this spec: Dropping and renaming columns, Row windows, Unique rows, Row index, Sorting by several keys, Sampling rows, Frame interpolation, Casting by data type, Several filter predicates, Group order parameter, Frame aggregations, Group-by shortcuts, Iterating over groups, Frame fillNan and select without a frame

missing-values modified +1

ADDED
Null literal

lit(nil) SHALL be a null literal (Python's pl.lit(None)), usable wherever an expression is, and fillNan(nil) SHALL turn NaN values into nulls.

let df = newDataFrame:
  x: [1.0, NaN, 3.0]
echo df.select(col.x.fillNan(nil).alias("x"), col.x.fillNan(nil).nullCount.alias("nulls"))
Scenario: Null column
  • WHEN select(lit(nil).alias("n")) runs with another column of 3 rows
  • THEN n holds 3 nulls

Unchanged in this spec: Nulls are read as Option, Plain reads refuse nulls, Inspecting nulls, Building columns with nulls, CSV null markers, Null expressions, Dropping rows with nulls, Interpolation, Filling nulls in whole frames

Tasks7 of 7 done

1. Implementation 7/7

  • 1.1nq_expr_lit_null, nq_expr_any_all
  • 1.2lit(nil), fillNan(nil), any, all (Expr and Series)
  • 1.3groupBy by column names
  • 1.4Frame gatherEvery
  • 1.5Eager GroupBy whose agg returns a DataFrame; callers drop .collect
  • 1.6Tests
  • 1.7The rest of the book's list goes to BACKLOG.md
Revisions2 revisions
r1 dd3c102 2026-11-01 any/all, lit(nil), groupBy by name, frame gatherEvery; eager agg returns a DataFrame

First version: proposal.md, specs/dataframe-api/spec.md, specs/expressions/spec.md, specs/frame-verbs/spec.md, specs/missing-values/spec.md, tasks.md

r2 22cc54c 2026-11-01 select("a", "b") with column names
proposal.md
§ What Changes
- `Expr.any(ignoreNulls)` and `Expr.all(ignoreNulls)` aggregations (also on Series). - `lit(nil)` null literal and `fillNan(nil)`. - `groupBy("a", "b")` and `select("a", "b")` with column names, on DataFrame and LazyFrame.LazyFrame (select from the explainer port). - `gatherEvery(n, offset)` on DataFrame and LazyFrame. - **BREAKING** On a DataFrame, `groupBy`, `groupByDynamic` and `rolling` return a `GroupBy` whose `agg` returns a DataFrame, as in Python (it returned a LazyFrame, so eager code needed `.collect`). LazyFrame keeps `LazyGroupBy`.
specs/dataframe-api/spec.md
§ Requirement: Expressions and lazy queries
### Requirement: Expressions and lazy queries The API SHALL provide `col`, `lit`, arithmetic, comparison and boolean operators on `Expr` (lifting Nim literals automatically), the aggregations sum, mean, min, max, count, first, last, nUnique and std, and `alias`. LazyFrame SHALL support select, withColumns, filter, groupBy/agg, sort, limit, explain and collect. `select` and `groupBy` SHALL take key expressions or column names (`select("a", "b")`, (`groupBy("species")`),`groupBy("species")`); and`groupBy` SHALL keep the groups in the order their keys first appear (Python's `maintain_order=True`, always on). On a DataFrame, `groupBy`, `groupByDynamic` and `rolling` followed by `agg` SHALL return a DataFrame, as in Python; on a LazyFrame they return a LazyFrame. DataFrame SHALL offer eager shortcuts for select, withColumns, filter and sort.
§ Scenario: Select by name
#### Scenario: Select by name - **WHEN** `df.select("c", "a")` runs - **THEN** the result has columns c and a, in that order

add-book-port-needs-0-5 Archived

openspec/changes/archive/2026-11-01-add-book-port-needs-0-5
  1. Proposal
  2. Specs
  3. Tasks
  4. Implement 6/6
  5. Archive
Proposal

Why

Porting the Nanuq Book chapters to 0.5 (about twelve chapters, against this PR) showed that nested display matches Python, and that list.eval, struct.field, explode, concatList, valueCounts and str.split work as written. It also found gaps that the port had to work around: Series had no struct/list namespaces and no HTML for notebooks, entropy and pl.len() were missing, sized integers (int32) did not build columns, and a few frame calls (interpolate, cast by data type, explode("a", "b"), pl.struct("a", "b")) had no Nanuq spelling.

It is the ninth change of the 0.5 release (#53).

What Changes

  • Series namespaces s.list, s.arr, s.struct, s.str, s.dt, s.cat, with every function of the Expr namespace of the same name.
  • toHtml(Series), the HTML Python shows for a Series (shape (n,)), so nimib's nbShow-style helpers work on a Series.
  • Expr.entropy(base = E, normalize = true).
  • len(), the row count expression (Python's pl.len()).
  • Columns from int8 ... uint64 and float32 values (top level, in lists and arrays, in newDataFrame), and toList for those types.
  • asStruct("a", "b") with column names.
  • interpolate() on DataFrame and LazyFrame.
  • cast({Float64: Float32}) and cast({col(SomeNumber): Float32}) on frames.
  • explode("a", "b") with several column names.

Capabilities

Modified Capabilities
  • series: namespaces, HTML, sized numbers.
  • expressions: entropy, row count.
  • struct-functions: structs from column names.
  • frame-verbs: frame interpolation, casting by data type.
  • list-functions: exploding several columns by name.

Differences from Polars

  • Python's Series namespaces are separate classes; in Nanuq s.list.len runs col(s.name).list.len on a one-column frame (a macro forwards the call), so every Expr namespace function works on a Series, but each call is one small query.
  • len() needs the parentheses: plain len is Nim's length proc.
  • cast keys are either all data types or all selectors in one call (a Nim table literal has one key type); Python mixes names, types and selectors in one dict.
  • Selectors are Nanuq's col(SomeNumber) (Python cs.numeric()).
  • uint64 values above high(int64) cannot build a column (they go through int).

Impact

  • Rust: nq_expr_entropy, nq_expr_len.
  • src/nanuq.nim: Series namespace types and dot-operator macros, toHtml(Series), entropy, len(), sized-number series and toList, asStruct(varargs[string]), frame interpolate, cast by type or selector, explode(a, b, ...).
  • Tests in tests/test_nested.nim.
Spec changesexpressions +2 · frame-verbs +2 · list-functions +1 · series +3 · struct-functions +1

expressions modified +2

ADDED
Entropy

Expr SHALL support entropy(base = E, normalize = true), an aggregation giving -sum(p * ln(p)) / ln(base), where p are the values (divided by their sum when normalize is true).

let df = newDataFrame:
  votes: [@[1, 1, 2], @[5]]
echo df.select(col.votes.list.agg(element().entropy).alias("entropy"))
Scenario: One value
  • WHEN the entropy of a single positive value is computed
  • THEN the result is 0.0
ADDED
Row count expression

len() with no argument SHALL be an expression counting rows, named len (Python's pl.len()); in a group-by it SHALL count the rows of each group.

let df = newDataFrame:
  team: ["a", "a", "b"]
echo df.groupBy("team").agg(len())
Scenario: Whole frame
  • WHEN df.select(len()) runs on 4 rows
  • THEN the result is one row with len = 4

Unchanged in this spec: Conditional expressions, choose macro, Membership and ranges, Arithmetic operators, Rounding, More aggregations, Null fill strategies, Window expressions, Ranking, Filtering inside expressions, Shape and position aggregations, Boolean aggregations, Several window keys and selector concatenation, Null-aware comparisons and closeness, More expression functions

frame-verbs modified +2

ADDED
Frame interpolation

DataFrame and LazyFrame SHALL support interpolate(how = InterpolationMethod.Linear), filling the nulls of every column as Expr.interpolate does (Python's DataFrame.interpolate).

let df = newDataFrame:
  day: [1, 2, 3]
  temp: [some(-2.0), none(float), some(1.0)]
echo df.interpolate
Scenario: Integer column
  • WHEN an integer column with a null between 1 and 5 is interpolated
  • THEN it becomes a float column holding 1.0, 3.0, 5.0
ADDED
Casting by data type

DataFrame and LazyFrame cast SHALL also take a mapping from data types, or from selectors, to data types: cast({Float64: Float32}) casts every Float64 column, cast({col(SomeNumber): Float32}) every column the selector picks; other columns are kept.

let df = newDataFrame:
  kg: [410.5, 380.0]
  cubs: [1, 0]
  bear: ["Ada", "Bo"]
echo df.cast({Float64: Float32}).schema
echo df.cast({col(SomeNumber): Float32}).schema
Scenario: Other columns kept
  • WHEN cast({Float64: Float32}) runs on a frame with an Int64 column
  • THEN the Int64 column is unchanged

Unchanged in this spec: Dropping and renaming columns, Row windows, Unique rows, Row index, Sorting by several keys, Sampling rows, Every n-th row, Several filter predicates, Group order parameter, Frame aggregations, Group-by shortcuts, Iterating over groups, Frame fillNan and select without a frame

list-functions modified +1

ADDED
Exploding several columns by name

DataFrame and LazyFrame explode SHALL also take several column names as separate arguments: explode("a", "b") is explode(["a", "b"]).

let df = newDataFrame:
  peak: ["Mont Blanc", "Monte Rosa"]
  huts: [@["Goûter", "Cosmiques"], @["Margherita", "Gnifetti"]]
  m: [@[3835, 3613], @[4554, 3647]]
echo df.explode("huts", "m")
Scenario: Lists of equal length
  • WHEN two list columns with lists of the same lengths are exploded together
  • THEN each row holds the matching elements of both

Unchanged in this spec: List aggregations and access, List transforms, Expressions on list elements, Explode and implode, Repeating values into lists, Seeds as plain ints

series modified +3

ADDED
Series namespaces

A Series SHALL have the namespaces list, arr, struct, str, dt and cat, each offering every function of the Expr namespace of the same name: s.ns.f(args) SHALL return the Series s.eval(col(s.name).ns.f(args)). The result keeps the name the expression gives (so s.struct.field("x") is named x).

let df = newDataFrame:
  p: [(x: 1, y: 2.0), (x: 3, y: 4.0)]
  l: [@[1, 2], @[3]]
echo df["p"].struct.field("x")
echo df["l"].list.len
Scenario: String function on a Series
  • WHEN s.str.toUppercase runs on a String Series holding "ab" and "c"
  • THEN the result holds "AB" and "C"
ADDED
Series as HTML

toHtml(s: Series, maxRows = 10) SHALL return the HTML that Python Polars shows for a Series in notebooks: the table of its one column, with the shape written (n,).

let s = series("kg", [410, 380])
echo s.toHtml
Scenario: Shape of a Series
  • WHEN a Series of 3 values is turned into HTML
  • THEN the HTML shows shape: (3,)
ADDED
Columns from sized numbers

series, newDataFrame, lists and arrays SHALL accept int8, int16, int32, int64, uint8, uint16, uint32, uint64 and float32 values (and Option of them), giving the Polars type of the same size, and toList SHALL read columns back as those types.

let df = newDataFrame:
  rgb: [[255'u8, 0, 0], [0'u8, 128, 255]]
  temp: [-1.5'f32, 2.0]
echo df
echo df.toList("temp", float32)
Scenario: Int32 column
  • WHEN series("a", [1'i32, 2]) is built
  • THEN its data type is Int32 and toList(int32) gives @[1'i32, 2]

Unchanged in this spec: Getting a Series, Reading a Series, Series operations, Series in frames, Binary functions on a Series

struct-functions modified +1

ADDED
Structs from column names

asStruct SHALL also take column names: asStruct("a", "b") is asStruct(col("a"), col("b")) (Python's pl.struct("a", "b")).

let df = newDataFrame:
  bear: ["Ada", "Bo"]
  kg: [410, 380]
echo df.select(asStruct("bear", "kg").alias("s"))
Scenario: Field names
  • WHEN asStruct("bear", "kg") is selected
  • THEN the struct has the fields bear and kg

Unchanged in this spec: Building structs, Struct fields, Unnesting frames, Value counts as an expression, Array functions

Tasks6 of 6 done

1. Implementation 6/6

  • 1.1nq_expr_entropy, nq_expr_len
  • 1.2Series namespaces (list, arr, struct, str, dt, cat) and toHtml(Series)
  • 1.3entropy, len()
  • 1.4Sized numbers in series, newDataFrame and toList
  • 1.5asStruct by name, frame interpolate, cast by data type or selector, explode by several names
  • 1.6Tests
Revisions1 revision
r1 d6f53fc 2026-11-01 0.5: book port needs (add-book-port-needs-0-5)

First version: proposal.md, specs/expressions/spec.md, specs/frame-verbs/spec.md, specs/list-functions/spec.md, specs/series/spec.md, specs/struct-functions/spec.md, tasks.md

add-book-port-needs-0-6 Archived

openspec/changes/archive/2026-11-01-add-book-port-needs-0-6
  1. Proposal
  2. Specs
  3. Tasks
  4. Implement 4/4
  5. Archive
Proposal

Why

Porting the chapters 0.5 already unlocks (O'Reilly ch5, ch9, ch13; Packt ch4, ch5; the user guide's aggregation pages), the 0.6 book thread found gaps the planning map could not see, because the names exist on expressions but not on frames or group-bys: frame aggregations (df.sum()), group-by shortcuts (group_by(...).max()), iterating over groups, df.fill_nan, and pl.select without a frame.

It is the tenth change of the 0.6 release.

What Changes

  • Frame aggregations on DataFrame and LazyFrame: sum, mean, median, product, min, max, std(ddof), var(ddof), quantile(q, interpolation), nUnique, count, nullCount(). Columns the aggregation does not apply to give null, as in Python.
  • Group-by shortcuts on GroupBy and LazyGroupBy: len(name), count, head(n), tail(n), first, last, sum, mean, median, min, max, nUnique, quantile(q), all (lists).
  • for key, part in df.groupBy(...): the groups in order of appearance.
  • fillNan(value | nil) on DataFrame and LazyFrame (float columns).
  • select(exprs...) without a frame (Python pl.select).
  • Round 2 from the book (O'Reilly ch9, Packt ch4, user guide data types):
  • operators on selectors (all() > 0 keeps each column's name, not "literal");
  • comparisons with a value on the left are mirrored (0 < col("a") is col("a") > 0, named a), as Python's reflected comparisons do;
  • over("a", "b") with several names; concatStr([all()], sep) with selectors;
  • describe prints datetimes and the mean of dates as Python's str(datetime) does (1986-09-04 00:00:00, no .000000).
  • xor came in add-frame-utilities-0-6.

Capabilities

Modified Capabilities
  • frame-verbs: frame aggregations, group-by shortcuts, group iteration, frame fillNan, select without a frame.
  • column-selectors: operators on selectors, mirrored comparisons.
  • expressions: over with several names, concatStr with selectors.
  • inspection: describe prints temporal values as Python.

Differences from Polars

  • Iterating a group-by yields the key as seq[string] (the key values as text, in by order), where Python yields a tuple of typed values.
  • Python's GroupBy.count() is deprecated in favour of len(); Nanuq keeps both, count naming its column count.
  • head, tail and iteration need a plain groupBy (not groupByDynamic or rolling), as in Python.
  • Series aggregations already exist since 0.4 and return a one-value Series (s.sum.item(float)); Python returns the scalar.
  • Nim has no reflected operators, so the mirroring is done by the overloads: arithmetic with a value on the left (1 + col("a")) is not mirrored and is named "literal", as in Python (__radd__ puts the literal first too).

Impact

  • src/rust/src/lib.rs, src/nanuq/ffi.nim: nq_lf_group_head (group head/tail).
  • src/nanuq.nim: the procs above, the rest in Nim over existing API.
  • New tests/test_bookneeds6.nim.
Spec changescolumn-selectors +1 · expressions +1 · frame-verbs +4 · inspection +1

column-selectors modified +1

ADDED
Operators on selectors

Arithmetic, comparison and logical operators SHALL accept a selector (all(), col("a", "b"), col(SomeNumber)) on either side, applying to each selected column and keeping its name; a comparison with a value on the left SHALL be mirrored (0 < x is x > 0), so the result keeps the column's name.

let df = newDataFrame(series("a", @[1, -1]), series("b", @[0, 2]))
echo df.select((all() > 0).name.suffix(" > 0"))
echo df.select(0 < col("a"))
TBD
Scenario: Selector times a number
  • WHEN all() * 2 is selected
  • THEN every column is doubled and keeps its name

Unchanged in this spec: Selecting by Nim type, Selecting by name, Excluding columns, Selectors as expressions, Output name suffix and prefix

expressions modified +1

ADDED
Several window keys and selector concatenation

over SHALL take several column names as separate arguments, and concatStr SHALL take selectors, expanding them to their columns.

let df = newDataFrame(series("c", @["x", "x", "y"]), series("b", @["p", "p", "q"]))
echo df.select(concatStr([all()], "-").alias("s"), lit(1).sum.over("c", "b").alias("n"))
TBD
Scenario: Two keys
  • WHEN col("v").sum.over("c", "b") is selected
  • THEN each row gets the sum of its (c, b) group

Unchanged in this spec: Conditional expressions, choose macro, Membership and ranges, Arithmetic operators, Rounding, More aggregations, Null fill strategies, Window expressions, Ranking, Filtering inside expressions, Shape and position aggregations, Boolean aggregations, Entropy, Row count expression, Null-aware comparisons and closeness, More expression functions

frame-verbs modified +4

ADDED
Frame aggregations

DataFrames and LazyFrames SHALL provide sum, mean, median, product, min, max, std(ddof = 1), var(ddof = 1), quantile(q, interpolation), nUnique, count and nullCount(), each giving one row with the aggregation of every column; columns of a type the aggregation does not apply to (strings for sum) SHALL give null.

let df = newDataFrame(series("bear", @["Ada", "Bo", "Cy"]), series("kg", @[410, 380, 455]))
echo df.sum
echo df.max
echo df.nullCount
TBD
Scenario: Lazy
  • WHEN df.lazy.mean.collect runs
  • THEN it equals df.mean
ADDED
Group-by shortcuts

GroupBy and LazyGroupBy SHALL provide len(name = "len"), count, head(n = 5), tail(n = 5), first, last, sum, mean, median, min, max, nUnique, quantile(q) and all, each aggregating every non-key column per group, with groups in order of appearance.

let df = newDataFrame(series("den", @["N", "S", "N"]), series("kg", @[410, 380, 455]))
echo df.groupBy("den").max
echo df.groupBy("den").len
echo df.groupBy("den").head(1)
TBD
Scenario: Not a plain group-by
  • WHEN head is called on a groupByDynamic
  • THEN InvalidOperationError is raised
ADDED
Iterating over groups

for key, part in df.groupBy(columns) SHALL yield each group's key values (as strings, in by order) and its rows, groups in order of appearance.

let df = newDataFrame(series("den", @["N", "S", "N"]), series("kg", @[410, 380, 455]))
for key, part in df.groupBy("den"):
  echo key, " ", part.height
TBD
Scenario: Several keys
  • WHEN a frame is grouped by two columns and iterated
  • THEN each key holds two values
ADDED
Frame fillNan and select without a frame

fillNan(value) on DataFrames and LazyFrames SHALL replace NaN in float columns (nil for null), and select(exprs...) SHALL evaluate expressions without a frame.

echo newDataFrame(series("x", @[1.0, NaN])).fillNan(0.0)
echo select(lit(1).alias("one"), intRange(0, 3).alias("i"))
TBD
Scenario: Other columns
  • WHEN a frame with an integer and a float column gets fillNan(0.0)
  • THEN the integer column is unchanged

Unchanged in this spec: Dropping and renaming columns, Row windows, Unique rows, Row index, Sorting by several keys, Sampling rows, Every n-th row, Frame interpolation, Casting by data type, Several filter predicates, Group order parameter

inspection modified +1

ADDED
Describe prints temporal values as Python

describe SHALL print Datetime statistics and the mean of a Date column as YYYY-MM-DD HH:MM:SS, with a fraction only when it is not zero.

let df = newDataFrame(series("d", @[date(1986, 9, 1), date(1986, 9, 7)]))
echo df.describe
TBD
Scenario: Date mean
  • WHEN the mean of 1986-09-01 and 1986-09-07 is described
  • THEN it reads 1986-09-04 00:00:00

Unchanged in this spec: glimpse, describe, Display config, Scoped display config, Table formatting options

Tasks4 of 4 done

1. Implementation 4/4

  • 1.1Crate: group head/tail
  • 1.2Frame aggregations, group-by shortcuts, group iteration, frame fillNan, select without a frame
  • 1.2bRound 2: operators on selectors, mirrored comparisons, over varargs, concatStr selectors, describe temporal strings
  • 1.3Tests in tests/test_bookneeds6.nim; nimble test and nimble specexamples pass; CHANGELOG
Revisions1 revision
r1 4ea5dad 2026-11-01 0.6: archive the 9 changes, fill spec example outputs, map_elements benchmark, dev log Designing Nanuq 0.6

First version: proposal.md, specs/column-selectors/spec.md, specs/expressions/spec.md, specs/frame-verbs/spec.md, specs/inspection/spec.md, tasks.md

add-categoricals Archived

openspec/changes/archive/2026-10-31-add-categoricals
  1. Proposal
  2. Specs
  3. Design
  4. Tasks
  5. Implement 8/8
  6. Archive
Proposal

Why

Many string columns hold a few distinct values: a team, a nationality, a medal, one of the five Monuments. Polars stores them as Categorical (categories found in the data) or Enum (a fixed, ordered set), which is smaller, faster to group and join, and for Enum sorts in a meaningful order. Nim already has the right tool for a fixed set of names, the enum, so Nanuq can map one to the other: the 0.3 explainer uses type Monument = enum to sort races in calendar order.

This change takes up the categoricals part of BACKLOG.md "More dtypes", following the dev log "Designing Nanuq 0.3" (categoricals moved into 0.3 by Pietro on 2026-10-31). It is the seventh change of the 0.3 release.

What Changes

  • Data types: DataTypeKind gains Categorical and Enum. Categorical is a DataType constant; Enum values carry their categories. $ gives Polars' names cat and enum.
  • Enum(["low", "high"]) builds an Enum dtype at run time (duplicates raise ValueError).
  • Nim enums are Polars Enums: dataType(Medal) is the Enum of $ of each value in order, so cast(Medal), series("m", [Gold, Silver]), the block form of newDataFrame, toList(df, "m", Medal) and df["m", i, Medal] work, Option-wrapped for nulls. Enum values can be compared with columns (col.medal == Gold) and used in isIn. Reading a value that is not in the Nim enum raises InvalidOperationError.
  • e.cat returns a CatNameSpace (a distinct Expr) with getCategories, lenBytes, lenChars, startsWith, endsWith and slice.
  • e.toPhysical gives the physical values (category indices, days, integers).
  • describe reports no min and max for Categorical and Enum columns, as Python does.
  • The Polars feature dtype-categorical (already compiled in) is used.

Not in this change: lexical ordering of Categoricals (Categorical("lexical")), local vs global category scopes (StringCache), cat.toLocal, appending to an Enum's categories.

Capabilities

New Capabilities
  • categoricals: Categorical and Enum columns, Nim enums, and the cat namespace.
Modified Capabilities
  • data-types: the two kinds, categories, and Nim enums in dataType.
  • native-bridge: NqCatOp joins the ordered enums.

Differences from Polars

Expected differences from Polars' Rust and Python APIs:

  • Nim enums have no Python or Rust counterpart as a dtype; Python accepts a Python enum.Enum class as pl.Enum(MyEnum), which is close. Nanuq uses $ of each value, so enums with string values (Flanders = "Ronde van Vlaanderen") name their categories freely.
  • Enum is a proc that returns a DataType (Python's pl.Enum([...]) class); comparing kinds needs DataTypeKind.Enum.
  • Categorical always uses Polars' global categories, as Python's default; there is no ordering argument.
  • Names follow Polars in camelCase: get_categories → getCategories, to_physical → toPhysical.

Impact

  • src/rust/src/lib.rs: the two dtype codes, Enum categories from NqDtypeSpec, nq_df_column_n_categories, nq_df_column_category, nq_series_cast and nq_expr_cat with NqCatOp.
  • src/nanuq/ffi.nim, src/nanuq.nim: the declarations, the DataType changes, enum overloads, CatNameSpace and toPhysical.
  • tests/test_categorical.nim (new); README; BACKLOG "More dtypes" drops categoricals.
Spec changescategoricals +3 · data-types ~2 · native-bridge ~1

categoricals modified +3

ADDED
Nim enums as Enum columns

A Nim enum type SHALL map to a Polars Enum whose categories are $ of its values in order. series, the block form of newDataFrame, cast(T), toList, df[c, i, T], comparisons and isIn SHALL accept the enum type or its values. Reading a value that is not in the enum SHALL raise InvalidOperationError.

type Monument = enum
  Sanremo = "Milano-Sanremo", Flanders = "Ronde van Vlaanderen",
  Roubaix = "Paris-Roubaix", Liege = "Liège-Bastogne-Liège", Lombardia = "Il Lombardia"
let wins = newDataFrame:
  race: ["Il Lombardia", "Milano-Sanremo", "Paris-Roubaix"]
  winner: ["Pogačar", "Pogačar", "van der Poel"]
let byRace = wins.withColumns(col.race.cast(Monument)).sort("race")
echo byRace
echo byRace.toList("race", Monument)
echo byRace.filter(col.race == Roubaix).toList("winner", string)
TBD
Scenario: Calendar order
  • WHEN a column of Monument names is cast to Monument and sorted
  • THEN the rows follow the order of the enum, not the alphabet
Scenario: Unknown value
  • WHEN a string that is not a category is cast to Monument strictly
  • THEN InvalidOperationError is raised
ADDED
Run-time Enum and Categorical

Enum(categories) SHALL build an Enum dtype from strings, raising ValueError on duplicates, and Categorical SHALL be the dtype of strings with categories found in the data. Both SHALL read back as strings.

let df = newDataFrame:
  team: ["UAE", "Visma", "UAE"]
  level: ["high", "low", "high"]
let t = df.select(col.team.cast(Categorical), col.level.cast(Enum(["low", "high"])))
echo t.schema
echo t.sort("level").toList("level", string)
TBD
Scenario: Categories of an Enum
  • WHEN dtype(df, c).categories is read for a column cast to Enum(["low", "high"])
  • THEN it is @["low", "high"]
ADDED
The cat namespace

e.cat SHALL give access to getCategories, lenBytes, lenChars, startsWith(prefix), endsWith(suffix) and slice(offset, length) on Categorical and Enum columns. e.toPhysical SHALL give the category indices.

type Medal = enum Gold, Silver, Bronze
let df = newDataFrame:
  medal: [Silver, Gold, Silver]
echo df.select(col.medal.cat.getCategories)
echo df.select(col.medal.toPhysical).toList("medal", int)
TBD
Scenario: All categories
  • WHEN cat.getCategories runs on an Enum column holding only Silver and Gold
  • THEN the result is Gold, Silver and Bronze

data-types modified ~2

MODIFIED
DataType values
The API SHALL provide a `DataType` value with a `kind` of type `DataTypeKind` (a pure enum, see `api-conventions`) covering Boolean, Int8, Int16, Int32, Int64, UInt8, UInt16, UInt32, UInt64, Float32, Float64, String, Null, Date, Datetime, Duration, Time, Categorical and Enum, plus `DataTypeKind.Other` carrying Polars' name for any other dtype. Datetime and Duration values SHALL carry a `timeUnit` (std/times' `TimeUnit`: `Nanoseconds`, `Microseconds` or `Milliseconds`), Datetime values a `timeZone` ("" when naive), and Enum values their `categories`. `dtype(df, col)` SHALL return a `DataType`. `dtype == T` with a Nim type SHALL compare with `dataType(T)`, except that `DateTime` and `Duration` SHALL match any time unit and zone. `$` SHALL print a data type as the Nanuq code that builds or names it: the constant (`Int64`), the constructor (`Enum(["low", "high"])`), or for temporal types the Nim type a column casts to (`Date`, `TimeOfDay`, `DateTime(Milliseconds, "Europe/Rome")`, `Duration(Microseconds)`). Table headers, `glimpse` and `toHtml` SHALL keep Polars' short names (`i64`). ```nim let df = newDataFrame(series("a", [1, 2])) echo df.dtype("a") # asPolars' Nanuqshort codename echo df.dtype("a") == Int64 echo df.dtype("a").kind let t = newDataFrame(series("at", [dateTime(2026, mJul, 4, zone = utc())], timeUnit = Milliseconds, timeZone = "Europe/Rome")) echo t.dtype("at"), " ", t.dtype("at").timeZone, " ", t.dtype("at") == DateTime ``` ```text Int64i64 true Int64 DateTime(Milliseconds,datetime[ms, "Europe/Rome")Europe/Rome] Europe/Rome true ``` Scenario: Column dtype - **WHEN** a DataFrame is built from a Nim `seq[int]` column `a` - **THEN** `df.dtype("a") == Int64` and `$df.dtype("a") == "Int64"`"i64"` Scenario: Unmodelled dtype - **WHEN** a column has a dtype Nanuq does not model - **THEN** its `kind` is `DataTypeKind.Other` and `$` returns Polars' name for it Scenario: Zoned datetime - **WHEN** a Datetime column has unit ms and zone Europe/Rome - **THEN** `$` gives `DateTime(Milliseconds,"datetime[ms, "Europe/Rome")`Europe/Rome]" and it equals `DateTime` Scenario: Enum categories - **WHEN** a column is cast to `Enum(["low", "high"])` - **THEN** `$` of its dtype gives `Enum(["low","enum" "high"])` and `categories` is `@["low", "high"]` Scenario: Tables keep short names - **WHEN** a frame with an Int64 column is printed or turned into HTML - **THEN** the column header shows `i64`
MODIFIED
Nim types map to DataType
`dataType(T)` SHALL map `int8` to `int64`, `uint8` to `uint64`, `float32`, `float64`, `bool` and `string` to their dtypes, `int` to `Int64` and `float` to `Float64`. `dataType(T, timeUnit = Microseconds, timeZone = "")` SHALL map `Date`, `DateTime`, std/times' `Duration` and `TimeOfDay` to Date, Datetime, Duration and Time. A Nim enum SHALL map to an Enum of `$` of its values. `seq[T]` SHALL map to a List, `array[N, T]` to an Array and objects and named tuples to a Struct of their fields, at any depth. Other types SHALL not compile. ```nim type Medal = enum Gold, Silver, Bronze echo dataType(int), " ", dataType(float32), " ", dataType(uint8), " ", dataType(string) echo dataType(Date), " ", dataType(DateTime), " ", dataType(Duration, Nanoseconds), " ", dataType(TimeOfDay) echo dataType(Medal), " ", dataType(Medal).categories echo dataType(seq[string]), " ", dataType(array[3, float]), " ", dataType(tuple[x: int, tags: seq[string]]).fields ``` ```text Int64i64 Float32f32 UInt8u8 Stringstr Datedate DateTime(Microseconds)datetime[μs] Duration(Nanoseconds)duration[ns] TimeOfDaytime Enum(["Gold", "Silver", "Bronze"]) @["Gold", "Silver", "Bronze"]TBD List(String) Array(Float64, 3) @[(name: "x", dtype: Int64), (name: "tags", dtype: List(String))] ``` Scenario: Platform int - **WHEN** `dataType(int)` is evaluated - **THEN** it equals `Int64`, the dtype `series` builds from `seq[int]` Scenario: Unsupported type - **WHEN** `col("a").cast(ref`col("a").cast(seq[int])` int)` is compiled - **THEN** compilation fails Scenario: Unsupported unit - **WHEN** `dataType(DateTime, Seconds)` is evaluated - **THEN** `ValueError` is raised Scenario: Nim enum - **WHEN** `dataType(Medal)` is evaluated for `enum Gold, Silver, Bronze` - **THEN** it equals `Enum(["Gold", "Silver", "Bronze"])` Scenario: Nested Nim types - **WHEN** `dataType(seq[seq[int]])` is evaluated - **THEN** it equals `List(List(Int64))`

Unchanged in this spec: DataType constants and predicates, Schemas, Casting, Full-range UInt64

native-bridge modified ~1

MODIFIED
Nim declarations mirror the C ABI
`src/nanuq/ffi.nim` SHALL declare every exported function with matching signatures, and the enums `NqBinOp`, `NqUnary`, `NqDtype`, `NqDtypeClass`, `NqJoinType`, `NqJoinValidation`, `NqMaintainOrderJoin`, `NqConcat`, `NqUniqueKeepStrategy`, `NqClosedInterval`, `NqQuantileMethod`, `NqFillNullStrategy`, `NqRoundMode`, `NqQuoteStyle`, `NqRankMethod`, `NqErrorKind`, `NqStrOp`, `NqTimeUnit`, `NqClosedWindow`, `NqDtOp`, `NqCatOp`, `NqParquetCompression` and `NqIpcCompression` SHALL keep the same order as in Rust. `NqDtype` SHALL also keep the order of `DataTypeKind`, and the option enums the order of their Nim API enums. Data types SHALL cross the ABI as an `NqDtypeSpec` struct (code, time unit, time zone, categories) with the same field order on both sides. Scenario: ABI change - **WHEN** a function is added or changed in `rust/src/lib.rs` - **THEN** `src/nanuq/ffi.nim` is updated in the same change

Unchanged in this spec: C ABI over Polars with opaque handles, Errors and panics never cross the boundary, Linking the static library, Columns cross in bulk, Library version check, Formatted cells, Polars version matches a py-polars release

Design

Design

Nim enums through strings

A Nim enum value crosses the ABI as its string ($v): a column is built as strings and cast to the Enum dtype (nq_series_cast), and read back as strings that are mapped to values with a table built from for v in T. Strings, not ordinals, are the stable identity: holey enums and enums with string values work, and a column read from a file maps to the Nim type as long as the names match.

bool is a Nim enum

bool is an enum in Nim, so the generic overloads use a private type class NimEnum = not bool and enum to keep bool on its own paths.

Categories in dtype specs

NqDtypeSpec already carries a categories array for this change; Rust builds FrozenCategories from it for Enum. Reading a column's categories uses two small calls (count, then one string each) to avoid inventing a string-list ABI.

Tasks8 of 8 done

1. Bridge 2/2

  • 1.1Add the Categorical and Enum dtype codes and Enum categories in NqDtypeSpec
  • 1.2Add nq_df_column_n_categories, nq_df_column_category, nq_series_cast and nq_expr_cat; mirror them in ffi.nim

2. Nim API 4/4

  • 2.1Add the kinds, categories, Categorical and Enum(...); Nim enums in dataType
  • 2.2Accept Nim enums in series, block newDataFrame, toList, [], comparisons and isIn
  • 2.3Add CatNameSpace, toPhysical; no min/max in describe
  • 2.4Write tests/test_categorical.nim; add it to nanuq.nimble and .gitignore

3. Docs and integration 2/2

  • 3.1README lists categoricals; nimble test and nimble specexamples pass
  • 3.2Archive the change: update BACKLOG "More dtypes", add CHANGELOG lines
Revisions1 revision
r1 057c2f9 2026-10-31 Add categoricals: Categorical, Enum, Nim enums and the cat namespace

First version: design.md, proposal.md, specs/categoricals/spec.md, specs/data-types/spec.md, specs/native-bridge/spec.md, tasks.md

add-cloud-storage Archived

openspec/changes/archive/2026-11-01-add-cloud-storage
  1. Proposal
  2. Specs
  3. Tasks
  4. Implement 4/4
  5. Archive
Proposal

Why

Polars reads and writes object stores (S3, Google Cloud Storage, Azure, plain HTTPS) by URI, and the book and explainers use public datasets that live there. The cost thread ("Weigh adding cloud storage to 0.6", https://claude.ai/artifact/F1haAENdb2wY6NGzJpQfab) measured the Polars features cloud, aws, gcp, azure and http at about +2% of the library (object_store, tokio, reqwest and rustls are already compiled in for streaming), and found HTTPS reads already working. Pietro asked for it in 0.6, with the databases and Excel (2026-11-01).

It is the fourteenth change of the 0.6 release.

What Changes

  • Polars features cloud, aws, gcp, azure, http.
  • storageOptions: openArray[(string, string)] (Python's storage_options) on scanCsv, readCsv, scanParquet, readParquet, scanIpc, readIpc, scanNdjson, readNdjson, on the four sinks (also partitioned), and on writeCsv, writeParquet, writeIpc, writeNdjson. Empty options leave credentials to the environment (AWS_*, GOOGLE_*, AZURE_* variables, config files), as in Polars.
  • Writes to a cloud URI run through a sink (the eager writers write local files).
  • isCloudPath(path).

Capabilities

New Capabilities
  • cloud-storage: cloud URIs, storage options, writing to object stores.

Differences from Polars

| Nanuq | Python | Rust (py-2.1.0) | |---|---|---| | storageOptions = {"aws_region": "eu-west-1"} | storage_options={"aws_region": ...} | CloudOptions::from_untyped_config | | writeParquet("s3://...") | write_parquet("s3://...") | sink with cloud_options | | isCloudPath | (internal _is_supported_cloud) | CloudScheme::from_path |

  • No credential_provider (Python's callable that refreshes credentials) and no retries argument; retries can go in storageOptions (max_retries).
  • readExcel, readJson and readDatabase stay local.

Impact

  • src/rust/Cargo.toml features; src/rust/src/lib.rs: nq_cloud_options_new, nq_cloud_options_free, a cloud_options argument on the four scans and in NqSinkOptions.
  • src/nanuq.nim, src/nanuq/ffi.nim; new tests/test_cloud.nim (a local HTTP server, and a local S3 with moto when moto_server is installed; CI installs it).
  • docs/coverage/polars.json: the cloud row becomes covered.
Spec changescloud-storage +3

cloud-storage modified +3

ADDED
Cloud URIs

Every scan* and read* function for CSV, Parquet, IPC and NDJSON files SHALL accept a cloud URI (s3://, gs://, az://, abfss://, hf://, http://, https://) in place of a local path, globs included. isCloudPath(path) SHALL tell such URIs from local paths.

echo isCloudPath("s3://polar-bears/census.parquet")
echo isCloudPath("https://example.org/bears.csv")
echo isCloudPath("data/bears.csv")
TBD
Scenario: HTTP
  • WHEN readParquet("http://127.0.0.1:<port>/bears.parquet") runs against a local
  • HTTP server
  • THEN the frame equals the file's
ADDED
Storage options

The cloud-capable reads, scans, writes and sinks SHALL take storageOptions, key/value pairs as Python's storage_options (aws_region, aws_endpoint_url, google_service_account, azure_storage_account_name, ...). Without them, credentials SHALL come from the environment as in Polars. Unknown keys SHALL be ignored, as in Polars; a failed request SHALL raise IOError.

let opts = {"aws_region": "eu-west-1", "aws_skip_signature": "true"}
let lf = scanParquet("s3://polar-bears/census.parquet", storageOptions = opts)
echo lf is LazyFrame
TBD
Scenario: Missing bucket
  • WHEN readParquet("s3://no-such-bucket/x.parquet", storageOptions = opts) runs
  • against a local S3
  • THEN IOError is raised
ADDED
Writing to object stores

writeParquet, writeCsv, writeIpc, writeNdjson and the sinks (also partitioned) SHALL write to a cloud URI, with storageOptions; the eager writes SHALL go through a streaming sink.

let df = newDataFrame(series("bear", @["Ada", "Bo"]), series("kg", @[410, 380]))
let opts = {"aws_endpoint_url": "http://127.0.0.1:9000", "aws_allow_http": "true"}
let sink = df.lazy.sinkParquet("s3://polar-bears/out.parquet", lazy = true,
                               storageOptions = opts)
echo sink is LazyFrame  # collect(sink) writes the file
TBD
Scenario: S3 round trip
  • WHEN a frame is written to s3://nanuq/bears.parquet on a local S3 (moto) and read
  • back with the same storageOptions
  • THEN the frames are equal
Tasks4 of 4 done

1. Implementation 4/4

  • 1.1Polars features cloud, aws, gcp, azure, http
  • 1.2storageOptions on scans, reads, sinks and writes; cloud writes through sinks
  • 1.3tests/test_cloud.nim (HTTP server, moto S3), CI installs moto
  • 1.4CHANGELOG, coverage row
Revisions1 revision
r1 889d13f 2026-11-01 Add cloud storage and 30 functions from the Polars coverage map

First version: proposal.md, specs/cloud-storage/spec.md, tasks.md

add-column-access-and-nulls Archived

created 2026-10-27 · openspec/changes/archive/2026-10-27-add-column-access-and-nulls
  1. Proposal
  2. Specs
  3. Design
  4. Tasks
  5. Implement 12/12
  6. Archive
Proposal

Why

Getting data out of Nanuq is slow and incomplete. toSeq makes one FFI call per cell, and nothing can represent a missing value: reading a null raises, and Nim data with gaps can't be built at all. Most of the backlog is blocked on this. That includes penguins (it has NAs), the ggplotnim module, Datamancer and Arraymancer interop, and nimib tables. Polars also works with nulls everywhere, so the API should expose them before outside users arrive.

This change takes up two BACKLOG.md entries: "Column access as Nim seqs without per-cell calls" (API) and the nulls half of "Nulls and more dtypes" (API). Dates and datetimes stay in the backlog.

What Changes

  • Whole columns cross the boundary in one FFI call (two for strings), with a validity mask, for int64, float64, bool and string.
  • toSeq(df, col, T) uses the bulk path. It raises NanuqError if the column has nulls; today it raises too, but only when it reaches the first null.
  • New toSeq(df, col, Option[T]) returns seq[Option[T]], with none for nulls.
  • New null-aware single cells: df[col, row, Option[T]].
  • New nullCount(df, col) and hasNulls(df, col).
  • New series(name, openArray[Option[T]]) builds columns with nulls from Nim.
  • readCsv gains nullValues (e.g. @["NA"]), so files like penguins load with real nulls instead of the string "NA".
  • New expressions isNull, isNotNull and fillNull(value), and dropNulls on LazyFrame and DataFrame (all columns, or a subset).
  • Reading a column as float accepts integer columns, and reading it as string accepts any dtype. Reading as int stays strict, so floats are not truncated.

Capabilities

New Capabilities
  • missing-values: how nulls are represented, built, read, tested, filled and dropped in the Nim API.
Modified Capabilities
  • dataframe-api: the "Building and reading data" requirement now covers bulk column reads, the dtype rules for reading, and readCsv null markers.
  • native-bridge: a new requirement that columns cross the C ABI in bulk with a validity mask, not cell by cell.

Differences from Polars

Expected differences from Polars' Rust and Python APIs:

  • Strict reads. Python's Series.to_list() returns None for nulls, and to_numpy() turns an integer column with nulls into floats with NaN. Nim's static types can't hold None in a seq[int], so toSeq(df, col, T) raises on nulls, and Option[T] is the explicit opt-in. This is closest to Rust's cont_slice(), which errors when there are nulls.
  • No NaN for nulls. Like Polars, Nanuq keeps NaN (a float value) and null (missing) distinct. It never converts one into the other the way to_numpy() does.
  • Per-column counts. nullCount(df, col) and hasNulls(df, col) take a column name. Python's DataFrame.null_count() returns a one-row DataFrame with a count per column, and isn't added here.
  • Cell access. Polars has no cell-level null test; Python's df[row, col] returns None. Nanuq's equivalent is df[col, row, Option[T]].
  • Names follow Polars in camelCase: is_null → isNull, is_not_null → isNotNull, fill_null → fillNull, drop_nulls → dropNulls, null_count → nullCount, has_nulls → hasNulls, null_values → nullValues.

Impact

  • rust/src/lib.rs: new column export functions (nq_df_column_{i64,f64,bool}, a two-step string export), nq_series_new_* variants with validity, nq_df_null_count, nq_df_cell_is_null, nq_df_read_csv with null values, nq_expr_fill_null, nq_lf_drop_nulls, and IsNull / IsNotNull appended to NqUnary. Adding the enum values at the end keeps the existing order. The Rust library is rebuilt, so the first CI run takes about 10 min.
  • src/nanuq/ffi.nim and src/nanuq.nim: the matching declarations and API. Imports std/options.
  • tests/: new tests for nulls and bulk reads, plus a small CSV fixture with NA values.
  • The per-cell getters stay and keep their behavior. Nothing that works today breaks, except that toSeq on a column with nulls now fails up front.
Spec changesdataframe-api ~1 · missing-values +7 · native-bridge +1

dataframe-api modified ~1

MODIFIED
Building and reading data
The API SHALL build a DataFrame from Nim arrays of int, float, bool and string (`series`, `newDataFrame`), read and write CSV with a header row, and expose `shape`, `columns`, `dtype`, `head`, `$` (Polars' table format), single cells and whole columnscolumns. (`toList`). ```nim letReading as `float` SHALL accept dfany =integer newDataFrame(series("bear",or ["Nanuq",float "Ursa"]),column; series("weight",reading [410.5,as 380.0])) echo`string` dfSHALL echoaccept df.shape,any "column, ",formatting df.columns,values "as ",Polars df["bear",does; 0,reading string],as "`int` ",SHALL df.toList("weight",accept float)only ``` ```text shape:integer (2,columns; 2) ┌───────┬────────┐ │reading bear ┆as weight`bool` │ │SHALL --- ┆accept --- │ │only str ┆boolean f64 │ ╞═══════╪════════╡ │columns. NanuqA ┆dtype 410.5 │ │that Ursa ┆ 380.0 │does └───────┴────────┘ (2,not 2)match @["bear",SHALL "weight"]raise Nanuq @[410.5, 380.0] ````NanuqError`. Scenario: Columns of different lengths - **WHEN** `newDataFrame` gets series of different lengths - **THEN** `PolarsError``NanuqError` is raised Scenario: Integers read as floats - **WHEN** an i64 column holding 1, 2 is Noread with `toSeq(df, "a", float)` - **THEN** the result is `@[1.0, 2.0]` Scenario: Floats are not truncated to int - **WHEN** an f64 column is clashread with `toSeq(df, "a", int)` - **THEN** `NanuqError` is raised Scenario: sequtilsBool column - **WHEN** a modulebool importscolumn `nanuq`is andread `std/[os,with sequtils]``toSeq(df, and"d", calls `toSeq(walkFiles("*.csv"))`bool)` - **THEN** itthe compilesresult and returnsholds the matchingcolumn's pathsvalues

Unchanged in this spec: Automatic memory management, Reading columns by type, Expressions and lazy queries, HTML tables, Block syntax for building a DataFrame, Column shorthand, True division, Errors as PolarsError

missing-values modified +7

Purpose: How Nanuq represents missing values (Polars nulls) in its Nim API: building data with gaps, reading it back, and testing, filling and dropping nulls in queries.

ADDED
Nulls are read as Option

Reading a column or a cell with the type Option[T] SHALL return none(T) for each null and some(value) otherwise, for T in int, float, bool and string.

Scenario: Column with gaps
  • WHEN a column holds 1, null, 3 and is read with toSeq(df, "a", Option[int])
  • THEN the result is @[some(1), none(int), some(3)]
Scenario: Single cell
  • WHEN the null cell is read with df["a", 1, Option[int]]
  • THEN the result is none(int)
ADDED
Plain reads refuse nulls

Reading a column or a cell with a plain type T SHALL raise NanuqError if the values read include a null, and the message SHALL name the column.

Scenario: Column with a null read as int
  • WHEN a column with one null is read with toSeq(df, "a", int)
  • THEN NanuqError is raised before any value is returned, naming column "a"
ADDED
Inspecting nulls

The API SHALL report the number of nulls in a column and whether it has any.

Scenario: Counting
  • WHEN a column of 3 values has 1 null
  • THEN nullCount(df, "a") is 1 and hasNulls(df, "a") is true
Scenario: No nulls
  • WHEN a column has no nulls
  • THEN nullCount is 0 and hasNulls is false
ADDED
Building columns with nulls

series SHALL accept openArray[Option[T]] for int, float, bool and string, storing none as null with the same dtype as the plain version.

Scenario: Round trip
  • WHEN a DataFrame is built from series("a", [some(1), none(int)])
  • THEN dtype(df, "a") is "i64", nullCount(df, "a") is 1, and reading it as Option[int] gives back the input
ADDED
CSV null markers

readCsv SHALL accept a list of strings to read as null. Without it, behavior is unchanged: only empty fields are null.

Scenario: NA marker
  • WHEN a CSV file with "NA" in a numeric column is read with nullValues = @["NA"]
  • THEN that column is numeric and the "NA" fields are null
ADDED
Null expressions

The API SHALL provide isNull and isNotNull on expressions (giving booleans), and fillNull replacing nulls with a literal or an expression.

Scenario: Filter out nulls
  • WHEN a LazyFrame is filtered with col("a").isNotNull and collected
  • THEN the result has no nulls in column "a"
Scenario: Fill nulls
  • WHEN withColumns(col("a").fillNull(0)) is applied to a column 1, null, 3
  • THEN column "a" becomes 1, 0, 3
ADDED
Dropping rows with nulls

LazyFrame and DataFrame SHALL provide dropNulls, removing rows with a null in any column, or only in the named columns when a subset is given.

Scenario: Subset
  • WHEN dropNulls(["a"]) is applied to rows where "a" has one null and "b" another, in different rows
  • THEN only the row with the null in "a" is removed

Unchanged in this spec: Interpolation, Null literal, Filling nulls in whole frames

native-bridge modified +1

ADDED
Columns cross in bulk

Reading a whole column into Nim SHALL take a constant number of FFI calls, independent of the number of rows, and SHALL transfer a validity mask alongside the values so nulls are not lost or replaced by placeholder values.

Scenario: Large column
  • WHEN a 1,000,000-row float column is read into a Nim seq
  • THEN at most two FFI calls are made for that column
Scenario: Validity
  • WHEN a column with nulls crosses the boundary
  • THEN Nim receives, for every row, whether the value is valid

Unchanged in this spec: C ABI over Polars with opaque handles, Errors and panics never cross the boundary, Nim declarations mirror the C ABI, Linking the static library, Library version check, Formatted cells, Polars version matches a py-polars release

Design

Design

Context

Today toSeq loops over rows and calls nq_df_get_{i64,f64,str} once per cell. Each call looks up the column, builds an AnyValue and checks the type. A null makes extract fail, so the call returns an error. Series can only be built from plain arrays. nq_df_read_csv uses CsvReadOptions::default() with a header and no null markers. NqUnary is a #[repr(C)] enum mirrored in ffi.nim.

Goals / Non-Goals

Goals:

  • One FFI call per numeric or bool column and two per string column, whatever the height.
  • No null is ever silently turned into a value (0, NaN, "").
  • Keep the ABI style: borrow arguments, caller frees, errors through nq_last_error.

Non-Goals:

  • Zero-copy. Values are still copied into Nim memory. Arrow C Data Interface sharing stays in the backlog.
  • Dates, datetimes and other dtypes (still in the backlog).
  • A null-aware Series read API. Reads go through DataFrame columns only, as today.

Decisions

Caller-allocated buffers for fixed-width columns

nq_df_column_i64(df, name, values: *mut i64, valid: *mut bool, len) -> bool (and _f64, _bool). Nim allocates height slots in seq[T] and seq[bool] and passes pointers. Rust casts the column to the target dtype (see the dtype rules below), checks len == height, and fills both buffers in one pass over chunked_array.iter() (one Option<T> per row).

  • Why: Nim owns the memory, so there is no extra free function and no double-ownership risk. Filling is a single tight loop.
  • Alternative: Rust allocates and returns a pointer plus a free function. That needs one more call and one more type to free, with no gain.
  • Alternative: return values only, and signal nulls through a separate null_count / is_null call. That is not constant-call when there are nulls.
Strings in two calls

nq_df_column_str_size(df, name) -> i64 returns the total UTF-8 byte length (-1 on error). nq_df_column_str(df, name, data: *mut u8, data_len, offsets: *mut u64, valid: *mut bool, len) -> bool writes the concatenated bytes and len + 1 offsets, which is Arrow's string layout. Nim then slices data into strings. Nulls have equal consecutive offsets and valid = false.

  • Why: there is no per-string allocation across the boundary, and the layout matches Arrow, so moving to zero-copy later stays close.
  • Alternative: return an array of C strings to free one by one. That costs N allocations and frees.
Dtype rules on the Rust side

For float, Rust casts any numeric dtype to Float64. For string, it casts any dtype to String. For int, it accepts only integer dtypes and casts them to Int64. For bool, it requires Boolean. Anything else is an error naming the column and its dtype. Casting in Rust reuses Polars' formatting and is a single vectorised operation.

Strict vs Option in Nim

toSeq(df, col, T) calls the bulk function and raises NanuqError if any valid[i] is false: "column 'a' has N nulls; read it as Option[T] or fill them first". toSeq(df, col, Option[T]) builds some/none from the mask. Both share one internal readColumn per type returning (values, valid). The single-cell df[col, row, Option[T]] uses a new nq_df_cell_is_null(df, name, row, out: *mut bool) together with the existing getters, because a single cell doesn't need the bulk path. That function is internal: the Nim API has no cell-level isNull (see proposal, "Differences from Polars"). nullCount uses nq_df_null_count, and hasNulls is nullCount > 0.

  • Why strict by default: a null that silently becomes 0 is the bug this change is meant to prevent. Users who want defaults write fillNull in the query, or map over the Option seq.
Building with nulls

nq_series_new_{i64,f64,bool,str}_opt(name, data, valid, len). Rust builds Vec<Option<T>> and Series::new. On the Nim side, series(name, openArray[Option[T]]) fills a values buffer (default value where none) and a mask.

Expressions and dropNulls
  • Append IsNull and IsNotNull to the end of NqUnary, so existing values keep their numbers, and mirror them in ffi.nim.
  • nq_expr_fill_null(e, value: *const Expr) -> *mut Expr. In Nim, fillNull takes an Expr or a literal through lit, like the binary operators.
  • nq_lf_drop_nulls(lf, names: *const *const c_char, len) -> *mut LazyFrame, where len == 0 means all columns. It maps to LazyFrame::drop_nulls(None | Some(selector)). The DataFrame shortcut goes through lazy/collect, like the other eager methods.
CSV null markers

nq_df_read_csv gains null_values: *const *const c_char, len. With len == 0 it behaves as today. Otherwise it sets CsvParseOptions::with_null_values( Some(NullValues::AllColumns(..))). In Nim, readCsv(path, nullValues: openArray[string] = []) keeps today's calls source-compatible. The old one-argument C function is replaced, which is fine because the Nim wrapper is the only caller.

Risks / Trade-offs

  • [Polars 0.55 API names, such as the drop_nulls selector type and the null-values option path, may differ from the above] → Check against the 0.55 docs while implementing; the behavior in the specs doesn't depend on them.
  • [Changing toSeq to fail up front on nulls] → It already failed at the first null; only the timing and message change. Note it in the CHANGELOG.
  • [Rust rebuild in CI costs about 10 min once] → Expected for any ABI change; the cache covers later runs.
  • [The ffi.nim and lib.rs signatures drift apart] → Every new function gets a test that calls it through the Nim API.
Tasks12 of 12 done

1. Bulk column reads 3/3

  • 1.1Add nq_df_column_{i64,f64,bool} with caller-allocated values and validity buffers and the dtype rules from design.md, and mirror them in ffi.nim; verify cargo build --release passes
  • 1.2Add nq_df_column_str_size and nq_df_column_str (bytes, offsets, validity), and mirror them in ffi.nim; verify cargo build --release passes
  • 1.3Reimplement toSeq(df, col, T) for int, float, bool and string on the bulk path, raising NanuqError naming the column when there are nulls; verify the existing tests still pass and new tests cover int→float, float→int error, bool and any→string

2. Reading and inspecting nulls 3/3

  • 2.1Add toSeq(df, col, Option[T]) from the validity mask; verify with a test on a column 1, null, 3
  • 2.2Add nq_df_null_count and nq_df_cell_is_null, plus nullCount, hasNulls and df[col, row, Option[T]] in Nim; verify with tests
  • 2.3Add nq_series_new_*_opt and series(name, openArray[Option[T]]) for the four types; verify a round-trip test (build with nulls, read back as Option, dtype unchanged)

3. Nulls in queries and IO 4/4

  • 3.1Append IsNull and IsNotNull to NqUnary in Rust and ffi.nim, and add isNull / isNotNull on Expr; verify with a filter test
  • 3.2Add nq_expr_fill_null and fillNull (Expr or literal); verify with a test
  • 3.3Add nq_lf_drop_nulls and dropNulls on LazyFrame and DataFrame (all columns or a subset); verify with tests for both forms
  • 3.4Add null markers to nq_df_read_csv and readCsv(path, nullValues = []); add tests/data/with_na.csv with "NA" fields; verify that a numeric column with NA reads as f64/i64 with nulls, and that calling without nullValues behaves as before

4. Docs and integration 2/2

  • 4.1Update README "What is there" and the toSeq doc comments for Option reads, nullCount, hasNulls, fillNull, dropNulls and nullValues; verify nimble test and nimble example pass
  • 4.2Check that CI is green on the PR, including the one-off Rust rebuild

Workflow follow-up 0/0

    Revisions1 revision
    r1 bb8c4a6 2026-10-27 Archive add-column-access-and-nulls

    First version: .openspec.yaml, design.md, proposal.md, specs/dataframe-api/spec.md, specs/missing-values/spec.md, specs/native-bridge/spec.md, tasks.md

    add-column-selectors Archived

    created 2026-10-31 · openspec/changes/archive/2026-10-31-add-column-selectors
    1. Proposal
    2. Specs
    3. Design
    4. Tasks
    5. Implement 10/10
    6. Archive
    Proposal

    Why

    Real tables have many columns, and many queries treat a group of them the same way: the mean of every numeric column, every column except the ID, all the weight_* columns. Nanuq can only name columns one at a time today. Polars solves this with selectors, and the 0.2 explainer post needs them (the census scene "mean of every numeric column per station, except the cub count").

    This is the fifth change of the 0.2 release (see the Polars coverage map, area "Column selection"). It has no BACKLOG.md entry. Pietro made the API choice on 2026-10-31 in the doc "Nanuq 0.2: API choices the explainer forces": select by Nim type through col, with all(), exclude, and regex. No set operators in 0.2. Add name.suffix/name.prefix, because applying two aggregations to one selector otherwise gives duplicate names.

    What Changes

    • By Nim type: col(SomeNumber) selects every numeric column. Each Nim typeclass maps onto a Polars dtype category:
    • SomeInteger is Integer
    • SomeSignedInt and SomeUnsignedInt are the signed and unsigned integers
    • SomeFloat is Float

    A concrete type selects exactly that dtype (col(int) is i64, col(string) is str), and several types select their union: col(float, int). A type with no dtype, such as col(seq[int]), does not compile.

    • By name: col("a", "b") selects several columns, all() selects every column, and col("^weight_.*$") selects by regex, as in Polars.
    • exclude: col(SomeNumber).exclude("cubs") and all().exclude("id", "name").
    • Selectors are expressions: a Selector converts to Expr, so col(SomeNumber).mean, select(all().exclude("id")) and agg(col(SomeFloat).max) all work, and Polars expands the expression to one column per selected column.
    • Output names: e.name.suffix("_mean") and e.name.prefix("avg_"). They rename every column an expression produces, for example agg(col(SomeNumber).mean.name.suffix("_mean"), col(SomeNumber).max.name.suffix("_max")).
    • The ABI stays 0.2.0-dev, and no Polars features are added.

    Capabilities

    New Capabilities
    • column-selectors: selecting columns by Nim type, by several names, by regex or all of them, with exclude, and renaming the outputs with name.suffix/name.prefix.
    Modified Capabilities
    • native-bridge: the dtype category enum joins the ones that keep the same order in Rust and ffi.nim.

    Differences from Polars

    Expected differences from Polars' Rust and Python APIs:

    • Nim types instead of a selectors module. Python's cs.numeric(), cs.integer(), cs.float(), cs.string() and cs.by_dtype(pl.Int64) become col(SomeNumber), col(SomeInteger), col(SomeFloat), col(string) and col(int). This is the same idea as cast(int32). There is no cs namespace.
    • No set operators. Python's cs.numeric() - cs.by_name("year") and |, &, ^, ~ are left out, because on expressions - already means subtraction. exclude covers the common case.
    • exclude takes names only. Excluding by dtype (exclude(pl.Int64)) is left for later.
    • col with one name stays an Expr. Several names, types, or all() give a Selector. A Selector converts to Expr automatically, so it works wherever an expression does.
    • Not in this change: cs.starts_with, ends_with, contains, by_index, first/last, temporal, categorical, name.map, name.keep and name.to_uppercase. Regex covers the name patterns.
    • Names follow Polars in camelCase: name.suffix and name.prefix are spelled as in Polars.

    Impact

    • src/rust/src/lib.rs:
    • nq_expr_selector builds a Polars Selector from names, dtype codes, a dtype category, a wildcard flag and excluded names, and returns it as an Expr.
    • nq_expr_name_affix adds a suffix or prefix.
    • New #[repr(C)] enum NqDtypeClass.
    • src/nanuq/ffi.nim and src/nanuq.nim: the Selector value type with its converter to Expr, col overloads for types, typeclasses and several names, all, exclude, name.suffix and name.prefix.
    • tests/test_selectors.nim: each selector form, exclude, regex, use in select, withColumns and agg, and suffixes that avoid duplicate names.
    • README.md lists the selectors.
    Spec changescolumn-selectors +5 · native-bridge ~1

    column-selectors modified +5

    ADDED
    Selecting by Nim type

    col SHALL accept Nim types and typeclasses and return a Selector.

    • SomeNumber, SomeInteger, SomeSignedInt, SomeUnsignedInt and SomeFloat SHALL select the matching Polars dtype category.
    • A concrete type SHALL select the dtype dataType gives it.
    • Several types SHALL select their union.
    • A type without a dtype SHALL not compile.
    Scenario: Numeric columns
    • WHEN select(col(SomeNumber)) runs on columns station (str), bears (i64) and weight (f64)
    • THEN the result has columns bears and weight
    Scenario: Exact types
    • WHEN select(col(float, string)) runs on the same frame
    • THEN the result has columns station and weight
    Scenario: Not a column type
    • WHEN col(seq[int]) is compiled
    • THEN compilation fails
    ADDED
    Selecting by name

    col(a, b, ...) with two or more names SHALL return a Selector for those columns in that order, and all() SHALL select every column. col with one name SHALL keep returning an Expr, and a name that starts with ^ and ends with $ SHALL be a regex.

    Scenario: Regex
    • WHEN select(col("^weight_.*$")) runs on columns weight_kg, weight_lb and name
    • THEN the result has columns weight_kg and weight_lb
    ADDED
    Excluding columns

    Selector SHALL support exclude(names: varargs[string]), which removes the named columns from the selection.

    Scenario: All but one
    • WHEN select(all().exclude("id")) runs on columns id, a and b
    • THEN the result has columns a and b
    ADDED
    Selectors as expressions

    A Selector SHALL convert to Expr automatically. An expression built from it SHALL apply to every selected column and keep each column's name.

    Scenario: Mean per group of every numeric column but one
    • WHEN a frame is grouped by station and aggregated with col(SomeNumber).exclude("cubs").mean
    • THEN the result has station and one mean column per remaining numeric column, with the original names
    ADDED
    Output name suffix and prefix

    Expr SHALL support name.suffix(s) and name.prefix(s), which append or prepend s to the name of every column the expression produces.

    Scenario: Two aggregations of one selector
    • WHEN agg(col(SomeFloat).mean.name.suffix("_mean"), col(SomeFloat).max.name.suffix("_max")) runs on float columns a and b
    • THEN the result has columns a_mean, b_mean, a_max and b_max

    Unchanged in this spec: Operators on selectors

    native-bridge modified ~1

    MODIFIED
    Nim declarations mirror the C ABI
    `src/nanuq/ffi.nim` SHALL declare every exported function with matching signatures, and the enums `NqBinOp`, `NqUnary`, `NqDtype`, `NqDtypeClass`, `NqJoinType`, `NqJoinValidation`, `NqMaintainOrderJoin`, `NqConcat`, `NqUniqueKeepStrategy`, `NqClosedInterval`, `NqQuantileMethod`, `NqFillNullStrategy`,`NqFillNullStrategy` `NqRoundMode`, `NqQuoteStyle`,and `NqRankMethod`, `NqErrorKind`, `NqStrOp`, `NqTimeUnit`, `NqClosedWindow`, `NqDtOp`, `NqCatOp`,`NqRoundMode` `NqParquetCompression` and `NqIpcCompression` SHALL keep the same order as in Rust. `NqDtype` SHALL also keep the order of `DataTypeKind`, and the option enums the order of their Nim API enums. Data types SHALL cross the ABI as an `NqDtypeSpec` struct (code, time unit, time zone, categories) with the same field order on both sides. Scenario: ABI change - **WHEN** a function is added or changed in `rust/src/lib.rs` - **THEN** `src/nanuq/ffi.nim` is updated in the same change

    Unchanged in this spec: C ABI over Polars with opaque handles, Errors and panics never cross the boundary, Linking the static library, Columns cross in bulk, Library version check, Formatted cells, Polars version matches a py-polars release

    Design

    Design

    Context

    In Polars 0.55, a Selector (polars_plan::dsl::Selector) is a tree: ByName, Matches(regex), ByDType(DataTypeSelector), Wildcard, plus set operations. DataTypeSelector has AnyOf([DataType]), Integer, SignedInteger, UnsignedInteger, Float and Numeric, among others. Selector::exclude_cols(names) removes names, and Selector::as_expr() turns a selector into an Expr that Polars expands against the schema. col("^...$") is already a regex selector. Expr::name().suffix(s) and .prefix(s) rename outputs.

    Goals / Non-Goals

    Goals:

    • Selectors in idiomatic Nim (types and typeclasses), with no extra namespace to import.
    • No opaque selector handles across the ABI.

    Non-Goals:

    • Set operators, by-index selection, and name helpers beyond regex.

    Decisions

    Selector is a Nim value built into an Expr on use

    A Nim Selector object holds what was asked for: names: seq[string], dtypes: seq[DataType], classes: set[DtypeClass], wildcard: bool and excluded: seq[string]. exclude returns a copy with more excluded names. A converter toExpr(s: Selector): Expr makes one call:

    nq_expr_selector(names: *const *const c_char, n_names: usize, dtypes: *const NqDtype,
                     n_dtypes: usize, classes: u32 /* bit set of NqDtypeClass */,
                     wildcard: bool, excluded: *const *const c_char, n_excluded: usize)
                     -> *mut Expr

    Rust takes the union of the parts (ByName | ByDType(AnyOf) | ByDType(category) | Wildcard), applies exclude_cols, and returns as_expr().

    • Why: it is the same pattern as the conditional chain (built in Nim, crossed once). Selectors stay plain values, and $ shows Polars' rendering of the selector.
    • Alternative: an opaque NqSelector with its own free function. That means more ABI surface, and it gains nothing until set operators exist.
    Types and typeclasses

    col(T: typedesc) is a macro. It looks at the type it is given:

    • SomeNumber, SomeInteger, SomeSignedInt, SomeUnsignedInt and SomeFloat map to the matching DtypeClass.
    • A concrete type maps through dataType(T), so col(int) is Int64 and col(int8) is Int8, the same rules as cast.
    • col(float, int) takes several types and unions them.
    • Any other type is a compile error with the message of dataType.
    Several names

    col(a, b: string, more: varargs[string]) returns a Selector, so col("a") keeps returning Expr with no ambiguity. all() sets wildcard. Regex needs no new code, because col("^w.*$") already passes the pattern to Polars.

    Output names

    proc name(e: Expr): ExprName returns a small wrapper. suffix(n: ExprName, s) and prefix(n: ExprName, s) call nq_expr_name_affix(e, s, is_prefix). A Selector reaches name through the converter.

    Risks / Trade-offs

    • Converters make overload errors harder to read. They are limited to Selector -> Expr, the same as Then -> Expr.
    • Typeclass dispatch in a macro depends on how Nim represents SomeNumber symbols. The tests cover each typeclass and a concrete type.
    Tasks10 of 10 done

    1. Bridge 3/3

    • 1.1Add #[repr(C)] NqDtypeClass (Numeric, Integer, SignedInteger, UnsignedInteger, Float) and nq_expr_selector (names, dtype codes, class bit set, wildcard, excluded names)
    • 1.2Add nq_expr_name_affix (suffix or prefix)
    • 1.3Mirror both in ffi.nim; verify that cargo build --release passes

    2. Nim API 5/5

    • 2.1Add the Selector value type, its converter to Expr, and $
    • 2.2Add col for Nim types and typeclasses (macro), several types, and several names; add all()
    • 2.3Add exclude(names) on Selector
    • 2.4Add name.suffix and name.prefix
    • 2.5Write tests/test_selectors.nim: each typeclass and concrete type, col(float, int), col("a", "b"), all(), regex, exclude, use in select/withColumns/agg, two aggregations with suffixes, and col(seq[int]) not compiling; add it to nanuq.nimble and .gitignore

    3. Docs and integration 2/2

    • 3.1List the selectors in the README "What is there"; verify that nimble test and nimble example pass
    • 3.2Check that CI is green on the PR

    Workflow follow-up 0/0

      Revisions1 revision
      r1 2b080c0 2026-10-31 Add column selectors (implements add-column-selectors)

      First version: .openspec.yaml, design.md, proposal.md, specs/column-selectors/spec.md, specs/native-bridge/spec.md, tasks.md

      add-coverage-easy-wins-0-6 Archived

      openspec/changes/archive/2026-11-01-add-coverage-easy-wins-0-6
      1. Proposal
      2. Specs
      3. Tasks
      4. Implement 5/5
      5. Archive
      Proposal

      Why

      The Polars coverage map (nanuq#60, docs/coverage/polars.json) lists the Python API Nanuq still misses. Its thread picked out 30 items that each take hours, not days (/mnt/project-files/nanuq-0.6/easy-wins.md), and Pietro asked for all three groups in 0.6 (2026-11-01): pure Nim helpers, small bridge calls on features already compiled in, and items that turn on one more Polars feature.

      It is the thirteenth change of the 0.6 release.

      What Changes

      • Pure Nim: empty frames (newDataFrame(schema = ...), clear(n)), isEmpty, getColumnIndex, rowsByKey, frame shift and dropNans, LazyFrame shift, first, last, dt.epoch(unit), table formatting options (setTblFormatting, setAsciiTables, setTblHide*, setTblCellAlignment, ...), bin on Series.
      • Small bridge calls: eqMissing, neMissing, nth, cumulativeEval, roundSigFigs, dt.century, dt.millennium, dt.dstOffset, dt.baseUtcOffset, timeRange, timeRanges, str.escapeRegex, concatArr, CSV commentPrefix, scanParquet(hivePartitioning), cache, QueryOptFlags (collect(optimizations), withOptimizations), rechunk, shrinkToFit, nChunks, matchToSchema, readOds.
      • One more Polars feature each: isClose (is_close), mergeSorted (merge_sorted), dt.addBusinessDays, dt.isBusinessDay, businessDayCount (business), str.normalize (string_normalize), reinterpret (reinterpret), readIpcStream and writeIpcStream (ipc_streaming), and cse so that the common subplan and subexpression optimizations exist (py-polars has them on).

      Capabilities

      Modified Capabilities
      • frame-utilities: empty frames, frame shortcuts, schema matching, merging sorted frames, query optimizations.
      • temporal: more date parts, time ranges, business days.
      • expressions: null-aware comparisons, closeness, nth, cumulativeEval, roundSigFigs, reinterpret, concatArr.
      • strings: escapeRegex, normalize.
      • series: the bin namespace on Series.
      • csv-io: comment lines.
      • parquet-ipc: Hive partitioning switch, IPC streams.
      • excel-io: readOds.
      • inspection: table formatting options.

      Differences from Polars

      | Nanuq | Python | Rust (py-2.1.0) | |---|---|---| | newDataFrame(schema = {...}) | pl.DataFrame(schema=...) | DataFrame::empty_with_schema | | clear(n) | clear(n) | (Python only) | | isEmpty | is_empty | is_empty | | getColumnIndex | get_column_index | get_column_index | | rowsByKey(key, K, T, unique) | rows_by_key(key, named, include_key, unique) | (Python only) | | shift, dropNans, first, last on frames | same | shift, drop_nans, first, last | | dt.epoch(EpochUnit) | dt.epoch(time_unit) | (Python only) | | setTblFormatting, setAsciiTables, setTblHide*, ... | Config.set_tbl_formatting, ... | POLARS_FMT_* variables | | s.bin.* | Series.bin.* | | | eqMissing, neMissing | eq_missing, ne_missing | eq_missing, neq_missing | | nth(indices) | pl.nth(*indices) | dsl::nth | | cumulativeEval(expr, minSamples) | cumulative_eval | cumulative_eval | | roundSigFigs(digits) | round_sig_figs | round_sig_figs | | dt.century, dt.millennium, dt.dstOffset, dt.baseUtcOffset | same | same | | timeRange, timeRanges | pl.time_range(s) | time_range(s) | | str.escapeRegex, str.normalize(UnicodeForm) | escape_regex, normalize | same | | concatArr | pl.concat_arr | concat_arr | | commentPrefix | comment_prefix | with_comment_prefix | | hivePartitioning | hive_partitioning | HiveOptions | | cache, QueryOptFlags, withOptimizations | cache, QueryOptFlags, collect(optimizations=) | cache, OptFlags | | rechunk, shrinkToFit, nChunks | rechunk, shrink_to_fit, n_chunks | rechunk_mut, shrink_to_fit, max_n_chunks | | matchToSchema | match_to_schema | match_to_schema | | readOds | read_ods | (calamine) | | isClose | is_close | is_close | | mergeSorted(other, key) | merge_sorted | merge_sorted | | dt.addBusinessDays, dt.isBusinessDay, businessDayCount | same | same | | reinterpret(signed) | reinterpret(signed=) | reinterpret | | readIpcStream, writeIpcStream | read_ipc_stream, write_ipc(..)/write_ipc_stream | IpcStreamReader, IpcStreamWriter |

      • rowsByKey returns an OrderedTable of Nim objects or tuples (T); the key column is in the rows only if T has a field for it (Python: include_key, named).
      • timeRange/timeRanges need start and stop (Python defaults to the whole day).
      • matchToSchema sets the same policy for every column and has no struct-field policies or fill expressions (Python takes a dict per column).
      • QueryOptFlags.none keeps type coercion and checks on, as Python's; Python's deprecated collect(predicate_pushdown=...) keywords are not offered.
      • Business days take weekMask: array[7, bool] and holidays: openArray[Date], and roll is a Roll enum (Python strings).
      • nth returns an expression, not a selector (it cannot be combined with |).
      • Table options are switches (setTblHideColumnNames(false) turns it off again); the withConfig block takes the most used of them.

      Impact

      • src/rust/src/lib.rs: nq_expr_win, nq_expr_business_day_count, nq_expr_time_range, nq_expr_concat_arr, nq_expr_nth, nq_lf_with_optimizations, nq_lf_cache, nq_lf_drop_nans, nq_lf_merge_sorted, nq_lf_match_to_schema, nq_df_rechunk, nq_df_shrink_to_fit, nq_df_n_chunks, IPC stream read/write, CSV comment_prefix, Parquet hive; features is_close, merge_sorted, business, string_normalize, reinterpret, ipc_streaming, cse.
      • src/nanuq.nim, src/nanuq/ffi.nim; new tests/test_easywins6.nim and tests/data/bears.ods.
      • docs/coverage/polars.json: these rows become covered.
      Spec changescsv-io +1 · excel-io +1 · expressions +2 · frame-utilities +5 · inspection +1 · parquet-ipc +2 · series +1 · strings +1 · temporal +2

      csv-io modified +1

      ADDED
      Comment lines

      readCsv and scanCsv SHALL skip lines starting with commentPrefix (none when empty).

      import std/streams
      echo readCsv(newStringStream("# measured 2026\nbear,kg\nAda,410\n"), commentPrefix = "#")
      TBD
      Scenario: No prefix
      • WHEN a CSV starting with "# note" is read without commentPrefix
      • THEN "# note" is the first column name

      Unchanged in this spec: Scanning CSV, CSV read options, CSV write options, Reading CSV from a stream, Quoting, encoding and new column names

      excel-io modified +1

      ADDED
      Reading OpenDocument

      readOds SHALL read a sheet of an .ods file with the options of readExcel.

      echo readOds("tests/data/bears.ods")
      TBD
      Scenario: Numbers
      • WHEN an .ods sheet with numeric cells is read
      • THEN those columns are Float64

      Unchanged in this spec: Writing Excel, Reading Excel

      expressions modified +2

      ADDED
      Null-aware comparisons and closeness

      eqMissing(other) and neMissing(other) SHALL compare as == and != with null equal to null, never giving null. isClose(other, absTol = 0.0, relTol = 1e-9, nansEqual = false) SHALL be true where abs(a - b) <= max(relTol * max(abs(a), abs(b)), absTol).

      let df = newDataFrame(series("a", [some(1.0), none(float)]), series("b", [some(1.05), none(float)]))
      echo df.select(col("a").eqMissing(col("b")).alias("eq"),
                     col("a").isClose(col("b"), absTol = 0.1).alias("close"))
      TBD
      Scenario: Nulls
      • WHEN eqMissing compares null with null
      • THEN the result is true
      ADDED
      More expression functions

      nth(indices) SHALL select columns by position (negative from the end). cumulativeEval(expr, minSamples = 1) SHALL run expr on the growing window up to each row, roundSigFigs(digits) SHALL round to significant figures, reinterpret(signed) SHALL read 64-bit integer bits as Int64 or UInt64, and concatArr(exprs) SHALL build fixed-size arrays per row.

      let df = newDataFrame(series("x", @[1.0, 22.0, 333.0]), series("y", @[4.0, 5.0, 6.0]))
      echo df.select(nth(-1), col("x").cumulativeEval(element().sum).alias("cum"),
                     col("x").roundSigFigs(1).alias("sig"), concatArr(col("x"), col("y")).alias("xy"))
      TBD
      Scenario: Cumulative sum
      • WHEN cumulativeEval(element().sum) runs on 1, 2, 3
      • THEN the result is 1, 3, 6

      Unchanged in this spec: Conditional expressions, choose macro, Membership and ranges, Arithmetic operators, Rounding, More aggregations, Null fill strategies, Window expressions, Ranking, Filtering inside expressions, Shape and position aggregations, Boolean aggregations, Entropy, Row count expression, Several window keys and selector concatenation

      frame-utilities modified +5

      ADDED
      Empty frames

      newDataFrame(schema = {...}) SHALL build a frame with those columns and types and no rows (a Schema works too). clear(n = 0) on a DataFrame or LazyFrame SHALL keep the columns and types with no rows, or n rows of nulls. isEmpty on a DataFrame or Series SHALL be true when it has no rows.

      let empty = newDataFrame(schema = {"bear": String, "kg": Int64})
      echo empty
      echo empty.isEmpty
      echo newDataFrame(series("kg", @[410, 380])).clear(1)
      TBD
      Scenario: Same schema
      • WHEN df.clear runs
      • THEN its schema equals df.schema and its height is 0
      ADDED
      Frame shortcuts

      getColumnIndex(name) SHALL give a column's position (raising ColumnNotFoundError). rowsByKey(key, K, T, unique = false) SHALL group the rows, as T objects or tuples, by the values of key in order of appearance (with unique, the last row per key). shift(n, fillValue) and dropNans(subset) SHALL work on frames as on each column; LazyFrame first and last SHALL keep the first or last row. rechunk SHALL put each column in one chunk, shrinkToFit SHALL drop spare capacity, and nChunks SHALL count chunks.

      import std/tables
      let df = newDataFrame(series("station", @["A", "B", "A"]), series("rain", @[1.5, NaN, 3.0]))
      echo df.getColumnIndex("rain")
      echo df.rowsByKey("station", string, tuple[rain: float])
      echo df.dropNans.shift(1)
      TBD
      Scenario: Unknown column
      • WHEN getColumnIndex("nope") runs
      • THEN ColumnNotFoundError is raised
      ADDED
      Schema matching

      matchToSchema(schema, missingColumns, extraColumns, integerCast, floatCast) SHALL put the columns in the schema's order and types. A missing column SHALL raise unless missingColumns = Insert (nulls), an extra column SHALL raise unless extraColumns = Ignore, and integers and floats SHALL change type only with CastPolicy.Upcast.

      let df = newDataFrame(series("b", @[1'i32]), series("a", @["x"]))
      echo df.matchToSchema({"a": String, "b": Int64, "c": Float64},
                            missingColumns = MissingColumns.Insert, integerCast = CastPolicy.Upcast)
      TBD
      Scenario: Missing column
      • WHEN the schema has a column the frame lacks and missingColumns is Raise
      • THEN PolarsError is raised
      ADDED
      Merging sorted frames

      mergeSorted(other, key) SHALL merge two frames sorted by key into one sorted frame.

      let a = newDataFrame(series("k", @[1, 4]))
      let b = newDataFrame(series("k", @[2, 3, 5]))
      echo a.mergeSorted(b, "k").toList("k", int)
      TBD
      Scenario: Same columns
      • WHEN both frames have the same columns, sorted by key
      • THEN the result has all their rows, sorted
      ADDED
      Query optimizations

      cache SHALL mark part of a query to compute once. QueryOptFlags SHALL hold the optimization switches (all on by default; QueryOptFlags.none turns off all but type coercion and checks), applied with withOptimizations or collect(optimizations, engine).

      let lf = newDataFrame(series("x", @[1, 2, 3])).lazy.filter(col("x") > 1)
      echo lf.collect(QueryOptFlags.none).height
      echo lf.cache.collect(QueryOptFlags(predicatePushdown: false)).height
      TBD
      Scenario: Same rows
      • WHEN a query is collected with every optimization on and with QueryOptFlags.none
      • THEN the rows are the same

      Unchanged in this spec: Smaller expression functions, Names and meta, Comparing and stacking frames, Updating, upsampling and partitions, Operator methods and xor, Ranges per row, Inequality joins, Frame and Series helpers, Unstack, Rolling Nim functions, Data type of an expression

      inspection modified +1

      ADDED
      Table formatting options

      setTblFormatting(TableFormat, roundedCorners), setAsciiTables, setTblHideColumnDataTypes, setTblHideColumnNames, setTblHideDataframeShape, setTblHideColumnSeparator, setTblDataframeShapeBelow, setTblColumnDataTypeInline, setTblCellAlignment, setTblCellNumericAlignment and setFmtTableCellListLen SHALL change how frames print; setConfig and withConfig SHALL take tblFormatting, asciiTables, tblHideColumnDataTypes, tblHideColumnNames, tblHideDataframeShape and tblCellAlignment, and resetConfig SHALL undo them all.

      let df = newDataFrame(series("bear", @["Ada"]), series("kg", @[410]))
      withConfig(tblFormatting = TableFormat.Markdown, tblHideDataframeShape = true):
        echo df
      TBD
      Scenario: ASCII
      • WHEN a frame prints inside withConfig(asciiTables = true)
      • THEN its borders use +, - and |

      Unchanged in this spec: glimpse, describe, Display config, Scoped display config, Describe prints temporal values as Python

      parquet-ipc modified +2

      ADDED
      Hive partitioning switch

      scanParquet and readParquet SHALL take hivePartitioning: true reads key=value directories as columns, false does not, none(bool) (default) decides by the path.

      let base = getTempDir() / "nanuq-hive"
      let df = newDataFrame(series("year", @[2024, 2025]), series("n", @[1, 2]))
      df.lazy.sinkParquet(PartitionBy(basePath: base, key: @["year"], includeKey: false), mkdir = true)
      echo scanParquet(base / "**/*.parquet", hivePartitioning = false).collect.columns
      TBD
      Scenario: On
      • WHEN the same files are scanned with hivePartitioning = true
      • THEN the frame has a year column
      ADDED
      Arrow IPC streams

      writeIpcStream(path, compression) SHALL write the Arrow IPC stream format, and readIpcStream SHALL read it from a path or a stream.

      let path = getTempDir() / "bears.arrows"
      newDataFrame(series("kg", @[410, 380])).writeIpcStream(path)
      echo readIpcStream(path).toList("kg", int)
      TBD
      Scenario: Compressed
      • WHEN a frame is written with IpcCompression.Zstd and read back
      • THEN the frames are equal

      Unchanged in this spec: Reading Parquet, Writing Parquet, Arrow IPC, Reading from streams

      series modified +1

      ADDED
      Binary functions on a Series

      s.bin SHALL give the bin namespace on a Series, as on an expression.

      let s = newDataFrame(series("b", @["ab", "c"])).select(col("b").cast(Binary)).getColumn("b")
      echo s.bin.size
      TBD
      Scenario: Same as the expression
      • WHEN s.bin.size runs
      • THEN it equals s.eval(col(s.name).bin.size)

      Unchanged in this spec: Getting a Series, Reading a Series, Series operations, Series in frames, Series namespaces, Series as HTML, Columns from sized numbers

      strings modified +1

      ADDED
      Escaping and normalizing

      str.escapeRegex SHALL escape regex metacharacters, and str.normalize(form = UnicodeForm.NFC) SHALL give the Unicode normal form (NFC, NFKC, NFD, NFKD).

      let df = newDataFrame(series("s", @["a.b*c", "é"]))
      echo df.select(col("s").str.escapeRegex.alias("escaped"),
                     col("s").str.normalize.str.lenChars.alias("chars"))
      TBD
      Scenario: Composed form
      • WHEN "e" followed by a combining acute accent is normalized to NFC
      • THEN the result is the one character "é"

      Unchanged in this spec: The str namespace, Matching, Replacing and stripping, Slicing and padding, Joining strings in an aggregation, Building strings from columns, Title case, Splitting and extracting into lists and structs, Many patterns at once, JSON in strings

      temporal modified +2

      ADDED
      More date parts and time ranges

      dt.epoch(EpochUnit) SHALL give the time since 1970-01-01 (whole seconds and days for Seconds and Days), dt.century and dt.millennium the century and millennium, dt.dstOffset and dt.baseUtcOffset the offsets of zoned datetimes as Durations. timeRange(start, stop, interval, closed) SHALL give times of day, timeRanges one list per row.

      let df = newDataFrame(series("d", @[date(2000, 6, 1), date(2001, 1, 1)]))
      echo df.select(col("d").dt.epoch(EpochUnit.Days).alias("days"),
                     col("d").dt.century.alias("century"))
      echo select(timeRange(timeOfDay(9), timeOfDay(11), "1h").alias("t"))
      TBD
      Scenario: Daylight saving
      • WHEN dt.dstOffset runs on 2026-07-01 12:00 in Europe/Rome
      • THEN the result is 1 hour
      ADDED
      Business days

      dt.addBusinessDays(n, weekMask, holidays, roll), dt.isBusinessDay(weekMask, holidays) and businessDayCount(start, stop, weekMask, holidays) SHALL count business days: Monday to Friday by default (weekMask, Monday first), minus holidays. roll SHALL say what a start date that is not a business day does (Raise, Forward, Backward).

      let df = newDataFrame(series("d", @[date(2026, 10, 30)]))
      echo df.select(col("d").dt.addBusinessDays(1).alias("next"),
                     col("d").dt.isBusinessDay.alias("business"))
      echo select(businessDayCount(date(2026, 11, 2), date(2026, 11, 9)).alias("n")).toList("n", int)
      TBD
      Scenario: Holiday
      • WHEN one business day is added to Friday 2026-10-30 with Monday 2026-11-02 a holiday
      • THEN the result is 2026-11-03

      Unchanged in this spec: Temporal values, Temporal ranges and durations, Parsing strings, Date and time parts, Formatting temporal values, Temporal arithmetic, Time zones, Dates from parts

      Tasks5 of 5 done

      1. Implementation 5/5

      • 1.1Pure Nim helpers (group A)
      • 1.2Bridge calls on features already on (group B)
      • 1.3Polars features is_close, merge_sorted, business, string_normalize, reinterpret, ipc_streaming, cse (group C)
      • 1.4tests/test_easywins6.nim, spec examples
      • 1.5CHANGELOG, coverage rows
      Revisions1 revision
      r1 889d13f 2026-11-01 Add cloud storage and 30 functions from the Polars coverage map

      First version: proposal.md, specs/csv-io/spec.md, specs/excel-io/spec.md, specs/expressions/spec.md, specs/frame-utilities/spec.md, specs/inspection/spec.md, specs/parquet-ipc/spec.md, specs/series/spec.md, specs/strings/spec.md, specs/temporal/spec.md, tasks.md

      add-csv-options-and-scan Archived

      created 2026-10-31 · openspec/changes/archive/2026-10-31-add-csv-options-and-scan
      1. Proposal
      2. Specs
      3. Design
      4. Tasks
      5. Implement 9/9
      6. Archive
      Proposal

      Why

      Real CSV files are rarely clean. They use ; as a separator, mark missing values with words like "lots" or "?", have a preamble before the header, need a column read as another type, or come as a folder of daily files. Nanuq's readCsv handles only a header row and null markers, and writeCsv has no options at all. Python Polars handles all of these with keyword arguments, and its lazy scan_csv reads a glob of files without loading them first. The 0.2 explainer post needs this in two scenes: it reads a season of daily logs lazily, and it writes a report for a spreadsheet that expects ; and decimal commas.

      This change takes up the "lazy scanCsv" part of the BACKLOG.md entry "More IO". Parquet and JSON stay in the entry. It is the sixth and last change of the 0.2 release (see the Polars coverage map, area "IO"). Pietro made the API choice on 2026-10-31 in the doc "Nanuq 0.2: API choices the explainer forces": named arguments with Polars' defaults, schemaOverrides taking DataType values, and a char separator.

      What Changes

      • scanCsv(path, ...) returns a LazyFrame. path can be a glob such as "logs/*.csv", and every matched file must have the same columns.
      • readCsv(path, ...) takes the same options and returns a DataFrame. readCsv(path) and readCsv(path, nullValues = [...]) keep working.
      • Read options, named as in Python Polars and with its defaults:
      • separator = ','
      • hasHeader = true
      • nullValues: openArray[string]
      • schemaOverrides: openArray[(string, DataType)], e.g. {"bears": Int64}
      • skipRows = 0
      • nRows = none(int)
      • columns: openArray[string] (read only these)
      • inferSchemaLength = some(100) (none scans every row)
      • ignoreErrors = false
      • decimalComma = false
      • writeCsv(df, path, ...) options:
      • separator = ','
      • includeHeader = true
      • nullValue = ""
      • quoteStyle = Necessary (a pure enum QuoteStyle: Necessary, Always, NonNumeric, Never)
      • floatPrecision = none(int)
      • decimalComma = false
      • nRows, inferSchemaLength and floatPrecision also accept a plain int, like sample's seed.
      • The ABI stays 0.2.0-dev, and no Polars features are added (lazy and csv already include scanning and globs).

      Capabilities

      New Capabilities
      • csv-io: reading, scanning and writing CSV with options.
      Modified Capabilities
      • native-bridge: NqQuoteStyle joins the enums that keep the same order in Rust and ffi.nim.

      Differences from Polars

      Expected differences from Polars' Rust and Python APIs:

      • Named arguments instead of Rust's builder. Rust's CsvReadOptions and LazyCsvReader builders become named arguments, as in Python.
      • separator is a char (';'), where Python takes a one-character string. A multi-character separator does not compile.
      • schemaOverrides takes DataType values ({"bears": Int64}), like cast, not Nim types.
      • quoteStyle is an enum (quoteStyle = Always), where Python takes a string.
      • Optional integers (nRows, inferSchemaLength, floatPrecision) are Option[int], and also accept a plain int.
      • readCsv is scanCsv(...).collect. The two take the same options and read the same data. Python's read_csv has a separate eager reader with a few extra options.
      • A glob of files with different columns fails. As in Polars, scanCsv expects the same columns in every file. Read the files separately and use concat(how = Diagonal) instead.
      • Not in this change:
      • Read options: quote_char, comment_prefix, encoding, try_parse_dates (dates are not modelled yet), row_index_name, truncate_ragged_lines, missing_utf8_is_empty_string, and per-column null_values (a dict).
      • schema (the full schema) and new_columns.
      • CSV from a string (its own BACKLOG entry).
      • Write options: quote_char, the date and time formats, float_scientific and line_terminator.
      • Names follow Polars in camelCase: has_header → hasHeader, null_values → nullValues, schema_overrides → schemaOverrides, n_rows → nRows, and so on.

      Impact

      • src/rust/src/lib.rs:
      • nq_lf_scan_csv maps every read option onto LazyCsvReader. It replaces nq_df_read_csv.
      • nq_df_write_csv gains the write options.
      • New #[repr(C)] enum NqQuoteStyle.
      • src/nanuq/ffi.nim, src/nanuq.nim: the declarations, QuoteStyle, scanCsv, and the new readCsv and writeCsv signatures.
      • tests/test_csv.nim: each option, globs, and reading back what writeCsv wrote with the same options.
      • README.md documents the options. BACKLOG.md keeps "More IO" for Parquet, JSON and scanParquet.
      Spec changescsv-io +3 · native-bridge ~1

      csv-io modified +3

      ADDED
      Scanning CSV

      The API SHALL provide scanCsv(path, ...), which returns a LazyFrame without reading the file until the query runs. path SHALL accept a glob that matches several files with the same columns. A glob whose files have different columns SHALL raise NanuqError when the query runs.

      Scenario: A folder of logs
      • WHEN scanCsv(dir / "*.csv").collect runs on two files with the same columns and 2 and 3 rows
      • THEN the result has 5 rows
      ADDED
      CSV read options

      readCsv and scanCsv SHALL take these named options with Polars' defaults:

      • separator = ',' and hasHeader = true
      • nullValues and schemaOverrides ((string, DataType) pairs)
      • skipRows = 0, nRows = none(int) and columns (all when empty)
      • inferSchemaLength = some(100), where none scans all rows
      • ignoreErrors = false and decimalComma = false

      nRows and inferSchemaLength SHALL also accept a plain int.

      Scenario: Semicolons and null words
      • WHEN a file with ; separators and the value "lots" is read with separator = ';', nullValues = ["lots"]
      • THEN the columns are split at ; and "lots" is null
      Scenario: Override a dtype
      • WHEN a column of whole numbers is read with schemaOverrides = {"n": Float64}
      • THEN dtype("n") == Float64
      Scenario: Preamble and limit
      • WHEN a file with two preamble lines and 10 data rows is read with skipRows = 2, nRows = 3
      • THEN the header is the third line and the result has 3 rows
      Scenario: Columns
      • WHEN a file with columns a, b and c is read with columns = ["c", "a"]
      • THEN the result has columns c and a
      ADDED
      CSV write options

      writeCsv(df, path, ...) SHALL take these named options:

      • separator = ',' and includeHeader = true
      • nullValue = ""
      • quoteStyle = Necessary, a pure enum QuoteStyle (Necessary, Always, NonNumeric, Never)
      • floatPrecision = none(int) (also a plain int)
      • decimalComma = false
      Scenario: Spreadsheet in a comma-decimal locale
      • WHEN a frame with 1.5 is written with separator = ';', decimalComma = true and read back with the same options
      • THEN the file holds 1,5 and the value read back is 1.5
      Scenario: Quote everything
      • WHEN a frame is written with quoteStyle = Always
      • THEN every field in the file is quoted
      Scenario: Null marker and precision
      • WHEN a frame with a null and 3.14159 is written with nullValue = "NA", floatPrecision = 2
      • THEN the file holds NA and 3.14

      Unchanged in this spec: Reading CSV from a stream, Quoting, encoding and new column names, Comment lines

      native-bridge modified ~1

      MODIFIED
      Nim declarations mirror the C ABI
      `src/nanuq/ffi.nim` SHALL declare every exported function with matching signatures, and the enums `NqBinOp`, `NqUnary`, `NqDtype`, `NqDtypeClass`, `NqJoinType`, `NqJoinValidation`, `NqMaintainOrderJoin`, `NqConcat`, `NqUniqueKeepStrategy`, `NqClosedInterval`, `NqQuantileMethod`, `NqFillNullStrategy`, `NqRoundMode`, `NqQuoteStyle`,`NqRoundMode` `NqRankMethod`, `NqErrorKind`, `NqStrOp`, `NqTimeUnit`,and `NqClosedWindow`,`NqQuoteStyle` `NqDtOp`, `NqCatOp`, `NqParquetCompression` and `NqIpcCompression` SHALL keep the same order as in Rust. `NqDtype` SHALL also keep the order of of `DataTypeKind`, and the option enums the order of their Nim API enums. Data types SHALL cross the ABI as an `NqDtypeSpec` struct (code, time unit, time zone, categories) with the same field order on both sides. Scenario: ABI change - **WHEN** a function is added or changed in `rust/src/lib.rs` - **THEN** `src/nanuq/ffi.nim` is updated in the same change

      Unchanged in this spec: C ABI over Polars with opaque handles, Errors and panics never cross the boundary, Linking the static library, Columns cross in bulk, Library version check, Formatted cells, Polars version matches a py-polars release

      Design

      Design

      Context

      readCsv calls nq_df_read_csv(path, null_values, n), which uses the eager CsvReadOptions reader. writeCsv calls nq_df_write_csv(df, path) with CsvWriter defaults. Polars 0.55 has LazyCsvReader::new(path) with with_separator, with_has_header, with_null_values, with_dtype_overwrite, with_skip_rows, with_n_rows, with_infer_schema_length, with_ignore_errors, with_decimal_comma and with_glob (on by default), ending in .finish(). CsvWriter has with_separator, include_header, with_null_value, with_quote_style(QuoteStyle), with_float_precision and with_decimal_comma.

      Goals / Non-Goals

      Goals:

      • One reader in Rust for both eager and lazy reads, so their behavior can't drift.
      • The option set the 0.2 explainer needs, with Polars' defaults.

      Non-Goals:

      • Every Python option. The rest come when someone needs them.
      • An options object. Pietro chose named arguments, and an object overload can be added later.

      Decisions

      One scan function
      nq_lf_scan_csv(path, separator: u8, has_header: bool,
                     null_values: *const *const c_char, n_nulls: usize,
                     override_names: *const *const c_char, override_dtypes: *const NqDtype,
                     n_overrides: usize, skip_rows: usize, n_rows: i64 /* <0: all */,
                     infer_schema_length: i64 /* <0: all rows */, ignore_errors: bool,
                     decimal_comma: bool) -> *mut LazyFrame

      readCsv is scanCsv(...).collect in Nim, and columns becomes a select after the scan, which Polars pushes down into the reader. nq_df_read_csv is removed. That is fine within 0.2.0-dev.

      • Why: one code path and one ABI function. The lazy plan gives projection pushdown for free.
      • Alternative: keep an eager reader with its own options. That duplicates the options for a small speed gain on tiny files.
      Separator as char

      Nim's char is one byte, the same as Rust's u8. A non-ASCII char literal cannot be written, so no runtime check is needed.

      Overrides as DataType

      schemaOverrides: openArray[(string, DataType)] goes across as names plus NqDtype codes, the same encoding as cast. An Other dtype raises NanuqError.

      Optional integers

      Option[int] values cross as -1 for none. The parameters are typed int | Option[int] (nRows, inferSchemaLength and floatPrecision), so a plain int works without extra overloads; a private toOpt turns either into Option[int]. (The proposal planned plain-int overloads from a template; the generic parameter turned out simpler.)

      writeCsv

      nq_df_write_csv(df, path, separator, include_header, null_value, quote_style: NqQuoteStyle, float_precision: i32 /* <0: none */, decimal_comma) -> bool.

      Risks / Trade-offs

      • readCsv through the lazy engine changes error messages for some malformed files. The tests keep the existing CSV tests passing.
      • Globs that match files with different columns fail. The proposal documents this, and the post uses diagonal concat.
      Tasks9 of 9 done

      1. Bridge 3/3

      • 1.1Add nq_lf_scan_csv with all read options (separator, header, nulls, overrides, skip rows, row limit, inference length, ignore errors, decimal comma); remove nq_df_read_csv
      • 1.2Add NqQuoteStyle and the write options to nq_df_write_csv
      • 1.3Mirror everything in ffi.nim; verify that cargo build --release passes

      2. Nim API 4/4

      • 2.1Add scanCsv with the read options, and make readCsv scanCsv(...).collect with the same options (columns as a select)
      • 2.2Add QuoteStyle and the writeCsv options
      • 2.3Accept a plain int (as int | Option[int]) for nRows, inferSchemaLength and floatPrecision
      • 2.4Write tests/test_csv.nim: every option, a glob over two files, a glob whose files have different columns failing, columns projection, schemaOverrides and its Other error, and round trips (; with decimal comma, quoteStyle = Always, nullValue, floatPrecision); add it to nanuq.nimble and .gitignore

      3. Docs and integration 2/2

      • 3.1Document the CSV options in the README; verify that nimble test, nimble example and the existing CSV tests pass
      • 3.2Check that CI is green on the PR, including the Rust rebuild

      Workflow follow-up 0/0

        Revisions1 revision
        r1 e6c3502 2026-10-31 Implement add-csv-options-and-scan

        First version: .openspec.yaml, design.md, proposal.md, specs/csv-io/spec.md, specs/native-bridge/spec.md, tasks.md

        add-cumulative-and-shift Archived

        openspec/changes/archive/2026-11-01-add-cumulative-and-shift
        1. Proposal
        2. Specs
        3. Tasks
        4. Implement 4/4
        5. Archive
        Proposal

        Why

        Comparing a row with the rows before it is the heart of time-series work: day-to-day change, running totals, records so far, how long a streak lasts. Nanuq has over and rank but no shift, diff or cumulative functions, so a port of a "change since yesterday" query needs a self-join. The O'Reilly chapter 8 sections "Operations that accumulate" and the Packt window recipes stop here, and so does the 0.4 explainer (El Niño events are runs of consecutive warm seasons).

        It is the second change of the 0.4 release.

        What Changes

        • Shifting and differences: shift(n = 1, fillValue), diff(n = 1, nullBehavior) with a NullBehavior pure enum (Ignore, Drop), and pctChange(n = 1).
        • Cumulative functions: cumSum, cumProd, cumMin, cumMax, cumCount, each with reverse = false.
        • Runs and peaks: rleId (an id that grows by one each time the value changes), peakMax, peakMin.
        • More aggregations: product, mode, argMin, argMax, skew(bias = true), kurtosis(fisher = true, bias = true).

        Capabilities

        New Capabilities
        • cumulative-functions: shift, diff, pctChange, cumulative functions, runs and peaks.
        Modified Capabilities
        • expressions: more aggregations (product, mode, argMin, argMax, skew, kurtosis).

        Differences from Polars

        • shift with a fill value is one proc with a named fillValue (Python's fill_value, Rust's shift_and_fill).
        • diff's nullBehavior is the NullBehavior pure enum (Python takes the strings "ignore" and "drop").
        • n is an int (Rust and Python also accept an expression); that covers every use in the Polars docs and books.
        • rle (which returns a Struct) waits for Struct columns in 0.5; rleId is here.

        Impact

        • src/rust/src/lib.rs: NqUnary grows (cumulative functions, product, mode, argMin, argMax, rleId, peaks), nq_expr_shift, nq_expr_diff, nq_expr_pct_change, nq_expr_moment; src/nanuq/ffi.nim, src/nanuq.nim.
        • New tests/test_cumulative.nim.
        Spec changescumulative-functions +4 · expressions +1

        cumulative-functions modified +4

        ADDED
        Shifting

        e.shift(n = 1) SHALL move values down by n rows (up when n is negative), filling the rows left empty with null, or with fillValue when it is given. Inside over, the shift SHALL happen within each group.

        let df = newDataFrame:
          month: ["Jan", "Feb", "Mar", "Apr"]
          anomaly: [0.5, 0.8, 1.2, 0.9]
        echo df.withColumns(col.anomaly.shift.alias("before"),
                            col.anomaly.shift(-1, fillValue = 0.0).alias("after"))
        TBD
        Scenario: Shift within groups
        • WHEN col.x.shift.over(col.g) runs on groups a = 1, 2 and b = 3, 4
        • THEN the result is null, 1, null, 3
        ADDED
        Differences

        e.diff(n = 1, nullBehavior = NullBehavior.Ignore) SHALL subtract from each value the value n rows above, with null where there is none; NullBehavior.Drop SHALL leave out those rows. e.pctChange(n = 1) SHALL return the relative change from the value n rows above.

        let df = newDataFrame:
          year: [2021, 2022, 2023, 2024]
          temp: [14.8, 14.9, 15.1, 15.3]
        echo df.select(col.year, col.temp.diff.round(2).alias("diff"),
                       col.temp.pctChange.round(4).alias("pct"))
        TBD
        Scenario: Drop the first row
        • WHEN diff(nullBehavior = Drop) runs on 1, 4, 9
        • THEN the result is 3, 5
        ADDED
        Cumulative functions

        cumSum, cumProd, cumMin, cumMax and cumCount SHALL return the running sum, product, minimum, maximum and count of non-null values from the first row, or from the last row with reverse = true.

        let df = newDataFrame:
          rain: [3, 0, 7, 2]
        echo df.withColumns(col.rain.cumSum.alias("total"), col.rain.cumMax.alias("wettest"),
                            col.rain.cumSum(reverse = true).alias("still_to_come"))
        TBD
        Scenario: Running record
        • WHEN cumMax runs on 3, 1, 5, 2
        • THEN the result is 3, 3, 5, 5
        Scenario: Count skips nulls
        • WHEN cumCount runs on 1, null, 3
        • THEN the result is 1, 1, 2
        ADDED
        Runs and peaks

        e.rleId SHALL number the runs of equal consecutive values, starting at 0 and growing by one each time the value changes. peakMax and peakMin SHALL be true at local maxima and minima.

        let df = newDataFrame:
          season: ["DJF", "JFM", "FMA", "MAM", "AMJ", "MJJ"]
          warm: [true, true, false, false, true, true]
        echo df.withColumns(col.warm.rleId.alias("run"))
        TBD
        Scenario: Run lengths
        • WHEN rows are grouped by rleId of true, true, false, true and counted
        • THEN the runs have lengths 2, 1 and 1

        expressions modified +1

        ADDED
        Shape and position aggregations

        Expressions SHALL have the aggregations product, mode (every most frequent value, in order of appearance), argMin and argMax (the row index of the first minimum or maximum), skew(bias = true) and kurtosis(fisher = true, bias = true).

        let df = newDataFrame:
          year: [2020, 2021, 2022, 2023]
          oni: [0.5, -1.0, -0.9, 1.9]
        echo df.select(col.oni.argMax.alias("warmest_row"),
                       col.oni.argMin.alias("coldest_row"), col.oni.skew.round(3).alias("skew"))
        TBD
        Scenario: Product
        • WHEN product runs on 2, 3, 4
        • THEN the result is 24
        Scenario: Several modes
        • WHEN mode runs on 1, 2, 2, 3, 3
        • THEN the result holds 2 and 3

        Unchanged in this spec: Conditional expressions, choose macro, Membership and ranges, Arithmetic operators, Rounding, More aggregations, Null fill strategies, Window expressions, Ranking, Filtering inside expressions, Boolean aggregations, Entropy, Row count expression, Several window keys and selector concatenation, Null-aware comparisons and closeness, More expression functions

        Tasks4 of 4 done

        1. Implementation 4/4

        • 1.1shift, diff (with NullBehavior), pctChange
        • 1.2Cumulative functions with reverse, rleId, peakMax, peakMin
        • 1.3product, mode, argMin, argMax, skew, kurtosis
        • 1.4Tests in tests/test_cumulative.nim; nimble test and nimble specexamples pass; CHANGELOG
        Revisions1 revision
        r1 570d956 2026-11-01 Nanuq 0.4, changes 1-7: math, cumulative, rolling, value functions, horizontal, reshaping, time grouping

        First version: proposal.md, specs/cumulative-functions/spec.md, specs/expressions/spec.md, tasks.md

        add-database-io Archived

        openspec/changes/archive/2026-11-01-add-database-io
        1. Proposal
        2. Specs
        3. Tasks
        4. Implement 2/2
        5. Archive
        Proposal

        Why

        Reading query results from a database and writing frames back is common enough that the 0.6 book map counts 10 sections needing read_database, read_database_uri or write_database (user guide io/database, O'Reilly ch6, Packt ch2 and ch11, the escobar-west cookbook ch9), and most use SQLite. Python Polars goes through SQLAlchemy, ADBC or ConnectorX, which have no Nim counterpart, but Nim's db_connector package (the database modules that left the standard library) talks to SQLite directly.

        It is the seventh change of the 0.6 release and takes the "databases" part of the coverage roadmap (Excel and databases in "More IO").

        What Changes

        • New optional module nanuq/database (like nanuq/datamancer, only it needs the extra package db_connector).
        • readDatabase(query, connection, schemaOverrides) for an open SQLite DbConn: types from the values (INTEGER → Int64, REAL → Float64, TEXT → String, BLOB → Binary; a column of only nulls from its declared type).
        • readDatabaseUri(query, uri, schemaOverrides) with sqlite:///path URIs.
        • writeDatabase(df, tableName, connection, ifTableExists = Fail | Replace | Append), creating the table from the frame's types, in one transaction; returns the rows written.

        Capabilities

        New Capabilities
        • database-io: reading and writing SQLite databases.

        Differences from Polars

        • SQLite only. Python accepts any SQLAlchemy, ADBC or DBAPI connection and URIs for PostgreSQL, MySQL and others through ConnectorX; PostgreSQL and MySQL through db_connector are a possible follow-up (they return values as text without types).
        • No execute_options, iter_batches, batch_size or infer_schema_length; no engine choice.
        • ifTableExists is an enum (Python strings "fail", "replace", "append"), and there is no engine_options.
        • Dates, times and datetimes are written as ISO text (SQLite has no date type), as Python does through SQLAlchemy.

        Impact

        • New src/nanuq/database.nim; not imported by nanuq itself.
        • New tests/test_database.nim; CI installs db_connector with Datamancer.
        Spec changesdatabase-io +2

        database-io modified +2

        ADDED
        Writing to a database

        writeDatabase(df, tableName, connection, ifTableExists = IfTableExists.Fail) in nanuq/database SHALL write the frame's rows to a SQLite table, creating it with column types from the frame (integers and booleans INTEGER, floats REAL, Binary BLOB, the rest TEXT), and return the number of rows written. An existing table SHALL raise ValueError with Fail, be dropped first with Replace, and receive the rows with Append.

        import nanuq/database, db_connector/db_sqlite
        let db = open(":memory:", "", "", "")
        let df = newDataFrame(series("bear", @["Ada", "Bo"]), series("kg", @[410, 380]))
        echo df.writeDatabase("bears", db)
        echo df.writeDatabase("bears", db, IfTableExists.Append)
        TBD
        Scenario: Table exists
        • WHEN a frame is written to an existing table with IfTableExists.Fail
        • THEN ValueError is raised and the table is unchanged
        ADDED
        Reading from a database

        readDatabase(query, connection, schemaOverrides = []) SHALL run a query on an open SQLite connection and return its rows, with INTEGER values as Int64, REAL (or mixed numbers) as Float64, TEXT as String and BLOB as Binary, and a column of only nulls typed from its declared type. readDatabaseUri(query, "sqlite:///path") SHALL open the database for the query and close it.

        import nanuq/database, db_connector/db_sqlite
        let db = open(":memory:", "", "", "")
        discard newDataFrame(series("bear", @["Ada", "Bo"]), series("kg", @[410.5, 380.0])).writeDatabase("bears", db)
        echo readDatabase("select bear, kg * 2 as double from bears where kg > 400", db)
        TBD
        Scenario: Bad query
        • WHEN the query names a table that does not exist
        • THEN IOError is raised
        Scenario: Other URIs
        • WHEN readDatabaseUri gets a postgres:// URI
        • THEN ValueError is raised
        Tasks2 of 2 done

        1. Implementation 2/2

        • 1.1src/nanuq/database.nim: readDatabase, readDatabaseUri, writeDatabase, IfTableExists
        • 1.2Tests in tests/test_database.nim; CI installs db_connector; spec examples pass; CHANGELOG
        Revisions1 revision
        r1 4ea5dad 2026-11-01 0.6: archive the 9 changes, fill spec example outputs, map_elements benchmark, dev log Designing Nanuq 0.6

        First version: proposal.md, specs/database-io/spec.md, tasks.md

        add-datamancer-interop Archived

        created 2026-10-28 · openspec/changes/archive/2026-10-28-add-datamancer-interop
        1. Proposal
        2. Specs
        3. Tasks
        4. Implement 6/6
        5. Archive
        Proposal

        Why

        Datamancer is Nim's pure-Nim dataframe, and ggplotnim plots only Datamancer DataFrames. Today moving data across means one toSeq per column and spelling out every column name (see the "Plotting with ggplotnim" post). A conversion both ways lets Datamancer code hand heavy queries to Polars and get the result back, and makes plotting a Nanuq result a single call.

        This takes up the BACKLOG.md entry "Datamancer interop both ways" (Ecosystem).

        What Changes

        • New optional module nanuq/datamancer (it imports pkg/datamancer; Nanuq itself does not require Datamancer):
        • toDatamancer(df): datamancer.DataFrame copies every column. Integer columns become int columns, floats float, booleans bool, strings string. Any other dtype (dates, categoricals, …) becomes a string column formatted by Polars, as toSeq(…, string) does.
        • A column with nulls becomes a Datamancer object column whose missing entries are Datamancer's null values, so drop_null and toTensor(…, dropNulls = true) work on it. Null-free columns keep their native type.
        • fromDatamancer(dm): nanuq.DataFrame copies every column back: int to i64, float to f64, bool, string to str, constant columns repeated to the frame's length, and object columns holding one kind of value (plus nulls) to that dtype with nulls. Mixed object columns raise NanuqError.
        • Column order and names are kept both ways.
        • The "Plotting with ggplotnim" post uses toDatamancer instead of one toSeq per column, and keeps its explanation of what happens underneath.
        • CI installs Datamancer for the tests.

        Capabilities

        New Capabilities
        • datamancer-interop: converting DataFrames between Nanuq and Datamancer.
        Modified Capabilities

        None.

        Differences from Polars

        • Python has the same idea for pandas: df.to_pandas() and pl.from_pandas(pdf). Nanuq follows those names in camelCase, as a function in a separate module (Nim cannot add methods, and Datamancer stays optional, like pandas is for Polars).
        • Nulls. to_pandas turns nulls into NaN or None depending on the dtype; Nanuq uses Datamancer's null values in an object column, Datamancer's own way to mark missing data.
        • Rust has no equivalent.
        • Copies. Like to_pandas without pyarrow-backed columns, the data is copied.

        Impact

        • src/nanuq/datamancer.nim (new). No bridge change: it is built on toSeq and series, including their Option variants.
        • tests/test_datamancer.nim (new); .github/workflows/ci.yml installs Datamancer in the test job.
        • docs/blog/plotting_with_ggplotnim.nim, README (one line on the module).
        Spec changesdatamancer-interop +4

        datamancer-interop modified +4

        Purpose: Converting DataFrames between Nanuq and Datamancer (nanuq/datamancer), so Datamancer and ggplotnim code can use Polars for queries. Datamancer stays an optional dependency.

        ADDED
        To Datamancer

        toDatamancer SHALL copy every column, in order and with its name, into a Datamancer DataFrame: integers as int, floats as float, booleans as bool, strings as string, and any other dtype as string formatted by Polars.

        Scenario: Penguins without nulls
        • WHEN penguins().dropNulls().toDatamancer is called
        • THEN the result has 333 rows, the same column names in order, and body_mass_g is an int column
        ADDED
        Nulls to Datamancer

        A column with nulls SHALL become an object column whose missing entries are Datamancer null values and whose other entries hold the values.

        Scenario: Body mass with nulls
        • WHEN penguins().toDatamancer is called
        • THEN body_mass_g is an object column with 2 null values, and drop_null on it leaves 342 rows
        ADDED
        From Datamancer

        fromDatamancer SHALL copy every column back in order: int to i64, float to f64, bool to bool, string to str, constant columns repeated, and object columns of one value kind plus nulls to that dtype with nulls. Other object columns SHALL raise NanuqError.

        Scenario: Round trip
        • WHEN a Nanuq DataFrame is converted with toDatamancer and back with fromDatamancer
        • THEN it has the same shape, columns, dtypes (for i64, f64, bool, str) and null counts
        Scenario: Mixed object column
        • WHEN a Datamancer object column holds both an int and a string
        • THEN fromDatamancer raises NanuqError naming the column
        ADDED
        Optional dependency

        Importing nanuq SHALL NOT require Datamancer; only importing nanuq/datamancer does.

        Scenario: Without Datamancer
        • WHEN a program imports only nanuq on a machine without Datamancer
        • THEN it compiles
        Tasks6 of 6 done

        1. Module 3/3

        • 1.1Add src/nanuq/datamancer.nim (importing pkg/datamancer) with toDatamancer, using toSeq for null-free columns and Option reads for columns with nulls; verify with tests for dtypes, column order and nulls
        • 1.2Add fromDatamancer, handling int, float, bool, string, constant and object columns; verify with tests for a round trip and a mixed object column
        • 1.3Add tests/test_datamancer.nim to nimble test and install Datamancer in the CI test job; verify nimble test passes, and that the other tests still compile without Datamancer installed

        2. Docs 3/3

        • 2.1Rewrite the conversion in "Plotting with ggplotnim" with toDatamancer (keeping the explanation of the copy and of nulls); verify the post renders and republish its artifact
        • 2.2Mention nanuq/datamancer in the README
        • 2.3Check CI is green on the PR

        Workflow follow-up 0/0

          Revisions1 revision
          r1 ed08e02 2026-10-28 Archive the dev-log index, HTML tables and Datamancer interop changes

          First version: .openspec.yaml, proposal.md, specs/datamancer-interop/spec.md, tasks.md

          add-datatype-and-cast Archived

          created 2026-10-31 · openspec/changes/archive/2026-10-31-add-datatype-and-cast
          1. Proposal
          2. Specs
          3. Design
          4. Tasks
          5. Implement 10/10
          6. Archive
          Proposal

          Why

          Nanuq has no Nim-side notion of a data type. dtype(df, col) returns Polars' display string ("i64", "str"), so code has to compare strings, and nothing can ask Polars to convert a column. Several parts of the 0.2 plan need a real type value first: cast, dtype column selectors, and CSV schema overrides. This change adds that type value, schemas, and casting, so the other 0.2 changes can build on it.

          This change takes up the casting part of the BACKLOG.md entry "More expressions" (API). The rest of that entry stays in the backlog. It is the first change of the 0.2 release (see the Polars coverage map, areas "Data types" and "Casting and types").

          What Changes

          • New DataType value with a kind (DataTypeKind) covering Polars' primitive dtypes: Boolean, Int8, Int16, Int32, Int64, UInt8, UInt16, UInt32, UInt64, Float32, Float64, String and Null. Dtypes Nanuq does not model yet (Date, List, Categorical, ...) come back as kind dkOther and keep Polars' name.
          • Constants named as in Polars: Boolean, Int8 ... UInt64, Float32, Float64, String, Null. $ gives Polars' short name ("i64"), as today.
          • Predicates isInteger, isSignedInteger, isUnsignedInteger, isFloat, isNumeric.
          • BREAKING: dtype(df, col) returns a DataType instead of a string. Code that compares with strings (df.dtype("a") == "i64") must compare with constants (== Int64) or use $.
          • New schema(df) and collectSchema(lf): the column names and types, in order, as a Schema (an OrderedTable[string, DataType]). New dtypes(df).
          • New cast, strict = true by default. The target is a Nim type where one is enough: col("a").cast(int32), df.cast(float64) (all columns). Named columns of a frame take DataType values, since a list can't hold different typedescs: df.cast({"a": Int32, "b": Float32}). Every form also accepts a DataType.
          • New dataType(T) maps a Nim type to its DataType: int8 .. int64, uint8 .. uint64, float32, float64, bool, string; int and float map to Int64 and Float64, matching how series builds them.
          • The C ABI version moves to 0.2.0-dev. Until lib-v0.2.0 is released, building from a checkout compiles the Rust library from source (prebuilt archives are only fetched for released versions).

          Capabilities

          New Capabilities
          • data-types: the DataType value, schemas, and casting.
          Modified Capabilities
          • native-bridge: the enums that must keep the same order in Rust and ffi.nim now include NqDtype.

          Differences from Polars

          Expected differences from Polars' Rust and Python APIs:

          • One value type, not a class hierarchy. Python has classes (pl.Int64, pl.Datetime("ms")) under pl.DataType; Rust has the DataType enum with data in some variants. Nim gets an object variant with a kind enum, which can grow parameters (time unit, inner type) later. The constants keep Polars' names, so df.cast({"a": Int32}) reads like Python.
          • Nim types as cast targets. Polars only takes its own dtypes. Nanuq also takes Nim types (col("a").cast(int32)), like toSeq(df, "a", int) does for reads. dtype and schema still return DataType values: a Nim type can't be returned at run time.
          • Unmodelled dtypes. Polars knows every dtype. Nanuq maps the ones it does not model yet to dkOther with Polars' name, and refuses to cast to them.
          • No 128-bit integers, no Decimal. Int128, UInt128 and Decimal are left out (they need extra Polars features); they would read as dkOther.
          • $ is Polars' short name. Python prints Int64; Rust's Display prints i64. Nanuq follows Rust, which is also what the table header shows in both. Nim names (int64, string) were considered and dropped: $df is rendered by Polars, so the tables would disagree with $ or need their dtype row rewritten.
          • Schema type. Python's pl.Schema is an ordered mapping; Nanuq uses Nim's OrderedTable[string, DataType]. Python's df.schema is a property; in Nim it is a proc, df.schema reads the same.
          • cast is a Nim keyword. Method-call syntax works (col("a").cast(int32), df.cast(float64)), but the prefix form needs backticks: cast(col("a"), int32) .
          • Frame cast arguments. Python's df.cast({"a": pl.Int32}) takes a dict; Nim takes an openArray[(string, DataType)], written with the same braces: df.cast({"a": Int32}).
          • Strict default. Like Python and Rust's strict_cast, cast fails when a value can't be converted; strict = false turns those values into nulls, like Polars.
          • No builders for other widths. series still builds int64, float64, bool and string columns; other widths come from cast. Reading any integer column as int and any numeric column as float works as today.
          • Names follow Polars in camelCase: collect_schema → collectSchema, is_integer → isInteger, is_signed_integer → isSignedInteger, is_unsigned_integer → isUnsignedInteger, is_float → isFloat, is_numeric → isNumeric.

          Impact

          • src/rust/src/lib.rs: a #[repr(C)] NqDtype enum, nq_df_column_dtype_kind, nq_lf_collect_schema (an empty DataFrame carrying the schema), nq_expr_cast, nq_lf_cast. nq_df_column_dtype (the string) stays and names dkOther dtypes. Cargo.toml adds Polars features dtype-i8, dtype-i16, dtype-u8, dtype-u16 and moves to version 0.2.0-dev. The Rust library is rebuilt, so the first CI run takes about 10 minutes.
          • src/nanuq/ffi.nim, src/nanuq.nim: the matching declarations and API; imports std/tables.
          • src/nanuq/datamancer.nim and the HTML table switch from dtype strings to DataType.
          • tests/: dtype string comparisons become constant comparisons; new tests for schemas and casts. The dev-log post "How Nanuq works" still prints dtype with echo, so its output is unchanged.
          • README.md: the API list mentions schema and cast.
          Spec changesdata-types +4 · native-bridge ~1

          data-types modified +4

          ADDED
          DataType values

          The API SHALL provide a DataType value with a kind of type DataTypeKind covering Boolean, Int8, Int16, Int32, Int64, UInt8, UInt16, UInt32, UInt64, Float32, Float64, String and Null, plus dkOther carrying Polars' name for any other dtype. It SHALL export constants with Polars' names (Int64, String, ...), ==, $ returning Polars' short name, and the predicates isInteger, isSignedInteger, isUnsignedInteger, isFloat and isNumeric. dtype(df, col) SHALL return a DataType.

          Scenario: Column dtype
          • WHEN a DataFrame is built from a Nim seq[int] column a
          • THEN df.dtype("a") == Int64 and $df.dtype("a") == "i64"
          Scenario: Unmodelled dtype
          • WHEN a column has a dtype Nanuq does not model
          • THEN its kind is dkOther and $ returns Polars' name for it
          Scenario: Predicates
          • WHEN isNumeric is called on UInt8, Float32 and String
          • THEN it returns true, true and false
          ADDED
          Schemas

          The API SHALL return the column names and dtypes of a DataFrame (schema) and of a LazyFrame without collecting it (collectSchema) as a Schema, an OrderedTable[string, DataType] in column order, and the dtypes alone with dtypes.

          Scenario: Schema in column order
          • WHEN schema is called on a DataFrame with columns a (i64) and b (str)
          • THEN the keys are a, b in that order and the values are Int64, String
          Scenario: Lazy schema
          • WHEN collectSchema is called on a LazyFrame that adds (col("a") * 1.5).alias("c")
          • THEN the schema has c with Float64, and the query is not executed
          ADDED
          Casting

          The API SHALL cast expressions (e.cast(target, strict = true)), all columns of a DataFrame or LazyFrame (cast(target, strict = true)), where target is a Nim type or a DataType, and named columns (cast({"a": Int32}, strict = true)) with DataType values. A strict cast SHALL raise NanuqError (when the query runs) if a value cannot be converted; a non-strict cast SHALL turn such values into nulls. Casting to a dkOther dtype SHALL raise NanuqError.

          Scenario: Narrow an integer column
          • WHEN df.cast({"a": Int32}) runs on an i64 column
          • THEN dtype("a") == Int32 and toSeq(df, "a", int) returns the same values
          Scenario: Nim type as target
          • WHEN col("a").cast(float32) is selected from an i64 column
          • THEN the result column has dtype Float32
          Scenario: Strict failure
          • WHEN a string column holding "1" and "x" is cast to Int64 with strict = true
          • THEN NanuqError is raised
          Scenario: Non-strict cast
          • WHEN the same column is cast with strict = false
          • THEN the result is 1 and null
          ADDED
          Nim types map to DataType

          dataType(T) SHALL map int8 to int64, uint8 to uint64, float32, float64, bool and string to their dtypes, int to Int64 and float to Float64. Other types SHALL not compile.

          Scenario: Platform int
          • WHEN dataType(int) is evaluated
          • THEN it equals Int64, the dtype series builds from seq[int]
          Scenario: Unsupported type
          • WHEN col("a").cast(seq[int]) is compiled
          • THEN compilation fails

          Unchanged in this spec: DataType constants and predicates, Full-range UInt64

          native-bridge modified ~1

          MODIFIED
          Nim declarations mirror the C ABI
          `src/nanuq/ffi.nim` SHALL declare every exported function with matching signatures, and the enums `NqBinOp`, `NqUnary`,`NqUnary` `NqDtype`,and `NqDtypeClass`,`NqDtype` `NqJoinType`, `NqJoinValidation`, `NqMaintainOrderJoin`, `NqConcat`, `NqUniqueKeepStrategy`, `NqClosedInterval`, `NqQuantileMethod`, `NqFillNullStrategy`, `NqRoundMode`, `NqQuoteStyle`, `NqRankMethod`, `NqErrorKind`, `NqStrOp`, `NqTimeUnit`, `NqClosedWindow`, `NqDtOp`, `NqCatOp`, `NqParquetCompression` and `NqIpcCompression` SHALL keep the same order as in Rust. `NqDtype` SHALL also keep the order of `DataTypeKind`, and`DataTypeKind` the option enumsin the order of their Nim API enums. Data types SHALL cross the ABI as an `NqDtypeSpec` struct (code, time unit, time zone, categories) with the same field order on both sides.API. Scenario: ABI change - **WHEN** a function is added or changed in `rust/src/lib.rs` - **THEN** `src/nanuq/ffi.nim` is updated in the same change

          Unchanged in this spec: C ABI over Polars with opaque handles, Errors and panics never cross the boundary, Linking the static library, Columns cross in bulk, Library version check, Formatted cells, Polars version matches a py-polars release

          Design

          Design

          Context

          nq_df_column_dtype returns col.dtype().to_string(). Nim exposes it as dtype(df, col): string, and datamancer.nim, the HTML table and the tests compare those strings. Expressions cross the C ABI as opaque Expr pointers, and enums (NqBinOp, NqUnary) as #[repr(C)] integers mirrored in ffi.nim. Polars is built with default-features = false and lazy, csv, fmt, so only 32 and 64 bit integers are compiled in.

          Goals / Non-Goals

          Goals:

          • A Nim type value that the rest of 0.2 (selectors, CSV schema overrides) can pass through the ABI.
          • Room to add parameterized dtypes (Datetime with unit and zone, List with an inner type) in 0.3 and later without breaking user code.
          • cast on expressions and frames with Polars' strict semantics.

          Non-Goals:

          • Temporal, nested, categorical and decimal dtypes (0.3 and 0.5 in the coverage map).
          • Building or reading columns in widths other than int64 / float64 (use cast).
          • Dtype selectors (cs.numeric()): they come with the column selectors change.

          Decisions

          DataType is an object variant with a kind enum
          type
            DataTypeKind* = enum
              dkBoolean, dkInt8, dkInt16, dkInt32, dkInt64, dkUInt8, dkUInt16, dkUInt32,
              dkUInt64, dkFloat32, dkFloat64, dkString, dkNull, dkOther
            DataType* = object
              case kind*: DataTypeKind
              of dkOther: name*: string   # Polars' name, e.g. "date", "list[i64]"
              else: discard
          
          const Int64* = DataType(kind: dkInt64)   # and so on for each primitive kind

          == compares kinds (and the name for dkOther). $ returns Polars' short name.

          • Why: Polars' Rust DataType is an enum with data in some variants; an object variant is the Nim equivalent, and later kinds (dkDatetime with unit and zone, dkList with an inner: ref DataType) are added as new branches without changing existing code.
          • Alternative: a plain enum DataType. Simplest today, but turning it into an object for Datetime or List would break every user of it.
          • Alternative: a ref object hierarchy like Python's classes. More allocation and of checks, with no gain over a variant.
          • Constants use Polars' names (Int64, String). They are exported from nanuq; a clash with a user symbol is resolved by qualifying, e.g. nanuq.String.
          Dtypes cross the ABI as a code

          #[repr(C)] enum NqDtype { Boolean = 0, Int8, ..., Null, Other }, mirrored in ffi.nim in the same order as DataTypeKind. nq_df_column_dtype_kind(df, name) -> i32 returns the code (or -1 on error). For Other, Nim also calls the existing nq_df_column_dtype for the name. Casting passes a code; Other is rejected in Nim before any call.

          • Why: fits the existing enum style, and a code is enough until dtypes have parameters. A parameterized dtype will need a small struct or a string form (Polars can parse dtype strings); that is decided when the first one arrives.
          Schemas reuse DataFrame accessors

          schema(df) loops over columns(df) and asks each dtype (one call per column, not per row). collectSchema(lf) calls nq_lf_collect_schema, which resolves the plan's schema (LazyFrame::collect_schema) and returns DataFrame::empty_with_schema; Nim then reads it with schema. Nothing is computed beyond schema resolution.

          • Why: no new type to free and no array-of-structs across the boundary.
          Cast functions
          • nq_expr_cast(e, code, strict: bool) -> *mut Expr uses strict_cast or cast with non-strict options in Polars 0.55.
          • nq_lf_cast(lf, names, codes, n, strict) -> *mut LazyFrame casts the named columns (LazyFrame::cast with a map). Casting all columns is done in Nim as cast(all columns) by passing every name from the schema, so one Rust function covers both forms. DataFrame versions are eager shortcuts over the lazy one, as for the other verbs.
          • Nim names: cast (a keyword, usable with method-call syntax, see the proposal).
          Nim types as cast targets

          cast has a typedesc overload next to the DataType one:

          proc cast*(e: Expr, T: typedesc, strict = true): Expr = e.cast(dataType(T), strict)

          dataType(T) is resolved at compile time (when T is int8: Int8 ...), and an unsupported type (an object, seq) is a compile error. Named frame casts stay on DataType ({"a": Int32}), because an openArray needs one element type and typedescs exist only at compile time; dataType(int32) gives the same value.

          • Why: reads already take Nim types (toSeq(df, "a", int)), so writes and casts should too; the Polars names stay available for run-time values.
          • Later: seq[T] can map to List and DateTime to Datetime, with a DataType for the cases a Nim type can't express (time unit, time zone).
          ABI version during 0.2

          Cargo.toml moves to 0.2.0-dev with this change. ffi.nim already treats -dev versions as development builds (no prebuilt download; local or cargo build). The other 0.2 changes keep 0.2.0-dev, and lib-v0.2.0 is released once, when 0.2 is complete, so there is one release cycle for the whole slice instead of one per change.

          Risks / Trade-offs

          • Breaking dtype. Comparisons with strings stop compiling (a DataType is not a string), which is loud rather than silent. Nanuq is pre-1.0 with no known users outside the repo; the CHANGELOG calls it out.
          • Binary size. Four small dtype features add a little code to an already large static library. Accepted.
          • Constant names may shadow. String, Boolean, Null are common words. Nim is case-sensitive on the first letter, so they do not clash with string or bool.
          Tasks10 of 10 done

          1. Bridge 3/3

          • 1.1Move src/rust/Cargo.toml to version 0.2.0-dev and add Polars features dtype-i8, dtype-i16, dtype-u8, dtype-u16; verify cargo build --release passes and ffi.nim falls back to the local build
          • 1.2Add #[repr(C)] NqDtype with conversions to and from Polars DataType, and nq_df_column_dtype_kind; mirror both in ffi.nim
          • 1.3Add nq_lf_collect_schema (empty DataFrame with the resolved schema), nq_expr_cast and nq_lf_cast (strict flag); mirror them in ffi.nim; verify cargo build --release passes

          2. Nim API 5/5

          • 2.1Add DataTypeKind, DataType, the constants, ==, $ and the predicates; verify with unit tests that need no DataFrame
          • 2.2Change dtype(df, col) to return DataType (name lookup for dkOther); update datamancer.nim, the HTML table and the tests that compare dtype strings; verify nimble test passes
          • 2.3Add Schema, schema(df), dtypes(df) and collectSchema(lf); verify column order and that a lazy schema does not execute the query
          • 2.4Add dataType(T) for the supported Nim types; verify the mapping, and with a compile-time check that an unsupported type does not compile
          • 2.5Add cast on Expr, and on LazyFrame and DataFrame for all columns (Nim type or DataType) and for named columns (DataType); verify narrowing, a Nim-type target, strict failure, non-strict nulls and the dkOther error

          3. Docs and integration 2/2

          • 3.1Update README "What is there" with DataType, schema and cast; verify nimble example passes and the dev-log post output is unchanged
          • 3.2Check that CI is green on the PR, including the one-off Rust rebuild

          Workflow follow-up 0/0

            Revisions2 revisions
            r1 e7c3da0 2026-10-31 Archive add-datatype-and-cast; BACKLOG and CHANGELOG

            First version: .openspec.yaml, design.md, proposal.md, specs/data-types/spec.md, specs/native-bridge/spec.md, tasks.md

            r2 f2217bf 2026-10-31 add-datatype-and-cast: CI green, tick task 3.2
            tasks.md
            § 3. Docs and integration
            - [x] 3.1 Update README "What is there" with `DataType`, `schema` and `cast`; verify `nimble example` passes and the dev-log post output is unchanged - [ ][x] 3.2 Check that CI is green on the PR, including the one-off Rust rebuild

            add-devlog-index Archived

            created 2026-10-28 · openspec/changes/archive/2026-10-28-add-devlog-index
            1. Proposal
            2. Specs
            3. Tasks
            4. Implement 7/7
            5. Archive
            Proposal

            Why

            The GitHub Pages root redirects to the latest dev-log post, so the other posts can only be found through the README. There are three posts now and more will follow.

            This takes up the BACKLOG.md entry "Blog index page" (Docs).

            What Changes

            • New nimib page docs/index.nim, rendered to the site root with the Nanuq theme. It lists every post in docs/blog, newest first, with its date, title and a one-line summary, each linking to the post.
            • The index is built from the rendered posts, so a new post needs no edit to the index: the date and link come from the post's dated file name (2026-10-27-…html), the title from its <title>, and the summary from a <meta name="description"> that the theme writes.
            • useNanuqTheme gets a summary parameter for that meta tag. The three existing posts get a summary.
            • CI renders the posts, then the index, and publishes the index as the site root instead of the redirect. Posts keep their URLs under blog/.
            • The README points to the index as well as the posts.

            Capabilities

            New Capabilities
            • dev-log: how the dev log is organised and published (posts, index, theme).
            Modified Capabilities
            • ci: the site root is the index instead of a redirect.

            Differences from Polars

            None: this is about Nanuq's own docs site, not the Polars API.

            Impact

            • docs/index.nim (new), docs/nanuqtheme.nim, the three posts in docs/blog/.
            • .github/workflows/ci.yml (docs job), README.md.
            • No library code changes.
            Spec changesci ~1 · dev-log +2

            ci modified ~1

            MODIFIED
            Tests, example and dev log
            CI SHALL run the test suite, whichsuite includes the spec examples, as one program (`tests/all.nim`), and the example, and render the site as one program (`docs/all.nim`): the nimib dev-log posts in `docs/blog` `docs/blog`,and then the index page `docs/index.nim` and`docs/index.nim`. the living pages (the Polars coverage page and the OpenSpec page). On `main`, after these succeed, it SHALL deploy the posts and the themindex to GitHub Pages, with the index as the site root. Scenario: Merge to main - **WHEN** a commit lands on `main` and the test and docs jobs pass - **THEN** the dev log and the living pages areis deployed to GitHub Pages, and the site root lists the posts Scenario: Stale spec example - **WHEN** a pull request changes behavior that a spec example shows - **THEN** the test job fails until the example's output is updated Scenario: New test file - **WHEN** a pull request adds `tests/test_x.nim` - **THEN** the test job runs it as part of `tests/all.nim`, with no list to update

            Unchanged in this spec: Build Rust only when the crate changes, Skip CI for non-code changes, Lib version follows the crate sources, Fast linking

            dev-log modified +2

            Purpose: The Nanuq dev log: dated nimib posts in docs/blog, an index page, and the Nanuq theme they share. It is published with GitHub Pages and is separate from the official documentation that will come later.

            ADDED
            Index of posts

            The site root SHALL be an index page listing every rendered post in docs/blog, newest first, each with its date, title, one-line summary and a link to the post. Adding a post SHALL NOT require editing the index.

            Scenario: New post
            • WHEN a post docs/blog/x.nim writing 2026-11-02-x.html is added and CI renders the site
            • THEN the index lists it first, dated 2 November 2026, with its title and summary
            Scenario: Post without a summary
            • WHEN a post does not set a summary
            • THEN the index still lists it, with date and title only
            ADDED
            Dated post files

            Each post SHALL render to a file in docs/blog named YYYY-MM-DD-<slug>.html, and its URL SHALL stay the same once published.

            Scenario: Existing links
            • WHEN the index is introduced
            • THEN the existing post URLs under blog/ keep working

            Unchanged in this spec: Polars coverage page, OpenSpec page, Review mode, Source files

            Tasks7 of 7 done

            1. Theme and posts 2/2

            • 1.1Add a summary parameter (default empty) to useNanuqTheme that writes <meta name="description">; verify a post renders with the tag
            • 1.2Give the three posts a one-line summary; verify each renders

            2. Index page 2/2

            • 2.1Add docs/index.nim: scan docs/blog/*.html, read date and slug from the file name, title from <title>, summary from the meta tag; render a newest-first list with the Nanuq theme to docs/index.html; verify locally after rendering the posts
            • 2.2Check the index at phone width and in dark mode

            3. CI and README 3/3

            • 3.1In the docs job, render the index after the posts and publish it as _site/index.html, with relative links into blog/; drop the redirect; verify the uploaded Pages artifact on the PR
            • 3.2Point the README's Documentation section to the index; verify the links
            • 3.3Check CI is green on the PR

            Workflow follow-up 0/0

              Revisions1 revision
              r1 ed08e02 2026-10-28 Archive the dev-log index, HTML tables and Datamancer interop changes

              First version: .openspec.yaml, proposal.md, specs/ci/spec.md, specs/dev-log/spec.md, tasks.md

              add-dynamic-group-by Archived

              openspec/changes/archive/2026-11-01-add-dynamic-group-by
              1. Proposal
              2. Specs
              3. Tasks
              4. Implement 4/4
              5. Archive
              Proposal

              Why

              Time series are grouped by calendar windows (monthly totals, weekly means, the three months around each month) and matched by nearest time (the reading at or before each event). Polars does this with group_by_dynamic, rolling and join_asof. Without them a Nanuq user has to truncate dates and join on them, which can't express overlapping windows or "the last value before". The O'Reilly chapters 1 and 13 and the user guide's time-series pages stop on group_by_dynamic (4 sections), and the 0.4 explainer needs joinAsof to line up El Niño seasons with monthly temperatures.

              It is the seventh change of the 0.4 release.

              What Changes

              • groupByDynamic(indexColumn, every, period, offset, includeBoundaries, closed, label, groupBy, startBy) on DataFrame and LazyFrame, followed by agg. Label and StartBy are pure enums; intervals are std/times intervals or Polars duration strings.
              • rolling(indexColumn, period, offset, closed, groupBy), the rolling group-by: one window per row, followed by agg.
              • joinAsof(other, on | leftOn + rightOn, by | byLeft + byRight, strategy, suffix, tolerance, allowExactMatches, checkSortedness, coalesce) with an AsofStrategy pure enum (Backward, Forward, Nearest) and a tolerance given as an interval or a number.
              • Small parameter types with converters, so that optional parameters accept several types: OptInterval (interval or string), JoinKey (name or expression), AsofTolerance (interval, string or number).

              Capabilities

              New Capabilities
              • temporal-grouping: dynamic and rolling group-by, as-of joins.

              Differences from Polars

              • groupBy inside groupByDynamic and rolling takes expressions (groupBy = [col.site]); Python also takes names.
              • joinAsof's on, leftOn and rightOn take one key each, as in Python.
              • rolling on a frame is the rolling group-by, as in Python; the rolling expression functions are rollingMean and friends.

              Impact

              • src/rust/src/lib.rs: nq_lf_group_by_dynamic_agg, nq_lf_rolling_agg, nq_lf_join_asof; src/nanuq/ffi.nim; src/nanuq.nim (LazyGroupBy gains the window options).
              • New tests/test_timegroups.nim.
              Spec changestemporal-grouping +3

              temporal-grouping modified +3

              ADDED
              Dynamic group-by

              groupByDynamic(indexColumn, every, period, offset, ...) on a DataFrame or LazyFrame SHALL group the rows of the sorted indexColumn into windows that start every every, span period (default every) and are shifted by offset, labelled as label says, and agg SHALL aggregate each window. Intervals SHALL be std/times intervals or Polars duration strings; groupBy SHALL group within the windows.

              let df = newDataFrame:
                day: [date(2026, 1, 1), date(2026, 1, 20), date(2026, 2, 3), date(2026, 3, 30)]
                rain: [12, 3, 40, 7]
              echo df.groupByDynamic("day", every = 1.months).agg(col.rain.sum).collect
              TBD
              Scenario: Overlapping windows
              • WHEN groupByDynamic("day", every = 1.months, period = 3.months) aggregates monthly rows
              • THEN each window sums three months of rows
              Scenario: Boundaries
              • WHEN includeBoundaries = true
              • THEN the result has _lower_boundary and _upper_boundary columns
              ADDED
              Rolling group-by

              rolling(indexColumn, period, offset, closed = Right, groupBy) SHALL make one group per row, holding the rows whose indexColumn lies in the period up to that row's value (shifted by offset), and agg SHALL aggregate each group.

              let df = newDataFrame:
                day: [date(2026, 7, 1), date(2026, 7, 2), date(2026, 7, 5)]
                rain: [4, 0, 10]
              echo df.rolling("day", period = 3.days).agg(col.rain.sum.alias("rain_3d")).collect
              TBD
              Scenario: Gap in the dates
              • WHEN rows on July 1, 2 and 5 are grouped with period = 3.days
              • THEN the July 5 group holds only the July 5 row
              ADDED
              As-of join

              joinAsof(other, on, ...) (or leftOn and rightOn) SHALL join each left row to one right row by a sorted key: the last one at or before it (Backward), the first one at or after it (Forward) or the closest (Nearest), only within tolerance when given and only among rows with equal by columns; rows without a match SHALL get nulls.

              let events = newDataFrame:
                day: [date(2026, 1, 15), date(2026, 3, 2)]
                event: ["flood", "drought"]
              let oni = newDataFrame:
                month: [date(2026, 1, 1), date(2026, 2, 1), date(2026, 3, 1)]
                oni: [1.8, 1.5, 1.1]
              echo events.joinAsof(oni, leftOn = "day", rightOn = "month")
              TBD
              Scenario: Tolerance
              • WHEN the nearest earlier right row is 2 days before and tolerance = 1.days
              • THEN the left row gets nulls
              Scenario: Missing keys
              • WHEN joinAsof is called without on and without leftOn and rightOn
              • THEN ValueError is raised

              Unchanged in this spec: Group keys by name

              Tasks4 of 4 done

              1. Implementation 4/4

              • 1.1groupByDynamic with Label, StartBy, intervals
              • 1.2rolling group-by
              • 1.3joinAsof with AsofStrategy, by, tolerance
              • 1.4Tests in tests/test_timegroups.nim; nimble test and nimble specexamples pass; CHANGELOG
              Revisions1 revision
              r1 570d956 2026-11-01 Nanuq 0.4, changes 1-7: math, cumulative, rolling, value functions, horizontal, reshaping, time grouping

              First version: proposal.md, specs/temporal-grouping/spec.md, tasks.md

              add-excel-io Archived

              openspec/changes/archive/2026-11-01-add-excel-io
              1. Proposal
              2. Specs
              3. Tasks
              4. Implement 3/3
              5. Archive
              Proposal

              Why

              Excel is how much tabular data arrives: the 0.6 book map counts 9 sections that need read_excel/write_excel (user guide io/excel, O'Reilly ch6 and ch13, Packt ch2), and BACKLOG.md "More IO" lists Excel. Rust Polars has no Excel support, so the crate adds two pure-Rust crates, compiled into the same static library as Polars: calamine to read and rust_xlsxwriter to write. Nothing outside the library is needed at run time.

              It is the sixth change of the 0.6 release (the fifth, a formula macro, was dropped). It takes the Excel part of the BACKLOG.md entry "More IO".

              What Changes

              • readExcel(path, sheetName, sheetId = 1, hasHeader, skipRows, columns, schemaOverrides): one sheet of an .xlsx, .xlsm, .xlsb, .xls or .ods file, with column types inferred from the cells (Boolean, Int64, Float64, Date, Datetime[ms], String).
              • readExcelSheets(path): every sheet, by name.
              • writeExcel(df, path, worksheet = "Sheet1", includeHeader, autofit, floatPrecision): one worksheet in a new .xlsx file.

              Capabilities

              New Capabilities
              • excel-io: reading and writing Excel workbooks.

              Differences from Polars

              • Python picks an engine (calamine through the Python package fastexcel by default, openpyxl, xlsx2csv) and writes through the Python package xlsxwriter. Nanuq has one built-in reader (the calamine crate) and one writer (the rust_xlsxwriter crate).
              • read_options={"skip_rows": n} and has_header become skipRows and hasHeader parameters; there is no engine_options, infer_schema_length or drop_empty_rows.
              • sheet_id = 0 (all sheets as a dict) is readExcelSheets; sheet_name as a list is not supported.
              • write_excel writes a plain sheet: header in bold, numbers, booleans, dates and datetimes as Excel values, everything else as text. Python's table styles, conditional formats, sparklines, formulas, column widths and positions are left out, as is writing into an existing workbook.
              • Date cells at midnight read as Date, other date-times as Datetime[ms]; Python's fastexcel follows the cell format instead.

              Impact

              • src/rust/Cargo.toml: calamine (feature dates), rust_xlsxwriter, chrono. The static library and the release archives grow by a few MB.
              • src/rust/src/lib.rs, src/nanuq/ffi.nim: nq_read_excel, nq_excel_sheet_names, nq_write_excel.
              • New tests/test_excel.nim.
              Spec changesexcel-io +2

              excel-io modified +2

              ADDED
              Writing Excel

              writeExcel(df, path, worksheet = "Sheet1", includeHeader = true, autofit = false, floatPrecision = none(int)) SHALL write the frame to one worksheet of a new .xlsx file: a header row, then numbers, booleans, dates and datetimes as Excel values and other values as text; nulls SHALL be empty cells.

              let path = getTempDir() / "bears.xlsx"
              let df = newDataFrame(series("bear", @["Ada", "Bo"]), series("kg", @[410.5, 380.0]),
                                    series("seen", @[date(2024, 3, 1), date(2024, 3, 9)]))
              df.writeExcel(path, worksheet = "census")
              echo fileExists(path)
              TBD
              Scenario: Missing directory
              • WHEN the target directory does not exist
              • THEN IOError is raised
              ADDED
              Reading Excel

              readExcel(path, sheetName = "", sheetId = 1, hasHeader = true, skipRows = 0, columns = [], schemaOverrides = []) SHALL read one sheet (by name, else by position from 1) of an .xlsx, .xlsm, .xlsb, .xls or .ods file. Column types SHALL be inferred from the cells: Boolean, Int64 for whole numbers, Float64, Date for dates at midnight, Datetime[ms], else String; schemaOverrides SHALL cast columns and columns keep only those. readExcelSheets(path) SHALL read every sheet into a table by sheet name.

              let path = getTempDir() / "bears.xlsx"
              newDataFrame(series("bear", @["Ada", "Bo"]), series("kg", @[410, 380]),
                           series("seen", @[date(2024, 3, 1), date(2024, 3, 9)])).writeExcel(path, worksheet = "census")
              echo readExcel(path)
              echo readExcel(path, sheetName = "census", skipRows = 1, hasHeader = false)
              echo readExcelSheets(path).len
              TBD
              Scenario: Missing sheet
              • WHEN readExcel(path, sheetName = "nope") is called
              • THEN IOError is raised
              Scenario: Round trip
              • WHEN a frame of strings, integers, floats, booleans and dates is written and read back
              • THEN the result equals the frame

              Unchanged in this spec: Reading OpenDocument

              Tasks3 of 3 done

              1. Implementation 3/3

              • 1.1Crate: calamine reader with type inference, rust_xlsxwriter writer, sheet names
              • 1.2readExcel, readExcelSheets, writeExcel
              • 1.3Tests in tests/test_excel.nim; nimble test and nimble specexamples pass; CHANGELOG; BACKLOG "More IO" updated
              Revisions1 revision
              r1 4ea5dad 2026-11-01 0.6: archive the 9 changes, fill spec example outputs, map_elements benchmark, dev log Designing Nanuq 0.6

              First version: proposal.md, specs/excel-io/spec.md, tasks.md

              add-explainer-needs-0-5 Archived

              openspec/changes/archive/2026-11-01-add-explainer-needs-0-5
              1. Proposal
              2. Specs
              3. Tasks
              4. Implement 4/4
              5. Archive
              Proposal

              Why

              Porting the 0.5 explainer "Above 4000" from Python to Nim (all 30 cells match py-polars) needed three workarounds: there is no frame-level fillNull(value) (df.fill_null(0)), frame filter takes one predicate where Python takes several, and groupBy has no maintainOrder parameter.

              It is the twelfth change of the 0.5 release (#53).

              What Changes

              • fillNull(value) and fillNull(strategy) on DataFrame and LazyFrame. A number fills the numeric columns (a float makes integer columns Float64), a string the String columns, a bool the Boolean ones, as Python's matches_supertype=True default does.
              • filter(a, b, ...) on frames with several predicates, joined with and.
              • groupBy(..., maintainOrder = ...) accepted for parity; Nanuq always keeps the first-seen group order.

              Capabilities

              Modified Capabilities
              • missing-values: frame-level null filling.
              • frame-verbs: several filter predicates; maintainOrder on groupBy.

              Differences from Polars

              • maintainOrder = false still keeps the order (Nanuq groups are always ordered).
              • No matchesSupertype = false option.

              Impact

              • src/nanuq.nim only. Tests in tests/test_nulls.nim and tests/test_verbs.nim.
              Spec changesframe-verbs +2 · missing-values +1

              frame-verbs modified +2

              ADDED
              Several filter predicates

              DataFrame and LazyFrame filter SHALL take several predicates, filter(a, b, ...), keeping the rows where all of them hold (Python's filter(a, b)).

              let df = newDataFrame:
                peak: ["Mont Blanc", "Monte Rosa", "Gran Paradiso"]
                m: [4806, 4634, 4061]
                italy: [true, true, true]
              echo df.filter(col.m > 4500, col.italy)
              Scenario: All must hold
              • WHEN a row meets one predicate but not the other
              • THEN it is dropped
              ADDED
              Group order parameter

              groupBy on DataFrame and LazyFrame SHALL accept maintainOrder (Python's maintain_order), with names or expressions; the groups SHALL keep the order their keys first appear whatever its value.

              let df = newDataFrame:
                country: ["CH", "IT", "CH"]
                m: [4634, 4061, 4506]
              echo df.groupBy("country", maintainOrder = true).agg(col.m.max)
              Scenario: Order kept
              • WHEN keys appear as CH, IT, CH and maintainOrder = false is passed
              • THEN the groups come out as CH, IT

              Unchanged in this spec: Dropping and renaming columns, Row windows, Unique rows, Row index, Sorting by several keys, Sampling rows, Every n-th row, Frame interpolation, Casting by data type, Frame aggregations, Group-by shortcuts, Iterating over groups, Frame fillNan and select without a frame

              missing-values modified +1

              ADDED
              Filling nulls in whole frames

              DataFrame and LazyFrame SHALL support fillNull(value), filling the columns the value fits (a number: numeric columns, where a float turns integer columns into Float64; a string: String columns; a bool: Boolean columns), and fillNull(strategy, limit) on every column (Python's df.fill_null).

              let df = newDataFrame:
                peak: ["Dom", "Täschhorn"]
                m: [some(4545), none(int)]
                first_ascent: [some(1858), none(int)]
              echo df.fillNull(0)
              Scenario: Float value
              • WHEN fillNull(0.5) runs on a frame with an Int64 column with nulls
              • THEN that column becomes Float64 and its nulls hold 0.5
              Scenario: String value
              • WHEN fillNull("x") runs on a frame with Int64 and String columns
              • THEN only the String column is filled

              Unchanged in this spec: Nulls are read as Option, Plain reads refuse nulls, Inspecting nulls, Building columns with nulls, CSV null markers, Null expressions, Dropping rows with nulls, Interpolation, Null literal

              Tasks4 of 4 done

              1. Implementation 4/4

              • 1.1Frame fillNull(value) and fillNull(strategy)
              • 1.2Frame filter(a, b, ...)
              • 1.3groupBy(..., maintainOrder)
              • 1.4Tests
              Revisions1 revision
              r1 72a6989 2026-11-01 0.5: explainer needs (add-explainer-needs-0-5)

              First version: proposal.md, specs/frame-verbs/spec.md, specs/missing-values/spec.md, tasks.md

              add-explainer-needs-0-6 Archived

              openspec/changes/archive/2026-11-01-add-explainer-needs-0-6
              1. Proposal
              2. Specs
              3. Tasks
              4. Implement 3/3
              5. Archive
              Proposal

              Why

              The 0.6 explainer ("Move 37", go games) stores moves as Binary values, hashes board positions with 64-bit Zobrist keys, and reads raw lines from text files. Its Python draft (py-polars 2.1) needs a few things the first nine 0.6 changes did not cover.

              It is the tenth change of the 0.6 release.

              What Changes

              • bin.slice(offset, length), bin.head(n), bin.tail(n), bin.get(index, nullOnOob) (index may be an expression); reading one Binary cell returns its raw bytes, zero bytes included.
              • str.toInteger(base = 10, dtype = Int64, strict = true), base 2 to 36 or a column.
              • UInt64 values above high(int64): series("u", @[x'u64]) and toList(uint64) keep all 64 bits.
              • readCsv/scanCsv: quoteChar (none(char) turns quoting off), encoding (CsvEncoding.Utf8Lossy) and newColumns.

              Capabilities

              Modified Capabilities
              • binary-decimal: binary slicing and byte access, str.toInteger.
              • csv-io: quoteChar, encoding, newColumns.
              • data-types: UInt64 values above high(int64).

              Differences from Polars

              • quoteChar is an Option[char] (Python: quote_char: str | None); encoding is an enum (Python strings "utf8", "utf8-lossy").
              • mod on Decimal columns is not in the Polars 0.55 crate (py-polars 2.1 has it): cast to Float64 first. This is part of the known version drift.
              • str.toInteger needs the Polars Int128/UInt128 types in the crate (a Polars 0.55 build requirement); they still read as DataTypeKind.Other.

              Impact

              • src/rust/src/lib.rs: nq_expr_bin_slice, nq_expr_str_to_integer, nq_series_new_u64, nq_df_column_u64, CSV options; features string_to_integer, dtype-i128, dtype-u128.
              • src/nanuq.nim, src/nanuq/ffi.nim; new tests/test_explainer6.nim.
              Spec changesbinary-decimal +2 · csv-io +1 · data-types +1

              binary-decimal modified +2

              ADDED
              Binary slicing and bytes

              The bin namespace SHALL provide slice(offset, length), head(n), tail(n) (negative values count from the end) and get(index, nullOnOob = false), which gives the byte as UInt8; index MAY be an expression. Reading a single Binary cell as string SHALL give its raw bytes, zero bytes included.

              let df = newDataFrame(series("m", @["\x03\x04\x10\x11", "ab"], Binary))
              echo df.select(col("m").bin.get(1).alias("second"),
                             col("m").bin.slice(2, 2).bin.encode(BinaryEncoding.Hex).alias("tail_hex"))
              TBD
              Scenario: Out of bounds
              • WHEN bin.get(9, nullOnOob = true) reads a 4-byte value
              • THEN the result is null
              ADDED
              Strings to integers

              str.toInteger(base = 10, dtype = Int64, strict = true) SHALL parse strings as integers in base (2 to 36, or a column of bases); with strict = false, values that do not parse SHALL be null instead of raising.

              let df = newDataFrame(series("k", @["zz", "10", "?"]))
              echo df.select(col("k").str.toInteger(base = 36, strict = false))
              TBD
              Scenario: Strict
              • WHEN a value does not parse and strict is true
              • THEN a PolarsError is raised

              Unchanged in this spec: Binary data, Decimal data, Binary functions, Bitwise operations

              csv-io modified +1

              ADDED
              Quoting, encoding and new column names

              readCsv and scanCsv SHALL take quoteChar = some('"') (none(char) turns quoting off), encoding = CsvEncoding.Utf8 (Utf8Lossy replaces invalid UTF-8 instead of raising) and newColumns, which renames the first columns.

              import std/os
              let path = getTempDir() / "lines.txt"
              writeFile(path, "a \"quoted, line\nplain\n")
              echo readCsv(path, separator = '\x01', hasHeader = false, quoteChar = none(char),
                           newColumns = ["line"])
              TBD
              Scenario: Invalid UTF-8
              • WHEN a line holds the byte 0xFF and encoding = CsvEncoding.Utf8Lossy
              • THEN the line is read, with a replacement character

              Unchanged in this spec: Scanning CSV, CSV read options, CSV write options, Reading CSV from a stream, Comment lines

              data-types modified +1

              ADDED
              Full-range UInt64

              UInt64 columns SHALL keep all 64 bits between Nim and Polars: series(name, seq[uint64]) (with or without Option) and toList(uint64) SHALL handle values above high(int64).

              let df = newDataFrame(series("key", @[1'u64, 9223372036854775809'u64]))
              echo df.toList("key", uint64)
              echo df.select(col("key").bitwiseXor)
              TBD
              Scenario: Nulls
              • WHEN series("u", [some(x), none(uint64)]) is built
              • THEN the second value is null

              Unchanged in this spec: DataType values, DataType constants and predicates, Schemas, Casting, Nim types map to DataType

              Tasks3 of 3 done

              1. Implementation 3/3

              • 1.1Crate: binary slicing, str.to_integer (features), u64 series in and out, CSV quote/encoding
              • 1.2Nim: bin.slice/head/tail/get, Binary cells as raw bytes, str.toInteger, UInt64, readCsv options
              • 1.3Tests in tests/test_explainer6.nim; nimble test and nimble specexamples pass; CHANGELOG
              Revisions1 revision
              r1 fdee4e0 2026-11-01 0.6: explainer needs (bin slicing, str.toInteger, full-range UInt64, CSV quoteChar/encoding/newColumns), book round 3 (readExcel headerRow/skipRows as fastexcel, GroupKeys), BACKLOG lean builds

              First version: proposal.md, specs/binary-decimal/spec.md, specs/csv-io/spec.md, specs/data-types/spec.md, tasks.md

              add-expr-essentials Archived

              created 2026-10-31 · openspec/changes/archive/2026-10-31-add-expr-essentials
              1. Proposal
              2. Specs
              3. Design
              4. Tasks
              5. Implement 13/13
              6. Archive
              Proposal

              Why

              Nanuq's expressions can do arithmetic, comparisons and a handful of aggregations. Most real queries need a few more things: a conditional column (when/then/otherwise), a membership or range test, modulo and powers, a median or a quantile, filling nulls from the row above, and aggregates computed per group without collapsing rows (over). These are the expressions the 0.2 explainer post leans on, and the ones users reach for first after filter and groupBy.

              This change takes up part of the BACKLOG.md entry "More expressions" (when/then/otherwise and window functions; string functions stay in the entry). It is the fourth change of the 0.2 release (see the Polars coverage map, area "Expressions"). The API choices for conditionals and fill strategies were made by Pietro on 2026-10-31 in the doc "Nanuq 0.2: API choices the explainer forces" (options A + D for conditionals, with the macro named choose; option A + B for fill strategies).

              What Changes

              • Conditionals, two spellings for one plan:
              • The Polars chain: when(cond).then(a).when(cond2).then(b).otherwise(c) . Only the first when needs backticks, because when is a Nim keyword. A chain without otherwise gives null for unmatched rows. A chain converts to Expr automatically.
              • A choose macro over Nim's if/elif/else, which builds the same chain:
                  let size = choose:
                    if col("weight_kg") < 150: "cub"
                    elif col("weight_kg") < 500: "adult"
                    else: "chonk"
              • Strings in then, otherwise and the macro branches are literal values, not column names. Use col("x") for a column.
              • Membership and ranges: isIn([1, 2, 3]) (Nim values) or isIn(expr), with nullsEqual = false. isBetween(lower, upper, closed = Both), where closed is a ClosedInterval (Both, Left, Right, None).
              • Arithmetic: mod (Polars' %), div (Polars' floor division //), pow and ^, abs, unary -, and round(decimals = 0, mode = HalfToEven) with a RoundMode (HalfToEven, HalfAwayFromZero, ToZero).
              • Aggregations: median, var(ddof = 1) (written e.var), std(ddof = 1) (gains ddof), quantile(q, interpolation = Nearest) with a QuantileMethod (Nearest, Lower, Higher, Midpoint, Linear, Equiprobable), and len (rows including nulls, unlike count).
              • Null strategies: fillNull(Forward), fillNull(strategy = Backward, limit = 2) with a FillNullStrategy (Forward, Backward, Mean, Min, Max, Zero, One), and the shortcuts forwardFill(limit) and backwardFill(limit). fillNull(value) is unchanged.
              • Windows: over("station"), over(["a", "b"]) or over([expr]) computes an expression per group and broadcasts it back to the rows.
              • New pure enums ClosedInterval, QuantileMethod, FillNullStrategy and RoundMode, following the api-conventions spec. Polars features is_in, is_between, abs and round_series are compiled in. The ABI stays 0.2.0-dev.

              Capabilities

              New Capabilities
              • expressions: conditionals, membership and range tests, extra arithmetic and aggregations, null fill strategies and window expressions.
              Modified Capabilities
              • native-bridge: the new enums join the ones that keep the same order in Rust and ffi.nim.

              Differences from Polars

              Expected differences from Polars' Rust and Python APIs:

              • when is backticked as a prefix call: when(cond) . .then, .when and .otherwise are written as in Polars. choose is Nanuq's own sugar and has no Polars counterpart. It builds the same plan, so $expr shows Polars' when/then/otherwise.
              • Strings are values in conditionals. Python's .then("cub") means the column "cub", a known gotcha that needs pl.lit("cub"). In Nanuq a string is a literal, as in fillNull("x") today.
              • Operators: Python's %, // and ** become Nim's mod, div and ^ (or pow). They keep Polars' semantics, not Nim's: mod and div round towards negative infinity (-7 mod 3 == 2), where Nim's integer mod/div truncate.
              • var is a Nim keyword, so it is written e.var (or var(e) ).
              • Option values are enums: closed = Left, method = Linear, fillNull(Forward). Rust's FillNullStrategy::Forward(limit) carries the limit, but a pure enum can't carry data, so limit is a separate argument, as in Python.
              • quantile takes a float, not an expression, in this change. Its option is named interpolation as in Python (Rust's type is QuantileMethod), because method is a Nim keyword and can't be a named argument.
              • over takes only the partition keys. Python's order_by and mapping_strategy are left for later.
              • round defaults to half-to-even, as Rust Polars and Python Polars do (Nim's round rounds half away from zero).
              • Not in this change: string functions, cum_*, rank, diff, shift, floor/ceil, log/exp, rolling windows, is_duplicated/is_unique, replace, and when with several conditions per branch (when(a, b), write a and b). They stay in the coverage map.
              • Names follow Polars in camelCase: is_in → isIn, is_between → isBetween, fill_null → fillNull, forward_fill → forwardFill, nulls_equal → nullsEqual.

              Impact

              • src/rust/src/lib.rs:
              • nq_expr_when_then builds a whole chain from lists of conditions and values plus an optional otherwise.
              • nq_expr_is_in, nq_expr_is_between, nq_expr_quantile, nq_expr_var_std (ddof), nq_expr_fill_null_strategy, nq_expr_over, nq_expr_round and nq_expr_lit_series (for isIn with Nim values).
              • New NqBinOp values Mod, FloorDiv and Pow; new NqUnary values Abs, Median, Len and Neg.
              • Cargo.toml adds four features.
              • src/nanuq/ffi.nim and src/nanuq.nim get the declarations, the four enums, the chain types with their converter to Expr, the choose macro and the procs.
              • tests/test_expressions.nim covers every function and option, and checks that the macro and the chain give the same plan.
              • README.md lists the new expressions. BACKLOG.md keeps "More expressions" for string functions only.
              Spec changesexpressions +8 · native-bridge ~1

              expressions modified +8

              ADDED
              Conditional expressions

              The API SHALL build conditional expressions with the chain when(cond).then(value) , optionally followed by more .when(cond).then(value) pairs and .otherwise(value). Rows matching no condition SHALL be null when there is no otherwise. A chain SHALL be usable wherever an Expr is expected. Values SHALL be expressions or Nim literals, and strings SHALL be literal values.

              Scenario: Three-way label
              • WHEN when(col("w") < 150).then("cub").when(col("w") < 500).then("adult").otherwise("chonk") is selected over weights 100, 300 and 900
              • THEN the result is "cub", "adult" and "chonk"
              Scenario: No otherwise
              • WHEN when(col("w") < 150).then(1) is selected over weights 100 and 900
              • THEN the result is 1 and null
              ADDED
              choose macro

              The API SHALL provide a choose macro that turns an if/elif/else expression with expression conditions into the same chain. A missing else SHALL mean null. Any other body SHALL fail to compile.

              Scenario: Same plan as the chain
              • WHEN a choose block and the equivalent chain are built
              • THEN their $ strings are equal
              Scenario: One line
              • WHEN choose(if col("collared"): "tracked" else: "free") is selected
              • THEN each row is "tracked" or "free"
              ADDED
              Membership and ranges

              Expr SHALL support isIn(values) for a list of Nim values or an expression, with nullsEqual = false, and isBetween(lower, upper, closed = Both) with a pure enum ClosedInterval (Both, Left, Right, None).

              Scenario: isIn
              • WHEN col("a").isIn([1, 3]) is selected over 1, 2 and 3
              • THEN the result is true, false and true
              Scenario: Half-open range
              • WHEN col("a").isBetween(1, 3, closed = Left) is selected over 1, 2 and 3
              • THEN the result is true, true and false
              ADDED
              Arithmetic operators

              Expr SHALL support mod, div (floor division), ^ and pow, abs and unary -, with Nim literals on either side of a binary operator. mod and div SHALL follow Polars' floor semantics.

              Scenario: Floor semantics
              • WHEN lit(-7) mod 3 and lit(-7) div 3 are evaluated
              • THEN the results are 2 and -3
              Scenario: Power
              • WHEN col("a") ^ 2 is selected over 3
              • THEN the result is 9
              ADDED
              Rounding

              Expr SHALL support round(decimals = 0, mode = HalfToEven) with a pure enum RoundMode (HalfToEven, HalfAwayFromZero, ToZero).

              Scenario: Two decimals
              • WHEN col("w").round(2) is selected over 1.23456
              • THEN the result is 1.23
              Scenario: Half to even by default
              • WHEN col("w").round and col("w").round(mode = HalfAwayFromZero) are selected over 2.5
              • THEN the results are 2.0 and 3.0
              ADDED
              More aggregations

              Expr SHALL support median, var(ddof = 1), std(ddof = 1), quantile(q, interpolation = Nearest) with a pure enum QuantileMethod (Nearest, Lower, Higher, Midpoint, Linear, Equiprobable), and len, which counts rows including nulls.

              Scenario: Median and quantile
              • WHEN median and quantile(0.25, interpolation = Linear) are computed over 1, 2, 3 and 4
              • THEN the results are 2.5 and 1.75
              Scenario: len vs count
              • WHEN len and count are computed over 1, null and 3
              • THEN the results are 3 and 2
              ADDED
              Null fill strategies

              Expr SHALL support fillNull(strategy, limit = none(int)) with a pure enum FillNullStrategy (Forward, Backward, Mean, Min, Max, Zero, One), and the shortcuts forwardFill(limit) and backwardFill(limit). limit SHALL also accept a plain int. A limit SHALL bound how many consecutive nulls are filled.

              Scenario: Forward with limit
              • WHEN col("a").forwardFill(1) is selected over 1, null, null and 4
              • THEN the result is 1, 1, null and 4
              Scenario: Mean
              • WHEN col("a").fillNull(Mean) is selected over 1, null and 3
              • THEN the result is 1, 2 and 3
              ADDED
              Window expressions

              Expr SHALL support over(partitionBy) with one column name, a list of names, or a list of expressions. It SHALL compute the expression per group and return one value per row.

              Scenario: Group mean per row
              • WHEN col("v").mean.over("g") is selected over groups x, x, y with values 1, 3, 10
              • THEN the result is 2, 2 and 10
              Scenario: Forward fill within groups
              • WHEN col("r").forwardFill.over("g") runs where group y starts with a null
              • THEN that null stays null, instead of taking the last value of group x

              Unchanged in this spec: Ranking, Filtering inside expressions, Shape and position aggregations, Boolean aggregations, Entropy, Row count expression, Several window keys and selector concatenation, Null-aware comparisons and closeness, More expression functions

              native-bridge modified ~1

              MODIFIED
              Nim declarations mirror the C ABI
              `src/nanuq/ffi.nim` SHALL declare every exported function with matching signatures, and the enums `NqBinOp`, `NqUnary`, `NqDtype`, `NqDtypeClass`,`NqJoinType`, `NqJoinType`,`NqJoinValidation`, `NqJoinValidation`, `NqMaintainOrderJoin`, `NqConcat`, `NqUniqueKeepStrategy`, `NqClosedInterval`, `NqClosedInterval`, `NqQuantileMethod`, `NqFillNullStrategy`,`NqFillNullStrategy` `NqRoundMode`, `NqQuoteStyle`,and `NqRankMethod`,`NqRoundMode` `NqErrorKind`, `NqStrOp`, `NqTimeUnit`, `NqClosedWindow`, `NqDtOp`, `NqCatOp`, `NqParquetCompression` and `NqIpcCompression` SHALL keep the same order as in Rust. `NqDtype` SHALL also keep the order of `DataTypeKind`, and the option enums the order of their Nim API enums. Data types SHALL cross the ABI as an `NqDtypeSpec` struct (code, time unit, time zone, categories) with the same field order on both sides. Scenario: ABI change - **WHEN** a function is added or changed in `rust/src/lib.rs` - **THEN** `src/nanuq/ffi.nim` is updated in the same change

              Unchanged in this spec: C ABI over Polars with opaque handles, Errors and panics never cross the boundary, Linking the static library, Columns cross in bulk, Library version check, Formatted cells, Polars version matches a py-polars release

              Design

              Design

              Context

              Expressions cross the ABI as opaque Expr pointers. Binary operators go through nq_expr_binary(a, NqBinOp, b) and one-argument functions through nq_expr_unary(e, NqUnary). Literals are lifted by lit. Polars 0.55 has:

              • when(c).then(a) returning Then, .when(c) returning ChainedWhen, .then returning ChainedThen, and .otherwise(e) returning Expr. Then and ChainedThen also convert into Expr (otherwise null).
              • is_in(other, nulls_equal) (feature is_in) and is_between(lower, upper, ClosedInterval) (feature is_between).
              • floor_div, % (Rem), pow, abs (feature abs) and round(decimals, RoundMode) (feature round_series).
              • median, var(ddof), std(ddof), quantile(Expr, QuantileMethod) and len.
              • fill_null_with_strategy(FillNullStrategy) and over(partition_by).

              Goals / Non-Goals

              Goals:

              • One plan, two spellings for conditionals: the chain is the reference, and choose is sugar that expands to it.
              • Strategy and option enums follow the api-conventions spec.
              • Few new ABI functions: extend NqBinOp and NqUnary where the shape fits.

              Non-Goals:

              • String, temporal and list namespaces.
              • over with order_by or mapping strategies.

              Decisions

              Conditionals are built in Nim and crossed once

              when returns a Nim When value holding the condition. .then(v) returns a Then value holding lists of conditions and values, and .when / .then on it extend those lists. otherwise(e), or the converter to Expr, makes one call:

              nq_expr_when_then(conds: *const *const Expr, values: *const *const Expr, n: usize,
                                otherwise: *const Expr /* NULL: none */) -> *mut Expr

              Rust folds the lists into when(c0).then(v0).when(c1).then(v1)... and ends with .otherwise(e), or .otherwise(lit(NULL)) when there is none.

              • Why: a single ABI function and no Rust Then/ChainedThen handles to free. Nim values are cheap.
              • Alternative: mirror Rust's four builder types across the ABI. That gives four more opaque types for no gain.
              choose macro

              choose(body) takes an if statement or expression (nnkIfStmt/nnkIfExpr), and turns each elif branch into .when(cond).then(value) and else into .otherwise(value). Any other node is a compile error with a message that points to if. Values go through lit when they are not Expr. About 30 lines in src/nanuq.nim.

              Typed value lifting

              then, otherwise and the macro accept Expr or SomeNumber | string | bool, as the binary operators already do. Strings become lit("...").

              isIn with Nim values

              isIn(values: openArray[T]) builds a Series from the values (the existing series procs), turns it into a literal with nq_expr_lit_series, and calls nq_expr_is_in(e, other, nulls_equal). Rust implodes the literal series when the other side is a plain column, which is what Polars expects in 0.55.

              Enums

              ClosedInterval, QuantileMethod, FillNullStrategy and RoundMode are pure enums with Rust's names, in Rust's order, mirrored as NqClosedInterval, NqQuantileMethod, NqFillNullStrategy and NqRoundMode (nq_expr_round(e, decimals, mode)). Fill uses nq_expr_fill_null_strategy(e, strategy, has_limit, limit). forwardFill(limit) and backwardFill(limit) are Nim one-liners on top. limit is Option[int], with plain-int overloads (like sample's seed).

              Operators

              NqBinOp gains Mod (Rust %), FloorDiv and Pow. In Nim, mod, div, ^ and pow are defined with defBinOp, so literals on either side work (2 ^ col("a")). NqUnary gains Abs, Median, Len and Neg.

              over

              nq_expr_over(e, partition_by, n) with key expressions. Nim overloads take a single name, a list of names, or a list of expressions.

              Risks / Trade-offs

              • Macro error messages are harder to read than proc errors. The macro checks the node kinds itself and reports "choose expects an if/elif/else expression".
              • mod/div with Polars' floor semantics may surprise Nim users who expect truncation. The difference is in the doc comments and the README conventions.
              Tasks13 of 13 done

              1. Bridge 4/4

              • 1.1Add the Polars features is_in, is_between, abs and round_series to src/rust/Cargo.toml
              • 1.2Add NqBinOp values Mod, FloorDiv and Pow, and NqUnary values Abs, Median, Len and Neg
              • 1.3Add nq_expr_when_then, nq_expr_is_in, nq_expr_lit_series, nq_expr_is_between (NqClosedInterval), nq_expr_quantile (NqQuantileMethod), nq_expr_var_std, nq_expr_fill_null_strategy (NqFillNullStrategy), nq_expr_round (NqRoundMode) and nq_expr_over
              • 1.4Mirror everything in ffi.nim; verify that cargo build --release passes

              2. Nim API 7/7

              • 2.1Add the conditional chain ( when , then, when, otherwise, and a converter to Expr) and the choose macro
              • 2.2Add isIn (values and expression) and isBetween with ClosedInterval
              • 2.3Add mod, div, ^/pow, abs, unary -, and round with RoundMode
              • 2.4Add median, var, std(ddof), quantile with QuantileMethod (interpolation), and len
              • 2.5Add fillNull(strategy, limit) with FillNullStrategy, plus forwardFill and backwardFill
              • 2.6Add over (name, names, expressions)
              • 2.7Write tests/test_expressions.nim: every function and option, a chain without otherwise, string literals in branches, the macro giving the same $expr as the chain, a macro misuse failing to compile, floor semantics of mod/div, and forward fill with and without over; add it to nanuq.nimble and .gitignore

              3. Docs and integration 2/2

              • 3.1List the new expressions in the README, and note in "Conventions" that operators keep Polars' semantics; verify that nimble test and nimble example pass
              • 3.2Check that CI is green on the PR, including the Rust rebuild

              Workflow follow-up 0/0

                Revisions1 revision
                r1 ab17ee2 2026-10-31 Add expression essentials (implements add-expr-essentials)

                First version: .openspec.yaml, design.md, proposal.md, specs/expressions/spec.md, specs/native-bridge/spec.md, tasks.md

                add-expr-filter Archived

                openspec/changes/archive/2026-10-31-add-expr-filter
                1. Proposal
                2. Specs
                3. Tasks
                4. Implement 3/3
                5. Archive
                Proposal

                Why

                Two small gaps found while porting real queries to Nanuq during 0.3:

                • The performance work on PDS-H found that query 21 needs an extra group-by and join in Nanuq because there is no Expr.filter, which aggregates over part of a group ("late deliveries per supplier"). That costs about 30% on that query.
                • The Nanuq Book port found that Python's pl.col(["a", "b"]) (or df.select(cols) with a list in a variable) has no direct twin: col("a", "b") takes varargs only.

                It is the eighth change of the 0.3 release.

                What Changes

                • e.filter(predicate) keeps the values of e where predicate is true, for conditional aggregations (agg(col.pts.filter(col.kind == "TT").sum)).
                • col(names) with an openArray[string] returns a Selector for those columns, in order.

                Capabilities

                Modified Capabilities
                • expressions: Expr.filter.
                • column-selectors: col with a list of names.

                Differences from Polars

                • None in behaviour. Python's Expr.filter also takes several predicates and keyword constraints (filter(a, b, kind="TT")); Nanuq takes one expression (combine with and).

                Impact

                • src/rust/src/lib.rs: nq_expr_filter; src/nanuq/ffi.nim, src/nanuq.nim.
                • Tests in tests/test_expressions.nim and tests/test_selectors.nim.
                Spec changescolumn-selectors ~1 · expressions +1

                column-selectors modified ~1

                MODIFIED
                Selecting by name
                `col(a, b, ...)` with two or more names, and `col(names)` with an `openArray[string]`, SHALL return a `Selector` for those columns in that order, and `all()` SHALL select every column. `col` with one name SHALL keep returning an `Expr`, and a name that starts with `^` and ends with `$` SHALL be a regex. ```nim let df = newDataFrame(series("weight_kg", [410.5]), series("weight_lb", [905.0]), series("name", ["Nanuq"])) echo df.select(col("^weight_.*$")).columns # regex echo df.select(col("name", "weight_kg")).columns echo df.select(all()).columns let wanted = @["weight_lb", "name"] echo df.select(col(wanted)).columns ``` ```text @["weight_kg", "weight_lb"] @["name", "weight_kg"] @["weight_kg", "weight_lb", "name"] @["weight_lb", "name"] ``` Scenario: Regex - **WHEN** `select(col("^weight_.*$"))` runs on columns `weight_kg`, `weight_lb` and `name` - **THEN** the result has columns `weight_kg` and `weight_lb` Scenario: Names from a seq - **WHEN** `select(col(@["c", "a"]))` runs on columns `a`, `b` and `c` - **THEN** the result has columns `c` and `a`

                Unchanged in this spec: Selecting by Nim type, Excluding columns, Selectors as expressions, Output name suffix and prefix, Operators on selectors

                expressions modified +1

                ADDED
                Filtering inside expressions

                e.filter(predicate) SHALL keep the values of e where predicate is true, so that an aggregation can run over part of each group.

                let df = newDataFrame:
                  rider: ["Pogačar", "Pogačar", "Vingegaard", "Vingegaard"]
                  stage: ["TT", "road", "TT", "road"]
                  secs: [3120, 15400, 3150, 15390]
                echo df.groupBy(col.rider).agg(col.secs.filter(col.stage == "TT").sum.alias("tt_secs"))
                  .sort("rider").collect
                TBD
                Scenario: Conditional sum
                • WHEN col.secs.filter(col.stage == "TT").sum is aggregated per rider
                • THEN each rider's sum counts only the TT rows

                Unchanged in this spec: Conditional expressions, choose macro, Membership and ranges, Arithmetic operators, Rounding, More aggregations, Null fill strategies, Window expressions, Ranking, Shape and position aggregations, Boolean aggregations, Entropy, Row count expression, Several window keys and selector concatenation, Null-aware comparisons and closeness, More expression functions

                Tasks3 of 3 done

                1. Implementation 3/3

                • 1.1Add nq_expr_filter and Expr.filter
                • 1.2Add col(openArray[string])
                • 1.3Tests; nimble test and nimble specexamples pass; CHANGELOG
                Revisions1 revision
                r1 c27d0a5 2026-10-31 Add Expr.filter and col with a list of names

                First version: proposal.md, specs/column-selectors/spec.md, specs/expressions/spec.md, tasks.md

                add-expr-math Archived

                openspec/changes/archive/2026-11-01-add-expr-math
                1. Proposal
                2. Specs
                3. Tasks
                4. Implement 4/4
                5. Archive
                Proposal

                Why

                The Nanuq Book ports stopped on elementwise math more often than on anything else that needs no new data type: the O'Reilly chapter 8 sections on mathematical transformations, trigonometry, rounding and missing or infinite values, and every query that takes a square root or a logarithm. NaN, which Polars keeps apart from null, has no API at all.

                It is the first change of the 0.4 release ("A real Series, and shaping", see the Polars coverage map).

                What Changes

                • Elementwise math on expressions: sqrt, cbrt, exp, log(base = E), log10, log1p, sign, floor, ceil, clip(lowerBound, upperBound) (or one bound, named), and dot(other).
                • Trigonometry: sin, cos, tan, cot, arcsin, arccos, arctan, sinh, cosh, tanh, arcsinh, arccosh, arctanh, degrees, radians, and arctan2(y, x).
                • NaN and infinity: isNan, isNotNan, isFinite, isInfinite, fillNan(value), dropNans, and Expr.dropNulls.
                • The wrapper crate becomes 0.4.0-dev and gains the Polars features 0.4 needs.

                Capabilities

                New Capabilities
                • math-functions: elementwise math, trigonometry, NaN and infinity.

                Differences from Polars

                • clip with one bound needs the bound named (clip(lowerBound = 0)): a single positional argument is a compile error, because Nim can't tell which bound it is. Python takes clip(lower_bound=None, upper_bound=None); Rust has clip, clip_min and clip_max.
                • log(base) defaults to e as in Python (Rust always takes the base). Nim's std/math ln, log2 are not added; log(2.0) does that.
                • arctan2(y, x) is a free function as in Python (pl.arctan2); in Rust it is a method.
                • These names overload std/math's float procs (sqrt, exp, floor, ...) for Expr; both work in the same module.

                Impact

                • src/rust/Cargo.toml (version, features), src/rust/src/lib.rs (NqUnary grows, nq_expr_clip, nq_expr_log, nq_expr_binary_fn), src/nanuq/ffi.nim, src/nanuq.nim.
                • New tests/test_math.nim.
                Spec changesmath-functions +5

                math-functions modified +5

                ADDED
                Elementwise math

                Expressions SHALL have sqrt, cbrt, exp, log(base = E), log10, log1p, sign, floor and ceil, computed value by value as in Polars, with nulls staying null. sqrt, cbrt, exp and the logarithms SHALL return Float64 for integer input.

                let df = newDataFrame:
                  x: [1.0, 4.0, 10.0, nil]
                echo df.select(col.x.sqrt.alias("sqrt"), col.x.log10.alias("log10"),
                               col.x.log(2.0).alias("log2"), col.x.exp.round(1).alias("exp"))
                TBD
                Scenario: Integer input
                • WHEN sqrt runs on an Int64 column holding 4 and 9
                • THEN the result is a Float64 column holding 2.0 and 3.0
                Scenario: Sign, floor and ceil
                • WHEN sign, floor and ceil run on -2.5 and 1.5
                • THEN they give -1 and 1, -3.0 and 1.0, -2.0 and 2.0
                ADDED
                Clipping

                clip(lowerBound, upperBound) SHALL limit values to the range, and clip(lowerBound = v) or clip(upperBound = v) SHALL limit them on one side. Bounds SHALL be literals or expressions.

                let df = newDataFrame:
                  anomaly: [-2.1, -0.3, 0.4, 2.6]
                echo df.select(col.anomaly.clip(-1.0, 1.0).alias("both"),
                               col.anomaly.clip(lowerBound = 0.0).alias("warm_only"))
                TBD
                Scenario: Both bounds
                • WHEN clip(-1.0, 1.0) runs on -2.1 and 2.6
                • THEN the result is -1.0 and 1.0
                ADDED
                Trigonometry

                Expressions SHALL have sin, cos, tan, cot, arcsin, arccos, arctan, sinh, cosh, tanh, arcsinh, arccosh, arctanh, degrees and radians, working in radians, and arctan2(y, x) SHALL return the angle of the point (x, y).

                let df = newDataFrame:
                  deg: [0.0, 90.0, 180.0]
                echo df.select(col.deg.radians.sin.round(3).alias("sin"),
                               arctan2(lit(1.0), lit(1.0)).degrees.alias("atan2"))
                TBD
                Scenario: Degrees round trip
                • WHEN radians and then degrees run on 90.0
                • THEN the result is 90.0
                ADDED
                NaN and infinity

                isNan, isNotNan, isFinite and isInfinite SHALL test float values (nulls give null), fillNan(value) SHALL replace NaN with a literal or expression, dropNans SHALL remove NaN values and Expr.dropNulls SHALL remove nulls. NaN SHALL stay distinct from null, as in Polars.

                let df = newDataFrame:
                  x: [1.0, NaN, Inf, nil]
                echo df.select(col.x.isNan.alias("nan"), col.x.isFinite.alias("finite"),
                               col.x.fillNan(0.0).alias("filled"))
                echo df.select(col.x.dropNans.dropNulls)
                TBD
                Scenario: NaN is not null
                • WHEN isNull runs on a column holding NaN
                • THEN the result is false
                Scenario: fillNan leaves nulls
                • WHEN fillNan(0.0) runs on NaN and null
                • THEN the result is 0.0 and null
                ADDED
                Dot product

                a.dot(b) SHALL return the sum of the elementwise products of two columns, as an aggregation.

                let df = newDataFrame:
                  a: [1, 2, 3]
                  b: [4, 5, 6]
                echo df.select(col.a.dot(col.b))
                TBD
                Scenario: Dot of two integer columns
                • WHEN col.a.dot(col.b) runs on a = 1, 2, 3 and b = 4, 5, 6
                • THEN the result is one row holding 32
                Tasks4 of 4 done

                1. Implementation 4/4

                • 1.1Crate version 0.4.0-dev and the Polars features for 0.4
                • 1.2Unary math, trigonometry and NaN functions through NqUnary
                • 1.3log, clip, fillNan, dot, arctan2
                • 1.4Tests in tests/test_math.nim; nimble test and nimble specexamples pass; CHANGELOG
                Revisions1 revision
                r1 570d956 2026-11-01 Nanuq 0.4, changes 1-7: math, cumulative, rolling, value functions, horizontal, reshaping, time grouping

                First version: proposal.md, specs/math-functions/spec.md, tasks.md

                add-expression-plugins Archived

                openspec/changes/archive/2026-11-06-add-expression-plugins
                1. Proposal
                2. Specs
                3. Tasks
                4. Implement 7/7
                5. Archive
                Proposal

                Why

                Polars can be extended with expression plugins: shared libraries that Polars loads and calls on Arrow arrays (Python's register_plugin_function). They are how polars-stats (vectorized distributions) and similar extensions ship. The plugin boundary is a plain C ABI (polars-ffi version_0, ABI 0.1), so a plugin can be written in Rust with pyo3-polars, or in Nim.

                The exploration "Polars plugins, without the Rust" (nanuq-more, 2026-11-05) wrote two plugins in Nim (ISO weeks as an extension type, and probability distributions) and loaded the same library from Python Polars and from Nanuq. Nanuq needed one new function for that, which this change proposes. Not from a BACKLOG.md entry.

                What Changes

                • registerPluginFunction(pluginPath, functionName, args, kwargs, isElementwise, changesLength, returnsScalar, castToSupertype, inputWildcardExpansion, passNameToApply, isDeterministic): Expr, as in Python Polars. kwargs are bytes already pickled (a dict), as Polars passes them to the plugin.
                • The C bridge gets nq_expr_plugin, which builds FunctionExpr::FfiPlugin. The crate enables the Polars features ffi_plugin (polars-plan and polars-lazy) and dtype-extension, so a plugin can return an extension type (ext[...]).
                • tests/test_plugins.nim builds a minimal Nim plugin (tests/data/plugins/double_it.nim, the ABI by hand) and checks a call, an error and a lazy group-by.

                Capabilities

                New Capabilities
                • expression-plugins: calling Polars expression plugins from Nanuq.

                Differences from Polars

                • Python resolves a relative plugin_path against the virtual environment and also accepts a directory; Nanuq takes the library file, relative to the working directory (made absolute), and has no use_abs_path.
                • Python pickles a kwargs dict itself; Nanuq takes the pickled bytes (nanuq-more has a small pickle writer). A typed kwargs parameter could come later.
                • Rust Polars builds the same expression through Expr::Function with FunctionExpr::FfiPlugin; it has no public helper of this name.
                • Extension types show as ext[<name>] (Python shows the registered class's repr); Nanuq has no registry of extension classes.

                Impact

                • src/rust/Cargo.toml (features), src/rust/src/lib.rs, src/nanuq/ffi.nim, src/nanuq.nim, a new test and its fixture. Needs a new library release.
                • Rust plugins built with pyo3 (polars-stats) link against libpython: Nanuq can load them only with libpython preloaded (LD_PRELOAD). Plugins written in Nim (or plain Rust without pyo3) load directly.
                • The plugin ABI is Polars' version 0 and extension types are unstable in Polars: either may change in a Polars release.
                Spec changesexpression-plugins +1

                expression-plugins modified +1

                ADDED
                Calling an expression plugin

                registerPluginFunction(pluginPath, functionName, args) SHALL give an expression that calls the function functionName of the Polars expression plugin at pluginPath (a shared library implementing the Polars plugin ABI 0.1) on the columns of args, with the options of Python's register_plugin_function (kwargs as pickled bytes, isElementwise, changesLength, returnsScalar, castToSupertype, inputWildcardExpansion, passNameToApply, isDeterministic). The output name and data type SHALL be the ones the plugin reports, extension types included. The expression SHALL compose like any other, lazily and in group-bys.

                # tests/data/plugins/double_it.nim, built as a library
                let lib = "tests/data/plugins/" & (DynlibFormat % "double_it")
                let df = newDataFrame(series("x", [1.5, 2.0, 4.0]))
                echo df.select(registerPluginFunction(lib, "double_it", [col"x"], isElementwise = true))
                shape: (3, 1)
                ┌─────┐
                │ x   │
                │ --- │
                │ f64 │
                ╞═════╡
                │ 3.0 │
                │ 4.0 │
                │ 8.0 │
                └─────┘
                Scenario: Plugin error
                • WHEN the plugin reports an error for a call (it returns no column and sets its last error message)
                • THEN running the query raises ComputeError with the plugin's message
                Scenario: Missing library
                • WHEN pluginPath is not a loadable library
                • THEN running the query raises ComputeError naming the path
                Scenario: Extension type output
                • WHEN the plugin's output field carries ARROW:extension:name
                • THEN the column has that extension type, shown as ext[<name>]
                Tasks7 of 7 done

                1. Bridge 2/2

                • 1.1nq_expr_plugin in src/rust/src/lib.rs; Polars features ffi_plugin and dtype-extension
                • 1.2nq_expr_plugin in src/nanuq/ffi.nim

                2. API 5/5

                • 2.1registerPluginFunction in src/nanuq.nim
                • 2.2tests/test_plugins.nim with the double_it fixture plugin
                • 2.3Spec delta for expression-plugins, with an example
                • 2.4Before archiving: the spec suite builds tests/data/plugins/double_it.nim so the example runs
                • 2.5README and coverage map (register_plugin_function)
                Revisions1 revision
                r1 60f21f8 2026-11-06 Release 0.6.1: archive add-expression-plugins, bump to 0.6.1

                First version: proposal.md, specs/expression-plugins/spec.md, tasks.md

                add-frame-utilities Archived

                openspec/changes/archive/2026-11-01-add-frame-utilities
                1. Proposal
                2. Specs
                3. Tasks
                4. Implement 3/3
                5. Archive
                Proposal

                Why

                The 0.4 book ports left a list of smaller Polars functions (BACKLOG.md, "Smaller Polars functions found by the 0.4 book ports"), and the 0.5 tally of "not yet" book sections adds a few more: equals (7 sections), upsample (6), vstack/hstack/extend, estimated_size, collect_all, update, meta.* and name.to_lowercase. Each is small.

                It is the eighth change of the 0.5 release. It takes up that BACKLOG.md entry.

                What Changes

                • Expressions: over(partitionBy, mappingStrategy), shuffle, sample, hash, get, argTrue, upperBound, lowerBound, extendConstant, rle, reshape; name.toLowercase, name.toUppercase; e.meta with outputName, rootNames, hasMultipleOutputs, isColumn, isLiteral, undoAliases.
                • Frames: equals (also on Series), vstack, hstack, extend, update, upsample, estimatedSize, partitionBy(asDict = true), and collectAll for several LazyFrames.

                Capabilities

                New Capabilities
                • frame-utilities: the smaller expression and frame functions above.

                Differences from Polars

                • MappingStrategy is a pure enum (GroupToRows, Join, Explode), not a string.
                • partitionBy(asDict = true) keys its table by the key values as strings (@["Biscoe"]), since Nim has no tuples of run-time types; Python keys by tuples of values.
                • hash(seed) uses one seed for Polars' four (seed, seed_1, seed_2, seed_3 in Python default to it too).
                • estimatedSize gives bytes as an int; estimatedSize(unit) a float in SizeUnit.
                • update supports how = Left, Inner and Full with on columns (or the row index), as Python does; includeNulls is left out.
                • extend returns a new frame (Nanuq frames are immutable), so it is vstack.

                Impact

                • src/rust/src/lib.rs and src/nanuq/ffi.nim: nq_expr_util, nq_expr_reshape, nq_expr_over_mapping, nq_expr_meta_*, nq_df_equals, nq_df_estimated_size, nq_df_upsample, nq_collect_all.
                • src/nanuq.nim; BACKLOG.md entry removed.
                • New tests/test_utilities.nim.
                Spec changesframe-utilities +4

                frame-utilities modified +4

                ADDED
                Smaller expression functions

                Expressions SHALL have shuffle(seed), sample(n or fraction), hash(seed), get(i), argTrue, upperBound, lowerBound, extendConstant(value, n), rle (a struct of len and value) and reshape(dims), and over(partitionBy, mappingStrategy) with MappingStrategy.GroupToRows, Join or Explode.

                let df = newDataFrame:
                  den: ["A", "A", "B"]
                  kg: [410, 380, 500]
                echo df.select(col("kg").get(1).alias("second"), col("kg").upperBound.alias("max"))
                echo df.select((col("kg") > 400).argTrue.alias("heavy"))
                echo df.select(col("den"), col("kg").over("den", MappingStrategy.Join).alias("all"))
                echo df.select(col("den").rle).unnest("den")
                TBD
                Scenario: Seeded shuffle
                • WHEN shuffle(seed = 1) is evaluated twice
                • THEN both results are the same permutation
                ADDED
                Names and meta

                name.toLowercase and name.toUppercase SHALL change output names, and e.meta SHALL give outputName, rootNames, hasMultipleOutputs, isColumn, isLiteral and undoAliases.

                let e = (col("kg") * 2).alias("double")
                echo e.meta.outputName, " ", e.meta.rootNames, " ", col("*").meta.hasMultipleOutputs
                let df = newDataFrame:
                  Bear: ["Ada"]
                echo df.select(col("Bear").name.toUppercase).columns
                TBD
                Scenario: No output name
                • WHEN outputName is asked of col("*")
                • THEN ComputeError is raised
                ADDED
                Comparing and stacking frames

                a.equals(b, nullEqual = true) SHALL tell whether two frames (or Series) have the same names, types and values; vstack and extend SHALL append the rows of a frame with the same schema, and hstack SHALL add Series or the columns of another frame.

                let a = newDataFrame:
                  bear: ["Ada"]
                  kg: [410]
                let b = newDataFrame:
                  bear: ["Bo"]
                  kg: [380]
                echo a.vstack(b).hstack([series("den", ["A", "B"])])
                echo a.equals(a), " ", a.equals(b)
                TBD
                Scenario: Nulls
                • WHEN two frames with a null in the same place are compared with nullEqual = false
                • THEN equals is false
                ADDED
                Updating, upsampling and partitions

                df.update(other, on, how) SHALL replace values of df with the non-null values of other in matching rows; df.upsample(timeColumn, every, groupBy) SHALL insert rows for missing times at a regular interval; estimatedSize SHALL give the frame's size; partitionBy(by, asDict = true) SHALL give a table from key values to frames; and collectAll(lfs) SHALL collect several LazyFrames.

                let df = newDataFrame:
                  bear: ["Ada", "Bo"]
                  kg: [410, 380]
                let fix = newDataFrame:
                  bear: ["Bo"]
                  kg: [395]
                echo df.update(fix, on = "bear")
                let t = newDataFrame:
                  day: [date(2026, 3, 1), date(2026, 3, 4)]
                  seen: [3, 1]
                echo t.upsample("day", every = "1d")
                echo df.partitionBy("bear", asDict = true).len, " ", collectAll([df.lazy, fix.lazy]).len
                TBD
                Scenario: Upsample by group
                • WHEN upsample is called with groupBy
                • THEN each group is filled between its own first and last time

                Unchanged in this spec: Operator methods and xor, Ranges per row, Inequality joins, Frame and Series helpers, Unstack, Rolling Nim functions, Data type of an expression, Empty frames, Frame shortcuts, Schema matching, Merging sorted frames, Query optimizations

                Tasks3 of 3 done

                1. Implementation 3/3

                • 1.1Crate: utility ops, reshape, over with mapping, meta, equals, estimated size, upsample, collect_all
                • 1.2Nim API for expressions and frames
                • 1.3Tests in tests/test_utilities.nim; nimble test and nimble specexamples pass; CHANGELOG
                Revisions1 revision
                r1 f94c8b7 2026-11-01 0.5: Nim callbacks and smaller functions (add-nim-callbacks, add-frame-utilities)

                First version: proposal.md, specs/frame-utilities/spec.md, tasks.md

                add-frame-utilities-0-6 Archived

                openspec/changes/archive/2026-11-01-add-frame-utilities-0-6
                1. Proposal
                2. Specs
                3. Tasks
                4. Implement 3/3
                5. Archive
                Proposal

                Why

                After 0.5 the book map (planning/book-ports-0.6.md) still finds sections blocked by single functions: append 5, unstack 3, ranges 3, method spellings (mul, sub) 4, dtype_of 4, join_where, rolling_map, explain_all, is_sorted, from_epoch, read_parquet_schema, hist, scatter/set, remove. Each is small; together they unblock about 25 sections.

                It is the ninth change of the 0.6 release.

                What Changes

                • Method spellings of operators: add, sub, mul, truediv, floordiv, eq, ne, lt, le, gt, ge, neg; xor (logical on booleans, bitwise on integers).
                • intRanges, dateRanges, datetimeRanges (one list per row), arange (intRange).
                • joinWhere(other, predicates...) (inequality joins), explainAll(lfs).
                • hist on Expr and Series; setSorted on Expr and DataFrame; Series.isSorted.
                • append (frame, in place), remove(predicate) (the opposite of filter).
                • fromEpoch(column, EpochUnit), readParquetSchema(path), threadPoolSize().
                • unstack(step, how, columns, fillValues).
                • rollingMap(f, windowSize, minPeriods, center) with a typed Nim proc of a window.
                • Series.scatter(indices, values) and Series.set(mask, value).
                • dtypeOf(expr | column) with cast(e, dtypeOf(...)), display and innerDtype.

                Capabilities

                Modified Capabilities
                • frame-utilities: the functions above.

                Differences from Polars

                • Python's and_/or_ methods have no Nim spelling (a trailing underscore is not a Nim identifier); a.and(b) and a.or(b) already work as operator calls ( a.and(b) ).
                • rollingMap passes the window's non-null values as a seq[T] to a typed proc (Python passes a Series to a Python function) and runs on the whole column at once, without weights.
                • unstack takes a fillValues expression (Python also takes a list per column).
                • fromEpoch takes an EpochUnit enum (Python strings "d", "s", "ms", "us", "ns").
                • dtypeOf supports cast, display and innerDtype; the rest of Python's datatype expressions (matches, to_dtype, struct and integer helpers) is left out.
                • set is spelled set when called with a prefix ( s.set(mask, 0) ), as set is also Nim's set type.
                • hist on a Series includes breakpoint and category by default, as Python does; on an Expr it does not.

                Impact

                • src/rust/src/lib.rs, src/nanuq/ffi.nim: nq_expr_xor, nq_expr_set_sorted, nq_expr_hist, nq_expr_int_ranges, nq_expr_date_ranges, nq_lf_join_where, nq_explain_all, nq_thread_pool_size, nq_expr_cast_dtype_of, nq_expr_dtype_display.
                • src/nanuq.nim: the procs above (several in Nim on top of existing API).
                • New tests/test_utilities6.nim.
                Spec changesframe-utilities +7

                frame-utilities modified +7

                ADDED
                Operator methods and xor

                Expressions SHALL have the method spellings add, sub, mul, truediv, floordiv, eq, ne, lt, le, gt, ge (with an expression, number, string or bool) and neg, giving the same result as the operators, and xor SHALL be logical on booleans and bitwise on integers.

                let df = newDataFrame(series("a", @[6, 3]), series("ok", @[true, false]))
                echo df.select(col("a").mul(2).alias("m"), col("a").floordiv(4).alias("f"),
                               (col("a") xor 5).alias("x"), (col("ok") xor true).alias("nx"))
                TBD
                Scenario: Same as operators
                • WHEN col("a").sub(1) and col("a") - 1 are selected
                • THEN both columns are equal
                ADDED
                Ranges per row

                intRanges(start, stop, step = 1, dtype = Int64), dateRanges(start, stop, interval) and datetimeRanges(start, stop, interval, closed, timeUnit, timeZone) SHALL give one list per row, with columns or values as bounds; arange SHALL be intRange.

                let df = newDataFrame(series("lo", @[1, 3]), series("hi", @[3, 6]))
                echo df.select(intRanges(col("lo"), col("hi")).alias("r"))
                TBD
                Scenario: Dates
                • WHEN dateRanges runs from 2024-01-01 to 2024-01-03
                • THEN the list holds 3 dates
                ADDED
                Inequality joins

                joinWhere(other, predicates..., suffix = "_right") on DataFrames and LazyFrames SHALL join the rows of both frames for which every predicate holds; clashing columns of other SHALL get suffix.

                let east = newDataFrame(series("id", @[100, 101]), series("dur", @[140, 100]))
                let west = newDataFrame(series("t_id", @[404, 498]), series("time", @[90, 130]))
                echo east.joinWhere(west, col("dur") < col("time"))
                TBD
                Scenario: No match
                • WHEN no pair of rows satisfies the predicates
                • THEN the result has no rows
                ADDED
                Frame and Series helpers

                The API SHALL provide append (rows of another frame, in place), remove(predicate) (rows where it is not true), setSorted, Series.isSorted(descending, nullsLast), explainAll(lfs), threadPoolSize(), readParquetSchema(path), fromEpoch(column, unit), hist(bins, binCount, includeCategory, includeBreakpoint) on Expr and Series, Series.scatter(indices, values) and set(mask, value) .

                var df = newDataFrame(series("a", @[1, 2]))
                df.append(newDataFrame(series("a", @[3])))
                echo df.remove(col("a") == 2)
                echo series("x", @[1.0, 2.0, 2.5, 4.0]).hist(bins = [0.0, 2.0, 4.0])
                echo series("x", @[1, 2, 3]).scatter([0, 2], [10, 30])
                TBD
                Scenario: Remove keeps nulls
                • WHEN remove(col("a") > 1) runs on a column with a null
                • THEN the null row stays
                ADDED
                Unstack

                unstack(step, how = UnstackDirection.Vertical, columns = [], fillValues = nil) SHALL reshape each column into columns <name>_<i> of step values each (Vertical) or with step values per row (Horizontal), padding the end with nulls or fillValues.

                let df = newDataFrame(series("x", @["a", "b", "c", "d", "e"]))
                echo df.unstack(2)
                TBD
                Scenario: Horizontal
                • WHEN 5 values are unstacked horizontally with step 2 and fill 0
                • THEN column _0 holds values 1, 3, 5 and column _1 holds 2, 4, 0
                ADDED
                Rolling Nim functions

                rollingMap(f, windowSize, minPeriods = windowSize, center = false) SHALL apply a typed Nim proc to each window's non-null values, giving null when a window has fewer than minPeriods values.

                import std/sequtils
                let df = newDataFrame(series("x", @[1.0, 2.0, 3.0, 4.0]))
                echo df.select(col("x").rollingMap(proc (w: seq[float]): float = w.foldl(a + b), windowSize = 2))
                TBD
                Scenario: Centered
                • WHEN center = true with window 3
                • THEN each value's window is the value and its two neighbours
                ADDED
                Data type of an expression

                dtypeOf(expr or column) SHALL stand for the type of an expression at run time: cast(e, dtypeOf(...)) casts to it, display gives its short name as a string value, innerDtype the inner type of a List or Array.

                let df = newDataFrame(series("a", @[1.5, 2.5]), series("b", @[1'i32, 2'i32]))
                echo df.select(col("a").cast(dtypeOf("b"), strict = false), dtypeOf("b").display.alias("type"))
                TBD
                Scenario: Unknown column
                • WHEN dtypeOf("nope") is used
                • THEN ColumnNotFoundError is raised when the query runs

                Unchanged in this spec: Smaller expression functions, Names and meta, Comparing and stacking frames, Updating, upsampling and partitions, Empty frames, Frame shortcuts, Schema matching, Merging sorted frames, Query optimizations

                Tasks3 of 3 done

                1. Implementation 3/3

                • 1.1Crate: xor, setSorted, hist, intRanges, dateRanges/datetimeRanges, joinWhere, explainAll, threadPoolSize, dtypeOf
                • 1.2Nim: the API, including Nim-only helpers (append, remove, isSorted, fromEpoch, readParquetSchema, unstack, rollingMap, scatter, set)
                • 1.3Tests in tests/test_utilities6.nim; nimble test and nimble specexamples pass; CHANGELOG
                Revisions1 revision
                r1 4ea5dad 2026-11-01 0.6: archive the 9 changes, fill spec example outputs, map_elements benchmark, dev log Designing Nanuq 0.6

                First version: proposal.md, specs/frame-utilities/spec.md, tasks.md

                add-frame-verbs Archived

                created 2026-10-31 · openspec/changes/archive/2026-10-31-add-frame-verbs
                1. Proposal
                2. Specs
                3. Design
                4. Tasks
                5. Implement 13/13
                6. Archive
                Proposal

                Why

                Nanuq can filter, select and sort by one column. But a lot of everyday table work happens between those steps: dropping or renaming columns, looking at the last rows or a window of them, taking a random sample, removing duplicate rows, numbering rows, and sorting by several keys with nulls at the end. Polars has a small, stable verb for each of these. Without them, Nanuq users have to write select lists by hand or go back through Nim seqs.

                This is the third change of the 0.2 release (see the Polars coverage map, area "Frame verbs"). It has no BACKLOG.md entry.

                What Changes

                • New verbs on LazyFrame, with eager DataFrame shortcuts:
                • drop("a") or drop(["a", "b"], strict = true) removes columns.
                • rename({"old": "new"}, strict = true) renames columns.
                • head(n = 5) (LazyFrame; DataFrame already has it) and tail(n = 5) keep the first or last rows.
                • slice(offset) and slice(offset, length) keep a window of rows. A negative offset counts from the end.
                • unique("a", keep = First, maintainOrder = false) (or a list of names) drops duplicate rows, judged on all columns or on the named ones. keep is a UniqueKeepStrategy: Any (default), First, Last or None.
                • reverse() reverses the row order.
                • withRowIndex(name = "index", offset = 0) adds a row number column first.
                • Sorting by several keys: sort(["species", "mass"], descending = [false, true], nullsLast = [true], maintainOrder = false), by column names or expressions. A single value in descending or nullsLast applies to every key. The one-column sort(by, descending) gains nullsLast and maintainOrder.
                • sample on DataFrame: sample(n, withReplacement = false, shuffle = false, seed = none(int)), and sample(fraction = 0.1, ...). seed = 42 works too, and setRandomSeed(42) seeds Polars' global generator (added during implementation, after Pietro picked this option for the 0.2 explainer).
                • New pure enum UniqueKeepStrategy, following the api-conventions spec.
                • Polars feature random is compiled in (for sample). The ABI stays 0.2.0-dev.

                Capabilities

                New Capabilities
                • frame-verbs: column and row verbs on DataFrames and LazyFrames (drop, rename, head/tail/slice, unique, reverse, withRowIndex, sample) and sorting by several keys.
                Modified Capabilities
                • native-bridge: NqUniqueKeepStrategy joins the enums that keep the same order in Rust and ffi.nim.

                Differences from Polars

                Expected differences from Polars' Rust and Python APIs:

                • keep is an enum. Python's keep="first" becomes keep = First (pure enum UniqueKeepStrategy, Rust's type and names).
                • descending and nullsLast in multi-key sort are lists. Python takes a bool or a list. Nim takes openArray[bool]: one value applies to all keys, as in Rust's SortMultipleOptions. Empty (the default) means all false. The one-column sort keeps plain bools.
                • slice without a length is a separate overload instead of Python's length=None.
                • sample is DataFrame only, as in Python (LazyFrame has no sample). n and fraction are two overloads, chosen by the argument name (fraction = 0.1) or type, and one of them is required (Python defaults to one row when both are missing). seed is an Option[int] or a plain int. setRandomSeed is Python's pl.set_random_seed.
                • rename takes pairs only. Python also accepts a function from old to new name. That form is left for later.
                • drop takes one name or a list, not Python's *columns: Nim varargs followed by strict can't take several positional names, so drop("a", "b") is written drop(["a", "b"]). unique's subset is one name or a list, as in Python. Selectors and expressions come with the column selectors change.
                • Not in this change: drop with selectors, gather_every, shift, top_k/bottom_k, clear, first/last on frames, with_row_count (deprecated in Python), and sort's multithreaded flag. They stay in the coverage map.
                • Names follow Polars in camelCase: with_row_index → withRowIndex, nulls_last → nullsLast, maintain_order → maintainOrder, with_replacement → withReplacement.

                Impact

                • src/rust/src/lib.rs: nq_lf_drop, nq_lf_rename, nq_lf_slice, nq_lf_unique, nq_lf_reverse, nq_lf_with_row_index, nq_df_sample, and nq_lf_sort_by replacing nq_lf_sort. New #[repr(C)] enum NqUniqueKeepStrategy. Cargo.toml adds the random feature. CI rebuilds the Rust library.
                • src/nanuq/ffi.nim and src/nanuq.nim get the matching declarations, the enum and the procs.
                • tests/test_verbs.nim covers each verb and its options.
                • README.md lists the new verbs in "What is there".
                Spec changesframe-verbs +6 · native-bridge ~1

                frame-verbs modified +6

                ADDED
                Dropping and renaming columns

                LazyFrame and DataFrame SHALL support drop(columns, strict = true), with one column name or a list of names, and rename(mapping: openArray[(string, string)], strict = true). With strict = true, a column that does not exist SHALL raise NanuqError. With strict = false, it SHALL be ignored.

                Scenario: Drop
                • WHEN df.drop("b") runs on columns a, b, c
                • THEN the columns are a, c, and df.drop(["a", "b"]) leaves c
                Scenario: Rename
                • WHEN df.rename({"a": "x"}) runs on columns a, b
                • THEN the columns are x, b
                Scenario: Strict
                • WHEN df.drop("zzz") runs
                • THEN NanuqError is raised, and df.drop("zzz", strict = false) returns the frame unchanged
                ADDED
                Row windows

                LazyFrame and DataFrame SHALL support head(n = 5), tail(n = 5), slice(offset) and slice(offset, length). A negative offset SHALL count from the end. reverse() SHALL reverse the row order.

                Scenario: Tail
                • WHEN tail(2) runs on rows 1 to 5
                • THEN the result is rows 4 and 5
                Scenario: Slice from the end
                • WHEN slice(-3, 2) runs on rows 1 to 5
                • THEN the result is rows 3 and 4
                Scenario: Slice to the end
                • WHEN slice(1) runs on rows 1 to 5
                • THEN the result is rows 2 to 5
                ADDED
                Unique rows

                LazyFrame and DataFrame SHALL support unique(subset = [], keep, maintainOrder = false), with one column name or a list of names, judging duplicates on all columns when the subset is empty. keep is a pure enum UniqueKeepStrategy (Any (default), First, Last, None). With maintainOrder = true, the rows SHALL keep their original order.

                Scenario: Keep first
                • WHEN unique("k", keep = First, maintainOrder = true) runs on keys a, b, a with values 1, 2, 3
                • THEN the result is (a, 1), (b, 2)
                Scenario: Keep none
                • WHEN the same frame is made unique on k with keep = None
                • THEN only (b, 2) remains
                ADDED
                Row index

                LazyFrame and DataFrame SHALL support withRowIndex(name = "index", offset = 0), which adds an unsigned integer column with that name as the first column, counting from offset.

                Scenario: Offset
                • WHEN withRowIndex("n", offset = 1) runs on three rows
                • THEN the first column is n with values 1, 2, 3
                ADDED
                Sorting by several keys

                LazyFrame and DataFrame SHALL sort by several column names or expressions with sort(by, descending: openArray[bool] = [], nullsLast: openArray[bool] = [], maintainOrder = false). An empty list SHALL mean false for every key, and one value SHALL apply to every key. Another length SHALL raise NanuqError. The one-column sort(by: string, descending = false, nullsLast = false, maintainOrder = false) SHALL remain.

                Scenario: Two keys
                • WHEN a frame is sorted by ["g", "v"] with descending = [false, true]
                • THEN rows are ordered by g ascending and, within each g, by v descending
                Scenario: Nulls last
                • WHEN a column holding null, 2, 1 is sorted with nullsLast = true
                • THEN the order is 1, 2, null
                Scenario: Length mismatch
                • WHEN a sort by three keys gets descending = [true, false]
                • THEN NanuqError is raised
                ADDED
                Sampling rows

                DataFrame SHALL support sample(n, withReplacement = false, shuffle = false, seed = none(int)) and sample(fraction, ...) with the same options. Asking for more rows than there are without replacement SHALL raise NanuqError. The same seed SHALL give the same rows.

                Scenario: Seeded sample
                • WHEN sample(3, seed = some(42)) runs twice on the same 10-row frame
                • THEN both results have 3 rows and are equal
                Scenario: Fraction
                • WHEN sample(fraction = 0.5) runs on 10 rows
                • THEN the result has 5 rows
                Scenario: Too many rows
                • WHEN sample(11) runs on 10 rows
                • THEN NanuqError is raised

                Unchanged in this spec: Every n-th row, Frame interpolation, Casting by data type, Several filter predicates, Group order parameter, Frame aggregations, Group-by shortcuts, Iterating over groups, Frame fillNan and select without a frame

                native-bridge modified ~1

                MODIFIED
                Nim declarations mirror the C ABI
                `src/nanuq/ffi.nim` SHALL declare every exported function with matching signatures, and the enums `NqBinOp`, `NqUnary`, `NqDtype`, `NqDtypeClass`,`NqJoinType`, `NqJoinType`,`NqJoinValidation`, `NqJoinValidation`, `NqMaintainOrderJoin`, `NqConcat`,`NqConcat` `NqUniqueKeepStrategy`, `NqClosedInterval`,and `NqQuantileMethod`, `NqFillNullStrategy`, `NqRoundMode`, `NqQuoteStyle`, `NqRankMethod`, `NqErrorKind`,`NqUniqueKeepStrategy` `NqStrOp`, `NqTimeUnit`, `NqClosedWindow`, `NqDtOp`, `NqCatOp`, `NqParquetCompression` and `NqIpcCompression` SHALL keep the same order as in Rust. `NqDtype` SHALL also keep the order of `DataTypeKind`, and the option enums the order of their Nim API enums. Data types SHALL cross the ABI as an `NqDtypeSpec` struct (code, time unit, time zone, categories) with the same field order on both sides. Scenario: ABI change - **WHEN** a function is added or changed in `rust/src/lib.rs` - **THEN** `src/nanuq/ffi.nim` is updated in the same change

                Unchanged in this spec: C ABI over Polars with opaque handles, Errors and panics never cross the boundary, Linking the static library, Columns cross in bulk, Library version check, Formatted cells, Polars version matches a py-polars release

                Design

                Design

                Context

                Lazy verbs cross the ABI as functions that borrow a LazyFrame and return a new one. Lists of names go across as a pointer and a length. Enums cross as #[repr(C)] integers mirrored in ffi.nim. DataFrame verbs are eager shortcuts: df.lazy.<verb>.collect.

                Polars 0.55 has:

                • LazyFrame::drop(Selector), rename(existing, new, strict), slice(offset: i64, len: IdxSize), tail(n) and limit(n).
                • unique_generic(Option<Vec<Expr>>, UniqueKeepStrategy) and its unique_stable variant, reverse(), with_row_index(name, Option<IdxSize>), and sort_by_exprs(exprs, SortMultipleOptions).
                • DataFrame::sample_n_literal and sample_frac, behind the random feature.

                Goals / Non-Goals

                Goals:

                • Each verb Python Polars has on DataFrame and LazyFrame in this list, with the same defaults.
                • One Rust function per verb, carrying all of its options.

                Non-Goals:

                • Selectors (cs.numeric(), regex) as verb arguments. That is the column selectors change, which can widen drop and unique later without breaking these forms.
                • A lazy sample. Python has none. It would need a select over every column with sample_n.

                Decisions

                drop and strict

                nq_lf_drop(lf, names, n, strict) builds by_name(names, strict). With strict = true, a missing column raises NanuqError when the query runs, as in Python.

                rename keeps both lists

                nq_lf_rename(lf, existing, new, n, strict) maps onto LazyFrame::rename. Nim takes openArray[(string, string)], so df.rename({"a": "x"}) reads like cast({"a": Int32}).

                slice, head, tail

                nq_lf_slice(lf, offset: i64, len: u32). When there is no length, Nim passes high(uint32), as Python does for length=None. LazyFrame head(n) is limit(n). tail(n) is slice(-n, n), done in Nim with no extra ABI function.

                unique

                nq_lf_unique(lf, names, n, keep: NqUniqueKeepStrategy, maintain_order) calls unique_stable_generic when maintain_order, and unique_generic otherwise. An empty subset means all columns.

                One sort function

                nq_lf_sort_by(lf, exprs, n, descending: *const bool, n_desc, nulls_last: *const bool, n_nulls, maintain_order) replaces nq_lf_sort. Nim builds col(name) for string keys. Rust passes the bool lists to SortMultipleOptions as they are: an empty list becomes [false], and one value broadcasts. A list whose length is neither 1 nor the number of keys raises NanuqError.

                • Why: one ABI function covers single and multiple keys and both key forms. The one-column sort(by: string, ...) in Nim becomes a thin wrapper.
                sample on DataFrame

                nq_df_sample(df, n: usize, fraction: f64, by_fraction: bool, with_replacement, shuffle, has_seed, seed: u64). Nim overloads sample(df, n: int, ...) and sample(df, fraction: float, ...). seed = none(int) means a random seed. A negative seed raises ValueError in Nim before the call.

                • Alternative: n = -1 and fraction = NaN as "unset" in one proc. Overloads read better and give a compile error when neither is passed.
                withRowIndex

                nq_lf_with_row_index(lf, name, offset: u32). A negative offset raises ValueError in Nim.

                Risks / Trade-offs

                • The random feature adds the rand crates to the build. That costs seconds against the Polars build.
                • Replacing nq_lf_sort changes the ABI. That is fine within 0.2.0-dev.
                Tasks13 of 13 done

                1. Bridge 6/6

                • 1.1Add the Polars feature random to src/rust/Cargo.toml
                • 1.2Add nq_lf_drop, nq_lf_rename, nq_lf_slice, nq_lf_reverse and nq_lf_with_row_index
                • 1.3Add NqUniqueKeepStrategy and nq_lf_unique (stable when maintain_order)
                • 1.4Replace nq_lf_sort with nq_lf_sort_by (expressions, bool lists, maintain_order)
                • 1.5Add nq_df_sample (n or fraction, replacement, shuffle, optional seed)
                • 1.6Mirror everything in ffi.nim; verify that cargo build --release passes

                2. Nim API 5/5

                • 2.1Add drop, rename, head (LazyFrame), tail, slice, reverse and withRowIndex on LazyFrame, with DataFrame shortcuts
                • 2.2Add the pure enum UniqueKeepStrategy and unique
                • 2.3Add multi-key sort (names and expressions), and nullsLast and maintainOrder on the one-column sort
                • 2.4Add sample on DataFrame (n and fraction overloads)
                • 2.5Write tests/test_verbs.nim covering each verb, strict failures, negative offsets, every keep strategy, sort broadcasting and the length mismatch error, and seeded samples that repeat; add it to nanuq.nimble and .gitignore

                3. Docs and integration 2/2

                • 3.1List the new verbs in the README "What is there"; verify that nimble test and nimble example pass
                • 3.2Check that CI is green on the PR, including the Rust rebuild

                Workflow follow-up 0/0

                  Revisions2 revisions
                  r1 32f6987 2026-10-31 Add frame verbs (implements add-frame-verbs)

                  First version: .openspec.yaml, design.md, proposal.md, specs/frame-verbs/spec.md, specs/native-bridge/spec.md, tasks.md

                  r2 e3c1120 2026-10-31 Add setRandomSeed and plain int seed for sample
                  proposal.md
                  § What Changes
                  - New verbs on LazyFrame, with eager DataFrame shortcuts: - `drop("a")` or `drop(["a", "b"], strict = true)` removes columns. - `rename({"old": "new"}, strict = true)` renames columns. - `head(n = 5)` (LazyFrame; DataFrame already has it) and `tail(n = 5)` keep the first or last rows. - `slice(offset)` and `slice(offset, length)` keep a window of rows. A negative offset counts from the end. - `unique("a", keep = First, maintainOrder = false)` (or a list of names) drops duplicate rows, judged on all columns or on the named ones. `keep` is a `UniqueKeepStrategy`: `Any` (default), `First`, `Last` or `None`. - `reverse()` reverses the row order. - `withRowIndex(name = "index", offset = 0)` adds a row number column first. - Sorting by several keys: `sort(["species", "mass"], descending = [false, true], nullsLast = [true], maintainOrder = false)`, by column names or expressions. A single value in `descending` or `nullsLast` applies to every key. The one-column `sort(by, descending)` gains `nullsLast` and `maintainOrder`. - `sample` on DataFrame: `sample(n, withReplacement = false, shuffle = false, seed = none(int))`, and `sample(fraction = 0.1, ...)`. `seed = 42` works too, and `setRandomSeed(42)` seeds Polars' global generator (added during implementation, after Pietro picked this option for the 0.2 explainer). - New pure enum `UniqueKeepStrategy`, following the `api-conventions` spec. - Polars feature `random` is compiled in (for `sample`). The ABI stays `0.2.0-dev`.
                  § Differences from Polars
                  - **`keep` is an enum.** Python's `keep="first"` becomes `keep = First` (pure enum `UniqueKeepStrategy`, Rust's type and names). - **`descending` and `nullsLast` in multi-key sort are lists.** Python takes a bool or a list. Nim takes `openArray[bool]`: one value applies to all keys, as in Rust's `SortMultipleOptions`. Empty (the default) means all false. The one-column `sort` keeps plain bools. - **`slice` without a length** is a separate overload instead of Python's `length=None`. - **`sample` is DataFrame only**, as in Python (LazyFrame has no `sample`). `n` and `fraction` are two overloads, chosen by the argument name (`fraction = 0.1`) or type, and one of them is required (Python defaults to one row when both are missing). `seed` is an `Option[int]`.`Option[int]` or a plain `int`. `setRandomSeed` is Python's `pl.set_random_seed`. - **`rename` takes pairs only.** Python also accepts a function from old to new name. That form is left for later. - **`drop` takes one name or a list**, not Python's `*columns`: Nim `varargs` followed by `strict` can't take several positional names, so `drop("a", "b")` is written `drop(["a", "b"])`. **`unique`'s subset** is one name or a list, as in Python. Selectors and expressions come with the column selectors change. - **Not in this change:** `drop` with selectors, `gather_every`, `shift`, `top_k`/`bottom_k`, `clear`, `first`/`last` on frames, `with_row_count` (deprecated in Python), and sort's `multithreaded` flag. They stay in the coverage map. - **Names** follow Polars in camelCase: `with_row_index` → `withRowIndex`, `nulls_last` → `nullsLast`, `maintain_order` → `maintainOrder`, `with_replacement` → `withReplacement`.

                  add-horizontal-and-ranges Archived

                  openspec/changes/archive/2026-11-01-add-horizontal-and-ranges
                  1. Proposal
                  2. Specs
                  3. Tasks
                  4. Implement 4/4
                  5. Archive
                  Proposal

                  Why

                  Wide tables keep one measurement per column (monthly rainfall in twelve columns, a score per judge), and the natural questions run across a row: the total, the warmest month, whether any value is missing, the first value that is present. Polars answers them with horizontal functions, which Nanuq lacks: the O'Reilly chapter 9 sections "Using functions" and "When, then, otherwise" stop on sum_horizontal, all_horizontal and any_horizontal. Generated columns (int_range, repeat, linear_space) and correlation (pl.corr, which the 0.4 explainer needs to relate El Niño to world temperature) are missing too.

                  It is the fifth change of the 0.4 release.

                  What Changes

                  • Horizontal functions: sumHorizontal, meanHorizontal (both with ignoreNulls), minHorizontal, maxHorizontal, allHorizontal, anyHorizontal and coalesce, taking expressions, literals, selectors or a list of column names.
                  • Ranges: intRange(start, stop, step, dtype), linearSpace(start, stop, numSamples, closed), repeat(value, n).
                  • Correlation: corr(a, b, correlationMethod, propagateNans) with a CorrelationMethod pure enum (Pearson, Spearman), and cov(a, b, ddof).

                  Capabilities

                  New Capabilities
                  • horizontal-functions: horizontal functions, ranges, correlation.

                  Differences from Polars

                  • corr's method parameter is called correlationMethod because method is a Nim keyword (Python: method="pearson"); usually it is passed positionally: corr("a", "b", Spearman).
                  • sumHorizontal and meanHorizontal take ignoreNulls only in the overloads with a list (sumHorizontal([col.a, col.b], ignoreNulls = false)), because the main overload takes any number of arguments.
                  • repeat of a string needs lit (repeat(lit("x"), 3)): with a plain string, std/strutils' repeat is chosen.
                  • intRange with one argument counts from 0, as Python's pl.int_range(n).
                  • Not included: fold, reduce, cum_fold (need Nim callbacks, 0.5), concat_list (List columns, 0.5), cum_sum_horizontal (returns a Struct), int_ranges.

                  Impact

                  • src/rust/src/lib.rs: nq_expr_horizontal, nq_expr_int_range, nq_expr_linear_space, nq_expr_repeat, nq_expr_corr; src/nanuq/ffi.nim, src/nanuq.nim.
                  • New tests/test_horizontal.nim.
                  Spec changeshorizontal-functions +3

                  horizontal-functions modified +3

                  ADDED
                  Horizontal functions

                  sumHorizontal, meanHorizontal, minHorizontal, maxHorizontal, allHorizontal, anyHorizontal and coalesce SHALL compute row by row over their arguments, which SHALL be expressions, literals, selectors (expanded to their columns) or a list of column names. sumHorizontal and meanHorizontal SHALL skip nulls unless ignoreNulls = false, and coalesce SHALL return the first non-null value.

                  let df = newDataFrame:
                    station: ["Lima", "Piura", "Tumbes"]
                    jan: [1.0, 4.0, nil]
                    feb: [2.0, 30.0, 61.0]
                    mar: [1.0, 80.0, 95.0]
                  echo df.select(col.station, sumHorizontal(col(float)).alias("total"),
                                 maxHorizontal("jan", "feb", "mar").alias("wettest"),
                                 coalesce(col.jan, col.feb).alias("first_reading"))
                  TBD
                  Scenario: Nulls in a sum
                  • WHEN sumHorizontal([col.a, col.b], ignoreNulls = false) runs on a row where b is null
                  • THEN that row's sum is null
                  Scenario: All and any
                  • WHEN allHorizontal and anyHorizontal run on a row holding true and false
                  • THEN they give false and true
                  ADDED
                  Generated columns

                  intRange(start, stop, step = 1, dtype = Int64) (or intRange(stop)) SHALL produce the integers from start up to stop excluded, linearSpace(start, stop, numSamples, closed) SHALL produce evenly spaced floats, and repeat(value, n) SHALL repeat a value n times.

                  echo newDataFrame().select(intRange(1950, 2026, 25).alias("year"),
                                             linearSpace(0, 1, 4).alias("share"),
                                             repeat("ENSO", 4).alias("index"))
                  TBD
                  Scenario: Zero step
                  • WHEN intRange(0, 5, step = 0) is built
                  • THEN ValueError is raised
                  ADDED
                  Correlation

                  corr(a, b, correlationMethod = Pearson) SHALL return the Pearson or Spearman correlation of two columns as an aggregation, and cov(a, b, ddof = 1) their covariance.

                  let df = newDataFrame:
                    oni: [-1.0, 0.0, 0.5, 2.0]
                    world: [14.6, 14.8, 14.9, 15.2]
                  echo df.select(corr("oni", "world").round(3).alias("pearson"),
                                 corr("oni", "world", Spearman).alias("spearman"))
                  TBD
                  Scenario: Perfect correlation
                  • WHEN corr runs on 1, 2, 3 and 2, 4, 6
                  • THEN the result is 1.0
                  Tasks4 of 4 done

                  1. Implementation 4/4

                  • 1.1Horizontal functions and coalesce
                  • 1.2intRange, linearSpace, repeat
                  • 1.3corr with CorrelationMethod, cov
                  • 1.4Tests in tests/test_horizontal.nim; nimble test and nimble specexamples pass; CHANGELOG
                  Revisions1 revision
                  r1 570d956 2026-11-01 Nanuq 0.4, changes 1-7: math, cumulative, rolling, value functions, horizontal, reshaping, time grouping

                  First version: proposal.md, specs/horizontal-functions/spec.md, tasks.md

                  add-html-tables Archived

                  created 2026-10-28 · openspec/changes/archive/2026-10-28-add-html-tables
                  1. Proposal
                  2. Specs
                  3. Tasks
                  4. Implement 6/6
                  5. Archive
                  Proposal

                  Why

                  In nimib documents a DataFrame can only be shown as Polars' text table. That table is the reference output and stays the default in the dev log (it is also a check that Nanuq prints exactly what Polars prints). For pages where a real HTML table reads better, Nanuq should offer the same HTML table that Python Polars shows in Jupyter.

                  This takes up the BACKLOG.md entry "nimib integration" (Ecosystem).

                  What Changes

                  • New toHtml(df, maxRows = 10, maxCols = 75): string, a port of Python Polars' DataFrame._repr_html_. It returns the same HTML, with the same information:
                  • shape: (344, 8) above the table, with _ thousand separators;
                  • a header row of column names and a row of dtypes (str, i64, f64, …);
                  • when there are more rows or columns than the limits, the first and last ones around a … row or column (10 rows show as 5, …, 5);
                  • each cell formatted by Polars itself, as Python shows it: floats as in the text table, strings in quotes and cut after 30 characters with …, nulls as null;
                  • HTML escaping, and the small <style> block and dataframe class Python emits.
                  • It works in any HTML context. In nimib it is used as nbRawHtml: df.toHtml, so Nanuq does not depend on nimib. The Nanuq theme gets CSS for table.dataframe.
                  • A new bridge function returns one cell formatted the way Python's get_fmt does (AnyValue's Display, with the string cut).
                  • The dev log uses it sparingly: one short section in "How Nanuq works" shows the same result as text and as HTML. Every other output stays Polars' text table.

                  Capabilities

                  New Capabilities

                  None.

                  Modified Capabilities
                  • dataframe-api: an added requirement for HTML tables.
                  • native-bridge: an added requirement for formatted cells.

                  Differences from Polars

                  • Rust has no HTML output; this follows Python.
                  • Python calls it _repr_html_ and reads the limits from the POLARS_FMT_MAX_ROWS, POLARS_FMT_MAX_COLS and POLARS_FMT_STR_LEN environment variables. Nanuq names it toHtml and takes the row and column limits as parameters with Python's defaults (10 and 75); the string length is fixed at Python's default (30). The POLARS_FMT_TABLE_HIDE_* switches are not supported.
                  • HTML vs text table. As in Python, the HTML defaults differ from the text table: the text table shows at most 8 columns, the HTML table 75. Rows match (10).

                  Impact

                  • src/rust/src/lib.rs and src/nanuq/ffi.nim: one new function. This changes the Rust library, so it needs a library build. lib-v0.1.0 is already released without it, so toHtml ships with the next library release (e.g. lib-v0.1.1); until then it works only with a local cargo build.
                  • src/nanuq.nim: toHtml. docs/nanuqtheme.nim: table CSS. docs/blog/how_nanuq_works.nim.
                  • New tests in tests/.
                  Spec changesdataframe-api +1 · native-bridge +1

                  dataframe-api modified +1

                  ADDED
                  HTML tables

                  toHtml(df, maxRows = 10, maxCols = 75) SHALL return the HTML that Python Polars' DataFrame._repr_html_ returns for the same data and limits: shape line, names and dtypes header rows, cells formatted by Polars, and … rows and columns when truncated.

                  Scenario: Same as Python
                  • WHEN toHtml is called on penguins()
                  • THEN the result equals what Python Polars' _repr_html_ returns for the same CSV read with null_values="NA"
                  Scenario: Truncation
                  • WHEN a DataFrame with 344 rows is rendered with maxRows = 10
                  • THEN the body shows rows 0 to 4, a … row, and rows 339 to 343
                  Scenario: Escaping and nulls
                  • WHEN a string cell holds <b> and another cell is null
                  • THEN the first is shown as "&lt;b&gt;" and the second as null

                  Unchanged in this spec: Automatic memory management, Building and reading data, Reading columns by type, Expressions and lazy queries, Block syntax for building a DataFrame, Column shorthand, True division, Errors as PolarsError

                  native-bridge modified +1

                  ADDED
                  Formatted cells

                  The bridge SHALL return a single cell as text formatted by Polars, as Python Polars' get_fmt does: the value's display form, with strings in quotes and cut to a given number of characters followed by ….

                  Scenario: Float cell
                  • WHEN a cell holding 5076.016260162602 is formatted
                  • THEN the text is the same as in Polars' text table, 5076.01626
                  Scenario: Long string
                  • WHEN a string of 40 characters is formatted with a limit of 30
                  • THEN the text is a quote, its first 30 characters and …

                  Unchanged in this spec: C ABI over Polars with opaque handles, Errors and panics never cross the boundary, Nim declarations mirror the C ABI, Linking the static library, Columns cross in bulk, Library version check, Polars version matches a py-polars release

                  Tasks6 of 6 done

                  1. Bridge 1/1

                  • 1.1Add a Rust function formatting one cell (by column and row, with a string length limit) like py-polars' get_fmt, returning the needed length when the buffer is too small; mirror it in ffi.nim; verify cargo build --release passes

                  2. toHtml 2/2

                  • 2.1Add toHtml(df, maxRows = 10, maxCols = 75) to src/nanuq.nim, ported from py-polars' HTMLFormatter / NotebookFormatter; verify with tests for truncation, escaping, nulls and a wide frame
                  • 2.2Compare with Python: render penguins and a small mixed-dtype frame in Python Polars (if available in the container) and check the HTML is identical; otherwise compare against stored expected output; record the Polars version used

                  3. Dev log 3/3

                  • 3.1Add table.dataframe CSS to docs/nanuqtheme.nim (light and dark)
                  • 3.2Add one short section to "How Nanuq works" showing a result as text and as nbRawHtml: summary.toHtml; leave every other output as text; verify the post renders and republish its artifact
                  • 3.3Check CI is green on the PR

                  Workflow follow-up 0/0

                    Revisions1 revision
                    r1 ed08e02 2026-10-28 Archive the dev-log index, HTML tables and Datamancer interop changes

                    First version: .openspec.yaml, proposal.md, specs/dataframe-api/spec.md, specs/native-bridge/spec.md, tasks.md

                    add-inspection-and-config Archived

                    openspec/changes/archive/2026-10-31-add-inspection-and-config
                    1. Proposal
                    2. Specs
                    3. Design
                    4. Tasks
                    5. Implement 6/6
                    6. Archive
                    Proposal

                    Why

                    The first thing the 0.3 explainer does with a new table is look at it: one line per column with glimpse, summary statistics with describe, and all 36 races of the season printed at once, which needs more than Polars' default of 8 rows. Nanuq has none of these. Python Polars has all three (glimpse, describe, pl.Config), and Rust Polars reads its table limits from environment variables that Python's Config sets.

                    This is the second change of the 0.3 release, following the dev log "Designing Nanuq 0.3" (section 7) and Pietro's follow-up on 2026-10-31: keep the four setTbl*-style setters (one line with semicolons is fine) and also offer setConfig(...) and a scoped withConfig(...).

                    What Changes

                    • glimpse(df, maxItemsPerColumn = 10, maxColnameLength = 50): string, Python's layout: Rows: and Columns:, then $ name <dtype> v1, v2, ... per column, strings quoted as Python's repr does. It returns the text (echo df.glimpse) instead of printing.
                    • describe(df, percentiles = [0.25, 0.5, 0.75], interpolation = Nearest): DataFrame: a statistic column (count, null_count, mean, std, min, the percentiles, max) and one column per input column, f64 for numeric and boolean columns, str for the others, built from expressions as Python Polars does. Also on LazyFrame.
                    • Display config, through the environment variables Rust Polars reads at every print:
                    • setters setTblRows(n), setTblCols(n), setTblWidthChars(n), setFmtStrLengths(n); -1 means no limit, none(int) restores the default;
                    • setConfig(tblRows = 12, tblCols = 10, tblWidthChars = 120, fmtStrLengths = 60), where an option left out stays as it is;
                    • resetConfig() restores every default;
                    • withConfig(tblRows = 40): body applies the options for the block and restores the previous values afterwards, also when the block raises.

                    Capabilities

                    New Capabilities
                    • inspection: glimpse, describe and the display config.
                    Modified Capabilities

                    None.

                    Differences from Polars

                    Expected differences from Polars' Rust and Python APIs:

                    • glimpse returns a string and never prints; Python prints by default and returns a string only with return_type="string". return_type="frame" is left out (it needs List columns). Rust Polars has no glimpse.
                    • describe follows Python's output. Rust Polars dropped describe, so Nanuq builds it from expressions in Nim, the way Python's LazyFrame.describe does. Python's thousands separator for counts in string columns is not applied (Nanuq has no thousands separator setting yet). Temporal columns get their statistics with the temporal change.
                    • Config is a set of procs and a withConfig block, Nim's version of Python's pl.Config used as a function, a context manager or a decorator (no decorator). Only the four table options are covered; Python's other options (tbl_formatting, float_precision, thousands_separator, ...) are left for later. Rust Polars has no config API, only the environment variables (POLARS_FMT_MAX_ROWS, POLARS_FMT_MAX_COLS, POLARS_TABLE_WIDTH, POLARS_FMT_STR_LEN), which Nanuq sets.
                    • Names follow Python in camelCase: set_tbl_rows → setTblRows, max_items_per_column → maxItemsPerColumn.

                    Impact

                    • src/nanuq.nim: glimpse, describe, the config procs and the withConfig macro. No change to the C ABI.
                    • tests/test_inspection.nim (new), added to nanuq.nimble and .gitignore.
                    • README lists the new procs.
                    Spec changesinspection +4

                    inspection modified +4

                    ADDED
                    glimpse

                    glimpse(df, maxItemsPerColumn = 10, maxColnameLength = 50) SHALL return, as a string, the lines Rows: <height> and Columns: <width>, then one line per column: $ <name> <<dtype>> <values>, with names left-aligned and dtypes right-aligned to a common width, and the first maxItemsPerColumn values joined by ", ". Nulls SHALL be null, booleans True/False, and strings quoted as Python's repr quotes them. Names longer than maxColnameLength SHALL be cut and end with ….

                    let df = newDataFrame:
                      rider: ["Pogačar", "Seixas", "Van der Poel"]
                      wins: [22, 8, nil]
                      pro: [true, false, true]
                      race: ["Giro d'Italia", "Tour", "Vuelta"]
                    echo df.glimpse
                    Rows: 3
                    Columns: 4
                    $ rider  <str> 'Pogačar', 'Seixas', 'Van der Poel'
                    $ wins   <i64> 22, 8, null
                    $ pro   <bool> True, False, True
                    $ race   <str> "Giro d'Italia", 'Tour', 'Vuelta'
                    
                    Scenario: Long frame
                    • WHEN a column of 100 rows is glimpsed with maxItemsPerColumn = 3
                    • THEN its line shows the first 3 values only
                    Scenario: Long name
                    • WHEN a column named with 60 characters is glimpsed
                    • THEN its line shows the first 49 characters followed by …
                    ADDED
                    describe

                    describe(percentiles = [0.25, 0.5, 0.75], interpolation = Nearest) on DataFrame and LazyFrame SHALL return a DataFrame with a statistic column holding count, null_count, mean, std, min, one row per percentile (labelled as 25%) and max, followed by one column per input column: f64 for numeric and boolean columns, str for the others, and null where a statistic does not apply.

                    let df = newDataFrame:
                      rider: ["Pogačar", "Seixas", "Van der Poel"]
                      wins: [22, 8, nil]
                      pro: [true, false, true]
                    echo df.describe
                    shape: (9, 4)
                    ┌────────────┬──────────────┬──────────┬──────────┐
                    │ statistic  ┆ rider        ┆ wins     ┆ pro      │
                    │ ---        ┆ ---          ┆ ---      ┆ ---      │
                    │ str        ┆ str          ┆ f64      ┆ f64      │
                    ╞════════════╪══════════════╪══════════╪══════════╡
                    │ count      ┆ 3            ┆ 2.0      ┆ 3.0      │
                    │ null_count ┆ 0            ┆ 1.0      ┆ 0.0      │
                    │ mean       ┆ null         ┆ 15.0     ┆ 0.666667 │
                    │ std        ┆ null         ┆ 9.899495 ┆ null     │
                    │ min        ┆ Pogačar      ┆ 8.0      ┆ 0.0      │
                    │ 25%        ┆ null         ┆ 8.0      ┆ null     │
                    │ 50%        ┆ null         ┆ 22.0     ┆ null     │
                    │ 75%        ┆ null         ┆ 22.0     ┆ null     │
                    │ max        ┆ Van der Poel ┆ 22.0     ┆ 1.0      │
                    └────────────┴──────────────┴──────────┴──────────┘
                    Scenario: Custom percentiles
                    • WHEN describe(percentiles = [0.1, 0.9]) runs
                    • THEN the statistic column holds count, null_count, mean, std, min, 10%, 90% and max
                    Scenario: Statistics that do not apply
                    • WHEN a frame with a string and a boolean column is described
                    • THEN mean, std and percentiles are null for the string column, and std and percentiles for the boolean one
                    Scenario: No columns
                    • WHEN newDataFrame().describe runs
                    • THEN NanuqError is raised
                    ADDED
                    Display config

                    The API SHALL set how tables print with setTblRows(n), setTblCols(n), setTblWidthChars(n) and setFmtStrLengths(n), where -1 means no limit and none(int) restores Polars' default; with setConfig(tblRows, tblCols, tblWidthChars, fmtStrLengths), where options left out are unchanged; and with resetConfig(), which restores every default. The settings SHALL apply to every later $ of a DataFrame.

                    let df = newDataFrame(series("n", [1, 2, 3, 4, 5, 6]))
                    setTblRows(4); setFmtStrLengths(10)
                    echo df
                    setConfig(tblRows = 2, tblCols = 5)
                    echo df
                    resetConfig()
                    shape: (6, 1)
                    ┌─────┐
                    │ n   │
                    │ --- │
                    │ i64 │
                    ╞═════╡
                    │ 1   │
                    │ 2   │
                    │ …   │
                    │ 5   │
                    │ 6   │
                    └─────┘
                    shape: (6, 1)
                    ┌─────┐
                    │ n   │
                    │ --- │
                    │ i64 │
                    ╞═════╡
                    │ 1   │
                    │ …   │
                    │ 6   │
                    └─────┘
                    Scenario: No limit
                    • WHEN setTblRows(-1) is called and a frame of 50 rows is printed
                    • THEN all 50 rows are shown
                    Scenario: Reset
                    • WHEN setTblRows(2) and then resetConfig() are called
                    • THEN a frame of 10 rows prints all 10 rows again
                    ADDED
                    Scoped display config

                    withConfig(options): body SHALL apply the named options (tblRows, tblCols, tblWidthChars, fmtStrLengths) while body runs, and SHALL restore the previous settings afterwards, also when body raises.

                    let df = newDataFrame(series("n", [1, 2, 3, 4, 5, 6]))
                    withConfig(tblRows = 2):
                      echo df
                    echo df.shape, " ", ($df).count('\n')
                    shape: (6, 1)
                    ┌─────┐
                    │ n   │
                    │ --- │
                    │ i64 │
                    ╞═════╡
                    │ 1   │
                    │ …   │
                    │ 6   │
                    └─────┘
                    (6, 1) 11
                    Scenario: Restored after an exception
                    • WHEN the body of withConfig(tblRows = 2) raises
                    • THEN the exception propagates and the row limit is back to its previous value

                    Unchanged in this spec: Describe prints temporal values as Python, Table formatting options

                    Design

                    Design

                    Context

                    Rust Polars' table formatter (polars-core/src/fmt.rs) reads POLARS_FMT_MAX_ROWS, POLARS_FMT_MAX_COLS, POLARS_TABLE_WIDTH and POLARS_FMT_STR_LEN with std::env::var every time a frame is formatted; negative values mean no limit. Python's pl.Config.set_tbl_rows and friends set these variables. Python's glimpse and describe are written in Python over expressions.

                    Decisions

                    Config through the process environment

                    Nim's putEnv/delEnv change the same process environment that Rust's std::env::var reads, so no ABI function is needed. withConfig saves the four variables (value or absent), applies the options with setConfig, runs the block in try/finally, and restores them. It is a macro over varargs[untyped] because a template with defaulted int | Option[int] parameters followed by a block does not match named arguments.

                    Options take int | Option[int]. In the setters, none(int) restores the default; in setConfig and withConfig, an option left out is left unchanged.

                    glimpse in Nim

                    Values are the first maxItemsPerColumn rows, read as Option[string], which uses Polars' formatting for non-string columns. Python formats them with str(), so booleans become True/False; string values are quoted like Python's repr (single quotes, double quotes when the value holds a single quote and no double quote, backslash escapes). Names longer than maxColnameLength are cut with ….

                    describe in Nim

                    For each column, the applicable metric expressions are selected in one query (count, nullCount, mean, std, min, quantiles, max), each cast to f64 for numeric and boolean columns and to str otherwise; the others are null in the result. The single result row is then reshaped in Nim into the output frame. Percentile labels use Python's f"{q * 100:g}%".

                    Risks / Trade-offs

                    • The environment is process-wide, so config is not thread-local, as in Python.
                    Tasks6 of 6 done

                    1. Nim API 4/4

                    • 1.1Add glimpse with Python's layout and value formatting
                    • 1.2Add describe on DataFrame and LazyFrame with percentiles and interpolation
                    • 1.3Add setTblRows, setTblCols, setTblWidthChars, setFmtStrLengths, setConfig, resetConfig and the withConfig macro
                    • 1.4Write tests/test_inspection.nim (glimpse truncation and quoting, describe on numeric, bool and string columns and custom percentiles, setters, withConfig restoring after an exception); add it to nanuq.nimble and .gitignore

                    2. Docs and integration 2/2

                    • 2.1README lists the new procs; nimble test and nimble specexamples pass
                    • 2.2Archive the change and add CHANGELOG lines
                    Revisions1 revision
                    r1 3280788 2026-10-31 OpenSpec add-inspection-and-config: glimpse, describe, display config

                    First version: design.md, proposal.md, specs/inspection/spec.md, tasks.md

                    add-joins-and-concat Archived

                    created 2026-10-31 · openspec/changes/archive/2026-10-31-add-joins-and-concat
                    1. Proposal
                    2. Specs
                    3. Design
                    4. Tasks
                    5. Implement 10/10
                    6. Archive
                    Proposal

                    Why

                    Nanuq can query one table, but real analyses combine several: measurements with a lookup table, this month's file with last month's, a set of keys with the rows that match them. Joins and concatenation are the most used Polars verbs that Nanuq still lacks, and the 0.2 plan puts them right after data types (casting key columns to a common type is the usual fix when a join refuses mismatched keys).

                    This change takes up the BACKLOG.md entry "Joins" (API) and adds concatenation, which has no entry. Joins are the first verbs with many option values, so the change also settles, for all of Nanuq, how option values are spelled in Nim (decided by Pietro on 2026-10-31 after a design note comparing strings, prefixed enums, pure enums and one proc per variant). It is the second change of the 0.2 release (see the Polars coverage map, area "Joins and concatenation").

                    What Changes

                    • New join on LazyFrame and DataFrame, with Polars' join types: inner, left, right, full, semi, anti and cross.
                    • Keys by name (on = ["station"]), or different names on each side (leftOn = ["id"], rightOn = ["station_id"]), as strings or expressions.
                    • how takes a JoinType value: how = Left.
                    • Options as named parameters with Polars' defaults: suffix = "_right", validate (JoinValidation, default ManyToMany), nullsEqual = false, coalesce (none(bool) = Polars' per-join-type default), and maintainOrder (MaintainOrderJoin, default None: no order guaranteed).
                    • A cross join takes no keys: a.join(b, how = Cross).
                    • New concat of several LazyFrames or DataFrames, with how a ConcatMethod: Vertical (default), VerticalRelaxed, Horizontal, Diagonal, DiagonalRelaxed.
                    • API convention for option values (all of Nanuq): a closed set of option values is a pure enum ({.pure.}) with the Rust Polars type name and its PascalCase variant names, e.g. JoinType.Left, written bare (how = Left) where the type is known. The convention is recorded as a new spec, in openspec/config.yaml (so every later proposal follows it) and in the README.
                    • BREAKING: DataTypeKind follows the convention: dkInt64 becomes DataTypeKind.Int64, dkOther becomes DataTypeKind.Other. The DataType constants (Int64, String, ...) are unchanged and still what users normally write.
                    • Polars features semi_anti_join, cross_join and diagonal_concat are compiled in. The ABI stays 0.2.0-dev (released as lib-v0.2.0 with the rest of 0.2).

                    Capabilities

                    New Capabilities
                    • combining-frames: joins and concatenation of DataFrames and LazyFrames.
                    • api-conventions: naming rules that apply across the Nim API, starting with how option values are spelled.
                    Modified Capabilities
                    • data-types: DataTypeKind values become pure PascalCase (DataTypeKind.Other).
                    • native-bridge: the enums that must keep the same order in Rust and ffi.nim now include the join and concat enums.

                    Differences from Polars

                    Expected differences from Polars' Rust and Python APIs:

                    • Enums instead of strings. Python's how="left", validate="1:m", maintain_order="left_right" and pl.concat(how="diagonal") become pure enums with Rust's names: JoinType.Left, JoinValidation.OneToMany, MaintainOrderJoin.LeftRight, and ConcatMethod.Diagonal. In a typed context the bare value works (how = Left); elsewhere it must be qualified, as in Rust. Two enums may share a value name (JoinType.Left, MaintainOrderJoin.Left), as in Rust.
                    • ConcatMethod is Nanuq's. Rust has no single enum for concat (it has separate functions and UnionArgs flags); the name and the values follow Python's how strings in PascalCase.
                    • coalesce is an Option[bool] (Python's None, True, False).
                    • No keyword-only checks. Python rejects on together with left_on; Nim overloads make the two forms separate procs, so mixing them doesn't compile.
                    • Not in this change: join_asof, join_where, merge_sorted, update, vstack/hstack/extend, pl.concat(how="align"), Series concatenation, and concat's rechunk/parallel flags. They stay in the coverage map for later releases.
                    • Names follow Polars in camelCase: left_on → leftOn, right_on → rightOn, nulls_equal → nullsEqual, maintain_order → maintainOrder.

                    Impact

                    • src/rust/src/lib.rs: #[repr(C)] enums NqJoinType, NqJoinValidation, NqMaintainOrderJoin, NqConcat; nq_lf_join and nq_lf_concat. Cargo.toml adds the three Polars features. The Rust library is rebuilt in CI (the first run takes about 10 minutes).
                    • src/nanuq/ffi.nim, src/nanuq.nim: the matching declarations, the enums and the procs; DataTypeKind becomes pure (its uses in src/nanuq.nim and the tests are updated).
                    • openspec/config.yaml: a proposal rule pointing at the api-conventions spec.
                    • tests/test_combining.nim: every join type, key forms, options, and every concat method.
                    • README.md: the API list mentions join and concat, and a short "Conventions" section states the option-value rule.
                    Spec changesapi-conventions +2 · combining-frames +3 · data-types ~2 · native-bridge ~1

                    api-conventions modified +2

                    ADDED
                    Option values are pure enums with Rust Polars names

                    A parameter that takes one of a closed set of option values SHALL use a {.pure.} enum whose type name and PascalCase value names are those of the corresponding Rust Polars enum (e.g. JoinType.Left for JoinType::Left). When Rust Polars has no such enum, Nanuq SHALL name one after Python Polars' parameter strings, in PascalCase. Strings SHALL NOT be used for closed sets of options. Internal C ABI enums in ffi.nim keep their Nq/nq prefixes and are exempt.

                    Scenario: Bare value in a typed context
                    • WHEN user code passes how = Left to join
                    • THEN it compiles and means JoinType.Left
                    Scenario: Shared value names
                    • WHEN user code passes how = Left, maintainOrder = Left
                    • THEN each resolves to its own enum's value, as in Rust
                    Scenario: Untyped context
                    • WHEN user code writes let x = Left with several enums exporting Left
                    • THEN compilation fails as ambiguous, and let x = JoinType.Left compiles
                    ADDED
                    The conventions are documented

                    The README SHALL state the API conventions (camelCase Polars names, pure enums with Rust names for option values), and every OpenSpec proposal SHALL follow them, listing any exception in its "Differences from Polars" section.

                    Scenario: New option type
                    • WHEN a proposal adds a parameter with a closed set of values
                    • THEN it uses the Rust Polars enum name and values as a pure enum, or explains why not

                    Unchanged in this spec: Python's method parameter is how, Parameters that take several types use converter types

                    combining-frames modified +3

                    ADDED
                    Joins

                    The API SHALL join two LazyFrames or two DataFrames with join, with how one of a JoinType: Inner (default), Left, Right, Full, Semi, Anti or Cross. Keys SHALL be given as on (same names on both sides) or leftOn and rightOn, as column names or expressions. A cross join SHALL take no keys.

                    Scenario: Left join
                    • WHEN a frame with keys 1, 2, 3 is left-joined on k to a frame with keys 1, 3
                    • THEN the result has three rows, and the right side's columns are null for key 2
                    Scenario: Semi and anti
                    • WHEN the same frames are semi-joined and anti-joined
                    • THEN the semi join keeps the rows with keys 1 and 3, and the anti join keeps the row with key 2, with only the left columns
                    Scenario: Different key names
                    • WHEN frames are joined with leftOn = ["id"] and rightOn = ["station_id"]
                    • THEN rows are matched on those columns
                    Scenario: Cross join
                    • WHEN a 2-row frame is joined to a 3-row frame with how = Cross
                    • THEN the result has 6 rows
                    Scenario: Keys missing
                    • WHEN join is called without keys and a join type other than Cross
                    • THEN NanuqError is raised
                    ADDED
                    Join options

                    join SHALL accept, with Polars' defaults: suffix ("_right") for clashing column names, validate (JoinValidation: ManyToMany, or ManyToOne, OneToMany, OneToOne), nullsEqual (false), coalesce (none(bool) for Polars' per-join-type default) and maintainOrder (MaintainOrderJoin: None, or Left, Right, LeftRight, RightLeft).

                    Scenario: Suffix
                    • WHEN both frames have a non-key column v and suffix = "_b"
                    • THEN the result has columns v and v_b
                    Scenario: Validation failure
                    • WHEN the right frame has a duplicate key and validate = ManyToOne
                    • THEN NanuqError is raised when the query runs
                    Scenario: Null keys
                    • WHEN both frames have a null key, joined with nullsEqual = true
                    • THEN the null keys match each other; with the default they don't
                    Scenario: Keep left order
                    • WHEN a left join runs with maintainOrder = Left
                    • THEN the result rows follow the left frame's order
                    ADDED
                    Concatenation

                    The API SHALL concatenate a list of LazyFrames or DataFrames with concat, with how a ConcatMethod: Vertical (default, same schema), VerticalRelaxed (cast to common supertypes), Horizontal (side by side), Diagonal (union of columns, missing ones null) or DiagonalRelaxed. An empty list SHALL raise NanuqError.

                    Scenario: Vertical
                    • WHEN two frames with the same columns and 2 and 3 rows are concatenated
                    • THEN the result has 5 rows in input order
                    Scenario: Vertical with different types
                    • WHEN frames whose column a is i64 in one and f64 in the other are concatenated
                    • THEN Vertical raises NanuqError and VerticalRelaxed returns a as f64
                    Scenario: Diagonal
                    • WHEN a frame with columns a, b and one with b, c are concatenated diagonally
                    • THEN the result has columns a, b, c, with nulls where a frame had no column
                    Scenario: Horizontal
                    • WHEN a frame with column a and one with column b are concatenated horizontally
                    • THEN the result has columns a and b

                    data-types modified ~2

                    MODIFIED
                    DataType values
                    The API SHALL provide a `DataType` value with a `kind` of type `DataTypeKind` (a pure enum, see `api-conventions`) covering Boolean, Int8, Int16, Int32, Int64, UInt8, UInt16, UInt32, UInt64, Float32, Float64, String, Null, Date, Datetime,String Duration, Time, Categorical and Enum,Null, plus `DataTypeKind.Other` carrying Polars' name for any other dtype. Datetime andIt Duration values SHALL carry a `timeUnit` (std/times' `TimeUnit`: `Nanoseconds`, `Microseconds` orexport `Milliseconds`), Datetime values a `timeZone` ("" when naive),constants and Enum values their `categories`. `dtype(df, col)` SHALL return a `DataType`. `dtype == T` with aPolars' Nimnames type SHALL(`Int64`, compare`String`, with...), `dataType(T)`, except`==`, that `DateTime` and `Duration` SHALL match any time unit and zone. `$` SHALL print a data type as the Nanuq code that builds or namesreturning it:Polars' theshort constantname, (`Int64`),and the constructorpredicates (`Enum(["low",`isInteger`, "high"])`), or for temporal`isSignedInteger`, types`isUnsignedInteger`, the`isFloat` Nimand type`isNumeric`. a`dtype(df, columncol)` casts to (`Date`, `TimeOfDay`, `DateTime(Milliseconds, "Europe/Rome")`, `Duration(Microseconds)`). Table headers, `glimpse` and `toHtml` SHALL keep Polars'return short names (`i64`). ```nima let df = newDataFrame(series("a", [1, 2])) echo df.dtype("a") # as Nanuq code echo df.dtype("a") == Int64 echo df.dtype("a").kind let t = newDataFrame(series("at", [dateTime(2026, mJul, 4, zone = utc())], timeUnit = Milliseconds, timeZone = "Europe/Rome")) echo t.dtype("at"), " ", t.dtype("at").timeZone, " ", t.dtype("at") == DateTime ````DataType`. ```text Int64 true Int64 DateTime(Milliseconds, "Europe/Rome") Europe/Rome true ``` Scenario: Column dtype - **WHEN** a DataFrame is built from a Nim `seq[int]` column `a` - **THEN** `df.dtype("a") == Int64` and `$df.dtype("a") == "Int64"`"i64"` Scenario: Unmodelled dtype - **WHEN** a column has a dtype Nanuq does not model - **THEN** its `kind` is `DataTypeKind.Other` and `$` returns Polars' name for it Scenario: Zoned datetimePredicates - **WHEN** a`isNumeric` Datetimeis columncalled hason unit`UInt8`, ms`Float32` and zone Europe/Rome`String` - **THEN** `$` gives `DateTime(Milliseconds, "Europe/Rome")` and it equalsreturns `DateTime` Scenario:true, Enum categories -true **WHEN** a column is cast to `Enum(["low", "high"])` - **THEN** `$` of its dtype gives `Enum(["low", "high"])` and `categories` is `@["low", "high"]` Scenario: Tables keep short names - **WHEN** a frame with an Int64 column is printed or turned into HTML - **THEN** the column header shows `i64`false
                    MODIFIED
                    Casting
                    The API SHALL cast expressions (`e.cast(target, strict = true)`), all columns of a DataFrame or LazyFrame (`cast(target, strict = true)`), where `target` is a Nim type or a `DataType`, and named columns (`cast({"a": Int32}, strict = true)`) with `DataType` values. Temporal Nim targets (`Date`, `DateTime`, `Duration`, `TimeOfDay`) SHALL take `timeUnit = Microseconds` and, for `DateTime`, `timeZone = ""`. A strict cast SHALL raise `PolarsError``NanuqError` (when the query runs) if a value cannot be converted; a non-strict cast SHALL turn such values into nulls. Casting to a `DataTypeKind.Other` dtype SHALL raise `PolarsError`.`NanuqError`. ```nim let df = newDataFrame(series("a", [1, 2]), series("s", ["1", "x"])) echo df.cast({"a": Int32}).dtype("a") echo df.select(col("a").cast(float32)).dtype("a") echo df.select(col("s").cast(Int64, strict = false)) echo df.select(col("a").cast(DateTime, timeUnit = Milliseconds, timeZone = "UTC")).dtype("a") ``` ```text Int32 Float32 shape: (2, 1) ┌──────┐ │ s │ │ --- │ │ i64 │ ╞══════╡ │ 1 │ │ null │ └──────┘ DateTime(Milliseconds, "UTC") ``` Scenario: Narrow an integer column - **WHEN** `df.cast({"a": Int32})` runs on an i64 column - **THEN** `dtype("a") == Int32` and `toList(df,`toSeq(df, "a", int)` returns the same values Scenario: Nim type as target - **WHEN** `col("a").cast(float32)` is selected from an i64 column - **THEN** the result column has dtype `Float32` Scenario: Strict failure - **WHEN** a string column holding "1" and "x" is cast to `Int64` with `strict = true` - **THEN** `PolarsError``NanuqError` is raised Scenario: Non-strict cast - **WHEN** the same column is cast with `strict = false` - **THEN** the result is 1 and null Scenario: Integers to dates - **WHEN** a column of microseconds `[0, 86_400_000_000]` is cast to `DateTime` and then to `Date` - **THEN** the result is 1970-01-01 and 1970-01-02

                    Unchanged in this spec: DataType constants and predicates, Schemas, Nim types map to DataType, Full-range UInt64

                    native-bridge modified ~1

                    MODIFIED
                    Nim declarations mirror the C ABI
                    `src/nanuq/ffi.nim` SHALL declare every exported function with matching signatures, and the enums `NqBinOp`, `NqUnary`, `NqDtype`, `NqDtypeClass`,`NqJoinType`, `NqJoinType`, `NqJoinValidation`, `NqMaintainOrderJoin`, `NqConcat`, `NqUniqueKeepStrategy`, `NqClosedInterval`,`NqMaintainOrderJoin` `NqQuantileMethod`,and `NqFillNullStrategy`,`NqConcat` `NqRoundMode`, `NqQuoteStyle`, `NqRankMethod`, `NqErrorKind`, `NqStrOp`, `NqTimeUnit`, `NqClosedWindow`, `NqDtOp`, `NqCatOp`, `NqParquetCompression` and `NqIpcCompression` SHALL keep the same order as in Rust. `NqDtype` SHALL also keep the order of `DataTypeKind`, and the optionjoin and concat enums the order of their Nim API enums. Data types SHALL cross the ABI as an `NqDtypeSpec` struct (code, time unit, time zone, categories) with the same field order on both sides. Scenario: ABI change - **WHEN** a function is added or changed in `rust/src/lib.rs` - **THEN** `src/nanuq/ffi.nim` is updated in the same change

                    Unchanged in this spec: C ABI over Polars with opaque handles, Errors and panics never cross the boundary, Linking the static library, Columns cross in bulk, Library version check, Formatted cells, Polars version matches a py-polars release

                    Design

                    Design

                    Context

                    Lazy verbs cross the ABI as functions that borrow a LazyFrame and return a new one (nq_lf_filter, nq_lf_cast, ...). Lists of expressions are passed as a pointer and a length, and enums as #[repr(C)] integers mirrored in ffi.nim. DataFrame verbs are eager shortcuts: df.lazy.<verb>.collect. In Polars 0.55, LazyFrame::join(other, left_on, right_on, JoinArgs) takes JoinArgs { how, validation, suffix, nulls_equal, coalesce, maintain_order, .. }, and concatenation is concat(lfs, UnionArgs), concat_lf_diagonal and concat_lf_horizontal.

                    Goals / Non-Goals

                    Goals:

                    • Every equi-join type and option Python Polars exposes, with the same defaults.
                    • One Rust function per verb, so options are added without new ABI functions.
                    • Joins and concat read naturally from Nim: a.join(b, on = ["k"], how = Left).
                    • One rule for option values that every later change reuses.

                    Non-Goals:

                    • As-of and inequality joins (later releases, need more features and sorted keys).
                    • Changing Polars' defaults, such as making join order deterministic by default.

                    Decisions

                    One join function with all options
                    nq_lf_join(left, right, left_on: *const *const Expr, n_left, right_on: *const *const Expr,
                               n_right, how: NqJoinType, suffix: *const c_char, validate: NqJoinValidation,
                               nulls_equal: bool, coalesce: i32 /* -1 default, 0 keep, 1 coalesce */,
                               maintain_order: NqMaintainOrderJoin) -> *mut LazyFrame

                    Nim builds the key expressions (col(name) for strings) and passes both lists; for on the same list goes on both sides. A cross join passes empty lists, and Rust rejects keys on a cross join and a missing key on any other join with a clear error.

                    • Why: a single entry point keeps the ABI small; the options map one to one onto JoinArgs.
                    • Alternative: an options struct across the ABI. More layout to keep in sync for no gain at this size.
                    Nim procs
                    proc join*(lf, other: LazyFrame, on: openArray[string], how = JoinType.Inner,
                               suffix = "_right", validate = JoinValidation.ManyToMany, nullsEqual = false,
                               coalesce = none(bool), maintainOrder = MaintainOrderJoin.None): LazyFrame
                    proc join*(lf, other: LazyFrame, leftOn, rightOn: openArray[string], how = JoinType.Inner, ...)
                    proc join*(lf, other: LazyFrame, on: openArray[Expr], ...)            # and leftOn/rightOn
                    proc join*(lf, other: LazyFrame, how: JoinType, suffix = "_right", ...)  # cross join

                    plus the same on DataFrame. on / leftOn / rightOn are named, so a.join(b, on = ["k"]) and a.join(b, leftOn = ["id"], rightOn = ["sid"]) both read clearly. The keyless overload is meant for how = Cross and raises NanuqError for any other join type.

                    Option values: pure enums with Rust's names (Nanuq-wide)
                    type
                      JoinType* {.pure.} = enum Inner, Left, Right, Full, Semi, Anti, Cross
                      JoinValidation* {.pure.} = enum ManyToMany, ManyToOne, OneToMany, OneToOne
                      MaintainOrderJoin* {.pure.} = enum None, Left, Right, LeftRight, RightLeft
                      ConcatMethod* {.pure.} = enum Vertical, VerticalRelaxed, Horizontal, Diagonal, DiagonalRelaxed

                    The rule, for every option type now and later: use the Rust Polars enum's type name and variant names, as a {.pure.} enum. Only when Rust has no enum (as for concat) does Nanuq name one, following Python's strings in PascalCase.

                    • Why: NEP 1 allows unprefixed values only for pure enums, in PascalCase, and the stdlib does the same (SortOrder.Ascending). Rust's names need no invention, map one to one onto Polars' Rust docs, and may repeat across types (JoinType.Left, MaintainOrderJoin.Left) because a pure value is resolved from the expected type, or qualified. Checked with Nim 2.2.4: join(how = Left, maintainOrder = Left) compiles and picks each type's value; let x = Left is ambiguous and must be qualified.
                    • Alternatives considered (design note of 2026-10-31): strings like Python (runtime typos, no completion, unusual in Nim); short prefixes jtLeft (NEP 1's default, cryptic, far from Polars); long prefixes joinLeft (verbose, needs invented prefixes); bare camelCase left (against NEP 1, forced the leftOrder workaround); one proc per variant leftJoin (still needs enums for the other options; possible later as sugar).
                    • DataTypeKind follows the rule: DataTypeKind.Int64, DataTypeKind.Other. Pure enum values and the DataType constants of the same name coexist: a bare Int64 where a DataType is expected picks the constant (checked).
                    • The enums in ffi.nim (NqJoinType, ...) are internal and keep their nq prefix.
                    Concat

                    nq_lf_concat(lfs: *const *const LazyFrame, n, how: NqConcat) -> *mut LazyFrame: Vertical and VerticalRelaxed call concat with to_supertypes false or true; Diagonal and DiagonalRelaxed call concat_lf_diagonal with the same flag; Horizontal calls concat_lf_horizontal. In Nim, concat(frames: openArray[LazyFrame], how = ConcatMethod.Vertical) and the DataFrame version (lazy, concat, collect). An empty list raises NanuqError, as in Polars.

                    Risks / Trade-offs

                    • Capitalised bare values in the namespace. Left, Inner, Vertical, ... are exported. Overload resolution by expected type makes clashes harmless in typed contexts; the qualified form is the escape hatch.
                    • Breaking DataTypeKind. Only code that names kinds (case t.kind) changes; the constants users write stay the same. Nanuq has no outside users yet.
                    • Unordered joins by default. Following Polars, a join's row order is not guaranteed unless maintainOrder is set. Tests and docs sort or set it. The README mentions it.
                    • Binary size. Three more Polars features; small next to the current library.
                    Tasks10 of 10 done

                    1. Bridge 3/3

                    • 1.1Add Polars features semi_anti_join, cross_join and diagonal_concat to src/rust/Cargo.toml (version stays 0.2.0-dev); verify cargo build --release passes
                    • 1.2Add #[repr(C)] NqJoinType, NqJoinValidation, NqMaintainOrderJoin and nq_lf_join (keys checks for cross and non-cross joins); mirror them in ffi.nim
                    • 1.3Add NqConcat and nq_lf_concat (vertical, relaxed, horizontal, diagonal); mirror them in ffi.nim; verify cargo build --release passes

                    2. Nim API 4/4

                    • 2.1Make DataTypeKind a pure enum with PascalCase values (DataTypeKind.Int64, DataTypeKind.Other); update src/nanuq.nim, datamancer.nim and tests; verify nimble test passes and a bare Int64 still means the DataType constant
                    • 2.2Add the pure enums JoinType, JoinValidation, MaintainOrderJoin, ConcatMethod, in the same order as the Rust enums
                    • 2.3Add join on LazyFrame and DataFrame for on and leftOn/rightOn (strings and expressions) and the keyless cross join, with all options; verify every join type, both key forms, suffix, validation failure, nullsEqual, coalesce, maintainOrder, and that how = Left, maintainOrder = Left compiles
                    • 2.4Add concat for LazyFrames and DataFrames; verify every method, the strict vertical failure and the empty list error

                    3. Conventions, docs and integration 3/3

                    • 3.1Add a proposal rule to openspec/config.yaml that option values follow the api-conventions spec
                    • 3.2Add a "Conventions" section to the README (Polars names in camelCase, pure enums with Rust names for option values, qualify outside typed contexts) and list join and concat in "What is there" (with the note that join order is not guaranteed without maintainOrder); verify nimble test and nimble example pass
                    • 3.3Check that CI is green on the PR, including the Rust rebuild

                    Workflow follow-up 0/0

                      Revisions1 revision
                      r1 2ef7787 2026-10-31 Add joins and concatenation (implements add-joins-and-concat)

                      First version: .openspec.yaml, design.md, proposal.md, specs/api-conventions/spec.md, specs/combining-frames/spec.md, specs/data-types/spec.md, specs/native-bridge/spec.md, tasks.md

                      add-json-io Archived

                      openspec/changes/archive/2026-11-01-add-json-io
                      1. Proposal
                      2. Specs
                      3. Tasks
                      4. Implement 3/3
                      5. Archive
                      Proposal

                      Why

                      JSON is the most common nested data format: read_json blocks 7 book sections and scan_ndjson/read_ndjson 7 more, and the coverage map says JSON is useful once nested dtypes exist, which they now do. It comes from the BACKLOG.md entry "More IO" (NDJSON; Excel, sinks and cloud storage stay there).

                      It is the fifth change of the 0.5 release.

                      What Changes

                      • readJson(path or Stream): a JSON array of objects (or an object of columns).
                      • readNdjson(path or Stream) and scanNdjson(path): newline-delimited JSON, one object per line, eager and lazy (globs, nRows, row index).
                      • Both take schema (all columns) or schemaOverrides (some), inferSchemaLength and ignoreErrors.
                      • writeJson(path or Stream) writes a JSON array of row objects, writeNdjson one object per line; toJson/toNdjson give the text.

                      Capabilities

                      New Capabilities
                      • json-io: reading and writing JSON and NDJSON.

                      Differences from Polars

                      • Python's write_json() without a file returns the text; Nanuq has toJson for that, so writeJson always writes.
                      • schema and schemaOverrides are {"name": dtype} pairs, as in readCsv.
                      • No cloud storage options.

                      Impact

                      • src/rust/src/lib.rs and src/nanuq/ffi.nim: nq_df_read_json, nq_lf_scan_ndjson, nq_df_write_json.
                      • src/nanuq.nim: the readers and writers.
                      • New tests/test_json.nim.
                      Spec changesjson-io +3

                      json-io modified +3

                      ADDED
                      Reading JSON

                      readJson(source) SHALL read a JSON array of objects (one row each) from a file path or a Stream, and readNdjson(source) newline-delimited JSON, with nested values becoming List and Struct columns. schema SHALL fix all column types, schemaOverrides some of them, inferSchemaLength SHALL bound the rows used to infer the rest, and ignoreErrors SHALL read values that do not parse as null.

                      import std/streams
                      let json = """[{"bear": "Ada", "cubs": ["Bo"], "den": {"lat": 78.2}},
                                     {"bear": "Cy", "cubs": [], "den": {"lat": 79.0}}]"""
                      let df = readJson(newStringStream(json))
                      echo df
                      echo readNdjson(newStringStream("{\"a\": 1}\n{\"a\": 2}\n"), schemaOverrides = {"a": Float64})
                      TBD
                      Scenario: Not JSON
                      • WHEN a file that is not JSON is read with readJson
                      • THEN ComputeError is raised
                      ADDED
                      Scanning NDJSON

                      scanNdjson(path) SHALL read newline-delimited JSON files lazily (a path or a glob), with nRows, rowIndexName and rowIndexOffset and the schema options of readNdjson.

                      let path = getTempDir() / "bears.ndjson"
                      writeFile(path, "{\"bear\": \"Ada\", \"kg\": 410}\n{\"bear\": \"Bo\", \"kg\": 380}\n")
                      echo scanNdjson(path, rowIndexName = "i").filter(col("kg") > 400).collect
                      TBD
                      Scenario: Limit rows
                      • WHEN a file of 3 lines is scanned with nRows = 2
                      • THEN the frame has 2 rows
                      ADDED
                      Writing JSON

                      writeJson(dest) SHALL write a frame as a JSON array of row objects to a path or a Stream, writeNdjson(dest) one object per line, and toJson/toNdjson SHALL return the same text; reading it back SHALL give the same frame.

                      let df = newDataFrame:
                        bear: ["Ada", "Bo"]
                        cubs: [@["Cy"], @[]]
                      echo df.toJson
                      echo df.toNdjson
                      TBD
                      Scenario: Round trip
                      • WHEN a frame with list and struct columns is written with writeNdjson and read with readNdjson
                      • THEN the result equals the frame
                      Tasks3 of 3 done

                      1. Implementation 3/3

                      • 1.1Crate: JSON reader, NDJSON scan, JSON writer
                      • 1.2readJson, readNdjson, scanNdjson, writeJson, writeNdjson, toJson, toNdjson
                      • 1.3Tests in tests/test_json.nim; nimble test and nimble specexamples pass; CHANGELOG
                      Revisions1 revision
                      r1 f27d0dd 2026-11-01 0.5: JSON and NDJSON IO (add-json-io)

                      First version: proposal.md, specs/json-io/spec.md, tasks.md

                      add-list-namespace Archived

                      openspec/changes/archive/2026-11-01-add-list-namespace
                      1. Proposal
                      2. Specs
                      3. Tasks
                      4. Implement 3/3
                      5. Archive
                      Proposal

                      Why

                      With List columns in Nanuq (add-nested-dtypes) the next step is computing on them. The book ports use explode (11 sections), list.eval with element() (11), concat_list (6) and list.first, list.get, list.len, list.sum (3 to 6 each), and the Polars coverage map puts the list namespace at P1.

                      It is the second change of the 0.5 release.

                      What Changes

                      • e.list, a namespace like e.str: aggregations (len, sum, min, max, mean, median, std, var, first, last, argMin, argMax, nUnique, any, all), access (get, gather, gatherEvery, slice, head, tail, contains, countMatches, join), transforms (sort, reverse, unique, dropNulls, diff, shift, sample, filter, union, setDifference, setIntersection, setSymmetricDifference, toArray, toStruct), and eval and agg with element().
                      • explode and implode on expressions, list.explode, explode(columns) on frames (eager and lazy, with emptyAsNull and keepNulls), and concatList(exprs).

                      Capabilities

                      New Capabilities
                      • list-functions: the list namespace, explode, implode and concatList.

                      Differences from Polars

                      • list.contains, countMatches and the set operations take a Nim value or an expression, as lit would turn it.
                      • list.sample takes n or fraction as overloads (Python has both as keyword arguments).
                      • toStruct(fields) takes the field names; Python also takes a function or a length, and its n_field_strategy is left out.
                      • union is spelled union (Python's set_union is an alias for it).
                      • No list namespace on Series yet: use s.eval(col(s.name).list.len).
                      • filter(predicate) is Python's list.filter, built on eval as in Polars.

                      Impact

                      • src/rust/src/lib.rs and src/nanuq/ffi.nim: nq_expr_list (one entry point with an op code, like nq_expr_str), nq_expr_explode, nq_expr_implode, nq_concat_list, nq_lf_explode.
                      • src/nanuq.nim: ListNameSpace.
                      • New tests/test_lists.nim.
                      Spec changeslist-functions +4

                      list-functions modified +4

                      ADDED
                      List aggregations and access

                      e.list SHALL give a namespace whose methods work on each list of a List (or Array) column: len, sum, min, max, mean, median, std, var, first, last, argMin, argMax, nUnique, any, all give one value per list; get(i) (negative from the end), gather, gatherEvery, slice, head, tail pick values; contains(x), countMatches(x) and join(separator) compare or join them.

                      let df = newDataFrame:
                        cubs: [@[2, 1, 3], @[], @[4]]
                        names: [@["Ada", "Bo"], @["Cy"], @[]]
                      echo df.select(col("cubs").list.len.alias("n"), col("cubs").list.sum.alias("sum"),
                                     col("cubs").list.get(0, nullOnOob = true).alias("first"),
                                     col("cubs").list.contains(3).alias("has3"),
                                     col("names").list.join(", ").alias("names"))
                      TBD
                      Scenario: Index out of bounds
                      • WHEN list.get(5) is evaluated on a list of 3 values without nullOnOob
                      • THEN ComputeError is raised; with nullOnOob = true the value is null
                      ADDED
                      List transforms

                      e.list SHALL have sort, reverse, unique, dropNulls, diff, shift, sample, filter(predicate), the set operations union, setDifference, setIntersection and setSymmetricDifference with another list expression, toArray(width) and toStruct(fields), each giving a list (array or struct) per row.

                      let df = newDataFrame:
                        a: [@[3, 1, 3], @[2]]
                        b: [@[1, 5], @[2, 4]]
                      echo df.select(col("a").list.sort.alias("sorted"), col("a").list.unique(maintainOrder = true).alias("unique"),
                                     col("a").list.union(col("b")).alias("union"),
                                     col("a").list.filter(element() > 1).alias("gt1"))
                      TBD
                      Scenario: Lists to structs
                      • WHEN list.toStruct(["x", "y"]) is evaluated on lists of two values
                      • THEN the result is a struct column with fields x and y
                      ADDED
                      Expressions on list elements

                      list.eval(e) SHALL evaluate e on the values of each list, with element() standing for them, and give a list per row; list.agg(e) SHALL do the same for an aggregation and give one value per row.

                      let df = newDataFrame:
                        weights: [@[410.0, 380.0], @[450.0, 470.0, 455.0]]
                      echo df.select(col("weights").list.eval(element().rank).alias("rank"),
                                     col("weights").list.agg(element().max - element().min).alias("spread"))
                      TBD
                      Scenario: Element outside a list
                      • WHEN element() is used in a select that is not inside list.eval
                      • THEN evaluating it raises a Polars error
                      ADDED
                      Explode and implode

                      e.explode and e.list.explode SHALL give one row per list value, df.explode(columns) SHALL do the same for whole rows (eager and lazy; emptyAsNull and keepNulls default to true, as in Polars), e.implode SHALL collect a column into one list, and concatList(exprs) SHALL join values and lists of several columns into one list per row.

                      let df = newDataFrame:
                        den: ["A", "B", "C"]
                        cubs: [@["Ada", "Bo"], @[], @["Cy"]]
                      echo df.explode("cubs")
                      echo df.select(concatList(col("den"), col("cubs")).alias("all"))
                      echo df.select(col("den").implode)
                      TBD
                      Scenario: Empty lists
                      • WHEN a frame with an empty list is exploded with emptyAsNull = false
                      • THEN that row is dropped instead of giving a null

                      Unchanged in this spec: Exploding several columns by name, Repeating values into lists, Seeds as plain ints

                      Tasks3 of 3 done

                      1. Implementation 3/3

                      • 1.1Crate: nq_expr_list, explode/implode, concat_list, frame explode
                      • 1.2ListNameSpace and its methods; explode, implode, concatList
                      • 1.3Tests in tests/test_lists.nim; nimble test and nimble specexamples pass; CHANGELOG
                      Revisions1 revision
                      r1 5c0aadf 2026-11-01 0.5: nested dtypes, list, struct and arr namespaces, nested strings

                      First version: proposal.md, specs/list-functions/spec.md, tasks.md

                      add-nested-dtypes Archived

                      openspec/changes/archive/2026-11-01-add-nested-dtypes
                      1. Proposal
                      2. Specs
                      3. Tasks
                      4. Implement 5/5
                      5. Archive
                      Proposal

                      Why

                      Lists, arrays and structs are the Polars data types Nanuq does not model yet. They block most of the book sections still marked "not yet" (str.split, explode, unnest, struct.field, list.eval, value_counts, JSON), and the 0.4 changelog lists them as the main limitation. Before any list or struct function, Nanuq needs the types themselves, and a way to move nested values between Nim and Polars.

                      It is the first change of the 0.5 release ("Nested data and user code"). It comes from the BACKLOG.md entry "More dtypes" (lists and structs; decimals and binary stay there).

                      What Changes

                      • DataType gains the kinds List, Array and Struct, with constructors List(Int64), Array(Float64, 3) (or a shape, Array(Int64, [2, 3])) and Struct({"x": Int64, "y": String}), accessors inner, width, shape and fields (a seq of Field, with name and dtype), and Polars' names (list[i64], array[f64, 3], struct[2]). dataType(T) maps seq[T] to List, array[N, T] to Array and objects and named tuples to Struct.
                      • Nested columns from Nim: series(name, values) and the newDataFrame block take seqs of seqs (@[@[1, 2], @[]]), arrays, objects and named tuples, at any depth, with Option (or nil in the block) for null rows and Option elements for null values. toDataFrame(rows) takes objects with such fields. lit(@[1, 2]) is a list literal.
                      • Nested values back to Nim: toList(column, seq[int]), toList(column, MyObject), Option of these, the same on Series, cell reads df[column, row, seq[string]], and row objects (rows(T)) whose fields are seqs or objects.
                      • Casting to nested types: col("a").cast(List(Int32)).
                      • The C ABI passes data types as handles (NqDataType), so nested types can be read and given at any depth, and builds nested Series from their parts (inner values and offsets, or fields).

                      Capabilities

                      New Capabilities
                      • nested-data: List, Array and Struct data types and nested values between Nim and Polars.
                      Modified Capabilities
                      • data-types: the type mapping covers seqs, arrays, objects and tuples.

                      Differences from Polars

                      • Struct values are Nim objects or named tuples, chosen by the caller; Python uses dicts. A struct literal in the block is a named tuple, (x: 1, y: 2.0), not {"x": 1}.
                      • Struct(...) takes {"name": dtype} pairs or a seq of Field; Python also takes a dict or a list of pl.Field, which are the same thing.
                      • Array(inner, [2, 3]) takes a shape as an array of ints; Python takes a tuple.
                      • Reading a struct field that is missing from the object raises ColumnNotFoundError (as rows does for columns); extra struct fields are ignored.
                      • An empty Nim seq has a static element type, so @[] columns are never list[null], unlike Python's pl.Series([[]]).

                      Impact

                      • C ABI: data type handles (nq_dtype_*) replace the per-property column functions; NqDtypeSpec gains a nested handle; new nq_series_list_from_parts, nq_series_array_from_inner, nq_series_struct_from_fields and readers nq_series_list_offsets, nq_series_inner, nq_series_struct_field, nq_series_validity. src/rust/src/lib.rs and src/nanuq/ffi.nim together.
                      • src/nanuq.nim: types, constructors, generic readers and writers.
                      • Polars crate features for 0.5 are all added here (list_, array_, json, sql, meta, ...).
                      • New tests/test_nested.nim.
                      Spec changesdata-types ~1 · nested-data +4

                      data-types modified ~1

                      MODIFIED
                      Nim types map to DataType
                      `dataType(T)` SHALL map `int8` to `int64`, `uint8` to `uint64`, `float32`, `float64`, `bool` and `string` to their dtypes, `int` to `Int64` and `float` to `Float64`. `dataType(T, timeUnit = Microseconds, timeZone = "")` SHALL map `Date`, `DateTime`, std/times' `Duration` and `TimeOfDay` to Date, Datetime, Duration and Time. A Nim enum SHALL map to an Enum of `$` of its values. `seq[T]` SHALL map to a List, `array[N, T]` to an Array and objects and named tuples to a Struct of their fields, at any depth. Other types SHALL not compile. ```nim type Medal = enum Gold, Silver, Bronze echo dataType(int), " ", dataType(float32), " ", dataType(uint8), " ", dataType(string) echo dataType(Date), " ", dataType(DateTime), " ", dataType(Duration, Nanoseconds), " ", dataType(TimeOfDay) echo dataType(Medal), " ", dataType(Medal).categories echo dataType(seq[string]), " ", dataType(array[3, float]), " ", dataType(tuple[x: int, tags: seq[string]]).fields ``` ```text Int64i64 Float32f32 UInt8u8 Stringstr Datedate DateTime(Microseconds)datetime[μs] Duration(Nanoseconds)duration[ns] TimeOfDaytime Enum(["Gold", "Silver",enum "Bronze"]) @["Gold", "Silver", "Bronze"] List(String)list[str] Array(Float64,array[f64, 3)3] @[(name: "x", dtype: Int64),i64), (name: "tags", dtype: List(String))]list[str])] ``` Scenario: Platform int - **WHEN** `dataType(int)` is evaluated - **THEN** it equals `Int64`, the dtype `series` builds from `seq[int]` Scenario: Unsupported type - **WHEN** `col("a").cast(ref int)` is compiled - **THEN** compilation fails Scenario: Unsupported unit - **WHEN** `dataType(DateTime, Seconds)` is evaluated - **THEN** `ValueError` is raised Scenario: Nim enum - **WHEN** `dataType(Medal)` is evaluated for `enum Gold, Silver, Bronze` - **THEN** it equals `Enum(["Gold", "Silver", "Bronze"])` Scenario: Nested Nim types - **WHEN** `dataType(seq[seq[int]])` is evaluated - **THEN** it equals `List(List(Int64))`

                      Unchanged in this spec: DataType values, DataType constants and predicates, Schemas, Casting, Full-range UInt64

                      nested-data modified +4

                      ADDED
                      Nested data types

                      DataType SHALL have the kinds List, Array and Struct, built by List(inner), Array(inner, width) (or a shape, Array(Int64, [2, 3])) and Struct(fields) (from {"name": dtype} pairs or a seq of Field). inner, width, shape and fields SHALL read them back, $ SHALL give Polars' names and == SHALL compare the whole type.

                      let point = Struct({"x": Float64, "y": Float64})
                      echo List(Int64), " ", Array(Float64, 3), " ", Array(Int64, [2, 3]), " ", point
                      echo List(point).inner == point, " ", Array(Int64, [2, 3]).shape, " ", point.fields[1].name
                      list[i64] array[f64, 3] array[i64, (2, 3)] struct[2]
                      true @[2, 3] y
                      Scenario: Schema of nested columns
                      • WHEN the schema of a frame with a list of strings column is read
                      • THEN its dtype is List(String) and $ gives list[str]
                      Scenario: Struct field types
                      • WHEN fields is read from the dtype of a struct column built from (x: 1, y: 2.0)
                      • THEN it holds x: Int64 and y: Float64, in order
                      ADDED
                      Nested columns from Nim

                      series(name, values) SHALL build a List column from seqs, an Array column from Nim arrays, and a Struct column from objects or named tuples, at any depth (seqs of objects, objects with seq fields). Option values SHALL be null rows, and Option elements null values inside a list. The newDataFrame block and toDataFrame(rows) SHALL take the same values; in the block nil SHALL be a null row. lit(seq) SHALL be a list literal.

                      let df = newDataFrame:
                        tags: [@["polar", "bear"], @[], nil]
                        point: [(x: 1, y: 2.0), (x: 3, y: 4.0), (x: 5, y: 6.0)]
                        rgb: [[255, 0, 0], [0, 255, 0], [0, 0, 255]]
                      echo df
                      echo df.select(lit(@[1, 2]).alias("lit"))
                      TBD
                      Scenario: Empty lists keep their type
                      • WHEN series("a", newSeq[seq[int]](2)) is built
                      • THEN its dtype is List(Int64) and both values are empty lists
                      Scenario: Null values inside a list
                      • WHEN series("a", @[@[some(1), none(int)]]) is built
                      • THEN the list holds 1 and null
                      ADDED
                      Nested values to Nim

                      toList(column, T) SHALL read a List column as seq[U], an Array column as array[N, U] or seq[U], and a Struct column as an object or named tuple matching fields by name, on frames and Series, at any depth; Option[T] SHALL read null rows as none. Cell reads df[column, row, T] and rows(T) SHALL take the same types. A null read into a plain type SHALL raise InvalidOperationError, and an object field without a struct field ColumnNotFoundError.

                      type Point = object
                        x: int
                        y: float
                      let df = newDataFrame:
                        tags: [@["polar", "bear"], @[]]
                        point: [Point(x: 1, y: 2.0), Point(x: 3, y: 4.0)]
                      echo df.toList("tags", seq[string])
                      echo df.toList("point", Point)
                      echo df["point", 1, tuple[x: int]]
                      for r in df.rows(tuple[tags: seq[string], point: Point]):
                        echo r.tags.len, " ", r.point.y
                      @[@["polar", "bear"], @[]]
                      @[(x: 1, y: 2.0), (x: 3, y: 4.0)]
                      (x: 3)
                      2 2.0
                      0 4.0
                      Scenario: Round trip
                      • WHEN a seq of objects with seq and object fields is turned into a frame and read back with rows
                      • THEN the result equals the original seq
                      Scenario: Null row
                      • WHEN a list column with a null row is read as seq[int] rows
                      • THEN InvalidOperationError is raised; read as Option[seq[int]] it gives none
                      ADDED
                      Casting to nested types

                      cast(dtype) and castTo SHALL accept nested data types, and cast(T) nested Nim types.

                      let df = newDataFrame(series("a", @[@[1, 2], @[3]]))
                      echo df.select(col("a").cast(List(Float64)), col("a").cast(seq[string]).alias("s"))
                      TBD
                      Scenario: List to array
                      • WHEN a list column whose lists all have 2 values is cast to Array(Int64, 2)
                      • THEN the result is an array column
                      Tasks5 of 5 done

                      1. Implementation 5/5

                      • 1.1Crate: 0.5 Polars features, data type handles, nested Series builders and readers
                      • 1.2DataType List/Array/Struct, Field, constructors, accessors, $, ==, dataType(T)
                      • 1.3series, newDataFrame block, toDataFrame, lit for nested values
                      • 1.4toList, cell reads, rows(T) for nested values; casting to nested types
                      • 1.5Tests in tests/test_nested.nim; nimble test and nimble specexamples pass; CHANGELOG
                      Revisions1 revision
                      r1 5c0aadf 2026-11-01 0.5: nested dtypes, list, struct and arr namespaces, nested strings

                      First version: proposal.md, specs/data-types/spec.md, specs/nested-data/spec.md, tasks.md

                      add-nested-strings Archived

                      openspec/changes/archive/2026-11-01-add-nested-strings
                      1. Proposal
                      2. Specs
                      3. Tasks
                      4. Implement 3/3
                      5. Archive
                      Proposal

                      Why

                      Nanuq 0.3 left out the string functions that return lists or structs: str.split alone blocks 12 book sections, extract_all 3, split_exact 2, and json_decode is how JSON in a string column becomes structs. With nested types in place (add-nested-dtypes), they can come in.

                      It is the third change of the 0.5 release.

                      What Changes

                      • str.split(by, inclusive) and str.extractAll(pattern) give list[str]; str.splitExact(by, n, inclusive), str.splitn(by, n) and str.extractGroups(pattern) give structs (fields field_0, ... or the regex groups).
                      • Matching many literal patterns at once (Aho-Corasick, as in Polars): str.containsAny(patterns), str.replaceMany(patterns, replaceWith) (also from a mapping {"a": "x"}), str.extractMany(patterns) and str.findMany(patterns).
                      • JSON in strings: str.jsonDecode(dtype) (or a Nim type) and str.jsonPathMatch(path).

                      Capabilities

                      Modified Capabilities
                      • strings: string functions that return lists and structs.

                      Differences from Polars

                      • jsonDecode needs the data type, as Polars' Expr.str.json_decode does; Python's Series.str.json_decode infers it, Nanuq does not (there are no Series namespaces).
                      • Patterns are a Nim array of strings, or an expression giving a list.

                      Impact

                      • src/rust/src/lib.rs and src/nanuq/ffi.nim: nq_expr_str_nested with an op code.
                      • src/nanuq.nim: methods on StrNameSpace.
                      • Tests in tests/test_strings.nim.
                      Spec changesstrings +3

                      strings modified +3

                      ADDED
                      Splitting and extracting into lists and structs

                      str.split(by) SHALL split each string into a list[str] (keeping by with inclusive = true), str.extractAll(pattern) SHALL give all regex matches as a list, str.splitExact(by, n) and str.splitn(by, n) SHALL give a struct of n + 1 or n fields named field_0, ..., and str.extractGroups(pattern) SHALL give a struct with one field per capture group, named after named groups or numbered from 1.

                      let df = newDataFrame:
                        station: ["Lima, Peru", "Piura, Peru", "Darwin"]
                      echo df.select(col("station").str.split(", ").alias("parts"),
                                     col("station").str.splitExact(", ", 1).alias("exact"),
                                     col("station").str.extractGroups(r"(?<city>\w+)(, (?<country>\w+))?").alias("groups"))
                      TBD
                      Scenario: Missing parts
                      • WHEN splitExact(", ", 1) is evaluated on a string without a comma
                      • THEN the second field is null
                      ADDED
                      Many patterns at once

                      str.containsAny(patterns), str.replaceMany(patterns, replaceWith) (or a mapping), str.extractMany(patterns) and str.findMany(patterns) SHALL match many literal patterns in one pass, with asciiCaseInsensitive and, for extract and find, overlapping.

                      let df = newDataFrame:
                        note: ["sea ice thin", "no ice", "open water"]
                      echo df.select(col("note").str.containsAny(["ice", "water"]).alias("any"),
                                     col("note").str.replaceMany({"ice": "ICE", "water": "WATER"}).alias("loud"),
                                     col("note").str.extractMany(["ice", "sea", "water"]).alias("found"))
                      TBD
                      Scenario: One replacement for all
                      • WHEN replaceMany(["a", "b"], "_") is evaluated on "abc"
                      • THEN the result is "__c"
                      ADDED
                      JSON in strings

                      str.jsonDecode(dtype) (or jsonDecode(T) with a Nim type) SHALL parse each string as JSON into a value of dtype, and str.jsonPathMatch(path) SHALL give the string at a JSONPath, null when there is none.

                      let df = newDataFrame:
                        json: ["""{"bear": "Ada", "kg": 410}""", """{"bear": "Bo", "kg": null}"""]
                      echo df.select(col("json").str.jsonDecode(tuple[bear: string, kg: Option[int]]).alias("v"),
                                     col("json").str.jsonPathMatch("$.bear").alias("bear"))
                      TBD
                      Scenario: Invalid JSON
                      • WHEN a string that is not JSON is decoded
                      • THEN ComputeError is raised

                      Unchanged in this spec: The str namespace, Matching, Replacing and stripping, Slicing and padding, Joining strings in an aggregation, Building strings from columns, Title case, Escaping and normalizing

                      Tasks3 of 3 done

                      1. Implementation 3/3

                      • 1.1Crate: nq_expr_str_nested
                      • 1.2split, splitExact, splitn, extractAll, extractGroups, containsAny, replaceMany, extractMany, findMany, jsonDecode, jsonPathMatch
                      • 1.3Tests; nimble test and nimble specexamples pass; CHANGELOG
                      Revisions1 revision
                      r1 5c0aadf 2026-11-01 0.5: nested dtypes, list, struct and arr namespaces, nested strings

                      First version: proposal.md, specs/strings/spec.md, tasks.md

                      add-nim-callbacks Archived

                      openspec/changes/archive/2026-11-01-add-nim-callbacks
                      1. Proposal
                      2. Specs
                      3. Tasks
                      4. Implement 3/3
                      5. Archive
                      Proposal

                      Why

                      Some work has no Polars expression: a Nim library call, a lookup, a custom parser. Python covers it with user functions (map_elements 7 book sections, fold 7, map_batches 6), and the coverage map lists a Nim callback bridge for 0.5.

                      It is the seventh change of the 0.5 release.

                      What Changes

                      • e.mapElements(proc (x: T): U): a typed Nim proc or closure per value. Values are read as T (objects and named tuples for struct rows, seqs for lists), the result type is dataType(U); nulls skip the call unless T is an Option.
                      • e.mapBatches(proc (s: Series): Series), with returnDtype and returnsScalar: the whole column, or each group in a group-by.
                      • fold, reduce, cumFold, cumReduce with a proc (acc, x: Series): Series.
                      • name.map(proc (name: string): string).
                      • groupBy(...).mapGroups(proc (df: DataFrame): DataFrame) on eager frames.
                      • A Nim exception in a callback becomes a ComputeError with its message.
                      • Series arithmetic broadcasts a Series of length 1 (as fold's first accumulator is).

                      Capabilities

                      New Capabilities
                      • callbacks: Nim functions called by Polars.

                      Differences from Polars

                      • mapElements is typed: the argument type says how values are read and the result type gives return_dtype, so neither is guessed from the first values as Python does.
                      • skip_nulls is the argument type: proc (x: int) skips nulls, proc (x: Option[int]) gets them.
                      • Callbacks run one at a time (Polars' worker threads take a lock around Nim code), so they never run in parallel; Python has the GIL for the same reason.
                      • mapGroups is eager only and runs groups in order of first occurrence.
                      • No rolling_map or cum_reduce with include_init.

                      Impact

                      • src/rust/src/lib.rs and src/nanuq/ffi.nim: C function pointers with a Nim environment (NqUdfFn, NqNameFn, NqDropFn), nq_expr_map_batches, nq_fold, nq_expr_name_map, nq_series_clone, nq_udf_set_error; the crate depends on polars-plan for function flags.
                      • src/nanuq.nim: the callback procs.
                      • New tests/test_callbacks.nim.
                      Spec changescallbacks +4

                      callbacks modified +4

                      ADDED
                      Typed element callbacks

                      e.mapElements(f) SHALL call the Nim proc or closure f: proc (x: T): U on each value of e, read as T (as toList reads it: objects and named tuples for structs, seqs for lists), and give a column of dataType(U). Nulls SHALL stay null without a call unless T is an Option. An exception in f SHALL raise ComputeError with its message when the query runs.

                      type Bear = object
                        name: string
                        kg: int
                      let df = newDataFrame:
                        name: ["Ada", "Bo", "Cy"]
                        kg: [410, nil, 500]
                      let tag = proc (b: Bear): string = b.name & " (" & $b.kg & " kg)"
                      echo df.select(col("kg").mapElements(proc (x: int): float = x / 1000).alias("t"),
                                     asStruct(col("name"), col("kg").fillNull(0)).mapElements(tag).alias("tag"))
                      TBD
                      Scenario: Error in the callback
                      • WHEN the callback raises ValueError("no bears")
                      • THEN collecting raises ComputeError whose message holds "no bears"
                      ADDED
                      Batch callbacks

                      e.mapBatches(f) SHALL call f: proc (s: Series): Series with the whole column, or in a group-by with each group's values; the result SHALL keep the input type unless returnDtype is given, and with returnsScalar a group-by SHALL get one value per group instead of a list.

                      let df = newDataFrame:
                        cubs: [1, 0, 1]
                        kg: [410, 380, 500]
                      echo df.select(col("kg").mapBatches(proc (s: Series): Series = s * 2))
                      echo df.groupBy("cubs").agg(col("kg").mapBatches(proc (s: Series): Series = s.max,
                                                                        returnsScalar = true)).sort("cubs")
                      TBD
                      Scenario: Other result type
                      • WHEN mapBatches(proc (s: Series): Series = s / 10, Float64) runs on an integer column
                      • THEN the result is a f64 column
                      ADDED
                      Folds

                      fold(acc, f, exprs) SHALL combine columns left to right with f: proc (acc, x: Series): Series, starting from acc; reduce(f, exprs) SHALL start from the first column, and cumFold and cumReduce SHALL keep each step as a struct field.

                      let df = newDataFrame:
                        a: [1, 2]
                        b: [10, 20]
                        c: [100, 200]
                      echo df.select(fold(lit(0), proc (acc, x: Series): Series = acc + x, col("*")).alias("sum"))
                      TBD
                      Scenario: Reduce
                      • WHEN reduce with + runs on columns a and b
                      • THEN the result is 11 and 22
                      ADDED
                      Name and group callbacks

                      name.map(f) SHALL rename outputs with f: proc (name: string): string, and groupBy(...).mapGroups(f) SHALL call f: proc (df: DataFrame): DataFrame on each group, in order of first occurrence, and concatenate the results.

                      let df = newDataFrame:
                        den: ["A", "B", "A"]
                        kg: [410, 380, 500]
                      echo df.select(col("*").name.map(proc (n: string): string = n.toUpperAscii))
                      echo df.groupBy("den").mapGroups(proc (g: DataFrame): DataFrame = g.sort("kg", descending = true).head(1))
                      TBD
                      Scenario: Empty frame
                      • WHEN mapGroups runs on an empty frame
                      • THEN the result is an empty frame with the same columns
                      Tasks3 of 3 done

                      1. Implementation 3/3

                      • 1.1Crate: Nim function wrapper (lock, errors, drop), map_batches, folds, name.map
                      • 1.2mapElements, mapBatches, fold, reduce, cumFold, cumReduce, name.map, mapGroups
                      • 1.3Tests in tests/test_callbacks.nim; nimble test and nimble specexamples pass; CHANGELOG
                      Revisions1 revision
                      r1 f94c8b7 2026-11-01 0.5: Nim callbacks and smaller functions (add-nim-callbacks, add-frame-utilities)

                      First version: proposal.md, specs/callbacks/spec.md, tasks.md

                      add-openspec-page Archived

                      openspec/changes/archive/2026-11-02-add-openspec-page
                      1. Proposal
                      2. Specs
                      3. Tasks
                      4. Implement 4/4
                      5. Archive
                      Proposal

                      Why

                      specview (tools/specview.nim) is the readable view of the OpenSpec specs and changes, but it only exists as a page attached to PR runs or published by hand as a Claude artifact, so there is no stable link to how Nanuq behaves today. Pietro asked (2026-11-02) for it to be a published page like the Polars coverage map, linked from the README's "How development works" and kept up to date.

                      What Changes

                      • docs/openspec.nim renders openspec.html with the Nanuq theme: the dev log's header and footer, a short introduction to specs and changes, then specview's report (the changes, archived ones behind the checkbox, and every spec in full).
                      • tools/specview.nim exposes its report (loadReport, renderNav, renderReport, reportCss, toggleJs) so the page reuses it; the standalone page is unchanged.
                      • CI renders the page in the docs job (with full git history, for revisions) and publishes it at the site root. On main, pushes that change openspec/, BACKLOG.md or tools/specview.nim now run CI, so the published page follows every merged change. Pull requests touching only those files still skip CI.
                      • nimble docs renders it; the README ("How development works"), the dev-log index and the coverage page link to it.

                      Capabilities

                      Modified Capabilities
                      • dev-log: a living OpenSpec page next to the Polars coverage page.
                      • ci: render and deploy the living pages; on main, OpenSpec-only pushes run CI.

                      Differences from Polars

                      None: this adds documentation, not API.

                      Impact

                      • New docs/openspec.nim.
                      • tools/specview.nim (refactor, no change to its output), .github/workflows/ci.yml, nanuq.nimble, docs/index.nim, docs/polars_coverage.nim, README.md.
                      • An OpenSpec-only merge to main now costs a CI run (the Rust library comes from cache; tests and docs take a few minutes).
                      Spec changesci ~2 · dev-log +1

                      ci modified ~2

                      MODIFIED
                      Skip CI for non-code changes
                      CI SHALL NOT run for pushes or pull requests that only change Markdown files, `LICENSE`, `.gitignore`, `openspec/` or `.claude/`, except `openspec/specs/`, whose examples CI runs. On `main`, CI SHALL also run for pushes that change `openspec/`, `BACKLOG.md` or `tools/specview.nim`, so the published OpenSpec page stays current. Scenario: OpenSpec-only change - **WHEN** a pull request only changes files under `openspec/changes/` - **THEN** no CI run starts Scenario: OpenSpec-only merge - **WHEN** a commit that only changes files under `openspec/changes/` lands on `main` - **THEN** CI runs and the site is deployed with the updated OpenSpec page Scenario: Main spec change - **WHEN** a pull request changes `openspec/specs/expressions/spec.md` - **THEN** CI runs, including the spec examples Scenario: Dev log change - **WHEN** a change touches `docs/` - **THEN** CI runs, so the dev log is rebuilt
                      MODIFIED
                      Tests, example and dev log
                      CI SHALL run the test suite, whichthe example includesand the spec examples,examples as(`nimble one programspecexamples`), (`tests/all.nim`), and the example, and render the site as one program (`docs/all.nim`): the nimib dev-log posts in `docs/blog`, then the index page `docs/index.nim` and the living pages (the Polars coverage page and the OpenSpec page). On `main`, after these succeed, it SHALL deploy them to GitHub Pages, with the index as the site root. Scenario: Merge to main - **WHEN** a commit lands on `main` and the test and docs jobs pass - **THEN** the dev log and the living pages are deployed to GitHub Pages, and the site root lists the posts Scenario: Stale spec example - **WHEN** a pull request changes behavior that a spec example shows - **THEN** the test job fails until the example's output is updated Scenario: New test file - **WHEN** a pull request adds `tests/test_x.nim` - **THEN** the test job runs it as part of `tests/all.nim`, with no list to update

                      Unchanged in this spec: Build Rust only when the crate changes, Lib version follows the crate sources, Fast linking

                      dev-log modified +1

                      ADDED
                      OpenSpec page

                      The site SHALL publish an OpenSpec page at openspec.html, linked from the index, the coverage page and the README's "How development works", rendered by tools/specview.nim with the dev log's header and footer: every change (archived ones hidden until the reader asks for them) and every spec in openspec/specs/ in full. The page is rebuilt from the repository each time the site is, so it shows the specs and changes on main. It is not a dated post and is not listed among the posts.

                      Scenario: A change is archived
                      • WHEN a pull request that archives a change into openspec/specs/ is merged
                      • THEN the published OpenSpec page shows the updated spec and lists the change as archived
                      Scenario: Index link
                      • WHEN the site is rendered
                      • THEN the index links to the OpenSpec page, and the page does not appear in the list of posts

                      Unchanged in this spec: Index of posts, Dated post files, Polars coverage page, Review mode, Source files

                      Tasks4 of 4 done

                      1. Implementation 4/4

                      • 1.1Expose specview's report from tools/specview.nim without changing its page
                      • 1.2docs/openspec.nim renders openspec.html with the Nanuq theme
                      • 1.3Render and publish in CI and nimble docs; run CI on main for OpenSpec-only pushes
                      • 1.4Link from the README, the dev-log index and the coverage page
                      Revisions1 revision
                      r1 5349b11 2026-11-02 Publish the OpenSpec page (specview) on the site

                      First version: proposal.md, specs/ci/spec.md, specs/dev-log/spec.md, tasks.md

                      add-parameter-type-convention Archived

                      openspec/changes/archive/2026-11-01-add-parameter-type-convention
                      1. Proposal
                      2. Specs
                      3. Tasks
                      4. Implement 1/1
                      5. Archive
                      Proposal

                      Why

                      0.4 introduced four parameter types with converters (ColumnNames, OptInterval, JoinKey, AsofTolerance) so that calls like pivot("season", index = "year") and joinAsof(..., tolerance = 7.days) read like Python. It is a new pattern in the API, and Pietro asked that it be tracked in the API conventions so later changes follow it.

                      Part of the 0.4 release (#51).

                      What Changes

                      • api-conventions gains the rule: parameters that take several types, with a default, use converter types; the four existing types are listed.
                      • No code change.

                      Capabilities

                      Modified Capabilities
                      • api-conventions: the converter parameter type rule.

                      Differences from Polars

                      • None in behaviour. Python accepts these unions dynamically; Nanuq accepts the same spellings through converters.

                      Impact

                      • Spec only.
                      Spec changesapi-conventions +1

                      api-conventions modified +1

                      ADDED
                      Parameters that take several types use converter types

                      Where Python Polars lets a parameter take values of different types (a name or a list of names, a duration string or a number) and the parameter needs a default, Nanuq SHALL use a small exported object type with a converter from each accepted type, instead of a generic union (string | openArray[string] = [] does not compile with a default in Nim) or one overload per combination. The existing types are ColumnNames (a name, a seq or an array of names), OptInterval (a std/times interval or a duration string), JoinKey (a column name or an expression) and AsofTolerance (an interval, a duration string, an int or a float). A new parameter of this kind SHALL reuse one of them when it fits, and a new type SHALL be listed here. Converters SHALL only convert into these types, so they apply only where such a parameter appears.

                      let df = newDataFrame:
                        year: [1997, 1997, 1998]
                        months: ["JJA", "SON", "JJA"]
                        anomaly: [1.5, 2.3, -0.2]
                      echo df.pivot("months", index = "year", values = "anomaly").columns
                      echo df.pivot(["months"], index = @["year"], values = "anomaly").columns
                      Scenario: One name or a list
                      • WHEN user code passes index = "year" or index = ["year", "month"] to pivot
                      • THEN both compile and mean one or two index columns
                      Scenario: Default left out
                      • WHEN user code calls joinAsof(other, on = "t") without tolerance
                      • THEN it compiles, and no tolerance is applied

                      Unchanged in this spec: Option values are pure enums with Rust Polars names, The conventions are documented, Python's method parameter is how

                      Tasks1 of 1 done

                      1. Spec 1/1

                      • 1.1Add the converter parameter type rule to api-conventions, with an example
                      Revisions1 revision
                      r1 c8c8526 2026-11-01 API conventions: converter parameter types

                      First version: proposal.md, specs/api-conventions/spec.md, tasks.md

                      add-parquet-ipc Archived

                      openspec/changes/archive/2026-10-31-add-parquet-ipc
                      1. Proposal
                      2. Specs
                      3. Design
                      4. Tasks
                      5. Implement 7/7
                      6. Archive
                      Proposal

                      Why

                      CSV is the only format Nanuq reads and writes. Parquet is what most data arrives in today and what Polars is fastest with; Arrow IPC (Feather v2) is the format other Arrow tools exchange without conversion. Both keep dtypes, which CSV loses: a Date column written to CSV comes back as a string. Reading from a Nim Stream lets a program parse data it already holds in memory (a download, an embedded table, a test fixture) without a temporary file.

                      This change takes up the BACKLOG.md entry "More IO" (Parquet and IPC) and follows the dev log "Designing Nanuq 0.3", section 5. It is the sixth change of the 0.3 release.

                      What Changes

                      • Parquet: scanParquet(path, nRows, columns, rowIndexName, rowIndexOffset, lowMemory) (a file or glob), readParquet(path or Stream, ...) and writeParquet(df, path, compression = ParquetCompression.Zstd, compressionLevel = none(int), statistics = true, rowGroupSize = none(int)). ParquetCompression is a pure enum: Lz4, Uncompressed, Snappy, Gzip, Brotli, Zstd.
                      • IPC: scanIpc, readIpc(path or Stream, ...) with the same read options, and writeIpc(df, path, compression = IpcCompression.Uncompressed), with IpcCompression Uncompressed, Lz4, Zstd.
                      • Streams: readCsv(stream, ...) with every CSV read option.
                      • Hive partitions are detected as in Polars' default for paths; in-memory bytes never are.
                      • Polars features parquet and ipc (already compiled in by the string change) are used.

                      Not in this change: writing to a stream or a string, cloud storage, sinkParquet and the other sink functions (streaming writes), Parquet useStatistics, parallel and hive options, readParquetSchema, IPC streams (readIpcStream), NDJSON and Excel.

                      Capabilities

                      New Capabilities
                      • parquet-ipc: reading and writing Parquet and Arrow IPC files and bytes.
                      Modified Capabilities
                      • csv-io: reading CSV from a stream.
                      • native-bridge: NqParquetCompression and NqIpcCompression join the ordered enums; nq_lf_scan_csv takes optional in-memory bytes.

                      Differences from Polars

                      Expected differences from Polars' Rust and Python APIs:

                      • Streams: Python reads any file-like object or bytes; Rust uses readers over Cursors. Nanuq reads a Nim Stream, all of it, when readCsv/readParquet/ readIpc is called. The scan* procs take paths only.
                      • Compression is a pure enum instead of Python's strings ("zstd") and Rust's enum with the level inside (Zstd(Some(ZstdLevel))); the level is a separate compressionLevel, as in Python. A level with a codec that has none raises ValueError (Python ignores it).
                      • statistics is a bool (Python also takes "full" or a dict).
                      • IpcCompression has Uncompressed as a value (Python's "uncompressed"; Rust uses None).
                      • Names follow Polars in camelCase: row_index_name → rowIndexName, compression_level → compressionLevel, row_group_size → rowGroupSize.

                      Impact

                      • src/rust/src/lib.rs: nq_lf_scan_parquet, nq_lf_scan_ipc, nq_df_write_parquet, nq_df_write_ipc, the two compression enums, and bytes for nq_lf_scan_csv.
                      • src/nanuq/ffi.nim, src/nanuq.nim: the declarations and procs; nanuq imports std/streams.
                      • tests/test_io.nim (new); README; BACKLOG "More IO" keeps the remaining formats.
                      Spec changescsv-io +1 · native-bridge ~1 · parquet-ipc +4

                      csv-io modified +1

                      ADDED
                      Reading CSV from a stream

                      readCsv SHALL also take a Nim Stream instead of a path, read all of it when called, and take every CSV read option.

                      import std/streams
                      let text = "station;bears\nNorth;3\nSouth;NA\n"
                      echo readCsv(newStringStream(text), separator = ';', nullValues = ["NA"])
                      TBD
                      Scenario: Same options
                      • WHEN CSV text with ; separators and "NA" is read from a stream with separator = ';', nullValues = ["NA"]
                      • THEN the result equals reading the same text from a file with those options
                      Scenario: Empty stream
                      • WHEN an empty stream is read
                      • THEN NoDataError is raised

                      Unchanged in this spec: Scanning CSV, CSV read options, CSV write options, Quoting, encoding and new column names, Comment lines

                      native-bridge modified ~1

                      MODIFIED
                      Nim declarations mirror the C ABI
                      `src/nanuq/ffi.nim` SHALL declare every exported function with matching signatures, and the enums `NqBinOp`, `NqUnary`, `NqDtype`, `NqDtypeClass`, `NqJoinType`, `NqJoinValidation`, `NqMaintainOrderJoin`, `NqConcat`, `NqUniqueKeepStrategy`, `NqClosedInterval`, `NqQuantileMethod`, `NqFillNullStrategy`, `NqRoundMode`, `NqQuoteStyle`, `NqRankMethod`, `NqErrorKind`, `NqStrOp`, `NqTimeUnit`, `NqClosedWindow`, `NqDtOp`, `NqCatOp`, `NqParquetCompression` and `NqIpcCompression` SHALL keep the same order as in Rust. `NqDtype` SHALL also keep the order of `DataTypeKind`, and the option enums the order of their Nim API enums. Data types SHALL cross the ABI as an `NqDtypeSpec` struct (code, time unit, time zone, categories) with the same field order on both sides. Scenario: ABI change - **WHEN** a function is added or changed in `rust/src/lib.rs` - **THEN** `src/nanuq/ffi.nim` is updated in the same change

                      Unchanged in this spec: C ABI over Polars with opaque handles, Errors and panics never cross the boundary, Linking the static library, Columns cross in bulk, Library version check, Formatted cells, Polars version matches a py-polars release

                      parquet-ipc modified +4

                      ADDED
                      Reading Parquet

                      The API SHALL provide scanParquet(path, ...), a lazy scan of a file or a glob, and readParquet(path, ...), which is scanParquet(...).collect. Both SHALL take nRows, columns, rowIndexName with rowIndexOffset = 0, and lowMemory = false. Every dtype Nanuq models SHALL round-trip through Parquet unchanged.

                      let path = getTempDir() / "riders.parquet"
                      let df = newDataFrame:
                        rider: ["Seixas", "Pogačar", "Evenepoel"]
                        born: [date(2006, 9, 24), date(1998, 9, 21), date(2000, 1, 25)]
                        wins: [3, 22, nil]
                      df.writeParquet(path)
                      echo readParquet(path, columns = ["rider", "born"], nRows = 2, rowIndexName = "nr")
                      TBD
                      Scenario: Round trip
                      • WHEN a DataFrame with string, date and nullable integer columns is written and read back
                      • THEN the result equals the original, dtypes included
                      Scenario: Not Parquet
                      • WHEN bytes that are not Parquet are read
                      • THEN PolarsError is raised
                      ADDED
                      Writing Parquet

                      writeParquet(df, path, compression = ParquetCompression.Zstd, compressionLevel = none(int), statistics = true, rowGroupSize = none(int)) SHALL write a Parquet file. compressionLevel SHALL apply to Gzip, Brotli and Zstd; with another codec it SHALL raise ValueError, and an out-of-range level SHALL raise PolarsError.

                      import std/sequtils
                      let path = getTempDir() / "sizes.parquet"
                      let df = newDataFrame(series("n", toSeq(1..1000)))
                      for c in [ParquetCompression.Uncompressed, ParquetCompression.Zstd]:
                        df.writeParquet(path, compression = c)
                        echo c, " ", getFileSize(path) < 5000
                      TBD
                      Scenario: Every codec
                      • WHEN a DataFrame is written with each ParquetCompression value
                      • THEN each file reads back with the same rows
                      Scenario: Level without a level
                      • WHEN writeParquet(path, compression = ParquetCompression.Snappy, compressionLevel = 3) is called
                      • THEN ValueError is raised
                      Scenario: Missing directory
                      • WHEN the target directory does not exist
                      • THEN IOError is raised
                      ADDED
                      Arrow IPC

                      The API SHALL provide scanIpc and readIpc with the read options of Parquet, and writeIpc(df, path, compression = IpcCompression.Uncompressed) with Lz4 and Zstd.

                      let path = getTempDir() / "riders.arrow"
                      let df = newDataFrame:
                        rider: ["Seixas", "Pogačar"]
                        start: [timeOfDay(13, 10), timeOfDay(13, 12)]
                      df.writeIpc(path, compression = IpcCompression.Lz4)
                      echo readIpc(path).schema
                      TBD
                      Scenario: Round trip
                      • WHEN a DataFrame is written with each IpcCompression and read back
                      • THEN the result equals the original
                      ADDED
                      Reading from streams

                      readParquet and readIpc SHALL also take a Nim Stream instead of a path, read all of it when called, and take the same options.

                      import std/streams
                      let path = getTempDir() / "one.parquet"
                      newDataFrame(series("a", [1, 2])).writeParquet(path)
                      echo readParquet(newStringStream(readFile(path))).shape
                      TBD
                      Scenario: Bytes in memory
                      • WHEN the bytes of a Parquet file are read with readParquet(newStringStream(bytes))
                      • THEN the result equals reading the file

                      Unchanged in this spec: Hive partitioning switch, Arrow IPC streams

                      Design

                      Design

                      One scan per format, paths or bytes

                      Every reader goes through a lazy scan in Rust, which takes either a path (file or glob) or a byte buffer (ScanSources::Buffers). Eager read* procs are scan*(...).collect, and the Stream overloads read the stream into a string and pass its bytes, which Rust copies. One code path per format keeps the options identical for files and streams.

                      Columns are a projection

                      columns becomes a select after the scan, as in scanCsv; Polars pushes it down into the reader, so unread columns are never decoded.

                      Hive partitions

                      Polars' Rust default enables hive partitioning, Python's detects it (None). Nanuq uses Python's behaviour for paths. Polars does not implement hive partitioning for in-memory buffers, so it is disabled there.

                      Tasks7 of 7 done

                      1. Bridge 2/2

                      • 1.1Add nq_lf_scan_parquet, nq_lf_scan_ipc, nq_df_write_parquet and nq_df_write_ipc with the compression enums
                      • 1.2Let nq_lf_scan_csv read in-memory bytes; mirror everything in ffi.nim

                      2. Nim API 3/3

                      • 2.1Add ParquetCompression, IpcCompression, scanParquet, readParquet, writeParquet, scanIpc, readIpc and writeIpc
                      • 2.2Add the Stream overloads of readCsv, readParquet and readIpc
                      • 2.3Write tests/test_io.nim; add it to nanuq.nimble and .gitignore

                      3. Docs and integration 2/2

                      • 3.1README lists the formats; nimble test and nimble specexamples pass
                      • 3.2Archive the change: update BACKLOG "More IO", add CHANGELOG lines
                      Revisions1 revision
                      r1 f846b99 2026-10-31 Add Parquet and Arrow IPC IO, and reading from streams

                      First version: design.md, proposal.md, specs/csv-io/spec.md, specs/native-bridge/spec.md, specs/parquet-ipc/spec.md, tasks.md

                      add-plan-serialization Archived

                      openspec/changes/archive/2026-11-01-add-plan-serialization
                      1. Proposal
                      2. Specs
                      3. Tasks
                      4. Implement 3/3
                      5. Archive
                      Proposal

                      Why

                      A serialized query plan can be stored, sent to another process or machine and run there; Python Polars uses it for Polars Cloud and for caching plans. The roadmap lists plan serialization and the rest of the meta namespace in 0.6 ("Engine and edges"). 0.5 added only meta.outputName, rootNames, hasMultipleOutputs, isColumn and isLiteral.

                      It is the second change of the 0.6 release.

                      What Changes

                      • SerializationFormat enum (Binary, Json).
                      • lf.serialize(format = Binary): string and lf.serialize(path, format); deserialize(LazyFrame, data, format) and deserializeFile(LazyFrame, path, format). The plan keeps in-memory frames, so a serialized eager frame's query carries its data.
                      • e.meta.serialize(format) and deserialize(Expr, data, format).
                      • More of meta: eq, ne, pop, isRegexProjection, isColumnSelection(allowAliasing), isLiteral(allowAliasing), treeFormat.

                      Capabilities

                      New Capabilities
                      • plan-serialization: serializing LazyFrames and expressions.

                      Differences from Polars

                      • Binary data is returned as a Nim string of bytes (Python bytes), and a file is written by an overload taking a path (Python's file argument).
                      • Python's classmethods pl.LazyFrame.deserialize(source) and pl.Expr.deserialize become deserialize(LazyFrame, data) and deserialize(Expr, data); reading a file is deserializeFile.
                      • Plans contain Nim callbacks (mapElements, mapBatches, ...) as function pointers, which cannot be serialized: serializing them raises ComputeError (Python pickles the Python function).
                      • Plans written by Nanuq (Rust Polars 0.55.2) and by py-polars are only compatible when their plan format version (DSL_VERSION) matches.
                      • No DataFrame.serialize; use writeIpc/writeParquet, or df.lazy.serialize.
                      • treeFormat returns the text; there is no return_as_string = false printing mode.

                      Impact

                      • src/rust/Cargo.toml: Polars features serde, serde-lazy; serde_json and polars-utils (for Polars' binary expression format).
                      • src/rust/src/lib.rs, src/nanuq/ffi.nim: nq_lf_serialize, nq_lf_deserialize, nq_expr_serialize, nq_expr_deserialize, more meta operations.
                      • New tests/test_serialization.nim.
                      Spec changesplan-serialization +3

                      plan-serialization modified +3

                      ADDED
                      Serializing query plans

                      lf.serialize(format = SerializationFormat.Binary) SHALL return the LazyFrame's plan as bytes (in a string), Json as JSON text, and lf.serialize(path, format) SHALL write it to a file. deserialize(LazyFrame, data, format) and deserializeFile(LazyFrame, path, format) SHALL rebuild a LazyFrame that collects to the same result. In-memory frames in the plan SHALL travel with it.

                      let lf = newDataFrame(series("kg", @[410, 380, 455])).lazy.filter(col("kg") > 400)
                      let bytes = lf.serialize
                      echo deserialize(LazyFrame, bytes).collect
                      echo lf.serialize(SerializationFormat.Json).len > 0
                      TBD
                      Scenario: Not a plan
                      • WHEN deserialize(LazyFrame, "garbage") is called
                      • THEN PolarsError is raised
                      Scenario: Nim callbacks
                      • WHEN a plan with mapElements is serialized
                      • THEN PolarsError is raised
                      ADDED
                      Serializing expressions

                      e.meta.serialize(format) SHALL return an expression as bytes or JSON, and deserialize(Expr, data, format) SHALL rebuild it.

                      let e = (col("kg") * 2).alias("double")
                      let back = deserialize(Expr, e.meta.serialize)
                      echo back.meta.eq(e)
                      echo newDataFrame(series("kg", @[1, 2])).select(back)
                      TBD
                      Scenario: JSON round trip
                      • WHEN an expression is serialized with Json and deserialized with Json
                      • THEN meta.eq with the original is true
                      ADDED
                      Expression metadata

                      The meta namespace SHALL also provide eq(other) and ne(other) (same expression tree), pop (the inputs of the outermost node), isRegexProjection, isColumnSelection(allowAliasing = false), isLiteral(allowAliasing) and treeFormat (the tree as text).

                      let e = (col("a") + col("b")).alias("c")
                      echo e.meta.undoAliases.meta.outputName
                      echo e.meta.pop.len
                      echo col("^x.*$").meta.isRegexProjection, " ", col("a").alias("b").meta.isColumnSelection(allowAliasing = true)
                      echo (col("a") + 1).meta.treeFormat
                      TBD
                      Scenario: Different trees
                      • WHEN col("a").meta.eq(col("b")) is called
                      • THEN it is false
                      Tasks3 of 3 done

                      1. Implementation 3/3

                      • 1.1Crate: features serde/serde-lazy; plan and expression (de)serialization; meta operations
                      • 1.2SerializationFormat, serialize, deserialize, deserializeFile, meta.*
                      • 1.3Tests in tests/test_serialization.nim; nimble test and nimble specexamples pass; CHANGELOG
                      Revisions1 revision
                      r1 4ea5dad 2026-11-01 0.6: archive the 9 changes, fill spec example outputs, map_elements benchmark, dev log Designing Nanuq 0.6

                      First version: proposal.md, specs/plan-serialization/spec.md, tasks.md

                      add-polars-coverage-page Archived

                      openspec/changes/archive/2026-11-01-add-polars-coverage-page
                      1. Proposal
                      2. Specs
                      3. Tasks
                      4. Implement 3/3
                      5. Archive
                      Proposal

                      Why

                      The Polars coverage map (every Polars feature group, and whether Nanuq has it) was made on 2026-10-28 as a planning artifact outside the repo, and it went stale after four releases. Pietro asked (2026-11-01) for it to be a separate document that gets updated, not a dev-log post, and chose a page on the Nanuq site built from a data file in the repo.

                      What Changes

                      • docs/coverage/polars.json: the catalogue for the latest release, 128 feature groups in 14 areas, each with the Polars names, a status (has it, partly, missing, not planned), a note on what is still missing, a priority for open groups and a mark on the groups new in that release. Older releases are not kept (Pietro, 2026-11-02); once the next release has a plan, rows can name the release that plans them.
                      • docs/polars_coverage.nim: renders it to polars_coverage.html with the Nanuq theme: release totals, a table by area, the groups still open by priority, and the catalogue, with the dev log's header and footer. It does not import Nanuq.
                      • The dev-log index links to the page; CI and nimble docs render it and publish it at the site root.
                      • Each release PR refreshes the data (the release, the changed rows and their new-marks).

                      Capabilities

                      Modified Capabilities
                      • dev-log: a living Polars coverage page next to the dated posts.

                      Differences from Polars

                      None: this adds documentation, not API. The page uses Polars' Python names and says that Nanuq spells them in camelCase.

                      Impact

                      • New docs/coverage/polars.json, docs/polars_coverage.nim.
                      • docs/index.nim (link), .github/workflows/ci.yml and nanuq.nimble (render and publish the page).
                      Spec changesdev-log +1

                      dev-log modified +1

                      ADDED
                      Polars coverage page

                      The site SHALL publish a Polars coverage page at polars_coverage.html, linked from the index and the README, rendered from the data file docs/coverage/polars.json. The page SHALL describe the latest Nanuq release only: the data names that release and lists Polars feature groups by area with their Polars names, a status (has it, partly, missing, not planned), a note naming what is still missing, a priority for open groups, and a mark on the groups whose status changed in that release. When the next release has a plan, the data MAY name it and mark the open groups it plans; the page SHALL then show them. The page SHALL show the release totals, counts by area, the open groups by priority and the full catalogue, with the dev log's header and footer. Each release PR SHALL refresh the data for that release. The page is not a dated post and is not listed among the posts.

                      Scenario: A release refreshes the data
                      • WHEN the 0.7 release PR sets the release to 0.7, clears the old new-marks, and updates and marks the rows that 0.7 changed
                      • THEN the page shows only 0.7 statuses, with the changed groups marked as new in 0.7
                      Scenario: No plan for the next release
                      • WHEN the data names no next release
                      • THEN the page shows no Planned column
                      Scenario: Index link
                      • WHEN the site is rendered
                      • THEN the index links to the coverage page, and the page does not appear in the list of posts

                      Unchanged in this spec: Index of posts, Dated post files, OpenSpec page, Review mode, Source files

                      Tasks3 of 3 done

                      1. Implementation 3/3

                      • 1.1Catalogue data in docs/coverage/polars.json, statuses for 0.5 (main) and 0.6 (#59)
                      • 1.2docs/polars_coverage.nim renders the page with the Nanuq theme
                      • 1.3Link from the dev-log index; render and publish in CI and nimble docs
                      Revisions2 revisions
                      r1 0d00929 2026-11-01 Add the Polars coverage map as a page on the Nanuq site

                      First version: proposal.md, specs/dev-log/spec.md, tasks.md

                      r2 6ede49a 2026-11-02 Coverage page: latest release only (0.6), no per-version history
                      proposal.md
                      § What Changes
                      - `docs/coverage/polars.json`: the catalogue,catalogue for the latest release, 128 feature groups in 14 areas, each with the Polars names, a status per Nanuq version (has it, partly, missing, not planned), a note on what is still missingmissing, and a priority for open groups.groups and a mark on the groups new in that release. Older Areleases versionare leftnot outkept of(Pietro, a2026-11-02); row keepsonce the previousnext version'srelease status,has soa aplan, releaserows onlycan addsname the rowsrelease that change.plans them. - `docs/polars_coverage.nim`: renders it to `polars_coverage.html` with the Nanuq theme: totalsrelease pertotals, version, a table by area, the groups still open by priority, and the catalogue.catalogue, with the dev log's header and footer. It does not import Nanuq. - The dev-log index links to the page; CI and `nimble docs` render it and publish it at the site root. - Each release PR refreshes the data (the (arelease, newthe versionchanged entryrows and thetheir rows that changed).new-marks).
                      specs/dev-log/spec.md
                      § Requirement: Polars coverage page
                      ### Requirement: Polars coverage page The site SHALL publish a Polars coverage page at `polars_coverage.html`, linked from the index,index and the README, rendered from the data file `docs/coverage/polars.json`. The page SHALL describe the latest Nanuq release only: the data SHALLnames that release and listlists Polars feature groups by area with their Polars names, a status for each Nanuq version (has it, partly, missing, not planned)planned), and a note naming what is still missing;missing, a priority for open groups, versionand a mark on the groups whose status changed in that release. When leftthe outnext ofrelease has a rowplan, the data MAY name it and mark the open groups SHALLit keepplans; the previouspage SHALL version'sthen status.show them. The page SHALL show totals the perrelease version,totals, counts by area, the open groups stillby priority and the full opencatalogue, inwith the newestdev versionlog's by priority,header and thefooter. full catalogue. Each release PR SHALL refresh the data for that release. The page is not a dated post and is not listed among the posts. #### Scenario: A release addsrefreshes athe versiondata - **WHEN** athe 0.7 release PR addssets versionthe `0.7`release to `versions`0.7, clears the old new-marks, and setsupdates `"0.7":and "done"`marks on the rows that it0.7 completeschanged - **THEN** the page shows aonly 0.7 column,statuses, with the changed groups marked as rowsnew in left0.7 #### unchangedScenario: showNo theirplan 0.6for statusthe undernext 0.7,release - and**WHEN** the changeddata names no next release - rows**THEN** arethe markedpage asshows newno inPlanned 0.7column

                      add-repeat-by-and-seeds Archived

                      openspec/changes/archive/2026-11-01-add-repeat-by-and-seeds
                      1. Proposal
                      2. Specs
                      3. Tasks
                      4. Implement 3/3
                      5. Archive
                      Proposal

                      Why

                      The 0.5 book port of the O'Reilly chapter 8 examples found two more small gaps: Expr.repeatBy was missing, and sample(n, seed = 42) needed seed = some(42) on expressions and lists (frames and shuffle already took a plain int).

                      It is the eleventh change of the 0.5 release (#53).

                      What Changes

                      • Expr.repeatBy(by), with by a count, a column name or an expression: each value repeated as a list.
                      • sample(..., seed = 42) with a plain int on Expr and on list.

                      Capabilities

                      Modified Capabilities
                      • list-functions: repeating values into lists; seeds as plain ints.

                      Differences from Polars

                      • None in behaviour. Python's seed=None is Nanuq's default; a seed is given as an int.

                      Impact

                      • Rust: nq_expr_repeat_by.
                      • src/nanuq.nim: repeatBy, sample overloads with seed: int.
                      Spec changeslist-functions +2

                      list-functions modified +2

                      ADDED
                      Repeating values into lists

                      Expr.repeatBy(by) SHALL repeat each value by times into a list, where by is an int, a column name or an expression (Python's repeat_by).

                      let df = newDataFrame:
                        hut: ["Goûter", "Margherita"]
                        nights: [2, 1]
                      echo df.select(col.hut.repeatBy("nights"))
                      Scenario: Constant count
                      • WHEN repeatBy(2) runs on "x"
                      • THEN the result is the list ["x", "x"]
                      ADDED
                      Seeds as plain ints

                      sample on expressions and on list SHALL take the seed as a plain int, sample(3, seed = 42), as shuffle and frame sample do; the same seed SHALL give the same values.

                      let df = newDataFrame:
                        m: [4806, 4634, 4061, 4506, 4478]
                      echo df.select(col.m.sample(3, seed = 42)).height
                      Scenario: Same seed
                      • WHEN sample(3, seed = 42) runs twice on the same column
                      • THEN both runs give the same values

                      Unchanged in this spec: List aggregations and access, List transforms, Expressions on list elements, Explode and implode, Exploding several columns by name

                      Tasks3 of 3 done

                      1. Implementation 3/3

                      • 1.1nq_expr_repeat_by and Expr.repeatBy
                      • 1.2sample(seed: int) overloads on Expr and list
                      • 1.3Tests
                      Revisions1 revision
                      r1 d8f7ab7 2026-11-01 0.5: repeatBy, int seeds, mapElements benchmark and fast path

                      First version: proposal.md, specs/list-functions/spec.md, tasks.md

                      add-reshaping Archived

                      openspec/changes/archive/2026-11-01-add-reshaping
                      1. Proposal
                      2. Specs
                      3. Tasks
                      4. Implement 4/4
                      5. Archive
                      Proposal

                      Why

                      Data arrives wide or long, and analysis wants the other shape: NOAA publishes its El Niño index as one row per year with twelve season columns, a spreadsheet keeps one column per month, and a report wants the stations as columns. Nanuq can't reshape at all: pivot was dropped from 0.3, and the book ports stop on unpivot, pivot and transpose (O'Reilly chapters 4, 9 and 17, the user guide's "Pivots" and "Unpivots" pages), and on partition_by (O'Reilly chapter 1, "Load").

                      It is the sixth change of the 0.4 release.

                      What Changes

                      • pivot on DataFrame (finds the new columns itself, in order of appearance or sorted with sortColumns) and on LazyFrame (with the new columns given in onColumns), with index, values, aggregateFunction (a PivotAgg pure enum or an expression on element()), maintainOrder and separator.
                      • unpivot on DataFrame and LazyFrame, with on, index, variableName and valueName.
                      • transpose with includeHeader, headerName and columnNames.
                      • partitionBy returning a seq[DataFrame], with maintainOrder and includeKey.
                      • toDummies with columns, separator, dropFirst and dropNulls.
                      • ColumnNames, a parameter type that takes one name or a list (index = "year" or index = ["year", "month"]), element() and Expr.item(allowEmpty).

                      Capabilities

                      New Capabilities
                      • reshaping: pivot, unpivot, transpose, partitionBy, toDummies.

                      Differences from Polars

                      • aggregateFunction is the PivotAgg pure enum (Item, First, Last, Sum, Mean, Median, Min, Max, Len) or an expression; Python takes strings or an expression and None, which Nanuq spells Item (the default, at most one value per cell).
                      • index, values and on take names (one or a list), not selectors.
                      • partitionBy has no as_dict; the frames come in a seq in order of appearance.
                      • column_naming is always Polars' "auto".

                      Impact

                      • src/rust/src/lib.rs: nq_lf_pivot, nq_lf_unpivot, nq_df_transpose, nq_df_partition_by, nq_df_array_free, nq_df_to_dummies, nq_expr_element, nq_expr_item; src/nanuq/ffi.nim, src/nanuq.nim.
                      • New tests/test_reshaping.nim.
                      Spec changesreshaping +5

                      reshaping modified +5

                      ADDED
                      Pivot

                      df.pivot(on, index, values, aggregateFunction = PivotAgg.Item, maintainOrder = true, sortColumns = false, separator = "_") SHALL turn each distinct value of the on columns into a column (in order of appearance, or sorted), with one row per distinct index value and cells from values combined by aggregateFunction, a PivotAgg or an expression on element(). When index or values is left out it SHALL mean every other column. lf.pivot(on, onColumns, ...) SHALL do the same lazily with the new columns listed in the DataFrame onColumns.

                      let df = newDataFrame:
                        year: [2023, 2023, 2024, 2024]
                        season: ["DJF", "JJA", "DJF", "JJA"]
                        oni: [-0.7, 1.1, 1.8, 0.0]
                      echo df.pivot("season", index = "year", values = "oni")
                      TBD
                      Scenario: Aggregating duplicates
                      • WHEN two rows share an index and an on value and aggregateFunction = Sum
                      • THEN their cell holds the sum of both values
                      Scenario: Duplicates without an aggregation
                      • WHEN two rows share an index and an on value and no aggregation is given
                      • THEN pivot raises a PolarsError
                      ADDED
                      Unpivot

                      unpivot(on, index, variableName = "variable", valueName = "value") on a DataFrame or LazyFrame SHALL turn the on columns (by default every column not in index) into rows, one per index value and on column, holding the column's name and value.

                      let df = newDataFrame:
                        year: [2023, 2024]
                        DJF: [-0.7, 1.8]
                        JJA: [1.1, 0.0]
                      echo df.unpivot(index = "year", variableName = "season", valueName = "oni")
                      TBD
                      Scenario: Round trip
                      • WHEN a long frame is pivoted and the result unpivoted on the new columns
                      • THEN the rows are the original rows
                      ADDED
                      Transpose

                      df.transpose(includeHeader = false, headerName = "column", columnNames) SHALL turn rows into columns, naming them columnNames or column_0, column_1, ..., and with includeHeader SHALL put the old column names in a first column headerName.

                      let df = newDataFrame:
                        lima: [22.1, 24.3]
                        quito: [14.0, 14.2]
                      echo df.transpose(includeHeader = true, headerName = "station", columnNames = ["jan", "feb"])
                      TBD
                      Scenario: Default names
                      • WHEN a frame with two rows is transposed without names
                      • THEN its columns are column_0 and column_1
                      ADDED
                      Partition

                      df.partitionBy(by, maintainOrder = true, includeKey = true) SHALL return one DataFrame per distinct value of the by columns, in order of appearance with maintainOrder, and without the by columns when includeKey is false.

                      let df = newDataFrame:
                        phase: ["El Niño", "La Niña", "El Niño"]
                        year: [2015, 2020, 2023]
                      for part in df.partitionBy("phase", includeKey = false):
                        echo part.toList("year", int)
                      TBD
                      Scenario: Several keys
                      • WHEN partitionBy(["a", "b"]) runs on rows with three distinct (a, b) pairs
                      • THEN the result has three frames
                      ADDED
                      Dummy columns

                      df.toDummies(columns, separator = "_", dropFirst = false, dropNulls = false) SHALL replace each listed column (all by default) by one 0/1 column per distinct value, named column, separator and value.

                      let df = newDataFrame:
                        phase: ["warm", "cold", "warm"]
                      echo df.toDummies()
                      TBD
                      Scenario: Drop first
                      • WHEN toDummies(dropFirst = true) runs on a column with values a and b
                      • THEN only one dummy column remains
                      Tasks4 of 4 done

                      1. Implementation 4/4

                      • 1.1ColumnNames, element(), Expr.item
                      • 1.2pivot on DataFrame and LazyFrame with PivotAgg
                      • 1.3unpivot, transpose, partitionBy, toDummies
                      • 1.4Tests in tests/test_reshaping.nim; nimble test and nimble specexamples pass; CHANGELOG
                      Revisions1 revision
                      r1 570d956 2026-11-01 Nanuq 0.4, changes 1-7: math, cumulative, rolling, value functions, horizontal, reshaping, time grouping

                      First version: proposal.md, specs/reshaping/spec.md, tasks.md

                      add-review-mode Archived

                      openspec/changes/archive/2026-11-19-add-review-mode
                      1. Proposal
                      2. Specs
                      3. Tasks
                      4. Implement 6/6
                      5. Archive
                      Proposal

                      Why

                      Pietro reviews the dev-log posts and explainers from his phone, and so far every remark went into a chat message that had to say where on the page it was. tabelline, his other nimib project, has a review mode for its pages (docs/review.nim, not yet in nimib): a reader opens it with ✎ Review, selects text, comments on it, and exports every comment as one text (Markdown with a YAML block naming the page, its source and the version read) that a coding agent applies to the page's source. Pietro asked (2026-11-19) for it on every nimib page of Nanuq, nanuq-more and the Nanuq book.

                      He also asked for tabelline's folded code (nbFoldCode): the posts name source files (ffi.nim, benchmarks/arrow_views.nim, an explainer's Python twin) that a reader can only find on GitHub. tabelline folds each piece of code a page talks about under its name and its length, in a section the page points to.

                      What Changes

                      • docs/review.nim and docs/review.js: tabelline's review mode, copied as they are (the version with review rounds, tabelline#102), without tabelline's notebook-look styles. They are meant to move to nimib; until then this copy follows tabelline's.
                      • useNanuqTheme turns the review mode on for every page that uses the theme (all posts, the index, the coverage map, the OpenSpec page, and nanuq-more's pages, which use the same theme), with review = false to leave it off. The version line (Version 8 · updated 2 Nov 2026) and ✎ Review sit in the masthead under the meta line; the review mode's colours come from the pack-ice palette, light and dark.
                      • docs/foldcode.nim: nbFoldCode (a file, or a part of it between start and stop, folded under its path or a title and its length) and nbSourceFiles, a "Source files" section at the end of a page. The theme says under the title that the section is there, links every file name the text shows as code (ffi.nim, src/nanuq/ffi.nim) to its fold, and a link to a fold opens it. Every post that mentions a file of this repository gets the section; the explainers' links to their Python twins, figures and data scripts on GitHub now lead to their folds. Files of other repositories stay links.
                      • The version of a page is the number of commits that touched its source, read from git when the page is built; the docs job already checks out the whole history.

                      Capabilities

                      Modified Capabilities
                      • dev-log: every page of the site has the review mode; pages that mention source files fold them in a "Source files" section.

                      Differences from Polars

                      None: this changes the documentation site, not the API.

                      Impact

                      • New docs/review.nim, docs/review.js, docs/foldcode.nim; docs/nanuqtheme.nim; the eleven pages that mention source files (ten posts and the OpenSpec page).
                      • Each page carries the review script inline (about 30 KB), so a page stays one file and works as a Claude artifact too.
                      • Comments live in the reader's browser (localStorage), keyed by page and version.
                      Spec changesdev-log +2

                      dev-log modified +2

                      ADDED
                      Review mode

                      Every page rendered with the Nanuq theme SHALL have the review mode of docs/review.nim (from tabelline, until nimib has it), unless the page passes review = false: a version line in the masthead (Version N · updated D, N being the commits that touched the page's source) with ✎ Review, which opens a mode where the reader selects text, comments on it, and exports the comments as Markdown with a YAML block (nimib-review format) naming the page, its source, its version and commit. The page SHALL stay readable at phone width in both modes, light and dark.

                      Scenario: Reviewing a post on a phone
                      • WHEN a reader opens a post on a phone, taps ✎ Review, selects a sentence and writes a note
                      • THEN the sentence is marked, the note is kept in the browser, and Export gives a text
                      • naming the post's source (docs/blog/<post>.nim), its version and the quoted sentence
                      Scenario: A new commit
                      • WHEN a commit changes a post's source and the site is built again
                      • THEN the post's version goes up by one, and its comments start empty
                      ADDED
                      Source files

                      A page that mentions source files of the repository SHALL fold them (whole, or the part it discusses) in a "Source files" section at its end, made with nbSourceFiles and nbFoldCode (from tabelline): each under its path or a title, with its number of lines. The top of the page SHALL point to the section, every file name shown as code in the text SHALL link to its fold, and following such a link SHALL open the fold.

                      Scenario: Reading a file a post names
                      • WHEN a reader taps ffi.nim in the text of a post
                      • THEN the page goes to the fold of src/nanuq/ffi.nim in "Source files", opened

                      Unchanged in this spec: Index of posts, Dated post files, Polars coverage page, OpenSpec page

                      Tasks6 of 6 done

                      Tasks 6/6

                      • Copy tabelline's review mode (rounds version) to docs/review.nim and docs/review.js
                      • Turn it on in useNanuqTheme, with the version line in the masthead and the palette's colours
                      • Check a post at phone width: reading, selecting, commenting, exporting
                      • Port nbFoldCode to docs/foldcode.nim, with nbSourceFiles, mention links and folds that open
                      • Add a Source files section to every page that mentions a source file of the repository
                      • Sync the dev-log spec and add the CHANGELOG line
                      Revisions1 revision
                      r1 37224c5 2026-11-19 Review mode and folded source files on every page of the site

                      First version: proposal.md, specs/dev-log/spec.md, tasks.md

                      add-rolling-and-ewm Archived

                      openspec/changes/archive/2026-11-01-add-rolling-and-ewm
                      1. Proposal
                      2. Specs
                      3. Tasks
                      4. Implement 5/5
                      5. Archive
                      Proposal

                      Why

                      Smoothing a noisy series is the first thing done with any measurement over time: a 7-day average of cases, a 30-year climate normal, NOAA's El Niño index (a 3-month running mean of sea temperature anomalies). Nanuq has none of Polars' rolling or exponentially weighted functions, and no way to fill a gap from its neighbours (interpolate, which the O'Reilly chapter on missing values uses three times).

                      It is the third change of the 0.4 release.

                      What Changes

                      • Fixed windows: rollingSum, rollingMean, rollingMin, rollingMax, rollingMedian, rollingStd, rollingVar and rollingQuantile, with windowSize, weights, minSamples and center.
                      • Time windows: the same functions with a By suffix (rollingMeanBy(by, 7.days)), over a sorted temporal or integer column, with minSamples and closed (ClosedWindow). Window sizes are std/times intervals or Polars duration strings, as in 0.3's dateRange.
                      • Exponentially weighted: ewmMean, ewmStd, ewmVar with exactly one of com, span, halfLife, alpha, plus adjust, bias, minSamples, ignoreNulls.
                      • Interpolation: interpolate(InterpolationMethod.Linear | Nearest) and interpolateBy(by).

                      Capabilities

                      New Capabilities
                      • rolling-windows: fixed and time-based rolling windows, exponentially weighted functions.
                      Modified Capabilities
                      • missing-values: interpolation.

                      Differences from Polars

                      • The decay parameters of ewmMean default to NaN, meaning "not given", and must be named (ewmMean(span = 12)); Python uses None. Rust takes only alpha; Nanuq converts com, span and halfLife the way Python does.
                      • minSamples follows Python 2's name (Rust: min_periods).
                      • The By variants take by as a column name or expression, and Nim intervals as well as Polars duration strings.
                      • Not included: rollingMap (needs Nim callbacks, 0.5), rollingSkew, rollingKurtosis, rollingRank, ewmMeanBy, and Python's rolling_* on frames (that is the rolling group-by in add-dynamic-group-by).

                      Impact

                      • src/rust/src/lib.rs: nq_expr_rolling, nq_expr_rolling_by, nq_expr_ewm, nq_expr_interpolate, NqBinaryFn.InterpolateBy; src/nanuq/ffi.nim, src/nanuq.nim.
                      • New tests/test_rolling.nim.
                      Spec changesmissing-values +1 · rolling-windows +3

                      missing-values modified +1

                      ADDED
                      Interpolation

                      e.interpolate() SHALL fill nulls that lie between two values on a straight line between them, or with the nearest value for interpolate(InterpolationMethod.Nearest); e.interpolateBy(by) SHALL interpolate linearly using the distances in column by. Nulls before the first and after the last value SHALL stay null.

                      let df = newDataFrame:
                        day: [1, 2, 4, 5]
                        temp: [10.0, nil, 16.0, nil]
                      echo df.withColumns(col.temp.interpolate.alias("linear"),
                                          col.temp.interpolateBy("day").alias("by_day"))
                      TBD
                      Scenario: Integer column
                      • WHEN interpolate runs on 1, null, 3
                      • THEN the result is 1.0, 2.0, 3.0

                      Unchanged in this spec: Nulls are read as Option, Plain reads refuse nulls, Inspecting nulls, Building columns with nulls, CSV null markers, Null expressions, Dropping rows with nulls, Null literal, Filling nulls in whole frames

                      rolling-windows modified +3

                      ADDED
                      Fixed rolling windows

                      rollingSum, rollingMean, rollingMin, rollingMax, rollingMedian, rollingStd, rollingVar and rollingQuantile SHALL compute their statistic over the last windowSize rows, or over a window centred on each row with center = true. A row SHALL get null until minSamples non-null values are in its window (by default windowSize), and weights, when given, SHALL multiply the values of each window.

                      let df = newDataFrame:
                        season: ["NDJ", "DJF", "JFM", "FMA", "MAM"]
                        anomaly: [1.9, 2.1, 1.6, 1.0, 0.4]
                      echo df.withColumns(col.anomaly.rollingMean(3).round(2).alias("mean3"),
                                          col.anomaly.rollingMean(3, center = true).round(2).alias("centred"),
                                          col.anomaly.rollingMax(2, minSamples = 1).alias("max2"))
                      TBD
                      Scenario: Window not full yet
                      • WHEN rollingSum(3) runs on 1, 2, 3, 4
                      • THEN the result is null, null, 6, 9
                      Scenario: Weights
                      • WHEN rollingSum(2, weights = [0.5, 1.0]) runs on 2.0, 4.0
                      • THEN the second value is 5.0
                      Scenario: Invalid window
                      • WHEN rollingMean(0) is built
                      • THEN ValueError is raised
                      ADDED
                      Time rolling windows

                      The same functions with a By suffix SHALL take a sorted column by (temporal or integer) and a window size as a std/times interval or Polars duration string; the window of each row SHALL span windowSize back from its by value, with ends included as closed (ClosedWindow, default Right) says, and rows SHALL need minSamples values (default 1).

                      let df = newDataFrame:
                        day: [date(2026, 7, 1), date(2026, 7, 2), date(2026, 7, 5), date(2026, 7, 6)]
                        rain: [4, 0, 10, 2]
                      echo df.withColumns(col.rain.rollingSumBy("day", 3.days).alias("last_3_days"))
                      TBD
                      Scenario: Gaps in the dates
                      • WHEN rollingSumBy("day", 3.days) runs on July 1, 2, 5, 6 with 4, 0, 10, 2
                      • THEN the result is 4, 4, 10, 12
                      ADDED
                      Exponentially weighted functions

                      ewmMean, ewmStd and ewmVar SHALL compute exponentially weighted statistics with the decay given by exactly one of com, span, halfLife or alpha, converted to alpha as Python Polars does, and SHALL take adjust, minSamples and ignoreNulls (and bias for std and var). Giving none or more than one decay parameter SHALL raise ValueError.

                      let df = newDataFrame:
                        temp: [14.0, 15.0, 13.0, 16.0]
                      echo df.withColumns(col.temp.ewmMean(alpha = 0.5).round(3).alias("ewm"),
                                          col.temp.ewmMean(span = 3, adjust = false).round(3).alias("span3"))
                      TBD
                      Scenario: Span and alpha agree
                      • WHEN ewmMean(span = 3) and ewmMean(alpha = 0.5) run on the same column
                      • THEN the results are equal
                      Scenario: Two decay parameters
                      • WHEN ewmMean(com = 1, alpha = 0.5) is built
                      • THEN ValueError is raised
                      Tasks5 of 5 done

                      1. Implementation 5/5

                      • 1.1Fixed-window rolling functions with weights, minSamples, center
                      • 1.2Time-window By variants with closed windows
                      • 1.3ewmMean, ewmStd, ewmVar with Python's alpha conversion
                      • 1.4interpolate, interpolateBy
                      • 1.5Tests in tests/test_rolling.nim; nimble test and nimble specexamples pass; CHANGELOG
                      Revisions1 revision
                      r1 570d956 2026-11-01 Nanuq 0.4, changes 1-7: math, cumulative, rolling, value functions, horizontal, reshaping, time grouping

                      First version: proposal.md, specs/missing-values/spec.md, specs/rolling-windows/spec.md, tasks.md

                      add-row-objects Archived

                      openspec/changes/archive/2026-11-01-add-row-objects
                      1. Proposal
                      2. Specs
                      3. Tasks
                      4. Implement 3/3
                      5. Archive
                      Proposal

                      Why

                      Nim code works with typed records. Getting rows out of a frame into objects (to feed a template, a plotting call or a simulation), or building a frame from a seq of objects, takes one toList or series call per column today. Python has df.rows(named=True), iter_rows and pl.DataFrame(list_of_dicts); the Datamancer gap analysis lists "row objects" as something Datamancer users expect, and the coverage map puts it in 0.4.

                      It is the tenth change of the 0.4 release.

                      What Changes

                      • df.rows(T) returns a seq[T] and df.iterRows(T) iterates, for T an object or named tuple whose fields name columns; df.row(i, T) returns one row.
                      • toDataFrame(seq[T]) builds a frame with one column per field.
                      • Field types: int, float, bool, string, temporal values (Date, DateTime, ...), Nim enums, and Option of these for columns with nulls.

                      Capabilities

                      New Capabilities
                      • row-objects: rows as typed Nim objects and back.

                      Differences from Polars

                      • The row type is a Nim type chosen by the caller; Python returns tuples or dicts.
                      • Fields match columns by exact name (no style-insensitive matching), and columns without a field are ignored.
                      • iterRows reads whole columns first; Python's iter_rows buffers rows in chunks.

                      Impact

                      • src/nanuq.nim: rows, iterRows, row, toDataFrame. No ABI change.
                      • New tests/test_rows.nim.
                      Spec changesrow-objects +2

                      row-objects modified +2

                      ADDED
                      Rows as objects

                      df.rows(T) SHALL return the rows as a seq[T] and df.iterRows(T) SHALL iterate them, for T an object or named tuple whose fields are named after columns, and df.row(i, T) SHALL return row i (negative from the end). Fields SHALL be int, float, bool, string, temporal values, Nim enums, or Option of these; a null read into a plain field SHALL raise InvalidOperationError, and a field without a column ColumnNotFoundError.

                      type Reading = object
                        station: string
                        rain: float
                      let df = newDataFrame:
                        station: ["Lima", "Piura", "Tumbes"]
                        rain: [1.5, 80.0, 95.0]
                        year: [1998, 1998, 1998]
                      for r in df.iterRows(Reading):
                        echo r.station, ": ", r.rain
                      echo df.row(-1, tuple[station: string, year: int])
                      TBD
                      Scenario: Missing column
                      • WHEN rows is called with a type that has a field wind and the frame has no column wind
                      • THEN ColumnNotFoundError is raised
                      ADDED
                      Objects to a frame

                      toDataFrame(rows) SHALL build a frame from a seq or array of objects or named tuples, with one column per field in field order; Option fields SHALL give columns with nulls.

                      type Event = object
                        year: int
                        peak: Option[float]
                      let events = @[Event(year: 1997, peak: some(2.4)), Event(year: 2014, peak: none(float))]
                      echo events.toDataFrame
                      TBD
                      Scenario: Round trip
                      • WHEN a seq of objects is turned into a frame and read back with rows
                      • THEN the result equals the original seq
                      Tasks3 of 3 done

                      1. Implementation 3/3

                      • 1.1rows, iterRows, row for objects and named tuples
                      • 1.2toDataFrame from a seq of objects
                      • 1.3Tests in tests/test_rows.nim; nimble test and nimble specexamples pass; CHANGELOG
                      Revisions1 revision
                      r1 46ae6c2 2026-11-01 Nanuq 0.4, changes 8-10: Series API, Arraymancer tensors, row objects

                      First version: proposal.md, specs/row-objects/spec.md, tasks.md

                      add-sample-datasets Archived

                      created 2026-10-27 · openspec/changes/archive/2026-10-27-add-sample-datasets
                      1. Proposal
                      2. Specs
                      3. Tasks
                      4. Implement 5/5
                      5. Archive
                      Proposal

                      Why

                      Examples, tests and docs need small, well-known data that loads with one call and no path. Today they read examples/iris_sample.csv, a 12-row iris sample found by relative path. Pietro wants penguins (palmerpenguins, CC0) instead of iris. Penguins is also a better showcase now that Nanuq supports nulls: it has missing values in five columns.

                      This takes up the BACKLOG.md entry "Sample datasets" (Datasets), including its sub-item "Replace iris with penguins".

                      What Changes

                      • New module nanuq/datasets with penguins(): DataFrame, the full palmerpenguins table (344 rows, 8 columns, "NA" read as null). It calls readCsv on the CSV that ships next to the module, with the path fixed at compile time (currentSourcePath), so it works from any working directory and needs no network and no change to the Rust bridge. This is a convenience while Nanuq is young; the datasets are expected to move out later.
                      • The README example, examples/basic.nim and the CSV tests use penguins instead of iris. (During implementation Pietro asked to switch the two dev-log posts to penguins too and remove examples/iris_sample.csv.)

                      Capabilities

                      New Capabilities
                      • datasets: bundled sample datasets, how they are loaded, and their licensing.
                      Modified Capabilities

                      None.

                      Differences from Polars

                      • Bundled datasets. Neither Polars (Rust or Python) nor pandas ship datasets. This follows the plotting libraries instead: seaborn's load_dataset("penguins") downloads and caches, Plotly Express bundles its data (px.data.iris()), and R bundles it in packages (palmerpenguins::penguins). Bundling in Nanuq is a convenience for early development, not a design choice. Once the library matures, the datasets will probably be dropped and vendored from elsewhere (see the backlog).
                      • Same table as seaborn and R. Columns and values match palmerpenguins' penguins.csv (the R package's data). Seaborn's copy has the same 344 rows but no year column and sex spelled MALE / FEMALE; Nanuq keeps the R version.
                      • Not embedded. Embedding the CSV with staticRead would make binaries self-contained, but needs a read-CSV-from-string function in the bridge. Since the datasets are temporary, penguins() reads the file instead: a compiled program needs the Nanuq sources on disk where it was built. Reading CSV from memory (Python's pl.read_csv(io.StringIO(...))) stays in the backlog.

                      Impact

                      • No change to rust/src/lib.rs or ffi.nim, so CI needs no Rust rebuild.
                      • src/nanuq/datasets.nim and src/nanuq/data/penguins.csv (with a credit and CC0 notice in src/nanuq/data/README.md). The data lives under src/ so it ships with the package.
                      • README.md, examples/basic.nim, tests/: switch to penguins.
                      Spec changesdatasets +3

                      datasets modified +3

                      Purpose: Small, well-known datasets loadable with one call and no file path, for examples, tests and documentation. They are bundled for convenience during early development and are expected to move out of the library later.

                      ADDED
                      Penguins dataset

                      nanuq/datasets SHALL provide penguins() returning the palmerpenguins table: 344 rows and the columns species, island, bill_length_mm, bill_depth_mm, flipper_length_mm, body_mass_g, sex and year, with "NA" fields as nulls.

                      Scenario: Shape and columns
                      • WHEN penguins() is called
                      • THEN the result has shape (344, 8) and the columns listed above, in that order
                      Scenario: Missing values
                      • WHEN penguins() is called
                      • THEN nullCount is 2 for body_mass_g and 11 for sex, and body_mass_g is an integer column
                      ADDED
                      Loading from any working directory

                      Bundled datasets SHALL load with no path from the caller and without using the network, whatever the program's working directory.

                      Scenario: Different working directory
                      • WHEN a compiled program calls penguins() from any working directory
                      • THEN the dataset loads
                      ADDED
                      Licensing

                      Every bundled dataset SHALL ship with its source, credit and license in the repository, and SHALL be under a license that allows redistribution.

                      Scenario: Penguins credit
                      • WHEN someone looks for where penguins comes from
                      • THEN the data folder names palmerpenguins, its authors and CC0
                      Tasks5 of 5 done

                      1. Datasets module 2/2

                      • 1.1Add src/nanuq/data/penguins.csv (palmerpenguins inst/extdata/penguins.csv) and src/nanuq/data/README.md with source, authors and CC0; verify the file has 345 lines
                      • 1.2Add src/nanuq/datasets.nim with penguins() calling readCsv on currentSourcePath.parentDir / "data" / "penguins.csv" with nullValues = ["NA"]; verify with tests for shape, column order, null counts and dtypes, run from a different working directory

                      2. Penguins instead of iris 3/3

                      • 2.1Rewrite the README example and its output, and examples/basic.nim, with penguins (e.g. mean body mass and count per species, after dropNulls); verify nimble example prints what the README shows
                      • 2.2Switch the CSV read test in tests/test_basic.nim to penguins or the fixture, and update the src/nanuq.nim module doc example; verify nimble test passes
                      • 2.3Check CI is green on the PR

                      Workflow follow-up 0/0

                        Revisions2 revisions
                        r1 5a0c831 2026-10-27 Archive add-sample-datasets: backlog to changelog

                        First version: .openspec.yaml, proposal.md, specs/datasets/spec.md, tasks.md

                        r2 ad5de5a 2026-10-27 Switch dev-log posts to penguins, drop iris sample, link posts in README
                        proposal.md
                        § What Changes
                        - New module `nanuq/datasets` with `penguins(): DataFrame`, the full palmerpenguins table (344 rows, 8 columns, "NA" read as null). It calls `readCsv` on the CSV that ships next to the module, with the path fixed at compile time (`currentSourcePath`), so it works from any working directory and needs no network and no change to the Rust bridge. This is a convenience while Nanuq is young; the datasets are expected to move out later. - The README example, `examples/basic.nim` and the CSV tests use penguins instead of iris. The(During implementation datedPietro dev-logasked poststo stayswitch asthe written,two sodev-log `examples/iris_sample.csv`posts staysto forpenguins them.too and remove `examples/iris_sample.csv`.)

                        add-series-api Archived

                        openspec/changes/archive/2026-11-01-add-series-api
                        1. Proposal
                        2. Specs
                        3. Tasks
                        4. Implement 4/4
                        5. Archive
                        Proposal

                        Why

                        Polars users reach for a single column all the time: df["oni"].max(), (s - s.mean()) / s.std(), s.value_counts(). In Nanuq a Series is only a way to build a frame; there is no way to get one back, so every question about one column needs select and toList. The coverage map put "a real Series" at the head of 0.4, and the user guide's "Series" snippets and Packt's chapter 1 lean on it.

                        Polars itself is moving towards expressions everywhere, and Series methods in py-polars are mostly thin wrappers that evaluate an expression. Nanuq can do the same: a Series method runs the expression of the same name on a one-column frame. This adds the whole Series surface with almost no new ABI.

                        It is the eighth change of the 0.4 release.

                        What Changes

                        • Getting a Series: df["name"], df.getColumn("name"), df.toSeries(index).
                        • Inspecting it: name, len, dtype, nullCount, $ (Polars' Series display), toList(T), s[i, T], item(T), toFrame, alias/rename, cast, describe, valueCounts.
                        • Operating on it: arithmetic and comparison operators with literals and other Series, filter(mask), and every expression method that takes no other column (aggregations, math, cumulative, rolling, ranking, distinct values, recoding, binning: s.rollingMean(3), s.cut([0.0])), each evaluated through the expression of the same name. eval(s, expr) runs any expression on a Series.
                        • Back into frames: df.withColumns(series) and lit(series) in expressions.

                        Capabilities

                        New Capabilities
                        • series: getting, inspecting and operating on single columns.

                        Differences from Polars

                        • Aggregations return a Series of one value (s.sum), read with item(T) (s.sum.item(float)); Python returns a Python scalar. Nim needs the type at compile time, and keeping a Series lets aggregations chain.
                        • A Series does not convert to an expression automatically: use lit(s) (Python accepts a Series wherever an expression goes).
                        • Series methods that would take other columns (sortBy, topKBy, interpolateBy, over) are not forwarded; use a frame.
                        • No in-place methods (append, extend, set, scatter): Nanuq values are immutable.

                        Impact

                        • src/rust/src/lib.rs: nq_df_get_column, nq_df_to_series, nq_series_to_frame, nq_series_name, nq_series_len, nq_series_rename, nq_series_to_string; src/nanuq/ffi.nim; src/nanuq.nim (the forwarding macro).
                        • New tests/test_series.nim.
                        Spec changesseries +4

                        series modified +4

                        ADDED
                        Getting a Series

                        df["name"] and df.getColumn("name") SHALL return the column as a Series, and df.toSeries(index = 0) the column at a position (negative from the end); a missing column SHALL raise ColumnNotFoundError. A Series SHALL have name, len, dtype, nullCount and $, which shows Polars' Series display.

                        let df = newDataFrame:
                          year: [1997, 2015, 2023]
                          oni: [2.4, 2.6, 2.0]
                        let s = df["oni"]
                        echo s
                        echo s.name, " ", s.len, " ", s.dtype
                        TBD
                        Scenario: Missing column
                        • WHEN df["nope"] runs on a frame without that column
                        • THEN ColumnNotFoundError is raised
                        ADDED
                        Reading a Series

                        s.toList(T) and s.toList(Option[T]) SHALL return the values, s[i, T] one value, and s.item(T) the only value of a one-value Series (raising InvalidOperationError otherwise). toFrame SHALL return a one-column frame, and alias/rename and cast SHALL return a renamed or converted Series.

                        let s = series("oni", [2.4, 2.6, 2.0])
                        echo s.toList(float), " ", s[1, float]
                        echo s.toFrame.columns
                        TBD
                        Scenario: item on a longer Series
                        • WHEN item(float) is called on a Series of three values
                        • THEN InvalidOperationError is raised
                        ADDED
                        Series operations

                        Series SHALL support the arithmetic, comparison and boolean operators with literals and other Series of the same length, filter(mask), and the expression methods that take no other column (aggregations, math, cumulative, rolling, ranking, distinct values, recoding, binning), each SHALL give the same values as the expression of the same name on a one-column frame. Aggregations SHALL return a Series of one value.

                        let s = series("oni", [0.5, -1.0, 2.0, 1.2])
                        echo s.max.item(float)
                        echo ((s - s.mean.item(float)) / s.std.item(float)).round(2).toList(float)
                        echo s.filter(s > 0.5).toList(float)
                        echo s.rollingMean(2).toList(Option[float])
                        TBD
                        Scenario: Two Series
                        • WHEN a + b runs on Series a = 1, 2 and b = 10, 20
                        • THEN the result is 11, 22 named like a
                        ADDED
                        Series in frames

                        df.withColumns(series...) SHALL add or replace columns with Series of the frame's height, and lit(series) SHALL use a Series as a column in an expression.

                        let df = newDataFrame:
                          year: [1997, 2015, 2023]
                        let peak = series("peak", [2.4, 2.6, 2.0])
                        echo df.withColumns(peak, (peak * 10).alias("tenths"))
                        TBD
                        Scenario: Expression with a Series
                        • WHEN select(col.year + lit(series("d", [1, 1, 1]))) runs
                        • THEN each year grows by one

                        Unchanged in this spec: Series namespaces, Series as HTML, Columns from sized numbers, Binary functions on a Series

                        Tasks4 of 4 done

                        1. Implementation 4/4

                        • 1.1Getting a Series from a frame; name, len, dtype, display, reads
                        • 1.2Operators, filter, eval, forwarded expression methods
                        • 1.3withColumns(series), lit(series), valueCounts, describe
                        • 1.4Tests in tests/test_series.nim; nimble test and nimble specexamples pass; CHANGELOG
                        Revisions1 revision
                        r1 46ae6c2 2026-11-01 Nanuq 0.4, changes 8-10: Series API, Arraymancer tensors, row objects

                        First version: proposal.md, specs/series/spec.md, tasks.md

                        add-spec-examples Archived

                        created 2026-10-31 · openspec/changes/archive/2026-10-31-add-spec-examples
                        1. Proposal
                        2. Specs
                        3. Design
                        4. Tasks
                        5. Implement 7/7
                        6. Archive
                        Proposal

                        Why

                        Scenarios state the rules precisely, but they are hard to read: a WHEN/THEN sentence describes a call and its result in prose, and the reader has to picture both. A short piece of Nim and the table it prints shows the same thing at a glance, the way Polars' own docs do.

                        Examples that nobody runs go stale, so they must be checked, like tests.

                        This change comes from a request in the project thread (no BACKLOG.md entry).

                        What Changes

                        • Every requirement that describes Nim API gets an example: a nim ` block right after the requirement text and before the scenarios, followed by a

                        Capabilities

                        New Capabilities
                        • spec-examples: runnable examples in the OpenSpec specs, their format, and the checker.
                        Modified Capabilities
                        • ci: main specs trigger CI again, and CI runs the spec examples.

                        Impact

                        • openspec/specs/*/spec.md (examples only, no requirement text changes)
                        • tools/specexamples.nim (new), tools/specview.nim, nanuq.nimble
                        • .github/workflows/ci.yml, openspec/config.yaml
                        • The specs grow by about 70%, mostly output tables.

                        Differences from Polars

                        None: this change adds no Nim API. The examples follow Polars' docs in showing code with the printed table under it.

                        Spec changesci ~2 · spec-examples +3

                        ci modified ~2

                        MODIFIED
                        Skip CI for non-code changes
                        CI SHALL NOT run for pushes or pull requests that only change Markdown files, `LICENSE`, `.gitignore`, `openspec/` or `.claude/`, except `openspec/specs/`, whose examples CI runs. On `main`, CI SHALL also run for pushes that change `openspec/`, `BACKLOG.md` or `tools/specview.nim`, so the published OpenSpec page stays current. Scenario: OpenSpec-only change - **WHEN** a pull request only changes files under `openspec/changes/` - **THEN** no CI run starts Scenario: OpenSpec-only merge - **WHEN** a commit that only changes files under `openspec/changes/` lands on `main` - **THEN** CI runs and the site is deployed with the updated OpenSpec page Scenario: Main spec change - **WHEN** a pull request changes `openspec/specs/expressions/spec.md` - **THEN** CI runs, including the spec examples Scenario: Dev log change - **WHEN** a change touches `docs/` - **THEN** CI runs, so the dev log is rebuilt
                        MODIFIED
                        Tests, example and dev log
                        CI SHALL run the test suite, whichthe example includesand the spec examples,examples as(`nimble one programspecexamples`), (`tests/all.nim`), and the example, and render the site as one program (`docs/all.nim`): the nimib dev-log posts in `docs/blog`,`docs/blog` and then the index page `docs/index.nim` and the living`docs/index.nim`. pages (the Polars coverage page and the OpenSpec page). On `main`, after these succeed, it SHALL deploy the posts themand the index to GitHub Pages, with the index as the site root. Scenario: Merge to main - **WHEN** a commit lands on `main` and the test and docs jobs pass - **THEN** the dev log andis the living pages are deployed to GitHub Pages, and the site root lists the posts Scenario: Stale spec example - **WHEN** a pull request changes behavior that a spec example shows - **THEN** the test job fails until the example's output is updated Scenario: New test file - **WHEN** a pull request adds `tests/test_x.nim` - **THEN** the test job runs it as part of `tests/all.nim`, with no list to update

                        Unchanged in this spec: Build Rust only when the crate changes, Lib version follows the crate sources, Fast linking

                        spec-examples modified +3

                        ADDED
                        API requirements have examples

                        Every requirement in openspec/specs/ that describes Nim API SHALL include an example: a

                        allowed use; failures stay in scenarios. Requirements about process (CI, releases, the dev log, the C ABI) need none.

                        let df = newDataFrame(series("a", [1, 2, 3]))
                        echo df.select(col("a").isIn([1, 3]))
                        shape: (3, 1)
                        ┌───────┐
                        │ a     │
                        │ ---   │
                        │ bool  │
                        ╞═══════╡
                        │ true  │
                        │ false │
                        │ true  │
                        └───────┘
                        Scenario: New API requirement
                        • WHEN a change adds or modifies a requirement that describes Nim API
                        • THEN its delta includes the example and the expected output
                        Scenario: Process requirement
                        • WHEN a requirement describes CI or the release process
                        • THEN it has no example
                        ADDED
                        Examples are run

                        nimble specexamples SHALL compile and run every nim block in openspec/specs/, with nanuq, nanuq/datasets and std/[options, os, strutils] imported, and fail when an example does not compile, fails at run time, or prints something other than its text block. With --update it SHALL write the actual output into the text blocks instead. Change deltas SHALL NOT be run.

                        nimble specexamples                                      # check every spec
                        nim r tools/specexamples.nim --update expressions        # refresh one spec's outputs
                        Scenario: Output drifts
                        • WHEN a behavior change makes an example print a different table
                        • THEN nimble specexamples fails and shows the expected and actual output
                        Scenario: Update
                        • WHEN it runs with --update
                        • THEN the text blocks hold the actual output and the run passes
                        Scenario: Proposal with future API
                        • WHEN an open change's delta has an example using API that does not exist yet
                        • THEN the checker ignores it
                        ADDED
                        specview shows examples

                        specview SHALL keep fenced code in a requirement verbatim, never reading a line inside a fence as a heading, and SHALL render text ` blocks as output, set apart from the code.

                        Scenario: Nim comment in an example
                        • WHEN an example has a line starting with # or ##
                        • THEN specview shows it in the code block, and the requirement and its scenarios are unchanged
                        Design

                        Design

                        Where examples go

                        Inside each requirement, after the SHALL text and before the first scenario. Tested with the OpenSpec CLI (1.16):

                        • openspec validate passes, and fences are parsed as code: a ### Requirement: line inside a fence does not start a requirement.
                        • The code does not count towards the "requirement text too long" warning.
                        • Archive keeps fenced blocks in ADDED and MODIFIED requirements, so a change that alters behavior restates and updates the example in its delta, and specview shows that diff.

                        A spec-level ## Examples section also validates and survives archive, but deltas can never change it, so it would drift. Rejected.

                        Format

                        let df = newDataFrame(series("a", [1, 2, 3])) echo df.select(col("a").isIn([1, 3]))

                        shape: (3, 1) ...

                        • nanuq, nanuq/datasets and std/[options, os, strutils] are imported implicitly; an example's own import lines (e.g. nanuq/datamancer) are hoisted.
                        • Each example is self-contained: tiny frames built inline, or penguins(). Files go in getTempDir().
                        • echo a frame when the shape or dtypes matter; echo toSeq, columns or shape when only values do. Full Polars tables are kept (decided by Pietro).
                        • A nim ` block with no text block after it is compiled and run, but its output is not compared.

                        The checker

                        tools/specexamples.nim builds one program per spec: each example inside a block:, preceded by an echo of a marker, so one compile covers a spec and the output splits back per example. The 46 examples take about 90 seconds locally. Extra -d: flags are passed to the compile (CI uses -d:nanuqNoCargo). --update writes the actual output into the text blocks; the diff is then reviewed like any other change.

                        Only openspec/specs/ is checked. A proposal's examples describe future API, so they cannot run; their outputs are written by hand and corrected with --update when the change is implemented and archived.

                        CI trigger

                        paths-ignore cannot re-include a path, and **.md matches every spec. ci.yml switches to paths with negated patterns, where the last matching pattern wins: "**", then "!**.md", "!openspec/**", ..., then "openspec/specs/**". The Rust library is cached, so a spec-only change costs a test run.

                        Tasks7 of 7 done

                        1. Checker 2/2

                        • 1.1Add tools/specexamples.nim (run, compare, --update, capability filter, pass-through -d: flags) and the nimble specexamples task
                        • 1.2Make tools/specview.nim fence-aware when parsing specs, and style text ` blocks as output

                        2. Examples 2/2

                        • 2.1Add an example to every API requirement of the 11 API specs and fill outputs with --update
                        • 2.2Review every output against the requirement and its scenarios

                        3. CI and conventions 3/3

                        • 3.1Switch ci.yml to paths with negations so openspec/specs/** triggers CI, and run nimble specexamples in the test job
                        • 3.2Add the example rule for spec deltas to openspec/config.yaml
                        • 3.3Archive the change; add a CHANGELOG line
                        Revisions1 revision
                        r1 6c9d2a0 2026-10-31 Implement add-spec-examples

                        First version: .openspec.yaml, design.md, proposal.md, specs/ci/spec.md, specs/spec-examples/spec.md, tasks.md

                        add-specview-full-specs Archived

                        openspec/changes/archive/2026-11-01-add-specview-full-specs
                        1. Proposal
                        2. Specs
                        3. Tasks
                        4. Implement 3/3
                        5. Archive
                        Proposal

                        Why

                        specview shows OpenSpec changes, but not the specs they produce: to read what the API promises today, Pietro has to open each openspec/specs/*/spec.md on GitHub. And with every change archived, the page is dominated by finished work. Pietro asked on 2026-11-01 for the full specs in the viewer and for archived changes to be hidden by default.

                        What Changes

                        • specview renders every main spec in full (purpose, requirements with their examples and scenarios), one collapsible block per capability, with an index. Specs touched by an open change, or changed since --base, are marked.
                        • Archived changes are hidden by default, in the overview and in the page, behind a "Show archived changes" checkbox (remembered in the browser). Archived changes that changed since --base stay visible, so a PR that archives changes still shows them. A link to a hidden change reveals it.
                        • A small navigation bar links to Changes, Specs and (with --base) the file diff.

                        Capabilities

                        New Capabilities
                        • spec-review: what the specview page shows.

                        Differences from Polars

                        None: this is repository tooling, with no API surface.

                        Impact

                        Spec changesspec-review +2

                        spec-review modified +2

                        ADDED
                        Full specs in specview

                        specview SHALL render every spec in openspec/specs/ in full, with its purpose, requirements, examples and scenarios, and SHALL mark the specs that an open change modifies or that changed since --base.

                        Scenario: Reading a spec
                        • WHEN a reviewer opens the Specs section and expands temporal
                        • THEN every requirement of openspec/specs/temporal/spec.md is shown with its example and scenarios
                        ADDED
                        Archived changes are hidden by default

                        specview SHALL hide archived changes until the reader ticks "Show archived changes", except archived changes that changed since --base. A link to a hidden change SHALL reveal it.

                        Scenario: No base
                        • WHEN specview runs without --base on a repository whose changes are all archived
                        • THEN no change is shown until the checkbox is ticked
                        Scenario: A PR that archives changes
                        • WHEN specview runs with --base:origin/main on a branch that archived three changes
                        • THEN those three changes are shown and the other archived ones are hidden
                        Tasks3 of 3 done

                        Tasks 3/3

                        • 1.1Render every main spec with an index and open-change markers
                        • 1.2Hide archived changes behind a checkbox, except those changed since --base
                        • 1.3Navigation bar; check the page in a browser with and without --base
                        Revisions1 revision
                        r1 b5d2d7e 2026-11-01 specview: show every spec in full, hide archived changes by default

                        First version: proposal.md, specs/spec-review/spec.md, tasks.md

                        add-sql Archived

                        openspec/changes/archive/2026-11-01-add-sql
                        1. Proposal
                        2. Specs
                        3. Tasks
                        4. Implement 3/3
                        5. Archive
                        Proposal

                        Why

                        SQL is the most used API still missing from the book ports: SQLContext.execute appears in 18 sections and SQLContext in 10, mostly the user guide's SQL chapters. For users coming from SQL it is also the shortest way in. The coverage map lists it as one bridge call behind the sql feature.

                        It is the sixth change of the 0.5 release.

                        What Changes

                        • SQLContext: newSQLContext() or newSQLContext({"bears": lf}), register (LazyFrame or DataFrame), unregister, tables, and execute(query) giving a LazyFrame (or a DataFrame with eager = true).
                        • sqlContext(bears, dens), a macro that registers frames under their variable names (what Python's register_globals and keyword arguments do).
                        • lf.sql(query, tableName = "self") and df.sql(...), and sql(query, frames).
                        • SQL table functions (read_csv, read_parquet, read_ipc, read_json) work in queries.

                        Capabilities

                        New Capabilities
                        • sql: running SQL queries on frames.

                        Differences from Polars

                        • No register_globals (Nim cannot list a scope's variables at run time); the sqlContext(a, b) macro names frames after the variables passed to it instead.
                        • execute returns a LazyFrame unless eager = true, as in Python; df.sql returns a DataFrame, lf.sql a LazyFrame.
                        • No register_many with a dict: newSQLContext and register take {"name": frame}.

                        Impact

                        • src/rust/src/lib.rs and src/nanuq/ffi.nim: nq_sql_* functions on an opaque context.
                        • src/nanuq.nim: SQLContext and helpers.
                        • New tests/test_sql.nim.
                        Spec changessql +3

                        sql modified +3

                        ADDED
                        SQL contexts

                        newSQLContext() SHALL make an empty context and newSQLContext({"name": frame}) one with frames registered; register(name, frame) SHALL add a LazyFrame or DataFrame, unregister(name) remove it and tables list the names in sorted order; execute(query) SHALL run a SQL query on the registered frames and give a LazyFrame, or a DataFrame with eager = true.

                        let bears = newDataFrame:
                          bear: ["Ada", "Bo", "Cy"]
                          kg: [410, 380, 500]
                        let ctx = newSQLContext({"bears": bears.lazy})
                        echo ctx.tables
                        echo ctx.execute("SELECT bear, kg FROM bears WHERE kg > 400 ORDER BY kg DESC", eager = true)
                        TBD
                        Scenario: Unknown table
                        • WHEN a query reads a table that is not registered
                        • THEN SqlError is raised
                        ADDED
                        Frames by variable name

                        sqlContext(a, b, ...) SHALL make a context with each frame registered under the name of the variable passed.

                        let bears = newDataFrame:
                          bear: ["Ada", "Bo"]
                          den: [1, 2]
                        let dens = newDataFrame:
                          den: [1, 2]
                          site: ["Kong Karls Land", "Hopen"]
                        let ctx = sqlContext(bears, dens)
                        echo ctx.execute("SELECT bear, site FROM bears JOIN dens USING (den)").collect
                        TBD
                        Scenario: Not a variable
                        • WHEN sqlContext(bears.lazy) is compiled
                        • THEN compilation fails with a message asking for a variable
                        ADDED
                        SQL on a frame

                        df.sql(query) and lf.sql(query) SHALL run a query on the frame, which the query calls self (or tableName), and sql(query, {"name": frame}) SHALL run a query on the given frames.

                        let df = newDataFrame:
                          island: ["Biscoe", "Dream", "Biscoe"]
                          kg: [4.5, 3.7, 5.1]
                        echo df.sql("SELECT island, AVG(kg) AS kg FROM self GROUP BY island ORDER BY island")
                        TBD
                        Scenario: Other table name
                        • WHEN df.sql("SELECT * FROM penguins", tableName = "penguins") is run
                        • THEN the result is the frame
                        Tasks3 of 3 done

                        1. Implementation 3/3

                        • 1.1Crate: SQL context new/free/register/unregister/tables/execute
                        • 1.2SQLContext, newSQLContext, sqlContext macro, sql on frames and as a function
                        • 1.3Tests in tests/test_sql.nim; nimble test and nimble specexamples pass; CHANGELOG
                        Revisions1 revision
                        r1 1b5c5b7 2026-11-01 0.5: SQL contexts and queries (add-sql)

                        First version: proposal.md, specs/sql/spec.md, tasks.md

                        add-streaming-and-sinks Archived

                        openspec/changes/archive/2026-11-01-add-streaming-and-sinks
                        1. Proposal
                        2. Specs
                        3. Tasks
                        4. Implement 3/3
                        5. Archive
                        Proposal

                        Why

                        Polars' streaming engine runs a query in batches, so it can process data larger than memory, and sinks write a query's result straight to files without collecting it first. The coverage roadmap puts both first in 0.6 ("Engine and edges"), the 0.6 book map needs sink_csv (Packt ch2) and the user guide's streaming page, and BACKLOG.md "More IO" names sink functions. The crate already compiles the streaming engine (the json feature pulls it in), so this is a thin layer.

                        It is the first change of the 0.6 release. It takes the "sink functions" part of the BACKLOG.md entry "More IO".

                        What Changes

                        • Engine enum (Auto, InMemory, Streaming) and collect(lf, engine), collectAll(lfs, engine).
                        • sinkParquet, sinkIpc, sinkCsv, sinkNdjson on LazyFrames, with the options of the matching write* procs plus maintainOrder and mkdir. They run the query with the streaming engine and write the file; with lazy = true they return the sink plan as a LazyFrame instead, to run later with collect or several at once with collectAll.
                        • PartitionBy(basePath, key, includeKey, maxRowsPerFile) as the target of a sink writes one file per key value (Hive-style directories) or per row count.
                        • profile(lf) returns the result and a frame of node timings.

                        Capabilities

                        New Capabilities
                        • streaming: the streaming engine, sinks and query profiling.

                        Differences from Polars

                        • Engine has no Gpu (Python only, through cuDF).
                        • lazy is a static bool: sinkParquet(path) returns nothing, sinkParquet(path, lazy = true) returns a LazyFrame (Python returns None or a LazyFrame from the same call).
                        • No cloud targets (storage_options, credential_provider, retries), no sync_on_close, no Parquet metadata or field_overwrites, no optimizations argument. PartitionBy has no file_path callback and no approximate_bytes_per_file.
                        • Python's profile can also show a plot; Nanuq returns the two frames.

                        Impact

                        • src/rust/src/lib.rs, src/nanuq/ffi.nim: nq_lf_collect_engine, nq_lf_sink, nq_lf_profile, engine argument on nq_collect_all.
                        • src/nanuq.nim: the procs above.
                        • New tests/test_streaming.nim.
                        Spec changesstreaming +4

                        streaming modified +4

                        ADDED
                        Choosing the engine

                        collect(lf, engine) SHALL run the query with the given Engine: Auto (Polars picks, today the in-memory engine), InMemory or Streaming, which processes the data in batches. Every engine SHALL give the same rows; collectAll(lfs, engine) SHALL take the same choice.

                        let lf = newDataFrame(series("kg", @[410, 380, 455])).lazy
                        echo lf.filter(col("kg") > 400).collect(engine = Engine.Streaming)
                        TBD
                        Scenario: Same result
                        • WHEN a group-by query is collected with Engine.InMemory and with Engine.Streaming
                        • THEN both frames are equal after sorting
                        ADDED
                        Sinks

                        sinkParquet, sinkIpc, sinkCsv and sinkNdjson SHALL run a LazyFrame with the streaming engine and write the result to a file, with the options of writeParquet, writeIpc, writeCsv and writeNdjson, plus maintainOrder = true and mkdir = false (create missing directories). With lazy = true they SHALL return the sink as a LazyFrame, which writes the file when collected; collectAll SHALL run several such sinks together.

                        let dir = getTempDir() / "nanuq-sinks"
                        let lf = newDataFrame(series("bear", @["Ada", "Bo"]), series("kg", @[410, 380])).lazy
                        lf.sinkCsv(dir / "bears.csv", mkdir = true)
                        echo readFile(dir / "bears.csv")
                        let sinks = [lf.sinkParquet(dir / "bears.parquet", lazy = true),
                                     lf.filter(col("kg") > 400).sinkNdjson(dir / "big.ndjson", lazy = true)]
                        discard collectAll(sinks)
                        echo readParquet(dir / "bears.parquet").height, " ", readFile(dir / "big.ndjson")
                        TBD
                        Scenario: Missing directory
                        • WHEN a sink targets a directory that does not exist and mkdir is false
                        • THEN IOError is raised and no file is written
                        ADDED
                        Partitioned sinks

                        A sink SHALL accept a PartitionBy(basePath, key, includeKey = true, maxRowsPerFile) target instead of a path: with key it SHALL write one Hive-style directory per key value (basePath/key=value/...), without it files of at most maxRowsPerFile rows.

                        let base = getTempDir() / "nanuq-by-year"
                        let df = newDataFrame(series("year", @[2024, 2024, 2025]), series("n", @[1, 2, 3]))
                        df.lazy.sinkParquet(PartitionBy(basePath: base, key: @["year"]), mkdir = true)
                        echo scanParquet(base / "**/*.parquet").sort("n").collect
                        TBD
                        Scenario: Rows per file
                        • WHEN 10 rows are sunk with PartitionBy(basePath: dir, maxRowsPerFile: 4)
                        • THEN reading every file in dir gives the 10 rows back
                        ADDED
                        Profiling

                        profile(lf) SHALL run the query and return a tuple of the result and a frame with one row per executed node (node, start, end, in microseconds).

                        let (res, timings) = newDataFrame(series("x", @[1, 2, 3])).lazy.select(col("x").sum).profile
                        echo res
                        echo timings.columns
                        TBD
                        Scenario: Timings
                        • WHEN a query is profiled
                        • THEN every end is at least its start
                        Tasks3 of 3 done

                        1. Implementation 3/3

                        • 1.1Crate: collect with engine, sinks (file and partitioned), profile, engine for collect_all
                        • 1.2Engine, collect(engine), collectAll(engine), sink*, PartitionBy, profile
                        • 1.3Tests in tests/test_streaming.nim; nimble test and nimble specexamples pass; CHANGELOG
                        Revisions1 revision
                        r1 4ea5dad 2026-11-01 0.6: archive the 9 changes, fill spec example outputs, map_elements benchmark, dev log Designing Nanuq 0.6

                        First version: proposal.md, specs/streaming/spec.md, tasks.md

                        add-string-expressions Archived

                        openspec/changes/archive/2026-10-31-add-string-expressions
                        1. Proposal
                        2. Specs
                        3. Design
                        4. Tasks
                        5. Implement 7/7
                        6. Archive
                        Proposal

                        Why

                        Real tables arrive with messy strings: en dashes in race names ("Paris–Nice"), times written as "73h 56′ 26″", riders whose names need upper-casing or trimming. Nanuq 0.2 has no string functions at all, so none of that can be cleaned inside a query. The 0.3 explainer needs replaceAll, extract, an aggregation that joins a rider's races into one string, and format to print cycling-style gaps.

                        This change takes up the BACKLOG.md entry "More expressions" (string functions). It is the fourth change of the 0.3 release, following the dev log "Designing Nanuq 0.3", section 4 (the str namespace as a distinct Expr, Rust regex, literal = true) and the later additions confirmed by Pietro on 2026-10-31 (format, str.join).

                        What Changes

                        • e.str returns a StrNameSpace (a distinct Expr) with Polars' string functions, in camelCase:
                        • lenChars, lenBytes, toUppercase, toLowercase, reverse;
                        • stripChars, stripCharsStart, stripCharsEnd (whitespace, or the given characters), stripPrefix, stripSuffix;
                        • startsWith, endsWith, contains(pattern, literal = false, strict = true), find, countMatches, extract(pattern, groupIndex = 1);
                        • replace(pattern, value, literal = false, n = 1), replaceAll(pattern, value, literal = false);
                        • slice(offset, length), head(n), tail(n), padStart(length, fillChar = ' '), padEnd, zfill;
                        • join(delimiter = "", ignoreNulls = true), an aggregation. Patterns, lengths and offsets take a Nim value or an expression.
                        • concatStr(exprs, separator = "", ignoreNulls = false) and format("{} ({})", col.rider, col.nat), as Polars' concat_str and format.
                        • Polars features strings, regex, string_pad, string_reverse, and concat_str are compiled in.

                        Not in this change: split, extractAll, extractGroups, splitExact (they return List or Struct columns), toTitlecase (needs Polars' nightly feature), strptime, toDate, toDatetime and toTime (the temporal change), toInteger (needs Polars' 128-bit integer dtypes; cast(int) parses decimal strings), normalize, json*, encode/decode, containsAny/replaceMany.

                        Capabilities

                        New Capabilities
                        • strings: the str namespace, concatStr and format.
                        Modified Capabilities
                        • native-bridge: NqStrOp joins the enums kept in the same order.

                        Differences from Polars

                        Expected differences from Polars' Rust and Python APIs:

                        • Regex syntax is Rust's regex crate, as in both Polars APIs: no backreferences, no lookaround.
                        • literal, strict, n, groupIndex are named arguments as in Python. Rust's contains_literal/find_literal and replace_n become the literal and n arguments.
                        • stripChars() without characters strips whitespace, as Python's strip_chars(None); Rust takes a null literal.
                        • format checks the number of placeholders against the arguments when the expression is built, as Python does; it is Nanuq's own proc, built on concatStr. It overloads strutils.format, which takes strings, not expressions.
                        • Names follow Polars in camelCase: len_chars → lenChars, strip_chars_start → stripCharsStart, concat_str → concatStr.

                        Impact

                        • src/rust/src/lib.rs: nq_expr_str (one entry point with NqStrOp) and nq_expr_concat_str; five Polars features in Cargo.toml.
                        • src/nanuq/ffi.nim, src/nanuq.nim: the declarations, StrNameSpace and its procs, concatStr, format.
                        • tests/test_strings.nim (new); README; BACKLOG "More expressions" is removed.
                        Spec changesnative-bridge ~1 · strings +6

                        native-bridge modified ~1

                        MODIFIED
                        Nim declarations mirror the C ABI
                        `src/nanuq/ffi.nim` SHALL declare every exported function with matching signatures, and the enums `NqBinOp`, `NqUnary`, `NqDtype`, `NqDtypeClass`, `NqJoinType`, `NqJoinValidation`, `NqMaintainOrderJoin`, `NqConcat`, `NqUniqueKeepStrategy`, `NqClosedInterval`, `NqQuantileMethod`, `NqFillNullStrategy`, `NqRoundMode`, `NqQuoteStyle`, `NqRankMethod`, `NqErrorKind`,`NqErrorKind` `NqStrOp`,and `NqTimeUnit`, `NqClosedWindow`,`NqStrOp` `NqDtOp`, `NqCatOp`, `NqParquetCompression` and `NqIpcCompression` SHALL keep the same order as in Rust. `NqDtype` SHALL also keep the order of of `DataTypeKind`, and the option enums the order of their Nim API enums. Data types SHALL cross the ABI as an `NqDtypeSpec` struct (code, time unit, time zone, categories) with the same field order on both sides. Scenario: ABI change - **WHEN** a function is added or changed in `rust/src/lib.rs` - **THEN** `src/nanuq/ffi.nim` is updated in the same change

                        Unchanged in this spec: C ABI over Polars with opaque handles, Errors and panics never cross the boundary, Linking the static library, Columns cross in bulk, Library version check, Formatted cells, Polars version matches a py-polars release

                        strings modified +6

                        ADDED
                        The str namespace

                        e.str SHALL give access to string functions that return expressions: lenChars, lenBytes, toUppercase, toLowercase and reverse. Nulls SHALL stay null in every string function, unless stated otherwise.

                        let df = newDataFrame:
                          rider: ["Pogačar", "Seixas", nil]
                        echo df.select(col.rider, col.rider.str.toUppercase.alias("upper"),
                                       col.rider.str.lenChars.alias("chars"), col.rider.str.lenBytes.alias("bytes"))
                        shape: (3, 4)
                        ┌─────────┬─────────┬───────┬───────┐
                        │ rider   ┆ upper   ┆ chars ┆ bytes │
                        │ ---     ┆ ---     ┆ ---   ┆ ---   │
                        │ str     ┆ str     ┆ u32   ┆ u32   │
                        ╞═════════╪═════════╪═══════╪═══════╡
                        │ Pogačar ┆ POGAČAR ┆ 7     ┆ 8     │
                        │ Seixas  ┆ SEIXAS  ┆ 6     ┆ 6     │
                        │ null    ┆ null    ┆ null  ┆ null  │
                        └─────────┴─────────┴───────┴───────┘
                        Scenario: Characters and bytes
                        • WHEN str.lenChars and str.lenBytes run over "Pogačar"
                        • THEN the results are 7 and 8
                        Scenario: Not a string column
                        • WHEN str.toUppercase runs over an i64 column
                        • THEN PolarsError is raised when the query runs
                        ADDED
                        Matching

                        The namespace SHALL provide startsWith(prefix), endsWith(suffix), contains(pattern, literal = false, strict = true), find(pattern, literal = false, strict = true), countMatches(pattern, literal = false) and extract(pattern, groupIndex = 1). Patterns SHALL be Rust regular expressions unless literal = true. With strict = false, an invalid regex SHALL give null instead of raising.

                        let df = newDataFrame:
                          race: ["Paris–Nice", "Milano-Sanremo", "Tour de France"]
                        echo df.select(col.race,
                                       col.race.str.contains("–", literal = true).alias("en_dash"),
                                       col.race.str.startsWith("Tour").alias("tour"),
                                       col.race.str.extract(r"^(\w+)", 1).alias("first"),
                                       col.race.str.countMatches("[aeiou]").alias("vowels"))
                        shape: (3, 5)
                        ┌────────────────┬─────────┬───────┬────────┬────────┐
                        │ race           ┆ en_dash ┆ tour  ┆ first  ┆ vowels │
                        │ ---            ┆ ---     ┆ ---   ┆ ---    ┆ ---    │
                        │ str            ┆ bool    ┆ bool  ┆ str    ┆ u32    │
                        ╞════════════════╪═════════╪═══════╪════════╪════════╡
                        │ Paris–Nice     ┆ true    ┆ false ┆ Paris  ┆ 4      │
                        │ Milano-Sanremo ┆ false   ┆ false ┆ Milano ┆ 6      │
                        │ Tour de France ┆ false   ┆ true  ┆ Tour   ┆ 5      │
                        └────────────────┴─────────┴───────┴────────┴────────┘
                        Scenario: Literal vs regex
                        • WHEN str.contains(".") and str.contains(".", literal = true) run over "abc"
                        • THEN the results are true and false
                        Scenario: No match
                        • WHEN str.extract(r"(\d+)'") runs over "73h"
                        • THEN the result is null
                        Scenario: Invalid regex
                        • WHEN str.contains("(") runs, and then str.contains("(", strict = false)
                        • THEN the first raises PolarsError and the second gives null
                        ADDED
                        Replacing and stripping

                        The namespace SHALL provide replace(pattern, value, literal = false, n = 1), replaceAll(pattern, value, literal = false), stripChars, stripCharsStart and stripCharsEnd (whitespace without an argument, otherwise the given characters), stripPrefix(prefix) and stripSuffix(suffix). In a regex replacement, $1 SHALL refer to a capture group.

                        let df = newDataFrame:
                          race: ["  Paris–Nice ", "Tirreno–Adriatico", "Strade Bianche"]
                        echo df.select(col.race.str.stripChars.str.replaceAll("–", "-", literal = true).alias("clean"),
                                       col.race.str.replace(r"(\w+) (\w+)", "$2 $1").alias("swapped"))
                        shape: (3, 2)
                        ┌───────────────────┬───────────────────┐
                        │ clean             ┆ swapped           │
                        │ ---               ┆ ---               │
                        │ str               ┆ str               │
                        ╞═══════════════════╪═══════════════════╡
                        │ Paris-Nice        ┆   Paris–Nice      │
                        │ Tirreno-Adriatico ┆ Tirreno–Adriatico │
                        │ Strade Bianche    ┆ Bianche Strade    │
                        └───────────────────┴───────────────────┘
                        Scenario: Replace the first n
                        • WHEN str.replace("a", "o", n = 2) runs over "banana"
                        • THEN the result is "bonona"
                        Scenario: Strip given characters
                        • WHEN str.stripChars("*") runs over "win"
                        • THEN the result is "win"
                        ADDED
                        Slicing and padding

                        The namespace SHALL provide slice(offset) and slice(offset, length) (a negative offset counts from the end), head(n), tail(n), padStart(length, fillChar = ' '), padEnd(length, fillChar = ' ') and zfill(length), counting characters.

                        let df = newDataFrame:
                          bib: ["1", "21", "141"]
                          nat: ["SLO", "FRA", "DEN"]
                        echo df.select(col.bib.str.zfill(3).alias("bib"), col.bib.str.padStart(4, '.').alias("dots"),
                                       col.nat.str.head(2).alias("head"), col.nat.str.slice(-2).alias("last2"))
                        shape: (3, 4)
                        ┌─────┬──────┬──────┬───────┐
                        │ bib ┆ dots ┆ head ┆ last2 │
                        │ --- ┆ ---  ┆ ---  ┆ ---   │
                        │ str ┆ str  ┆ str  ┆ str   │
                        ╞═════╪══════╪══════╪═══════╡
                        │ 001 ┆ ...1 ┆ SL   ┆ LO    │
                        │ 021 ┆ ..21 ┆ FR   ┆ RA    │
                        │ 141 ┆ .141 ┆ DE   ┆ EN    │
                        └─────┴──────┴──────┴───────┘
                        Scenario: Slice with a length
                        • WHEN str.slice(1, 2) runs over "Pogačar"
                        • THEN the result is "og"
                        ADDED
                        Joining strings in an aggregation

                        str.join(delimiter = "", ignoreNulls = true) SHALL aggregate a column into one string, in row order, per group in agg. With ignoreNulls = false, a null SHALL make the result null.

                        let wins = newDataFrame:
                          rider: ["Pogačar", "Seixas", "Pogačar"]
                          race: ["Strade Bianche", "Flèche Wallonne", "Il Lombardia"]
                        echo wins.groupBy(col.rider).agg(col.race.str.join(", ").alias("races")).sort("rider").collect
                        shape: (2, 2)
                        ┌─────────┬────────────────────────────────┐
                        │ rider   ┆ races                          │
                        │ ---     ┆ ---                            │
                        │ str     ┆ str                            │
                        ╞═════════╪════════════════════════════════╡
                        │ Pogačar ┆ Strade Bianche, Il Lombardia   │
                        │ Seixas  ┆ Flèche Wallonne                │
                        └─────────┴────────────────────────────────┘
                        Scenario: Whole column
                        • WHEN select(col.race.str.join("|")) runs over "a", null, "b"
                        • THEN the result is one row holding "a|b"
                        ADDED
                        Building strings from columns

                        concatStr(exprs, separator = "", ignoreNulls = false) SHALL concatenate expressions row by row into a string column, and format(template, args...) SHALL replace each {} in template by the next argument. Non-string arguments SHALL be formatted as Polars casts them to strings. A null argument SHALL make the row null, unless ignoreNulls = true in concatStr. A template whose placeholders don't match the number of arguments SHALL raise ValueError.

                        let gaps = newDataFrame:
                          rider: ["Vingegaard", "Pogačar"]
                          minutes: [4, 0]
                          seconds: [23, 7]
                        echo gaps.select(format("{}: {}′ {}″", col.rider, col.minutes, col.seconds).alias("gap"),
                                         concatStr([col.rider, lit("UAE")], separator = " / ").alias("team"))
                        shape: (2, 2)
                        ┌────────────────────┬──────────────────┐
                        │ gap                ┆ team             │
                        │ ---                ┆ ---              │
                        │ str                ┆ str              │
                        ╞════════════════════╪══════════════════╡
                        │ Vingegaard: 4′ 23″ ┆ Vingegaard / UAE │
                        │ Pogačar: 0′ 7″     ┆ Pogačar / UAE    │
                        └────────────────────┴──────────────────┘
                        Scenario: Wrong number of arguments
                        • WHEN format("{} {}", col.a) is called
                        • THEN ValueError is raised
                        Scenario: Next to strutils
                        • WHEN a module imports std/strutils and nanuq and calls format("{}", col.a) and "$1".format("x")
                        • THEN both compile, the first giving an expression and the second "x"

                        Unchanged in this spec: Title case, Splitting and extracting into lists and structs, Many patterns at once, JSON in strings, Escaping and normalizing

                        Design

                        Design

                        Decisions

                        One ABI function for the namespace

                        Polars' string functions differ only in which arguments they take: up to two expressions (pattern and value, offset and length), up to two booleans (literal, strict), a count, a fill character, and for join a delimiter string. A single nq_expr_str(e, op, a, b, flag1, flag2, n, ch, s) with an NqStrOp enum covers them all, the same way nq_expr_unary covers one-argument functions. A NULL expression argument means a null literal (for stripChars() and an open-ended slice).

                        StrNameSpace is a distinct Expr

                        col.race.str.replaceAll(...) reads like Polars, and names can't clash with Expr procs or with future namespaces (str.len vs list.len). Converting back is free.

                        format in Nim

                        Python's pl.format splits the template on {} and calls concat_str; Nanuq does the same, so no ABI function is needed.

                        Tasks7 of 7 done

                        1. Bridge 2/2

                        • 1.1Add the Polars features strings, regex, string_pad, string_reverse, and concat_str
                        • 1.2Add nq_expr_str with NqStrOp, and nq_expr_concat_str; mirror them in ffi.nim

                        2. Nim API 3/3

                        • 2.1Add StrNameSpace, str and every function listed in the proposal
                        • 2.2Add concatStr and format
                        • 2.3Write tests/test_strings.nim: each function, literal vs regex, strict vs not, nulls, join in agg, format with too few or too many arguments, format next to strutils; add it to nanuq.nimble and .gitignore

                        3. Docs and integration 2/2

                        • 3.1README lists the namespace; nimble test and nimble specexamples pass
                        • 3.2Archive the change: remove BACKLOG "More expressions", add CHANGELOG lines
                        Revisions1 revision
                        r1 603f9ac 2026-10-31 OpenSpec add-string-expressions: str namespace, concatStr, format

                        First version: design.md, proposal.md, specs/native-bridge/spec.md, specs/strings/spec.md, tasks.md

                        add-struct-namespace Archived

                        openspec/changes/archive/2026-11-01-add-struct-namespace
                        1. Proposal
                        2. Specs
                        3. Tasks
                        4. Implement 3/3
                        5. Archive
                        Proposal

                        Why

                        Struct columns (add-nested-dtypes) need their functions: struct.field blocks 11 book sections, pl.struct(...) 9, unnest 8 and value_counts 12 (Polars' expression value_counts returns a struct). The arr namespace for Array columns comes along, as the coverage map pairs them.

                        It is the fourth change of the 0.5 release.

                        What Changes

                        • asStruct(exprs) builds a struct column (Python's pl.struct).
                        • e.struct: field(name) (also e.struct["name"]), field(names) and field(index), unnest (all fields as columns), renameFields, withFields, jsonEncode.
                        • df.unnest(columns, separator) (eager and lazy): fields become columns.
                        • Expr.valueCounts(sort, parallel, name, normalize) gives a struct of value and count.
                        • e.arr: len, sum, min, max, mean, median, std, var, argMin, argMax, first, last, get, join, contains, countMatches, sort, slice, head, tail, shift, toList, toStruct, explode, eval, agg.

                        Capabilities

                        New Capabilities
                        • struct-functions: struct construction, the struct and arr namespaces, unnest and expression valueCounts.

                        Differences from Polars

                        • The constructor is asStruct (the Rust name): struct is the namespace, col("a").struct, and struct(col("a")) could not be told apart from it.
                        • asStruct takes expressions only; Python also takes keyword arguments (pl.struct(x=...)): use .alias.
                        • struct.withFields refers to the struct's own fields with col inside struct.field, not with Python's pl.field.
                        • arr.toStruct names the fields field_0, ...; Python can also take a function.
                        • No prefixFields/suffixFields (not in Rust Polars 0.55's DSL).

                        Impact

                        • src/rust/src/lib.rs and src/nanuq/ffi.nim: nq_expr_struct, nq_as_struct, nq_expr_value_counts, nq_lf_unnest, nq_expr_arr.
                        • src/nanuq.nim: StructNameSpace, ArrayNameSpace.
                        • New tests/test_structs.nim.
                        Spec changesstruct-functions +5

                        struct-functions modified +5

                        ADDED
                        Building structs

                        asStruct(exprs) SHALL build a struct column with one field per expression, named after its output name.

                        let df = newDataFrame:
                          bear: ["Ada", "Bo"]
                          kg: [410, 380]
                        echo df.select(asStruct(col("bear"), col("kg") * 2).alias("s"))
                        TBD
                        Scenario: Duplicate names
                        • WHEN two expressions with the same output name are put in one struct
                        • THEN DuplicateError is raised
                        ADDED
                        Struct fields

                        e.struct.field(name) (also e.struct[name]) SHALL give one field as a column, field(names) several, field(index) one by position, and e.struct.unnest all of them; renameFields(names) SHALL rename the fields in order, withFields(exprs) add or replace fields, and jsonEncode give each struct as a JSON string.

                        let df = newDataFrame:
                          p: [(x: 1, y: 2.0), (x: 3, y: 4.0)]
                        echo df.select(col("p").struct.field("x"), col("p").struct["y"].alias("y"),
                                       col("p").struct.jsonEncode.alias("json"))
                        echo df.select(col("p").struct.renameFields(["a", "b"]).struct.unnest)
                        TBD
                        Scenario: Unknown field
                        • WHEN struct.field("z") is evaluated on a struct without z
                        • THEN StructFieldNotFoundError is raised
                        ADDED
                        Unnesting frames

                        df.unnest(columns) SHALL replace each struct column by its fields (eager and lazy); with separator, the new columns SHALL be named <column><separator><field>.

                        let df = newDataFrame:
                          bear: ["Ada", "Bo"]
                          den: [(lat: 78.2, lon: 15.6), (lat: 79.0, lon: 16.1)]
                        echo df.unnest("den")
                        echo df.unnest("den", separator = "_").columns
                        TBD
                        Scenario: Not a struct
                        • WHEN a list column is unnested
                        • THEN InvalidOperationError or SchemaError is raised
                        ADDED
                        Value counts as an expression

                        e.valueCounts(sort, parallel, name, normalize) SHALL give a struct column with the distinct values and their counts (or fractions with normalize), named count (or proportion) unless name is given.

                        let df = newDataFrame:
                          island: ["Biscoe", "Dream", "Biscoe"]
                        echo df.select(col("island").valueCounts(sort = true)).unnest("island")
                        TBD
                        Scenario: Sorted counts
                        • WHEN valueCounts(sort = true) is evaluated
                        • THEN the most frequent value comes first
                        ADDED
                        Array functions

                        e.arr SHALL give a namespace of functions on each array of an Array column: len, sum, min, max, mean, median, std, var, argMin, argMax, first, last, get, join, contains, countMatches, sort, slice, head, tail, shift, toList, toStruct, explode, eval and agg.

                        let df = newDataFrame:
                          rgb: [[255, 0, 0], [10, 20, 30]]
                        echo df.select(col("rgb").arr.sum.alias("sum"), col("rgb").arr.get(1).alias("g"),
                                       col("rgb").arr.toList.alias("list"))
                        TBD
                        Scenario: Array to struct
                        • WHEN arr.toStruct is evaluated on arrays of width 3
                        • THEN the result is a struct with fields field_0, field_1 and field_2

                        Unchanged in this spec: Structs from column names

                        Tasks3 of 3 done

                        1. Implementation 3/3

                        • 1.1Crate: struct and arr entry points, as_struct, value_counts, frame unnest
                        • 1.2asStruct, StructNameSpace, unnest, Expr.valueCounts, ArrayNameSpace
                        • 1.3Tests in tests/test_structs.nim; nimble test and nimble specexamples pass; CHANGELOG
                        Revisions1 revision
                        r1 5c0aadf 2026-11-01 0.5: nested dtypes, list, struct and arr namespaces, nested strings

                        First version: proposal.md, specs/struct-functions/spec.md, tasks.md

                        add-temporal-types Archived

                        openspec/changes/archive/2026-10-31-add-temporal-types
                        1. Proposal
                        2. Specs
                        3. Design
                        4. Tasks
                        5. Implement 10/10
                        6. Archive
                        Proposal

                        Why

                        Nanuq 0.2 cannot hold a date. Every real table has one: a rider's birth date, a stage date, a finishing time, a gap to the winner. The 0.3 explainer "Aged 19" is built on them (age of a winner on race day, gaps in hours and minutes, finish times across time zones), and the dev log "Designing Nanuq 0.3" names temporal types the critical item of the release.

                        Nim's standard library makes this harder than in Python: std/times has DateTime and Duration, but no date without a time, no time of day, only local and UTC zones, and a TimeInterval (calendar steps such as 1.months) next to Duration (exact lengths). The design (dev log section 1) keeps the std/times types where they fit and adds two small Nanuq types where they do not.

                        This change takes up the dates part of the BACKLOG.md entry "More dtypes". It is the fifth change of the 0.3 release.

                        What Changes

                        • Data types: DataTypeKind gains Date, Datetime, Duration and Time. Datetime and Duration carry a timeUnit (std/times' TimeUnit, limited to Nanoseconds, Microseconds, Milliseconds), and Datetime an optional timeZone (an IANA name). $ gives Polars' names (datetime[μs, Europe/Rome]). schema[c] == DateTime matches any unit and zone.
                        • Nim values: Date (a distinct int32 of days since 1970-01-01, with date(y, m, d), year, month, monthday, $, +/- days and comparisons) and TimeOfDay (with timeOfDay(h, m, s, ns)), next to std/times' DateTime and Duration. series, block newDataFrame, lit, toList, df[c, i, T], fillNull and the comparison operators accept them. nanuq exports std/times.
                        • Casts: cast(Date), cast(DateTime, timeUnit = Milliseconds, timeZone = "Europe/Rome"), cast(Duration) and cast(TimeOfDay).
                        • Constructors: dateRange(start, stop, interval = "1d", closed = ClosedWindow.Both) and datetimeRange(...) return expressions; duration(weeks = ..., days = ..., hours = ..., ..., nanoseconds = ...) takes ints or expressions. Intervals are Polars strings ("1mo") or std/times TimeIntervals (1.months), converted by toPolarsInterval.
                        • Parsing: str.strptime(T, format, strict, exact, cache), str.toDate, str.toDatetime(format, timeUnit, timeZone, ambiguous) and str.toTime, with chrono format codes. readCsv and scanCsv take tryParseDates = false.
                        • The dt namespace (a distinct Expr, like str): year, isoYear, quarter, month, week, weekday, day, ordinalDay, hour, minute, second, millisecond, microsecond, nanosecond, date, time, isLeapYear, daysInMonth, monthStart, monthEnd, timestamp, castTimeUnit, toString/strftime (a format string, or DurationFormat.Iso/Polars for durations), truncate, round, offsetBy, convertTimeZone, replaceTimeZone(tz, ambiguous, nonExistent), combine(time) and totalDays…totalNanoseconds(fractional = false).
                        • Inspection: glimpse and describe handle temporal columns.
                        • Polars features temporal, dtype-date, dtype-datetime, dtype-duration, dtype-time, timezones, offset_by, range, month_start and month_end (already compiled in by the string change) are used.

                        Not in this change: groupByDynamic and rolling windows, dt.weekday names, business-day functions, dt.epoch variants beyond timestamp, upsample.

                        Capabilities

                        New Capabilities
                        • temporal: temporal values, constructors, parsing and the dt namespace.
                        Modified Capabilities
                        • data-types: the four temporal kinds, time units and zones, temporal cast targets and the Nim type mapping.
                        • csv-io: tryParseDates.
                        • native-bridge: NqTimeUnit, NqClosedWindow and NqDtOp join the ordered enums; dtypes cross the ABI as an NqDtypeSpec struct.

                        Differences from Polars

                        Expected differences from Polars' Rust and Python APIs:

                        • Nim value types: Python uses datetime.date, datetime.datetime, datetime.timedelta and datetime.time; Rust uses chrono. Nanuq uses std/times' DateTime and Duration plus its own Date and TimeOfDay.
                        • DateTime values are instants. A DateTime given to series or lit is stored as its UTC instant, and naive (no zone) unless timeZone is given. Values read back are UTC DateTimes, whatever the column's zone. Python keeps naive datetimes as wall-clock time and returns zone-aware ones in the column's zone.
                        • Style insensitivity: Nim cannot tell Datetime from DateTime, so the cast target and the == right-hand side are std/times' DateTime; DataTypeKind.Datetime names the kind. col(DateTime) selects only naive microsecond datetimes (an exact dtype); use a DataType for other units and zones.
                        • Time units reuse std/times' TimeUnit (Milliseconds, not "ms"); other values raise ValueError.
                        • Intervals accept std/times' TimeInterval (1.months + 2.days) next to Polars' strings; mixed signs raise ValueError.
                        • dateRange and datetimeRange return expressions only (Python's eager = true is newDataFrame().select(...)).
                        • Enums for string options: ClosedWindow, Ambiguous (Raise, Earliest, Latest, Null), NonExistent (Null, Raise) and DurationFormat (Iso, Polars) are pure enums; Ambiguous.Null must always be qualified.
                        • dt.toString takes DurationFormat for durations instead of the strings "iso" and "polars"; strftime is an alias, as in Python.
                        • describe shows datetime statistics with Polars' cast to string (2026-07-05 00:00:00.000000) and durations in Polars' format (4m 23s), where Python formats them itself.
                        • Names follow Polars in camelCase: ordinal_day → ordinalDay, convert_time_zone → convertTimeZone, try_parse_dates → tryParseDates.

                        Impact

                        • src/rust/src/lib.rs: NqDtypeSpec replaces the dtype code in casts, selectors and schema overrides; temporal series, literals, ranges, duration, strptime and nq_expr_dt with NqDtOp.
                        • src/nanuq/ffi.nim, src/nanuq.nim: the declarations, Date, TimeOfDay, the temporal DataType fields, casts, constructors, parsing and DtNameSpace.
                        • tests/test_temporal.nim (new); README; BACKLOG "More dtypes" keeps only the remaining dtypes.
                        Spec changescsv-io ~1 · data-types ~3 · native-bridge ~1 · temporal +7

                        csv-io modified ~1

                        MODIFIED
                        CSV read options
                        `readCsv` and `scanCsv` SHALL take these named options with Polars' defaults: - `separator = ','` and `hasHeader = true` - `nullValues` and `schemaOverrides` (`(string, DataType)` pairs) - `skipRows = 0`, `nRows = none(int)` and `columns` (all when empty) - `inferSchemaLength = some(100)`, where `none` scans all rows - `ignoreErrors = false` and `decimalComma = false` - `tryParseDates = false`, which reads ISO dates, datetimes and times as temporal columns `nRows` and `inferSchemaLength` SHALL also accept a plain `int`. ```nim let path = getTempDir() / "survey.csv" writeFile(path, "Polar survey 2026\nexported by hand\nstation;bears;weight\n" & "North;3;410\nSouth;lots;380\nEast;1;355\n") echo readCsv(path, separator = ';', skipRows = 2, nRows = 2, nullValues = ["lots"], schemaOverrides = {"weight": Float64}, columns = ["station", "weight", "bears"]) let stages = getTempDir() / "stages.csv" writeFile(stages, "stage,day,start\n1,2026-07-04,13:10:00\n2,2026-07-05,12:45:00\n") echo readCsv(stages, tryParseDates = true).schema ``` ```text shape: (2, 3) ┌─────────┬────────┬───────┐ │ station ┆ weight ┆ bears │ │ --- ┆ --- ┆ --- │ │ str ┆ f64 ┆ i64 │ ╞═════════╪════════╪═══════╡ │ North ┆ 410.0 ┆ 3 │ │ South ┆ 380.0 ┆ null │ └─────────┴────────┴───────┘ {"stage": Int64, "day": Date, "start": TimeOfDay}TBD ``` Scenario: Semicolons and null words - **WHEN** a file with `;` separators and the value "lots" is read with `separator = ';', nullValues = ["lots"]` - **THEN** the columns are split at `;` and "lots" is null Scenario: Override a dtype - **WHEN** a column of whole numbers is read with `schemaOverrides = {"n": Float64}` - **THEN** `dtype("n") == Float64` Scenario: Preamble and limit - **WHEN** a file with two preamble lines and 10 data rows is read with `skipRows = 2, nRows = 3` - **THEN** the header is the third line and the result has 3 rows Scenario: Columns - **WHEN** a file with columns `a`, `b` and `c` is read with `columns = ["c", "a"]` - **THEN** the result has columns `c` and `a` Scenario: Dates - **WHEN** a column of ISO dates is read with and without `tryParseDates = true` - **THEN** its dtype is `Date` and `String`

                        Unchanged in this spec: Scanning CSV, CSV write options, Reading CSV from a stream, Quoting, encoding and new column names, Comment lines

                        data-types modified ~3

                        MODIFIED
                        DataType values
                        The API SHALL provide a `DataType` value with a `kind` of type `DataTypeKind` (a pure enum, see `api-conventions`) covering Boolean, Int8, Int16, Int32, Int64, UInt8, UInt16, UInt32, UInt64, Float32, Float64, String, Null, Date, Datetime, Duration,Duration Time, Categorical and Enum,Time, plus `DataTypeKind.Other` carrying Polars' name for any other dtype. Datetime and Duration values SHALL carry a `timeUnit` (std/times' `TimeUnit`: `Nanoseconds`, `Microseconds` or `Milliseconds`), and Datetime values a `timeZone` ("" when naive), and Enum values their `categories`.naive). `dtype(df, col)` SHALL return a `DataType`. `dtype == T` with a Nim type SHALL compare with `dataType(T)`, except that `DateTime` and `Duration` SHALL match any time unit and zone. `$` SHALL print a data type as the Nanuq code that builds or names it: the constant (`Int64`), the constructor (`Enum(["low", "high"])`), or for temporal types the Nim type a column casts to (`Date`, `TimeOfDay`, `DateTime(Milliseconds, "Europe/Rome")`, `Duration(Microseconds)`). Table headers, `glimpse` and `toHtml` SHALL keep Polars' short names (`i64`). ```nim let df = newDataFrame(series("a", [1, 2])) echo df.dtype("a") # asPolars' Nanuqshort codename echo df.dtype("a") == Int64 echo df.dtype("a").kind let t = newDataFrame(series("at", [dateTime(2026, mJul, 4, zone = utc())], timeUnit = Milliseconds, timeZone = "Europe/Rome")) echo t.dtype("at"), " ", t.dtype("at").timeZone, " ", t.dtype("at") == DateTime ``` ```text Int64i64 true Int64 DateTime(Milliseconds, "Europe/Rome") Europe/Rome trueTBD ``` Scenario: Column dtype - **WHEN** a DataFrame is built from a Nim `seq[int]` column `a` - **THEN** `df.dtype("a") == Int64` and `$df.dtype("a") == "Int64"`"i64"` Scenario: Unmodelled dtype - **WHEN** a column has a dtype Nanuq does not model - **THEN** its `kind` is `DataTypeKind.Other` and `$` returns Polars' name for it Scenario: Zoned datetime - **WHEN** a Datetime column has unit ms and zone Europe/Rome - **THEN** `$` gives `DateTime(Milliseconds,"datetime[ms, "Europe/Rome")`Europe/Rome]" and it equals `DateTime` Scenario: Enum categories - **WHEN** a column is cast to `Enum(["low", "high"])` - **THEN** `$` of its dtype gives `Enum(["low", "high"])` and `categories` is `@["low", "high"]` Scenario: Tables keep short names - **WHEN** a frame with an Int64 column is printed or turned into HTML - **THEN** the column header shows `i64`
                        MODIFIED
                        Casting
                        The API SHALL cast expressions (`e.cast(target, strict = true)`), all columns of a DataFrame or LazyFrame (`cast(target, strict = true)`), where `target` is a Nim type or a `DataType`, and named columns (`cast({"a": Int32}, strict = true)`) with `DataType` values. Temporal Nim targets (`Date`, `DateTime`, `Duration`, `TimeOfDay`) SHALL take `timeUnit = Microseconds` and, for `DateTime`, `timeZone = ""`. A strict cast SHALL raise `PolarsError` (when the query runs) if a value cannot be converted; a non-strict cast SHALL turn such values into nulls. Casting to a `DataTypeKind.Other` dtype SHALL raise `PolarsError`. ```nim let df = newDataFrame(series("a", [1, 2]), series("s", ["1", "x"])) echo df.cast({"a": Int32}).dtype("a") echo df.select(col("a").cast(float32)).dtype("a") echo df.select(col("s").cast(Int64, strict = false)) echo df.select(col("a").cast(DateTime, timeUnit = Milliseconds, timeZone = "UTC")).dtype("a") ``` ```text Int32i32 Float32f32 shape: (2, 1) ┌──────┐ │ s │ │ --- │ │ i64 │ ╞══════╡ │ 1 │ │ null │ └──────┘ DateTime(Milliseconds, "UTC")TBD ``` Scenario: Narrow an integer column - **WHEN** `df.cast({"a": Int32})` runs on an i64 column - **THEN** `dtype("a") == Int32` and `toList(df, "a", int)` returns the same values Scenario: Nim type as target - **WHEN** `col("a").cast(float32)` is selected from an i64 column - **THEN** the result column has dtype `Float32` Scenario: Strict failure - **WHEN** a string column holding "1" and "x" is cast to `Int64` with `strict = true` - **THEN** `PolarsError` is raised Scenario: Non-strict cast - **WHEN** the same column is cast with `strict = false` - **THEN** the result is 1 and null Scenario: Integers to dates - **WHEN** a column of microseconds `[0, 86_400_000_000]` is cast to `DateTime` and then to `Date` - **THEN** the result is 1970-01-01 and 1970-01-02
                        MODIFIED
                        Nim types map to DataType
                        `dataType(T)` SHALL map `int8` to `int64`, `uint8` to `uint64`, `float32`, `float64`, `bool` and `string` to their dtypes, `int` to `Int64` and `float` to `Float64`. `dataType(T, timeUnit = Microseconds, timeZone = "")` SHALL map `Date`, `DateTime`, std/times' `Duration` and `TimeOfDay` to Date, Datetime, Duration and Time. A Nim enum SHALL map to an Enum of `$` of its values. `seq[T]` SHALL map to a List, `array[N, T]` to an Array and objects and named tuples to a Struct of their fields, at any depth. Other types SHALL not compile. ```nim type Medal = enum Gold, Silver, Bronze echo dataType(int), " ", dataType(float32), " ", dataType(uint8), " ", dataType(string) echo dataType(Date), " ", dataType(DateTime), " ", dataType(Duration, Nanoseconds), " ", dataType(TimeOfDay) echo dataType(Medal), " ", dataType(Medal).categories echo dataType(seq[string]), " ", dataType(array[3, float]), " ", dataType(tuple[x: int, tags: seq[string]]).fields ``` ```text Int64i64 Float32f32 UInt8u8 Stringstr Date DateTime(Microseconds) Duration(Nanoseconds) TimeOfDayTBD Enum(["Gold", "Silver", "Bronze"]) @["Gold", "Silver", "Bronze"] List(String) Array(Float64, 3) @[(name: "x", dtype: Int64), (name: "tags", dtype: List(String))] ``` Scenario: Platform int - **WHEN** `dataType(int)` is evaluated - **THEN** it equals `Int64`, the dtype `series` builds from `seq[int]` Scenario: Unsupported type - **WHEN** `col("a").cast(ref`col("a").cast(seq[int])` int)` is compiled - **THEN** compilation fails Scenario: Unsupported unit - **WHEN** `dataType(DateTime, Seconds)` is evaluated - **THEN** `ValueError` is raised Scenario: Nim enum - **WHEN** `dataType(Medal)` is evaluated for `enum Gold, Silver, Bronze` - **THEN** it equals `Enum(["Gold", "Silver", "Bronze"])` Scenario: Nested Nim types - **WHEN** `dataType(seq[seq[int]])` is evaluated - **THEN** it equals `List(List(Int64))`

                        Unchanged in this spec: DataType constants and predicates, Schemas, Full-range UInt64

                        native-bridge modified ~1

                        MODIFIED
                        Nim declarations mirror the C ABI
                        `src/nanuq/ffi.nim` SHALL declare every exported function with matching signatures, and the enums `NqBinOp`, `NqUnary`, `NqDtype`, `NqDtypeClass`, `NqJoinType`, `NqJoinValidation`, `NqMaintainOrderJoin`, `NqConcat`, `NqUniqueKeepStrategy`, `NqClosedInterval`, `NqQuantileMethod`, `NqFillNullStrategy`, `NqRoundMode`, `NqQuoteStyle`, `NqRankMethod`, `NqErrorKind`, `NqStrOp`, `NqTimeUnit`, `NqClosedWindow`,`NqClosedWindow` `NqDtOp`,and `NqCatOp`,`NqDtOp` `NqParquetCompression` and `NqIpcCompression` SHALL keep the same order as in Rust. `NqDtype` SHALL also keep the order of `DataTypeKind`, and the option enums the order of their Nim API enums. Data types SHALL cross the ABI as an `NqDtypeSpec` struct (code, time unit, time zone, categories) with the same field order on both sides. Scenario: ABI change - **WHEN** a function is added or changed in `rust/src/lib.rs` - **THEN** `src/nanuq/ffi.nim` is updated in the same change

                        Unchanged in this spec: C ABI over Polars with opaque handles, Errors and panics never cross the boundary, Linking the static library, Columns cross in bulk, Library version check, Formatted cells, Polars version matches a py-polars release

                        temporal modified +7

                        ADDED
                        Temporal values

                        The API SHALL provide Date (date(y, m, d)) and TimeOfDay (timeOfDay(h, m, s, ns)), and SHALL accept them and std/times' DateTime and Duration wherever Nim values build columns or literals. toList and df[c, i, T] SHALL read them back, as Option for nulls. DateTime values SHALL be stored and read back as UTC instants. nanuq SHALL export std/times.

                        let df = newDataFrame:
                          rider: ["Seixas", "Pogačar"]
                          born: [date(2006, 9, 24), date(1998, 9, 21)]
                          start: [timeOfDay(13, 10), timeOfDay(13, 12)]
                          gap: [initDuration(minutes = 4, seconds = 23), initDuration()]
                          finish: [dateTime(2026, mJul, 4, 17, 21, zone = utc()), nil]
                        echo df
                        echo df.filter(col.born > date(2000, 1, 1)).toList("rider", string)
                        echo df.toList("born", Date)[0].year, " ", df["finish", 1, Option[DateTime]].isNone
                        TBD
                        Scenario: Round trip
                        • WHEN a column built from [date(2026, 7, 4), nil] is read with toList(df, c, Option[Date])
                        • THEN the result is @[some(date(2026, 7, 4)), none(Date)]
                        Scenario: Out of range
                        • WHEN timeOfDay(24) is called
                        • THEN ValueError is raised
                        Scenario: Wrong reader
                        • WHEN a Date column is read with toList(df, c, DateTime)
                        • THEN InvalidOperationError is raised
                        ADDED
                        Temporal ranges and durations

                        dateRange(start, stop, interval = "1d", closed = ClosedWindow.Both) and datetimeRange(..., timeUnit, timeZone) SHALL return expressions. interval SHALL be a Polars interval string or a TimeInterval, converted by toPolarsInterval, which raises ValueError on mixed signs. duration(weeks, days, hours, ..., nanoseconds) SHALL build a Duration from ints or expressions.

                        let months = newDataFrame().select(dateRange(date(2026, 1, 31), date(2026, 4, 30), 1.months).alias("day"))
                        echo months.toList("day", Date)
                        echo toPolarsInterval(1.years + 2.days)
                        let gaps = newDataFrame:
                          h: [73, 0]
                          m: [56, 4]
                        echo gaps.select(duration(hours = col.h, minutes = col.m, seconds = 26).alias("gap"))
                        TBD
                        Scenario: Calendar steps
                        • WHEN dateRange(date(2026, 1, 31), date(2026, 4, 30), 1.months) is selected
                        • THEN the dates are the last days of January to April
                        Scenario: Half-open range
                        • WHEN dateRange(date(2026, 1, 1), date(2026, 1, 15), "1w", closed = ClosedWindow.Left) is selected
                        • THEN the result has 2 rows
                        Scenario: Mixed signs
                        • WHEN toPolarsInterval(1.days - 2.hours) is called
                        • THEN ValueError is raised
                        ADDED
                        Parsing strings

                        e.str SHALL provide strptime(T, format, strict = true, exact = true, cache = true) for T in Date, DateTime and TimeOfDay, and the shorthands toDate(format), toDatetime(format, timeUnit, timeZone, ambiguous) and toTime(format). Formats SHALL use chrono's codes; an empty format SHALL let Polars infer it. A strict parse SHALL raise PolarsError when a value does not match; a non-strict one SHALL give null. exact = false SHALL allow the format to match part of the string.

                        let df = newDataFrame:
                          born: ["17 July 1993", "24 September 2006", "smudged"]
                        echo df.select(col.born.str.toDate("%d %B %Y", strict = false))
                        TBD
                        Scenario: Strict failure
                        • WHEN str.toDate("%d %B %Y") runs over a value "smudged"
                        • THEN PolarsError is raised
                        Scenario: Zoned datetimes
                        • WHEN str.toDatetime("%Y-%m-%d %H:%M", timeZone = "Australia/Adelaide") is selected
                        • THEN the dtype is datetime[μs, Australia/Adelaide]
                        ADDED
                        Date and time parts

                        e.dt SHALL return a DtNameSpace with year, isoYear, quarter, month, week, weekday (Monday 1 to Sunday 7), day, ordinalDay, hour, minute, second, millisecond, microsecond, nanosecond, date, time, isLeapYear, daysInMonth, monthStart and monthEnd, each returning an expression with Polars' result dtype.

                        let df = newDataFrame:
                          at: [dateTime(2026, mJul, 4, 13, 10, zone = utc()), dateTime(2024, mFeb, 29, zone = utc())]
                        echo df.select(col.at.dt.year.alias("y"), col.at.dt.weekday.alias("wd"),
                                       col.at.dt.ordinalDay.alias("od"), col.at.dt.date.alias("d"),
                                       col.at.dt.time.alias("t"), col.at.dt.isLeapYear.alias("leap"))
                        TBD
                        Scenario: Parts of a datetime
                        • WHEN dt.day and dt.hour run over 2026-07-04 13:10
                        • THEN the results are 4 and 13
                        Scenario: Not temporal
                        • WHEN dt.year runs over a string column
                        • THEN PolarsError is raised when the query runs
                        ADDED
                        Formatting temporal values

                        dt.toString(format) and its alias dt.strftime(format) SHALL format dates, datetimes and times with chrono's codes. dt.toString(DurationFormat.Iso) and dt.toString(DurationFormat.Polars) SHALL format durations as ISO 8601 or Polars' short form.

                        let df = newDataFrame:
                          at: [dateTime(2026, mJul, 4, 13, 10, zone = utc())]
                          gap: [initDuration(minutes = 4, seconds = 23)]
                        echo df.select(col.at.dt.toString("%d %B %Y"), col.gap.dt.toString(DurationFormat.Iso).alias("iso"),
                                       col.gap.dt.toString(DurationFormat.Polars).alias("short"))
                        TBD
                        Scenario: Duration formats
                        • WHEN a 4 min 23 s duration is formatted with DurationFormat.Iso and DurationFormat.Polars
                        • THEN the results are "PT4M23S" and "4m 23s"
                        ADDED
                        Temporal arithmetic

                        Subtracting dates or datetimes SHALL give a Duration. dt SHALL provide truncate(every), round(every), offsetBy(by) (intervals as strings or TimeIntervals), timestamp(timeUnit), castTimeUnit(timeUnit), and on durations totalDays … totalNanoseconds, whole numbers unless fractional = true.

                        let df = newDataFrame:
                          born: [date(2006, 9, 24), date(1998, 9, 21)]
                          race: [date(2026, 3, 21), date(2026, 3, 21)]
                        echo df.select((col.race - col.born).dt.totalDays.alias("days"),
                                       col.born.dt.offsetBy(19.years).alias("turns_19"),
                                       col.race.dt.truncate(1.months).alias("month"))
                        TBD
                        Scenario: Leap day
                        • WHEN 2024-02-29 is offset by 1.years
                        • THEN the result is 2025-02-28
                        Scenario: Fractional totals
                        • WHEN dt.totalDays(fractional = true) runs over 36 hours
                        • THEN the result is 1.5
                        ADDED
                        Time zones

                        dt.replaceTimeZone(timeZone, ambiguous = Ambiguous.Raise, nonExistent = NonExistent.Raise) SHALL attach a zone to wall-clock times (or remove it with ""), dt.convertTimeZone(timeZone) SHALL show the same instants in another zone, and dt.combine(time) SHALL join a date and a time of day into a datetime.

                        let stage = newDataFrame:
                          day: [date(2026, 1, 20)]
                          finish: [timeOfDay(14, 3)]
                        let local = col.day.dt.combine(col.finish).dt.replaceTimeZone("Australia/Adelaide")
                        echo stage.select(local.alias("adelaide"), local.dt.convertTimeZone("Europe/Paris").alias("paris"))
                        TBD
                        Scenario: Same instant
                        • WHEN 14:03 in Adelaide on 2026-01-20 is converted to Europe/Paris
                        • THEN the time is 04:33 and the value read back equals 03:33 UTC
                        Scenario: Unknown zone
                        • WHEN dt.convertTimeZone("Mars/Olympus") runs
                        • THEN PolarsError is raised

                        Unchanged in this spec: Dates from parts, More date parts and time ranges, Business days

                        Design

                        Design

                        Values cross as physical integers

                        Polars stores Date as i32 days, Datetime and Duration as i64 in their time unit, and Time as i64 nanoseconds. Nim values are converted to these integers on the Nim side (toPhysical), sent with the existing integer buffers, and cast to the temporal dtype in Rust (nq_series_new_temporal, nq_expr_lit_temporal). Reading back goes the other way through nq_expr_to_physical. No date logic lives in Rust.

                        Dtype specs

                        A dtype is no longer a single enum code: Datetime carries a unit and a zone, and the categorical change will carry categories. NqDtypeSpec (code, time unit, zone C string, categories pointer and count) crosses the ABI by value wherever a dtype did. Nim keeps the zone strings alive for the call (toSpecs).

                        Date and TimeOfDay

                        Date is distinct int32, the same days count Polars stores, so it round-trips without loss and sorts as an integer. TimeOfDay wraps nanoseconds since midnight. Both convert to and from DateTime (toDateTime, toDate, toTimeOfDay). They are deliberately small: calendar arithmetic goes through DateTime or the dt namespace.

                        Instants, not wall-clock times

                        A std/times DateTime is always an instant with a zone (local or UTC). Nanuq stores its UTC instant. A naive column therefore holds UTC wall-clock times; a zoned column the same instant in that zone. Reading back always gives UTC DateTimes, because std/times cannot represent IANA zones. This keeps the conversion lossless and documented, at the price of differing from Python for naive local times.

                        dt as one entry point

                        As with str, the namespace is a distinct Expr, and Rust has one nq_expr_dt(expr, op, arg expr, string, flag, unit, nonExistent) that switches on NqDtOp, so new functions need no new ABI symbols.

                        Intervals

                        toPolarsInterval(TimeInterval) writes Polars' duration language (1y2mo3d4h). A TimeInterval with mixed signs has no single Polars string, so it raises ValueError.

                        Tasks10 of 10 done

                        1. Bridge 3/3

                        • 1.1Add NqDtypeSpec and use it for casts, selectors and schema overrides
                        • 1.2Add temporal series, literals, nq_expr_to_physical, time unit and zone getters
                        • 1.3Add nq_expr_date_range, nq_expr_duration, nq_expr_strptime and nq_expr_dt with NqDtOp; mirror everything in ffi.nim

                        2. Nim API 5/5

                        • 2.1Add the temporal DataTypeKinds, timeUnit/timeZone, Date, TimeOfDay and the conversions
                        • 2.2Accept temporal values in series, block newDataFrame, lit, toList, [], fillNull and casts
                        • 2.3Add dateRange, datetimeRange, duration, toPolarsInterval and the parsing procs; tryParseDates
                        • 2.4Add DtNameSpace and every function listed in the proposal; temporal glimpse and describe
                        • 2.5Write tests/test_temporal.nim; add it to nanuq.nimble and .gitignore

                        3. Docs and integration 2/2

                        • 3.1README lists temporal types; nimble test and nimble specexamples pass
                        • 3.2Archive the change: update BACKLOG "More dtypes", add CHANGELOG lines
                        Revisions1 revision
                        r1 6fa49c8 2026-10-31 Add temporal types: Date, Datetime, Duration, Time and the dt namespace

                        First version: design.md, proposal.md, specs/csv-io/spec.md, specs/data-types/spec.md, specs/native-bridge/spec.md, specs/temporal/spec.md, tasks.md

                        add-testing-helpers Archived

                        openspec/changes/archive/2026-11-01-add-testing-helpers
                        1. Proposal
                        2. Specs
                        3. Tasks
                        4. Implement 2/2
                        5. Archive
                        Proposal

                        Why

                        Tests of code that builds frames need a good equality check: one that says where two frames differ, compares floats with a tolerance, and can ignore row or column order. Python Polars ships it as polars.testing (assert_frame_equal and friends); the roadmap lists "testing helpers" in 0.6, and Nanuq's own tests and the book's checks would read better with it than with equals plus toList.

                        It is the eighth change of the 0.6 release.

                        What Changes

                        • New module nanuq/testing (no extra dependency) with assertFrameEqual, assertFrameNotEqual, assertSeriesEqual, assertSeriesNotEqual.
                        • Options as in Python: checkRowOrder, checkColumnOrder, checkDtypes, checkNames (Series), checkOrder (Series), checkExact, rtol, atol.
                        • Failures raise AssertionDefect whose message names the first difference (columns, heights, dtypes, or the column, row and both values).

                        Capabilities

                        New Capabilities
                        • testing-helpers: assertions comparing frames and Series.

                        Differences from Polars

                        • Python raises AssertionError; Nanuq raises AssertionDefect, as doAssert does, which std/unittest reports as a failed test.
                        • Python's rel_tol/abs_tol are rtol/atol (the names Python used before 1.0 and NumPy uses); there is no categorical_as_str (compare with checkDtypes = false).
                        • Messages are Nanuq's own wording, not Polars'.

                        Impact

                        • New src/nanuq/testing.nim, new tests/test_testing.nim.
                        Spec changestesting-helpers +2

                        testing-helpers modified +2

                        ADDED
                        Comparing frames in tests

                        assertFrameEqual(left, right, checkRowOrder = true, checkColumnOrder = true, checkDtypes = true, checkExact = false, rtol = 1e-5, atol = 1e-8) in nanuq/testing SHALL return when the frames (or collected LazyFrames) have the same columns, types and rows, with nulls equal to nulls and floats equal within atol + rtol * abs(right) unless checkExact, and raise AssertionDefect naming the first difference otherwise. assertFrameNotEqual SHALL do the opposite.

                        import nanuq/testing
                        let df = newDataFrame(series("bear", @["Ada", "Bo"]), series("kg", @[410.0, 380.5]))
                        assertFrameEqual(df, newDataFrame(series("bear", @["Ada", "Bo"]), series("kg", @[410.0, 380.5000001])))
                        try:
                          assertFrameEqual(df, newDataFrame(series("bear", @["Ada", "Cy"]), series("kg", @[410.0, 380.5])))
                        except AssertionDefect as e:
                          echo e.msg
                        TBD
                        Scenario: Ignoring order
                        • WHEN two frames hold the same rows and columns in another order and both order checks are off
                        • THEN assertFrameEqual returns
                        ADDED
                        Comparing Series in tests

                        assertSeriesEqual(left, right, checkDtypes = true, checkNames = true, checkOrder = true, checkExact = false, rtol = 1e-5, atol = 1e-8) SHALL compare two Series the same way, also checking their names unless checkNames = false; assertSeriesNotEqual SHALL do the opposite.

                        import nanuq/testing
                        let a = series("kg", @[410, 380])
                        assertSeriesEqual(a, series("mass", @[410, 380]), checkNames = false)
                        assertSeriesNotEqual(a, series("kg", @[410, 381]))
                        echo "ok"
                        TBD
                        Scenario: NaN
                        • WHEN both Series hold NaN at the same row
                        • THEN assertSeriesEqual returns
                        Tasks2 of 2 done

                        1. Implementation 2/2

                        • 1.1src/nanuq/testing.nim: the four assertions
                        • 1.2Tests in tests/test_testing.nim; spec examples pass; CHANGELOG
                        Revisions1 revision
                        r1 4ea5dad 2026-11-01 0.6: archive the 9 changes, fill spec example outputs, map_elements benchmark, dev log Designing Nanuq 0.6

                        First version: proposal.md, specs/testing-helpers/spec.md, tasks.md

                        add-top-k-rows-and-date-parts Archived

                        openspec/changes/archive/2026-11-01-add-top-k-rows-and-date-parts
                        1. Proposal
                        2. Specs
                        3. Tasks
                        4. Implement 10/10
                        5. Archive
                        Proposal

                        Why

                        The 0.4 explainer ("Counting El Niños") was drafted in Python Polars first. Its findings list the calls the 0.4 API could not mirror. The most used call in the post, df.top_k(5, by="peak"), returns whole rows, and 0.4 had only the one-column Expr.topK. The post also builds dates from year and month columns (pl.date(year, month, 15)) and prints its tables with pl.Config(float_precision=2).

                        It is the twelfth change of the 0.4 release (#51).

                        What Changes

                        • Frame topK(k, by, reverse) and bottomK(k, by, reverse), eager and lazy.
                        • date(year, month, day) with expression parts gives a Date column.
                        • setFloatPrecision(n), and floatPrecision in setConfig and withConfig.
                        • Specs now state two things that already worked: groupBy keeps first-seen group order, and joinAsof(coalesce = false) keeps the right key.

                        Capabilities

                        New Capabilities

                        (none)

                        Modified Capabilities
                        • value-functions: top k rows.
                        • temporal: dates from parts.
                        • inspection: float precision.
                        • temporal-grouping: coalesce in the as-of join requirement.
                        • dataframe-api: group order.

                        Differences from Polars

                        • Python's top_k does not promise an order; Nanuq returns largest first (bottomK: smallest first), which is what Rust Polars does.
                        • reverse is one bool for all keys; Python also takes a list.
                        • date with three numbers returns a Nim Date value, not an expression (use lit(date(2026, 1, 1)) for a literal column).
                        • Nanuq's groupBy always keeps group order; Python's default (maintain_order=False) does not, and Nanuq has no maintainOrder parameter.
                        • datetime(year, month, day, hour, ...) is not added: datetime would clash with std/times' dateTime (Nim names are style-insensitive). It can come with a better name later.

                        Impact

                        • Rust: nq_lf_top_k, nq_expr_date, nq_set_float_precision, nq_get_float_precision.
                        • src/nanuq.nim: topK/bottomK frame overloads, date expression, float precision in the display config.
                        • Tests in tests/test_values.nim, tests/test_temporal.nim, tests/test_inspection.nim.
                        Spec changesdataframe-api ~1 · inspection ~2 · temporal +1 · temporal-grouping ~1 · value-functions +1

                        dataframe-api modified ~1

                        MODIFIED
                        Expressions and lazy queries
                        The API SHALL provide `col`, `lit`, arithmetic, comparison and boolean operators on `Expr` (lifting Nim literals automatically), the aggregations sum, mean, min, max, count, first, last, nUnique and std, and `alias`. LazyFrame SHALL support select, withColumns, filter, groupBy/agg, sort, limit, explain and collect. `select` and `groupBy` SHALL take expressions or column names (`select("a", "b")`, `groupBy("species")`); `groupBy` SHALL keep the groups in the order their keys first appear (Python's `maintain_order=True`, always on). On a DataFrame, `groupBy`, `groupByDynamic` and `rolling` followed by `agg` SHALL return a DataFrame, as in Python; on a LazyFrame they return a LazyFrame. DataFrame SHALL offer eager shortcuts for select, withColumns, filter and sort. ```nim let query = penguins().lazy .filter(col("body_mass_g").isNotNull) .groupBy(col("species")) .agg(col("body_mass_g").mean.alias("mass"), col("species").count.alias("n")) .sort("mass", descending = true) echo query.collect # nothing runs before collect ``` ```text shape: (3, 3) ┌───────────┬─────────────┬─────┐ │ species ┆ mass ┆ n │ │ --- ┆ --- ┆ --- │ │ str ┆ f64 ┆ u32 │ ╞═══════════╪═════════════╪═════╡ │ Gentoo ┆ 5076.01626 ┆ 123 │ │ Chinstrap ┆ 3733.088235 ┆ 68 │ │ Adelie ┆ 3700.662252 ┆ 151 │ └───────────┴─────────────┴─────┘ ``` Scenario: Eager group by - **WHEN** `df.groupBy("a").agg(col.v.sum)` runs on a DataFrame - **THEN** the result is a DataFrame, with no `collect` needed Scenario: Select by name - **WHEN** `df.select("c", "a")` runs - **THEN** the result has columns c and a, in that order Scenario: Keys by name - **WHEN** `df.groupBy("a", "b")` is followed by `agg` - **THEN** it groups as `df.groupBy(col.a, col.b)` does Scenario: Group order - **WHEN** a frame with keys b, a, b, c is grouped by the key - **THEN** the groups come out as b, a, c Scenario: Lazy group by - **WHEN** a LazyFrame is filtered, grouped, aggregated and sorted - **THEN** nothing runs until `collect`, which returns the resulting DataFrame

                        Unchanged in this spec: Automatic memory management, Building and reading data, Reading columns by type, HTML tables, Block syntax for building a DataFrame, Column shorthand, True division, Errors as PolarsError

                        inspection modified ~2

                        MODIFIED
                        Display config
                        The API SHALL set how tables print with `setTblRows(n)`, `setTblCols(n)`, `setTblWidthChars(n)` and `setFmtStrLengths(n)`, where `-1` means no limit and `none(int)` restores Polars' default; with `setFloatPrecision(n)`, the number of decimal places floats print with (`none(int)` for Polars' default); with `setConfig(tblRows, tblCols, tblWidthChars, fmtStrLengths, floatPrecision)`, where options left out are unchanged; and with `resetConfig()`, which restores every default. The settings SHALL apply to every later `$` of a DataFrame. ```nim let df = newDataFrame(series("n", [1, 2, 3, 4, 5, 6])) setTblRows(4); setFmtStrLengths(10) echo df setConfig(tblRows = 2, tblCols = 5) echo df resetConfig() ``` ```text shape: (6, 1) ┌─────┐ │ n │ │ --- │ │ i64 │ ╞═════╡ │ 1 │ │ 2 │ │ … │ │ 5 │ │ 6 │ └─────┘ shape: (6, 1) ┌─────┐ │ n │ │ --- │ │ i64 │ ╞═════╡ │ 1 │ │ … │ │ 6 │ └─────┘ ``` Scenario: Float precision - **WHEN** `setConfig(floatPrecision = 2)` is called and a frame holding 0.05333 prints - **THEN** the value shows as 0.05 Scenario: No limit - **WHEN** `setTblRows(-1)` is called and a frame of 50 rows is printed - **THEN** all 50 rows are shown Scenario: Reset - **WHEN** `setTblRows(2)` and then `resetConfig()` are called - **THEN** a frame of 10 rows prints all 10 rows again
                        MODIFIED
                        Scoped display config
                        `withConfig(options): body` SHALL apply the named options (`tblRows`, `tblCols`, `tblWidthChars`, `fmtStrLengths`, `floatPrecision`) while `body` runs, and SHALL restore the previous settings afterwards, also when `body` raises. ```nim let df = newDataFrame(series("n", [1, 2, 3, 4, 5, 6])) withConfig(tblRows = 2): echo df echo df.shape, " ", ($df).count('\n') ``` ```text shape: (6, 1) ┌─────┐ │ n │ │ --- │ │ i64 │ ╞═════╡ │ 1 │ │ … │ │ 6 │ └─────┘ (6, 1) 12 ``` Scenario: Restored after an exception - **WHEN** the body of `withConfig(tblRows = 2)` raises - **THEN** the exception propagates and the row limit is back to its previous value

                        Unchanged in this spec: glimpse, describe, Describe prints temporal values as Python, Table formatting options

                        temporal modified +1

                        ADDED
                        Dates from parts

                        date(year, month, day) SHALL build a Date column when at least one part is an expression; each part SHALL be an integer expression or a number, as Polars' date. Invalid dates (month 13, 30 February) SHALL raise when the query runs. With three numbers date SHALL keep returning a Date value.

                        let seasons = newDataFrame:
                          year: [1982, 1997, 2015]
                          month: [12, 11, 11]
                        echo seasons.select(date(col.year, col.month, 15).alias("mid"))
                        echo date(2026, 2, 1)
                        Scenario: Mixed parts
                        • WHEN date(col.year, 1, 1) runs on years 1950 and 1951
                        • THEN the result is the dates 1950-01-01 and 1951-01-01
                        Scenario: Invalid date
                        • WHEN date(col.year, 2, 30) runs
                        • THEN a PolarsError is raised

                        Unchanged in this spec: Temporal values, Temporal ranges and durations, Parsing strings, Date and time parts, Formatting temporal values, Temporal arithmetic, Time zones, More date parts and time ranges, Business days

                        temporal-grouping modified ~1

                        MODIFIED
                        As-of join
                        `joinAsof(other, on, ...)` (or `leftOn` and `rightOn`) SHALL join each left row to one right row by a sorted key: the last one at or before it (`Backward`), the first one at or after it (`Forward`) or the closest (`Nearest`), only within `tolerance` when given and only among rows with equal `by` columns; rows without a match SHALL get nulls. With `coalesce = false` the right key column SHALL be kept (with `suffix` if its name is taken), showing which right row matched. ```nim let events = newDataFrame: day: [date(2026, 1, 15), date(2026, 3, 2)] event: ["flood", "drought"] let oni = newDataFrame: month: [date(2026, 1, 1), date(2026, 2, 1), date(2026, 3, 1)] oni: [1.8, 1.5, 1.1] echo events.joinAsof(oni, leftOn = "day", rightOn = "month") ``` ```text shape: (2, 4) ┌────────────┬─────────┬────────────┬─────┐ │ day ┆ event ┆ month ┆ oni │ │ --- ┆ --- ┆ --- ┆ --- │ │ date ┆ str ┆ date ┆ f64 │ ╞════════════╪═════════╪════════════╪═════╡ │ 2026-01-15 ┆ flood ┆ 2026-01-01 ┆ 1.8 │ │ 2026-03-02 ┆ drought ┆ 2026-03-01 ┆ 1.1 │ └────────────┴─────────┴────────────┴─────┘ ``` Scenario: Tolerance - **WHEN** the nearest earlier right row is 2 days before and `tolerance = 1.days` - **THEN** the left row gets nulls Scenario: Keep the right key - **WHEN** `joinAsof(other, on = "t", coalesce = false)` runs - **THEN** the result has both `t` and `t_right` Scenario: Missing keys - **WHEN** `joinAsof` is called without `on` and without `leftOn` and `rightOn` - **THEN** `ValueError` is raised

                        Unchanged in this spec: Dynamic group-by, Rolling group-by, Group keys by name

                        value-functions modified +1

                        ADDED
                        Top k rows

                        LazyFrame and DataFrame SHALL support topK(k, by, reverse = false) and bottomK(k, by, reverse = false), returning the k whole rows with the largest (topK) or smallest (bottomK) values of by, in that order. by SHALL be a column name, a list of names, an expression or a list of expressions; with several keys the later ones break ties. reverse = true SHALL swap the direction. Nulls SHALL come last and ties SHALL keep their original order.

                        let events = newDataFrame:
                          start: ["1972 MJJ", "1982 AMJ", "1997 AMJ", "2015 MAM", "2023 MJJ"]
                          peak: [2.1, 2.2, 2.4, 2.6, 2.0]
                        echo events.topK(3, by = "peak")
                        echo events.bottomK(1, by = col.peak)
                        Scenario: Reverse
                        • WHEN topK(2, by = "peak", reverse = true) runs
                        • THEN it returns the same rows as bottomK(2, by = "peak")
                        Scenario: k larger than the frame
                        • WHEN topK(10, by = "peak") runs on 5 rows
                        • THEN all 5 rows are returned, largest first

                        Unchanged in this spec: Ordering values, Picking values, Distinct values, Recoding values, Binning, Value counts

                        Tasks10 of 10 done

                        1. Top k rows 3/3

                        • 1.1nq_lf_top_k (Rust LazyFrame::top_k / bottom_k)
                        • 1.2topK/bottomK for LazyFrame and DataFrame, by as names or expressions
                        • 1.3Tests

                        2. Dates from parts 3/3

                        • 2.1nq_expr_date (Rust datetime(DatetimeArgs) cast to Date)
                        • 2.2date(year, month, day) with expression parts
                        • 2.3Tests

                        3. Float precision 3/3

                        • 3.1nq_set_float_precision / nq_get_float_precision
                        • 3.2setFloatPrecision, setConfig(floatPrecision), withConfig, resetConfig
                        • 3.3Tests

                        4. Specs for what already worked 1/1

                        • 4.1groupBy group order, joinAsof(coalesce = false)
                        Revisions1 revision
                        r1 9bcedea 2026-11-01 Frame topK/bottomK, date(year, month, day) expressions, float precision

                        First version: proposal.md, specs/dataframe-api/spec.md, specs/inspection/spec.md, specs/temporal-grouping/spec.md, specs/temporal/spec.md, specs/value-functions/spec.md, tasks.md

                        add-typed-errors Archived

                        openspec/changes/archive/2026-10-31-add-typed-errors
                        1. Proposal
                        2. Specs
                        3. Tasks
                        4. Implement 7/7
                        5. Archive
                        Proposal

                        Why

                        Every failure in Nanuq raises one NanuqError, so a script can't tell a missing column from a strict cast that hit a bad value, and the 0.3 explainer wants exactly that: catch the error a smudged result sheet causes and carry on. Python Polars raises a hierarchy of typed exceptions (ColumnNotFoundError, InvalidOperationError, ...), each matching a Rust PolarsError variant, and Nim picks an except branch by type.

                        This is the third change of the 0.3 release, following the dev log "Designing Nanuq 0.3", section 6: rename NanuqError to PolarsError, add Python's subtypes, raise Nim's own IOError for IO failures, and add nq_last_error_kind to the ABI.

                        What Changes

                        • BREAKING: NanuqError is renamed PolarsError, the base of every Polars error.
                        • Subtypes of PolarsError, named as in Python: ColumnNotFoundError, ComputeError, DuplicateError, InvalidOperationError, NoDataError, OutOfBoundsError, SchemaError, SchemaFieldNotFoundError, ShapeError, StructFieldNotFoundError and SqlError. Each Rust variant raises its subtype; a variant wrapped in context raises the subtype of the error inside.
                        • IO failures raise Nim's IOError (e.g. reading a file that does not exist), not a PolarsError.
                        • Errors Nanuq raises itself in Nim use the closest subtype: reading a column with nulls as a plain type, casting to a dtype Nanuq does not model, describing a frame with no columns and converting an unsupported Datamancer column raise InvalidOperationError.
                        • The C ABI adds nq_last_error_kind(), which tells the kind of the last error (NqErrorKind).

                        Capabilities

                        New Capabilities

                        None.

                        Modified Capabilities
                        • dataframe-api: errors are typed; PolarsError replaces NanuqError in every requirement.
                        • native-bridge: nq_last_error_kind, and NqErrorKind joins the enums kept in the same order.
                        • combining-frames, csv-io, data-types, datamancer-interop, frame-verbs, inspection, missing-values: requirements that raised NanuqError now raise PolarsError (or a named subtype).

                        Differences from Polars

                        Expected differences from Polars' Rust and Python APIs:

                        • One base type, not Rust's enum: Rust has one PolarsError enum with variants; Nanuq, like Python, has a type per variant. Python's base is PolarsError too.
                        • Names: SchemaMismatch is SchemaError and ShapeMismatch is ShapeError, as in Python. Python's two SQL errors (SQLInterfaceError, SQLSyntaxError) are one SqlError, since Nanuq has no SQL yet. StringCacheMismatch and AssertionError raise the base PolarsError (Nanuq has no string cache, and Nim's AssertionDefect is a defect, not an error).
                        • IO: Python raises built-in FileNotFoundError / OSError; Nanuq raises Nim's IOError, which is not a PolarsError.
                        • Panics inside Polars raise the base PolarsError with the panic message; Python raises PanicException, which is not an Exception.
                        • Python's warnings (PolarsWarning and friends) have no counterpart.

                        Impact

                        • src/rust/src/lib.rs: a thread-local error kind next to the message, set when a PolarsError is converted; nq_last_error_kind; NqErrorKind.
                        • src/nanuq/ffi.nim and src/nanuq.nim: the declaration, the error types, raiseLast picking the type.
                        • src/nanuq/datamancer.nim, tests, README and docs: PolarsError instead of NanuqError.
                        Spec changescombining-frames ~3 · csv-io ~1 · data-types ~1 · dataframe-api +1 ~2 −1 · datamancer-interop ~1 · frame-verbs ~3 · inspection ~1 · missing-values ~1 · native-bridge ~2

                        combining-frames modified ~3

                        MODIFIED
                        Joins
                        The API SHALL join two LazyFrames or two DataFrames with `join`, with `how` one of a `JoinType`: `Inner` (default), `Left`, `Right`, `Full`, `Semi`, `Anti` or `Cross`. Keys SHALL be given as `on` (same names on both sides) or `leftOn` and `rightOn`, as column names or expressions. A cross join SHALL take no keys. ```nim let bears = newDataFrame(series("k", [1, 2, 3]), series("bear", ["Nanuq", "Ursa", "Kuma"])) let seen = newDataFrame(series("k", [1, 3]), series("where", ["ice", "shore"])) echo bears.join(seen, on = ["k"], how = Left, maintainOrder = Left) echo bears.join(seen, on = ["k"], how = Anti) ``` ```text shape: (3, 3) ┌─────┬───────┬───────┐ │ k ┆ bear ┆ where │ │ --- ┆ --- ┆ --- │ │ i64 ┆ str ┆ str │ ╞═════╪═══════╪═══════╡ │ 1 ┆ Nanuq ┆ ice │ │ 2 ┆ Ursa ┆ null │ │ 3 ┆ Kuma ┆ shore │ └─────┴───────┴───────┘ shape: (1, 2) ┌─────┬──────┐ │ k ┆ bear │ │ --- ┆ --- │ │ i64 ┆ str │ ╞═════╪══════╡ │ 2 ┆ Ursa │ └─────┴──────┘ ``` Scenario: Left join - **WHEN** a frame with keys 1, 2, 3 is left-joined on `k` to a frame with keys 1, 3 - **THEN** the result has three rows, and the right side's columns are null for key 2 Scenario: Semi and anti - **WHEN** the same frames are semi-joined and anti-joined - **THEN** the semi join keeps the rows with keys 1 and 3, and the anti join keeps the row with key 2, with only the left columns Scenario: Different key names - **WHEN** frames are joined with `leftOn = ["id"]` and `rightOn = ["station_id"]` - **THEN** rows are matched on those columns Scenario: Cross join - **WHEN** a 2-row frame is joined to a 3-row frame with `how = Cross` - **THEN** the result has 6 rows Scenario: Keys missing - **WHEN** `join` is called without keys and a join type other than `Cross` - **THEN** `PolarsError` is raised
                        MODIFIED
                        Join options
                        `join` SHALL accept, with Polars' defaults: `suffix` (`"_right"`) for clashing column names, `validate` (`JoinValidation`: `ManyToMany`, or `ManyToOne`, `OneToMany`, `OneToOne`), `nullsEqual` (false), `coalesce` (`none(bool)` for Polars' per-join-type default) and `maintainOrder` (`MaintainOrderJoin`: `None`, or `Left`, `Right`, `LeftRight`, `RightLeft`). ```nim let a = newDataFrame(series("k", [1, 2]), series("v", [10, 20])) let b = newDataFrame(series("k", [1, 2]), series("v", [100, 200])) echo a.join(b, on = ["k"], suffix = "_b", validate = OneToOne, maintainOrder = Left) ``` ```text shape: (2, 3) ┌─────┬─────┬─────┐ │ k ┆ v ┆ v_b │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ i64 │ ╞═════╪═════╪═════╡ │ 1 ┆ 10 ┆ 100 │ │ 2 ┆ 20 ┆ 200 │ └─────┴─────┴─────┘ ``` Scenario: Suffix - **WHEN** both frames have a non-key column `v` and `suffix = "_b"` - **THEN** the result has columns `v` and `v_b` Scenario: Validation failure - **WHEN** the right frame has a duplicate key and `validate = ManyToOne` - **THEN** `PolarsError` is raised when the query runs Scenario: Null keys - **WHEN** both frames have a null key, joined with `nullsEqual = true` - **THEN** the null keys match each other; with the default they don't Scenario: Keep left order - **WHEN** a left join runs with `maintainOrder = Left` - **THEN** the result rows follow the left frame's order
                        MODIFIED
                        Concatenation
                        The API SHALL concatenate a list of LazyFrames or DataFrames with `concat`, with `how` a `ConcatMethod`: `Vertical` (default, same schema), `VerticalRelaxed` (cast to common supertypes), `Horizontal` (side by side), `Diagonal` (union of columns, missing ones null) or `DiagonalRelaxed`. An empty list SHALL raise `PolarsError`. ```nim let ab = newDataFrame(series("a", [1]), series("b", [2])) let bc = newDataFrame(series("b", [3]), series("c", [4])) echo concat([ab, bc], how = Diagonal) ``` ```text shape: (2, 3) ┌──────┬─────┬──────┐ │ a ┆ b ┆ c │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ i64 │ ╞══════╪═════╪══════╡ │ 1 ┆ 2 ┆ null │ │ null ┆ 3 ┆ 4 │ └──────┴─────┴──────┘ ``` Scenario: Vertical - **WHEN** two frames with the same columns and 2 and 3 rows are concatenated - **THEN** the result has 5 rows in input order Scenario: Vertical with different types - **WHEN** frames whose column `a` is i64 in one and f64 in the other are concatenated - **THEN** `Vertical` raises `PolarsError` and `VerticalRelaxed` returns `a` as f64 Scenario: Diagonal - **WHEN** a frame with columns `a, b` and one with `b, c` are concatenated diagonally - **THEN** the result has columns `a, b, c`, with nulls where a frame had no column Scenario: Horizontal - **WHEN** a frame with column `a` and one with column `b` are concatenated horizontally - **THEN** the result has columns `a` and `b`

                        csv-io modified ~1

                        MODIFIED
                        Scanning CSV
                        The API SHALL provide `scanCsv(path, ...)`, which returns a `LazyFrame` without reading the file until the query runs. `path` SHALL accept a glob that matches several files with the same columns. A glob whose files have different columns SHALL raise `PolarsError` when the query runs. ```nim let dir = getTempDir() / "census" createDir dir writeFile(dir / "week_01.csv", "station,bears\nNorth,3\nSouth,5\n") writeFile(dir / "week_02.csv", "station,bears\nNorth,4\nSouth,2\nEast,1\n") let weeks = scanCsv(dir / "*.csv") # nothing is read yet echo weeks.groupBy(col("station")).agg(col("bears").sum).sort("station").collect ``` ```text shape: (3, 2) ┌─────────┬───────┐ │ station ┆ bears │ │ --- ┆ --- │ │ str ┆ i64 │ ╞═════════╪═══════╡ │ East ┆ 1 │ │ North ┆ 7 │ │ South ┆ 7 │ └─────────┴───────┘ ``` Scenario: A folder of logs - **WHEN** `scanCsv(dir / "*.csv").collect` runs on two files with the same columns and 2 and 3 rows - **THEN** the result has 5 rows

                        Unchanged in this spec: CSV read options, CSV write options, Reading CSV from a stream, Quoting, encoding and new column names, Comment lines

                        data-types modified ~1

                        MODIFIED
                        Casting
                        The API SHALL cast expressions (`e.cast(target, strict = true)`), all columns of a DataFrame or LazyFrame (`cast(target, strict = true)`), where `target` is a Nim type or a `DataType`, and named columns (`cast({"a": Int32}, strict = true)`) with `DataType` values. Temporal Nim targets (`Date`, `DateTime`, `Duration`, `TimeOfDay`) SHALL take `timeUnit = Microseconds` and, for `DateTime`, `timeZone = ""`. A strict cast SHALL raise `PolarsError` (when the query runs) if a value cannot be converted; a non-strict cast SHALL turn such values into nulls. Casting to a `DataTypeKind.Other` dtype SHALL raise `PolarsError`. ```nim let df = newDataFrame(series("a", [1, 2]), series("s", ["1", "x"])) echo df.cast({"a": Int32}).dtype("a") echo df.select(col("a").cast(float32)).dtype("a") echo df.select(col("s").cast(Int64, strict = false)) echo df.select(col("a").cast(DateTime, timeUnit = Milliseconds, timeZone = "UTC")).dtype("a") ``` ```text Int32i32 Float32f32 shape: (2, 1) ┌──────┐ │ s │ │ --- │ │ i64 │ ╞══════╡ │ 1 │ │ null │ └──────┘ DateTime(Milliseconds, "UTC") ``` Scenario: Narrow an integer column - **WHEN** `df.cast({"a": Int32})` runs on an i64 column - **THEN** `dtype("a") == Int32` and `toList(df, "a", int)` returns the same values Scenario: Nim type as target - **WHEN** `col("a").cast(float32)` is selected from an i64 column - **THEN** the result column has dtype `Float32` Scenario: Strict failure - **WHEN** a string column holding "1" and "x" is cast to `Int64` with `strict = true` - **THEN** `PolarsError` is raised Scenario: Non-strict cast - **WHEN** the same column is cast with `strict = false` - **THEN** the result is 1 and null Scenario: Integers to dates - **WHEN** a column of microseconds `[0, 86_400_000_000]` is cast to `DateTime` and then to `Date` - **THEN** the result is 1970-01-01 and 1970-01-02

                        Unchanged in this spec: DataType values, DataType constants and predicates, Schemas, Nim types map to DataType, Full-range UInt64

                        dataframe-api modified +1 ~2 −1

                        REMOVED
                        Errors as NanuqError

                        Reason: Replaced by typed errors under the base PolarsError. Migration: Catch PolarsError (or a subtype such as ColumnNotFoundError) instead of NanuqError.

                        ADDED
                        Errors as PolarsError

                        Any failing FFI call SHALL raise a PolarsError, or Nim's IOError for IO failures, carrying the message from Rust. The type SHALL follow the Rust PolarsError variant: ColumnNotFoundError, ComputeError, DuplicateError, InvalidOperationError, NoDataError, OutOfBoundsError, SchemaError, SchemaFieldNotFoundError, ShapeError, StructFieldNotFoundError and SqlError, all subtypes of PolarsError.

                        let df = newDataFrame(series("a", [1]), series("s", ["x"]))
                        try:
                          discard df.select(col("nope"))
                        except ColumnNotFoundError as e:
                          echo e.msg.splitLines[0]
                        try:
                          discard df.select(col("s").cast(int))
                        except PolarsError as e:
                          echo e.name
                        try:
                          discard readCsv("no/such/file.csv")
                        except IOError:
                          echo "IOError"
                        not found: unable to find column "nope"; valid columns: ["a", "s"]
                        InvalidOperationError
                        IOError
                        Scenario: Bad column
                        • WHEN a query selects a column that does not exist
                        • THEN ColumnNotFoundError is raised with the Polars error message
                        Scenario: Subtypes are PolarsErrors
                        • WHEN a strict cast fails and the code catches PolarsError
                        • THEN the handler runs, with an InvalidOperationError
                        Scenario: Missing file
                        • WHEN readCsv gets a path that does not exist
                        • THEN IOError is raised, and it is not a PolarsError
                        MODIFIED
                        Building and reading data
                        The API SHALL build a DataFrame from Nim arrays of int, float, bool and string (`series`, `newDataFrame`), read and write CSV with a header row, and expose `shape`, `columns`, `dtype`, `head`, `$` (Polars' table format), single cells and whole columns (`toList`). ```nim let df = newDataFrame(series("bear", ["Nanuq", "Ursa"]), series("weight", [410.5, 380.0])) echo df echo df.shape, " ", df.columns, " ", df["bear", 0, string], " ", df.toList("weight", float) ``` ```text shape: (2, 2) ┌───────┬────────┐ │ bear ┆ weight │ │ --- ┆ --- │ │ str ┆ f64 │ ╞═══════╪════════╡ │ Nanuq ┆ 410.5 │ │ Ursa ┆ 380.0 │ └───────┴────────┘ (2, 2) @["bear", "weight"] Nanuq @[410.5, 380.0] ``` Scenario: Columns of different lengths - **WHEN** `newDataFrame` gets series of different lengths - **THEN** `PolarsError` is raised Scenario: No clash with sequtils - **WHEN** a module imports `nanuq` and `std/[os, sequtils]` and calls `toSeq(walkFiles("*.csv"))` - **THEN** it compiles and returns the matching paths
                        MODIFIED
                        Reading columns by type
                        Reading as `float` SHALL accept any integer or float column; as `string`, any column, formatted as Polars does; as `int`, only integer columns; as `bool`, only boolean columns. A dtype that does not match SHALL raise `PolarsError`. ```nim let df = newDataFrame(series("a", [1, 2])) echo df.toList("a", float) # integers widen to float echo df.toList("a", string) # any column formats as text ``` ```text @[1.0, 2.0] @["1", "2"] ``` Scenario: Integers read as floats - **WHEN** an i64 column holding 1, 2 is read with `toList(df, "a", float)` - **THEN** the result is `@[1.0, 2.0]` Scenario: Floats are not truncated to int - **WHEN** an f64 column is read with `toList(df, "a", int)` - **THEN** `PolarsError` is raised Scenario: Bool column - **WHEN** a bool column is read with `toList(df, "d", bool)` - **THEN** the result holds the column's values

                        Unchanged in this spec: Automatic memory management, Expressions and lazy queries, HTML tables, Block syntax for building a DataFrame, Column shorthand, True division

                        datamancer-interop modified ~1

                        MODIFIED
                        From Datamancer
                        `fromDatamancer` SHALL copy every column back in order: `int` to i64, `float` to f64, `bool` to bool, `string` to str, constant columns repeated, and object columns of one value kind plus nulls to that dtype with nulls. Other object columns SHALL raise `PolarsError`. ```nim import nanuq/datamancer let back = penguins().toDatamancer.fromDatamancer echo back.shape, " ", back.nullCount("body_mass_g") ``` ```text (344, 8) 2 ``` Scenario: Round trip - **WHEN** a Nanuq DataFrame is converted with `toDatamancer` and back with `fromDatamancer` - **THEN** it has the same shape, columns, dtypes (for i64, f64, bool, str) and null counts Scenario: Mixed object column - **WHEN** a Datamancer object column holds both an int and a string - **THEN** `fromDatamancer` raises `PolarsError` naming the column

                        Unchanged in this spec: To Datamancer, Nulls to Datamancer, Optional dependency

                        frame-verbs modified ~3

                        MODIFIED
                        Dropping and renaming columns
                        LazyFrame and DataFrame SHALL support `drop(columns, strict = true)`, with one column name or a list of names, and `rename(mapping: openArray[(string, string)], strict = true)`. With `strict = true`, a column that does not exist SHALL raise `PolarsError`. With `strict = false`, it SHALL be ignored. ```nim let df = newDataFrame(series("a", [1]), series("b", [2]), series("c", [3])) echo df.drop("b").columns # one name echo df.drop(["a", "b"]).columns # several echo df.drop("zzz", strict = false).columns echo df.rename({"a": "x"}).columns ``` ```text @["a", "c"] @["c"] @["a", "b", "c"] @["x", "b", "c"] ``` Scenario: Drop - **WHEN** `df.drop("b")` runs on columns `a`, `b`, `c` - **THEN** the columns are `a`, `c`, and `df.drop(["a", "b"])` leaves `c` Scenario: Rename - **WHEN** `df.rename({"a": "x"})` runs on columns `a`, `b` - **THEN** the columns are `x`, `b` Scenario: Strict - **WHEN** `df.drop("zzz")` runs - **THEN** `PolarsError` is raised, and `df.drop("zzz", strict = false)` returns the frame unchanged
                        MODIFIED
                        Sorting by several keys
                        LazyFrame and DataFrame SHALL sort by several column names or expressions with `sort(by, descending: openArray[bool] = [], nullsLast: openArray[bool] = [], maintainOrder = false)`. An empty list SHALL mean false for every key, and one value SHALL apply to every key. Another length SHALL raise `PolarsError`. The one-column `sort(by: string, descending = false, nullsLast = false, maintainOrder = false)` SHALL remain. ```nim let df = newDataFrame(series("g", ["b", "a", "b", "a"]), series("v", [1, 2, 3, 4])) echo df.sort(["g", "v"], descending = [false, true]) ``` ```text shape: (4, 2) ┌─────┬─────┐ │ g ┆ v │ │ --- ┆ --- │ │ str ┆ i64 │ ╞═════╪═════╡ │ a ┆ 4 │ │ a ┆ 2 │ │ b ┆ 3 │ │ b ┆ 1 │ └─────┴─────┘ ``` Scenario: Two keys - **WHEN** a frame is sorted by `["g", "v"]` with `descending = [false, true]` - **THEN** rows are ordered by `g` ascending and, within each `g`, by `v` descending Scenario: Nulls last - **WHEN** a column holding null, 2, 1 is sorted with `nullsLast = true` - **THEN** the order is 1, 2, null Scenario: Length mismatch - **WHEN** a sort by three keys gets `descending = [true, false]` - **THEN** `PolarsError` is raised
                        MODIFIED
                        Sampling rows
                        DataFrame SHALL support `sample(n, withReplacement = false, shuffle = none(bool),false, seed = none(int))` and `sample(fraction, ...)` with the same options. `shuffle` SHALL also accept a plain `bool`: `true` shuffles the rows, `false` keeps their order and `none` gives no order guarantee, as in Polars. Asking for more rows than there are without replacement SHALL raise `PolarsError`. The same seed SHALL give the same rows. `seed` SHALL also accept a plain `int` (`seed = 42`), and `setRandomSeed(seed)` SHALL seed Polars' global generator, used when no seed is passed. ```nim let df = newDataFrame(series("n", [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])) echo df.sample(3, seed = 42) == df.sample(3, seed = 42) # same seed, same rows echo df.sample(fraction = 0.5).shape setRandomSeed(42) let a = df.sample(4) setRandomSeed(42) echo a == df.sample(4) ``` ```text false (5, 1) false ``` Scenario: Seeded sample - **WHEN** `sample(3, seed = some(42))` runs twice on the same 10-row frame - **THEN** both results have 3 rows and are equal Scenario: Global seed - **WHEN** `setRandomSeed(42)` is called before each of two `sample(4)` calls on the same frame - **THEN** both results are equal Scenario: Fraction - **WHEN** `sample(fraction = 0.5)` runs on 10 rows - **THEN** the result has 5 rows Scenario: Too many rows - **WHEN** `sample(11)` runs on 10 rows - **THEN** `PolarsError` is raised

                        Unchanged in this spec: Row windows, Unique rows, Row index, Every n-th row, Frame interpolation, Casting by data type, Several filter predicates, Group order parameter, Frame aggregations, Group-by shortcuts, Iterating over groups, Frame fillNan and select without a frame

                        inspection modified ~1

                        MODIFIED
                        describe
                        `describe(percentiles = [0.25, 0.5, 0.75], interpolation = Nearest)` on DataFrame and LazyFrame SHALL return a DataFrame with a `statistic` column holding `count`, `null_count`, `mean`, `std`, `min`, one row per percentile (labelled as `25%`) and `max`, followed by one column per input column: f64 for numeric and boolean columns, str for the others, and null where a statistic does not apply. ```nim let df = newDataFrame: rider: ["Pogačar", "Seixas", "Van der Poel"] wins: [22, 8, nil] pro: [true, false, true] echo df.describe ``` ```text shape: (9, 4) ┌────────────┬──────────────┬──────────┬──────────┐ │ statistic ┆ rider ┆ wins ┆ pro │ │ --- ┆ --- ┆ --- ┆ --- │ │ str ┆ str ┆ f64 ┆ f64 │ ╞════════════╪══════════════╪══════════╪══════════╡ │ count ┆ 3 ┆ 2.0 ┆ 3.0 │ │ null_count ┆ 0 ┆ 1.0 ┆ 0.0 │ │ mean ┆ null ┆ 15.0 ┆ 0.666667 │ │ std ┆ null ┆ 9.899495 ┆ null │ │ min ┆ Pogačar ┆ 8.0 ┆ 0.0 │ │ 25% ┆ null ┆ 8.0 ┆ null │ │ 50% ┆ null ┆ 22.0 ┆ null │ │ 75% ┆ null ┆ 22.0 ┆ null │ │ max ┆ Van der Poel ┆ 22.0 ┆ 1.0 │ └────────────┴──────────────┴──────────┴──────────┘ ``` Scenario: Custom percentiles - **WHEN** `describe(percentiles = [0.1, 0.9])` runs - **THEN** the statistic column holds `count`, `null_count`, `mean`, `std`, `min`, `10%`, `90%` and `max` Scenario: Statistics that do not apply - **WHEN** a frame with a string and a boolean column is described - **THEN** mean, std and percentiles are null for the string column, and std and percentiles for the boolean one Scenario: No columns - **WHEN** `newDataFrame().describe` runs - **THEN** `PolarsError` is raised

                        Unchanged in this spec: glimpse, Display config, Scoped display config, Describe prints temporal values as Python, Table formatting options

                        missing-values modified ~1

                        MODIFIED
                        Plain reads refuse nulls
                        Reading a column or a cell with a plain type T SHALL raise `InvalidOperationError` if the values read include a null, and the message SHALL name the column. ```nim let df = newDataFrame(series("a", [some(1), none(int)])) try: discard df.toList("a", int) except PolarsError as e: echo e.name ``` ```text InvalidOperationError ``` Scenario: Column with a null read as int - **WHEN** a column with one null is read with `toList(df, "a", int)` - **THEN** `InvalidOperationError` is raised before any value is returned, naming column "a"

                        Unchanged in this spec: Nulls are read as Option, Inspecting nulls, Building columns with nulls, CSV null markers, Null expressions, Dropping rows with nulls, Interpolation, Null literal, Filling nulls in whole frames

                        native-bridge modified ~2

                        MODIFIED
                        Errors and panics never cross the boundary
                        Every FFI function SHALL catch Polars errors and Rust panics, signal failure with a NULL (or false / -1) return, and make the message available through `nq_last_error` and its kind through `nq_last_error_kind`. Scenario: Polars error - **WHEN** an operation fails in Polars (e.g. a missing column) - **THEN** the function returns NULL and `nq_last_error` returns the Polars message Scenario: Rust panic - **WHEN** Polars panics inside an FFI call - **THEN** the panic is caught, the call returns NULL, and no unwinding reaches Nim Scenario: Error kind - **WHEN** an operation fails with a Polars `ColumnNotFound` error, possibly wrapped in context - **THEN** `nq_last_error_kind` returns `ColumnNotFound`
                        MODIFIED
                        Nim declarations mirror the C ABI
                        `src/nanuq/ffi.nim` SHALL declare every exported function with matching signatures, and the enums `NqBinOp`, `NqUnary`, `NqDtype`, `NqDtypeClass`, `NqJoinType`, `NqJoinValidation`, `NqMaintainOrderJoin`, `NqConcat`, `NqUniqueKeepStrategy`, `NqClosedInterval`, `NqQuantileMethod`, `NqFillNullStrategy`, `NqRoundMode`, `NqQuoteStyle`, `NqRankMethod`,`NqRankMethod` `NqErrorKind`,and `NqStrOp`, `NqTimeUnit`, `NqClosedWindow`, `NqDtOp`, `NqCatOp`, `NqParquetCompression` and`NqErrorKind` `NqIpcCompression` SHALL keep the same order as in Rust. `NqDtype` SHALL also keep the order of of `DataTypeKind`, and the option enums the order of their Nim API enums. Data types SHALL cross the ABI as an `NqDtypeSpec` struct (code, time unit, time zone, categories) with the same field order on both sides. Scenario: ABI change - **WHEN** a function is added or changed in `rust/src/lib.rs` - **THEN** `src/nanuq/ffi.nim` is updated in the same change

                        Unchanged in this spec: C ABI over Polars with opaque handles, Linking the static library, Columns cross in bulk, Library version check, Formatted cells, Polars version matches a py-polars release

                        Tasks7 of 7 done

                        1. Bridge 2/2

                        • 1.1Record the kind of the last error next to its message (NqErrorKind), unwrapping context; panics and Nanuq's own errors are Generic
                        • 1.2Export nq_last_error_kind; mirror it and the enum in ffi.nim

                        2. Nim API 3/3

                        • 2.1Rename NanuqError to PolarsError and add the subtypes; raiseLast raises the subtype, or IOError for IO
                        • 2.2Nanuq's own errors raise InvalidOperationError
                        • 2.3Rename everywhere (Datamancer module, tests, README, docs); tests for a missing column, a strict cast, a duplicate column, a missing file and except PolarsError catching subtypes

                        3. Docs and integration 2/2

                        • 3.1nimble test and nimble specexamples pass
                        • 3.2Archive the change and add CHANGELOG lines
                        Revisions1 revision
                        r1 62e73bd 2026-10-31 OpenSpec add-typed-errors: PolarsError hierarchy, IOError for IO

                        First version: proposal.md, specs/combining-frames/spec.md, specs/csv-io/spec.md, specs/data-types/spec.md, specs/dataframe-api/spec.md, specs/datamancer-interop/spec.md, specs/frame-verbs/spec.md, specs/inspection/spec.md, specs/missing-values/spec.md, specs/native-bridge/spec.md, tasks.md

                        add-value-functions Archived

                        openspec/changes/archive/2026-11-01-add-value-functions
                        1. Proposal
                        2. Specs
                        3. Tasks
                        4. Implement 6/6
                        5. Archive
                        Proposal

                        Why

                        A whole family of Polars expressions works on the values of one column as a set or a sequence: sort it, take the top five, find duplicates, recode values, bin numbers into categories, count how often each value occurs. Nanuq 0.3 has them only at frame level (sort, unique, head), so they can't be used inside agg or over, and recoding or binning needs a when chain. The book ports hit top_k, value_counts, is_unique, replace, cut and sort_by across the O'Reilly chapters 8 and 13 and the user guide.

                        It is the fourth change of the 0.4 release.

                        What Changes

                        • Order: Expr.sort(descending, nullsLast), argSort, sortBy(by, descending), reverse.
                        • Picking values: Expr.head(n), tail(n), slice(offset, length), gather(indices), gatherEvery(n, offset), topK(k), bottomK(k), topKBy(by, k, reverse), bottomKBy, indexOf(value), searchSorted(element, side) with a SearchSortedSide pure enum.
                        • Distinct values: Expr.unique(maintainOrder), argUnique, isUnique, isDuplicated, isFirstDistinct, isLastDistinct, uniqueCounts, approxNUnique.
                        • Recoding and binning: replace(old, new) and replace({old: new, ...}), replaceStrict with default, cut(breaks, labels, leftClosed), qcut(quantiles or n, labels, leftClosed, allowDuplicates).
                        • Counting: valueCounts(column, sort, normalize, name) on DataFrame and LazyFrame.

                        Capabilities

                        New Capabilities
                        • value-functions: order, picking, distinct values, recoding, binning and counting.

                        Differences from Polars

                        • valueCounts is a frame method taking the column (Python: Series.value_counts, or Expr.value_counts, which returns a Struct; Struct columns come in 0.5).
                        • replace takes a Nim mapping literal {"a": "x"} (an array of pairs) where Python takes a dict; replaceStrict has no return_dtype (cast the result instead).
                        • cut and qcut have no include_breaks (it returns a Struct). They return an Enum, as in Python Polars 2, which deprecates cut in favour of bin_intervals; Nanuq keeps Rust's name cut.
                        • topKBy takes by before k so that k can keep its default; Python is top_k_by(by, k=5) too, Rust is top_k_by(k, by, reverse).
                        • Expr.head and tail default to 10 values as in Python (frames default to 5).

                        Impact

                        • src/rust/src/lib.rs: NqUnary and NqBinaryFn grow, nq_expr_sort, nq_expr_sort_by, nq_expr_top_k_by, nq_expr_slice, nq_expr_gather_every, nq_expr_replace, nq_expr_cut, nq_lf_value_counts; src/nanuq/ffi.nim, src/nanuq.nim.
                        • New tests/test_values.nim.
                        Spec changesvalue-functions +6

                        value-functions modified +6

                        ADDED
                        Ordering values

                        e.sort(descending, nullsLast) SHALL sort the values of e, e.argSort SHALL return the row indices that sort them, e.sortBy(by, descending) SHALL order e by one or more other columns, and e.reverse SHALL reverse it, so that these work inside agg and over.

                        let df = newDataFrame:
                          basin: ["Pacific", "Pacific", "Atlantic", "Atlantic"]
                          storm: ["Ana", "Bud", "Cleo", "Dan"]
                          wind: [120, 185, 150, 95]
                        echo df.groupBy(col.basin).agg(col.storm.sortBy(col.wind, descending = true).first
                                                       .alias("strongest")).sort("basin").collect
                        TBD
                        Scenario: Sorted column
                        • WHEN col.x.sort(descending = true) is selected on 2, 3, 1
                        • THEN the result is 3, 2, 1
                        ADDED
                        Picking values

                        e.head(n = 10), e.tail(n = 10), e.slice(offset, length), e.gather(indices), e.gatherEvery(n, offset = 0), e.topK(k = 5), e.bottomK(k = 5), e.topKBy(by, k = 5, reverse) and e.bottomKBy(...) SHALL return those values of e; e.indexOf(value) SHALL return the index of the first occurrence of value (or null), and e.searchSorted(element, side) the index at which element would be inserted to keep e sorted.

                        let df = newDataFrame:
                          year: [1982, 1997, 2015, 2023]
                          oni: [2.2, 2.4, 2.6, 2.0]
                        echo df.select(col.year.topKBy(col.oni, k = 2).alias("top2"),
                                       col.oni.topK(2).alias("peak"))
                        TBD
                        Scenario: Gather by position
                        • WHEN col.x.gather([0, 2]) is selected on 10, 20, 30
                        • THEN the result is 10, 30
                        Scenario: Insertion point
                        • WHEN searchSorted(2) runs on 1, 2, 2, 3 with side Left and Right
                        • THEN the results are 1 and 3
                        ADDED
                        Distinct values

                        e.unique(maintainOrder = false) SHALL return the distinct values, isUnique, isDuplicated, isFirstDistinct and isLastDistinct SHALL flag rows by how their value repeats, argUnique SHALL return the index of each value's first occurrence, uniqueCounts the number of occurrences of each distinct value in order of appearance, and approxNUnique an estimate of the number of distinct values.

                        let df = newDataFrame:
                          station: ["Lima", "Quito", "Lima", "Paita"]
                        echo df.withColumns(col.station.isDuplicated.alias("dup"),
                                            col.station.isFirstDistinct.alias("first"))
                        TBD
                        Scenario: Unique in order
                        • WHEN unique(maintainOrder = true) runs on b, a, b, c
                        • THEN the result is b, a, c
                        ADDED
                        Recoding values

                        e.replace(old, new) and e.replace({old: new, ...}) SHALL replace each listed value and keep the others and the data type; e.replaceStrict(...) SHALL require every value to be listed, unless a default is given, and SHALL take the data type of the new values.

                        let df = newDataFrame:
                          phase: ["N", "EN", "LN", "EN"]
                        echo df.withColumns(col.phase.replaceStrict({"EN": "El Niño", "LN": "La Niña"},
                                                                    default = "neutral").alias("name"))
                        TBD
                        Scenario: Value not listed
                        • WHEN replaceStrict({"a": 1}) runs on a column holding "a" and "b"
                        • THEN collecting raises InvalidOperationError
                        Scenario: Unequal lists
                        • WHEN replace([1, 2], [10]) is built
                        • THEN ValueError is raised
                        ADDED
                        Binning

                        e.cut(breaks, labels, leftClosed = false) SHALL put each value in the interval between breaks it falls into, as a Categorical labelled like "(-0.5, 0.5]" or with labels (one more than breaks), and e.qcut(quantiles, ...) SHALL do the same at the quantiles of the values, given as probabilities or as a number of equal groups.

                        let df = newDataFrame:
                          oni: [-1.6, -0.2, 0.3, 0.9, 2.4]
                        echo df.withColumns(col.oni.cut([-0.5, 0.5], labels = ["La Niña", "neutral", "El Niño"])
                                            .alias("phase"))
                        TBD
                        Scenario: Default labels
                        • WHEN cut([0.0]) runs on -1.0 and 1.0
                        • THEN the labels are "(-inf, 0]" and "(0, inf]"
                        ADDED
                        Value counts

                        valueCounts(column, sort = false, normalize = false, name) on a DataFrame or LazyFrame SHALL return each distinct value of column with its number of occurrences in a column count (or its share in proportion with normalize, or the column name), most frequent first with sort.

                        let df = newDataFrame:
                          phase: ["neutral", "El Niño", "neutral", "La Niña", "neutral", "El Niño"]
                        echo df.valueCounts("phase", sort = true)
                        TBD
                        Scenario: Proportions
                        • WHEN valueCounts("x", normalize = true) runs on a, a, b, b
                        • THEN each value has proportion 0.5

                        Unchanged in this spec: Top k rows

                        Tasks6 of 6 done

                        1. Implementation 6/6

                        • 1.1sort, argSort, sortBy, reverse on expressions
                        • 1.2head, tail, slice, gather, gatherEvery, topK, bottomK, topKBy, bottomKBy, indexOf, searchSorted
                        • 1.3Distinct-value functions
                        • 1.4replace, replaceStrict, cut, qcut
                        • 1.5valueCounts on frames
                        • 1.6Tests in tests/test_values.nim; nimble test and nimble specexamples pass; CHANGELOG
                        Revisions1 revision
                        r1 570d956 2026-11-01 Nanuq 0.4, changes 1-7: math, cumulative, rolling, value functions, horizontal, reshaping, time grouping

                        First version: proposal.md, specs/value-functions/spec.md, tasks.md

                        build-lib-with-nightly Archived

                        openspec/changes/archive/2026-10-31-build-lib-with-nightly
                        1. Proposal
                        2. Specs
                        3. Tasks
                        4. Implement 5/5
                        5. Archive
                        Proposal

                        Why

                        Nanuq 0.2 runs the PDS-H benchmark (scale factor 1) about 4x slower than py-polars on the same machine: 13.6 s against 3.07 s on an M3 Pro. The performance investigation (BACKLOG.md, Performance) traced almost all of it to how the library is built, not to the wrapper: py-polars is compiled with nightly Rust and Polars' nightly feature (SIMD and other nightly-only code paths) and uses jemalloc. Measured on the same Mac, best of 3:

                        | Build | PDS-H SF1 | |---|---| | py-polars 2.1 | 3.07 s | | prebuilt lib-v0.2.0 (stable) | 13.6 s | | nightly + polars/nightly | 3.56 s | | nightly + polars/nightly + jemalloc | 3.20 s (1.04x py-polars) |

                        Polars' git version, the performant feature, CSE and the streaming engine made no real difference. This change was requested by Pietro on 2026-10-31 for 0.3.

                        What Changes

                        • Crate features, both off by default so that local builds keep working on stable Rust: nightly = ["polars/nightly"] and jemalloc = ["dep:tikv-jemallocator"] (tikv-jemallocator 0.6, optional), which sets jemalloc as Rust's global allocator.
                        • Release archives (release-lib.yml) are built with a pinned toolchain, nightly-2026-04-01, and --features "nightly jemalloc"; Windows uses nightly only (py-polars uses mimalloc there, and jemalloc does not build for windows-gnu). aarch64 Linux builds set JEMALLOC_SYS_WITH_LG_PAGE=16, as Polars does, so they also run on kernels with 64 KiB pages. No rust-toolchain.toml: stable stays the default.
                        • str.toTitlecase, which Polars only has with its nightly feature: available with the release libraries; a stable local build raises InvalidOperationError.
                        • The release smoke test also runs tests/test_strings.nim with -d:nanuqNightly, which checks that the archive was built with the nightly feature.
                        • Polars stays at 0.55.2.

                        Capabilities

                        Modified Capabilities
                        • binary-distribution: how release archives are built.
                        • strings: str.toTitlecase.

                        Differences from Polars

                        • None in behaviour: this matches how py-polars is built. toTitlecase depends on the library build, which Python users never see.

                        Impact

                        • src/rust/Cargo.toml (features, optional dependency), src/rust/src/lib.rs (global allocator, ToTitlecase), src/nanuq/ffi.nim, src/nanuq.nim.
                        • .github/workflows/release-lib.yml; openspec/config.yaml context ("stable Rust").
                        • jemalloc as Rust's global allocator is safe because every Rust allocation is freed by Rust through the nq_*_free functions; Nim never frees Rust memory itself.
                        Spec changesbinary-distribution +1 · strings +1

                        binary-distribution modified +1

                        ADDED
                        Release build configuration

                        Release archives SHALL be built with a pinned nightly Rust toolchain and the crate features nightly (Polars' nightly feature) and jemalloc (jemalloc as Rust's global allocator), except on Windows, where only nightly is used. Both features SHALL be off by default, so that a local build needs only stable Rust.

                        Scenario: Local build
                        • WHEN a contributor runs nimble buildRust with stable Rust
                        • THEN the library builds without either feature, and everything except str.toTitlecase works
                        Scenario: Release smoke test
                        • WHEN a release archive is smoke-tested
                        • THEN str.toTitlecase works with it

                        Unchanged in this spec: Lib releases, Archives are tested before release, Portable binaries, Committed checksums decide what can be downloaded, Download, verify and cache, CPU variant selection

                        strings modified +1

                        ADDED
                        Title case

                        str.toTitlecase SHALL upper-case the first letter of each word and lower-case the rest, when the native library is built with the nightly feature, as the release libraries are. With a library built without it, it SHALL raise InvalidOperationError when the expression is built.

                        Scenario: Release library
                        • WHEN str.toTitlecase runs over "tour de france" with a release library
                        • THEN the result is "Tour De France"
                        Scenario: Stable build
                        • WHEN str.toTitlecase is called with a library built on stable Rust
                        • THEN InvalidOperationError is raised

                        Unchanged in this spec: The str namespace, Matching, Replacing and stripping, Slicing and padding, Joining strings in an aggregation, Building strings from columns, Splitting and extracting into lists and structs, Many patterns at once, JSON in strings, Escaping and normalizing

                        Tasks5 of 5 done

                        1. Build 3/3

                        • 1.1Add the nightly and jemalloc features and the jemalloc global allocator
                        • 1.2Build the release archives with nightly-2026-04-01 and the features; smoke-test toTitlecase
                        • 1.3Check a local nightly build with both features passes the tests

                        2. API and docs 2/2

                        • 2.1Add str.toTitlecase with a clear error on stable builds
                        • 2.2Update openspec/config.yaml, README, CHANGELOG and BACKLOG (Performance)
                        Revisions1 revision
                        r1 418fa96 2026-11-01 Archive build-lib-with-nightly

                        First version: proposal.md, specs/binary-distribution/spec.md, specs/strings/spec.md, tasks.md

                        one-program-builds Archived

                        openspec/changes/archive/2026-11-02-one-program-builds
                        1. Proposal
                        2. Specs
                        3. Tasks
                        4. Implement 7/7
                        5. Archive

                        From the backlog: Cache rendered dev-log posts in CI

                        Proposal

                        Why

                        CI took about 15 minutes a run, and almost all of it was the same work repeated. Every test file (45), every spec's examples (47) and every dev-log page (16) was compiled into its own binary, and each binary links the static Polars library (~310 MB): about 9 s of GNU ld per binary, on top of compiling Nanuq again each time. On main run #175 the test job took 14 min (tests 6m45s, spec examples 5m56s) and the docs job 4m45s (nimble install 1m26s, rendering 2m57s). Pietro asked (2026-11-02) for a single test runner and a single doc runner, able to run one file or all, and for times that actually go down.

                        What Changes

                        • tests/all.nim runs every tests/test_*.nim in one program. It finds them at compile time, so there is no list to keep. The files that need an optional package (Datamancer, Arraymancer, db_connector) are left out when it is missing. A single file still runs on its own, and unittest filters work.
                        • The spec examples become unittest tests. tests/specsuite.nim reads openspec/specs/*/spec.md at compile time and turns each example into a test named <capability>:<line>. Its output is captured at the file descriptor and compared with the text block. tests/test_specs.nim holds the specs that need no other package. The Arraymancer, Datamancer and SQLite specs get their own files, because their imports clash with the rest (quantile). tools/specexamples.nim keeps --update, and now also builds one program instead of one per spec.
                        • docs/all.nim renders the whole site in one program: the posts in file-name order, then the index, the coverage map and the OpenSpec page. Each page renders when its module is initialised, so the posts do not change, and each still renders on its own. useDevlogPost calls resetConfig(), so one post's display options cannot reach the next.
                        • config.nims links with lld and leaves out the library's debug info (-fuse-ld=lld -Wl,--strip-debug) on Linux when ld.lld is installed. This takes a link from 9.2 s to 0.7 s. -d:nanuqKeepDebugInfo turns it off. Nim's stack traces do not use DWARF.
                        • CI uses the runners, drops the separate spec-examples step, and caches ~/.nimble (test and docs jobs) and the moto venv. nimble test and nimble docs use the runners.

                        Capabilities

                        Modified Capabilities
                        • ci: tests, spec examples and the site each build as one program; fast linking.
                        • spec-examples: the examples run as unittest tests in the test suite.

                        Differences from Polars

                        None: this changes how Nanuq is tested and built, not its API.

                        Impact

                        • New tests/all.nim, tests/specsuite.nim, tests/test_specs*.nim, docs/all.nim.
                        • tools/specexamples.nim (one program, exports its parser), docs/nanuqtheme.nim, config.nims, nanuq.nimble, .github/workflows/ci.yml.
                        • Measured: test job 14m05s → 2m21s and docs job 4m45s → 2m55s on the first PR run, before caching. Locally, on 4 cores with a cold cache: tests 9m32s → 47 s, spec examples 6m00s → 35 s, docs 4m46s → 1m25s with byte-identical HTML.
                        • Editing one test file now recompiles the whole suite (~26 s), not one file (~12 s). When iterating on one file, run it on its own.
                        • Partly covers the backlog entry "Cache rendered dev-log posts in CI". Installs are cached and rendering is one program, but every post is still re-rendered.
                        Spec changesci +1 ~1 · spec-examples ~1

                        ci modified +1 ~1

                        MODIFIED
                        Tests, example and dev log
                        CI SHALL run the test suite, which includes the spec examples, as one program (`tests/all.nim`), and the example, and render the site as one program (`docs/all.nim`): the nimib dev-log posts in `docs/blog`, then the index page `docs/index.nim` and the living pages (the Polars coverage page and the OpenSpec page). On `main`, after these succeed, it SHALL deploy them to GitHub Pages, with the index as the site root. Scenario: Merge to main - **WHEN** a commit lands on `main` and the test and docs jobs pass - **THEN** the dev log and the living pages are deployed to GitHub Pages, and the site root lists the posts Scenario: Stale spec example - **WHEN** a pull request changes behavior that a spec example shows - **THEN** the test job fails until the example's output is updated Scenario: New test file - **WHEN** a pull request adds `tests/test_x.nim` - **THEN** the test job runs it as part of `tests/all.nim`, with no list to update
                        ADDED
                        Fast linking

                        Builds in the repository SHALL link with lld, without debug info, on Linux when ld.lld is installed, unless -d:nanuqKeepDebugInfo is given. CI SHALL make sure lld is installed.

                        Scenario: Linking a test program
                        • WHEN CI links a program against the static Polars library
                        • THEN it uses lld and the link takes about a second, not about nine

                        Unchanged in this spec: Build Rust only when the crate changes, Skip CI for non-code changes, Lib version follows the crate sources

                        spec-examples modified ~1

                        MODIFIED
                        Examples are run
                        Every ```` ```nim ```` block in `openspec/specs/` SHALL be a unittest test of the test suite (`tests/test_specs*.nim`, named `<capability>:<line>`), with `nanuq`, `nanuq/datasets` and `std/[options, os, strutils]` imported, that fails when the example does not compile, fails at run time, or prints something other than its ```` ```text ```` block. Specs that import other packages SHALL be in test files of their own. `nimble specexamples` SHALL check the same examples, and with `--update` write the actual output into the text blocks instead. Change deltas SHALL NOT be run. ```sh nim r tests/test_specs.nim "spec expressions::*" # check one spec nimble specexamples # check every spec nim r tools/specexamples.nim --update expressions # refresh one spec's outputs ``` #### Scenario: Output drifts - **WHEN** a behavior change makes an example print a different table - **THEN** the test suite fails and shows the expected and actual output #### Scenario: Update - **WHEN** it runs with `--update` - **THEN** the text blocks hold the actual output and the run passes #### Scenario: Proposal with future API - **WHEN** an open change's delta has an example using API that does not exist yet - **THEN** the checker ignores it ### Requirement: specview shows examples specview SHALL keep fenced code in a requirement verbatim, never reading a line inside a fence as a heading, and SHALL render ```` ```text ```` blocks as output, set apart from the code. #### Scenario: Nim comment in an example - **WHEN** an example has a line starting with `#` or `##` - **THEN** specview shows it in the code block, and the requirement and its scenarios are unchanged

                        Unchanged in this spec: API requirements have examples

                        Tasks7 of 7 done

                        1. Implementation 7/7

                        • 1.1tests/all.nim: every test file in one program, optional packages detected
                        • 1.2tests/specsuite.nim + tests/test_specs*.nim: spec examples as unittest tests
                        • 1.3tools/specexamples.nim: one program for all specs (own program for specs importing other packages)
                        • 1.4docs/all.nim: the whole site in one program; useDevlogPost resets the display config
                        • 1.5config.nims: lld without debug info when available
                        • 1.6CI and nimble tasks use the runners; cache ~/.nimble and moto
                        • 1.7Measure CI before/after with warm caches (test job 14m05s → 1m16s, docs 4m45s → 1m47s)
                        Revisions1 revision
                        r1 8308247 2026-11-02 Archive one-program-builds: specs ci and spec-examples updated

                        First version: proposal.md, specs/ci/spec.md, specs/spec-examples/spec.md, tasks.md

                        pin-polars-to-py-release Archived

                        openspec/changes/archive/2026-11-01-pin-polars-to-py-release
                        1. Proposal
                        2. Specs
                        3. Tasks
                        4. Implement 3/3
                        5. Archive
                        Proposal

                        Why

                        Nanuq pinned the newest Polars crate on crates.io (0.55.2). The Rust crates are released by hand every few months, and 0.55.2 matches py-polars 1.43, while the book and the explainers compare against py-polars 2.1.0, about 940 commits later. The 0.5 and 0.6 ports kept finding the drift: SQL table functions with named options fail, hash and sample give other values, SQL COUNT(*) has another type, Decimal mod is missing. The research thread "Understand how Polars and py-polars versions align" (/mnt/project-files/polars-versions/report.md) recommends pinning the git tag of the py-polars release instead. Pietro asked for it in the 0.6 release (2026-11-01).

                        It is the twelfth change of the 0.6 release.

                        What Changes

                        • src/rust/Cargo.toml: polars, polars-core, polars-plan, polars-utils and polars-arrow come from git = "https://github.com/pola-rs/polars", tag = "py-2.1.0" (commit 7f902bd), with the workspace's [patch.crates-io] entries copied (a git dependency does not inherit them).
                        • Release builds (release-lib.yml) use the tag's toolchain, nightly-2026-09-01.
                        • The wrapper adapts to the Polars API changes between 0.55 and py-2.1.0.
                        • Breaking, as in Polars 2.0: profile and cat.getCategories are gone (both are compile-time errors that say what to use instead); hash(seed) uses one seed.
                        • Behavior that follows Polars 2.0: CSV read without a header names its columns column_0, column_1, ... (was column_1, ...); topK/bottomK on expressions and series no longer happen to come out sorted (as documented); a left join without maintainOrder no longer keeps the left order (the join example now passes maintainOrder = Left); unpivot emits rows in row-major order.
                        • BACKLOG "Track the Rust Polars that py-polars ships" is done.

                        Capabilities

                        Modified Capabilities
                        • native-bridge: which Polars the crate builds on.
                        • streaming: profile removed.
                        • categoricals: cat.getCategories removed.

                        Differences from Polars

                        • None added: the point is to remove the version drift. Nanuq now matches py-polars 2.1.0 (same commit); the book and explainers keep py-polars 2.1.0 as their oracle.

                        Impact

                        • src/rust/Cargo.toml, Cargo.lock, src/rust/src/lib.rs (API updates), .github/workflows/release-lib.yml; spec example outputs that changed with Polars.
                        • A cold build fetches the Polars repository by git (CI caches target/ and the cargo home as before).
                        Spec changescategoricals ~1 · native-bridge +1 · streaming −1

                        categoricals modified ~1

                        MODIFIED
                        The cat namespace
                        `e.cat` SHALL give access to `lenBytes`, `lenChars`, `startsWith(prefix)`, `endsWith(suffix)` and `slice(offset, length)` on Categorical and Enum columns. `e.toPhysical` SHALL give the category indices. `getCategories`, removed in Polars 2.0, SHALL be a compile-time error pointing to `unique()` and the dtype's `categories`. ```nim type Medal = enum Gold, Silver, Bronze let df = newDataFrame: medal: [Silver, Gold, Silver] echo df.select(col.medal.cat.lenChars) echo df.select(col.medal.toPhysical).toList("medal", int) echo df.dtype("medal").categories ``` ```text shape: (3, 1) ┌───────┐ │ medal │ │ --- │ │ u32 │ ╞═══════╡ │ 6 │ │ 4 │ │ 6 │ └───────┘ @[1, 0, 1] @["Gold", "Silver", "Bronze"]TBD ``` Scenario: All categories - **WHEN** the categories of an Enum column holding only Silver and Gold are needed - **THEN** `dtype(df, c).categories` gives Gold, Silver and Bronze

                        Unchanged in this spec: Nim enums as Enum columns, Run-time Enum and Categorical

                        native-bridge modified +1

                        ADDED
                        Polars version matches a py-polars release

                        The nanuq_ffi crate SHALL depend on Polars by the git tag of a py-polars release (py-X.Y.Z), the same version the Nanuq Book and the explainers use as their Python oracle, with the [patch.crates-io] entries of Polars' workspace at that tag; release builds SHALL use that tag's Rust toolchain. Moving to a new py-polars release SHALL move the tag, the patches, the toolchain and the Python oracle together.

                        Scenario: Same results as Python
                        • WHEN a book chapter runs the same query in Nanuq and in the pinned py-polars
                        • THEN the outputs agree, including SQL table functions and seeded hash/sample

                        Unchanged in this spec: C ABI over Polars with opaque handles, Errors and panics never cross the boundary, Nim declarations mirror the C ABI, Linking the static library, Columns cross in bulk, Library version check, Formatted cells

                        streaming modified −1

                        REMOVED
                        Profiling

                        Reason: Polars 2.0 removed LazyFrame.profile (its timings were misleading under the streaming engine), and the py-2.1.0 crates no longer have it. Migration: use explain to see the plan, and time collect for the run; calling profile is a compile-time error with this message.

                        Unchanged in this spec: Choosing the engine, Sinks, Partitioned sinks

                        Tasks3 of 3 done

                        1. Implementation 3/3

                        • 1.1Cargo.toml git tag py-2.1.0 + [patch.crates-io]; release toolchain nightly-2026-09-01
                        • 1.2Adapt lib.rs to the API changes; nimble test and nimble specexamples pass
                        • 1.3BACKLOG item removed, CHANGELOG, known-limitations text updated
                        Revisions1 revision
                        r1 da2c150 2026-11-01 Pin Polars to the py-2.1.0 git tag

                        First version: proposal.md, specs/categoricals/spec.md, specs/native-bridge/spec.md, specs/streaming/spec.md, tasks.md

                        refine-book-needs-0-6 Archived

                        openspec/changes/archive/2026-11-01-refine-book-needs-0-6
                        1. Proposal
                        2. Specs
                        3. Tasks
                        4. Implement 3/3
                        5. Archive
                        Proposal

                        Why

                        The book ports against the 0.6 branch (round 3) found two mismatches with Python: readExcel(skipRows = 1) skipped rows before the header, while py-polars' default engine (fastexcel) skips them after it (O'Reilly's top2000 workbook has an empty row under its header); and rolling(..., groupBy = "store") did not compile.

                        It is the eleventh change of the 0.6 release.

                        What Changes

                        • readExcel and readExcelSheets: skipRows skips rows after the header row; new headerRow (from 0) says which row holds the names. Without a header, skipRows still skips from the top. Breaking only against the unreleased 0.6 branch.
                        • rolling and groupByDynamic: groupBy takes names or expressions (GroupKeys).

                        Capabilities

                        Modified Capabilities
                        • excel-io: Reading Excel (header row and skipped rows).
                        • temporal-grouping: group keys by name.

                        Differences from Polars

                        • Python passes these as read_options={"header_row": ..., "skip_rows": ...}; Nanuq has them as parameters, headerRow and skipRows.

                        Impact

                        • src/rust/src/lib.rs (nq_read_excel gains header_row), src/nanuq/ffi.nim, src/nanuq.nim; tests in tests/test_bookneeds6.nim.
                        Spec changesexcel-io ~1 · temporal-grouping +1

                        excel-io modified ~1

                        MODIFIED
                        Reading Excel
                        `readExcel(path, sheetName = "", sheetId = 1, hasHeader = true, headerRow = 0, skipRows = 0, columns = [], schemaOverrides = [])` SHALL read one sheet (by name, else by position from 1) of an .xlsx, .xlsm, .xlsb, .xls or .ods file. Row `headerRow` SHALL hold the column names, and `skipRows` rows SHALL be skipped after it (from the top when `hasHeader = false`), as Python's default engine (fastexcel) does. Column types SHALL be inferred from the cells: Boolean, Int64 for whole numbers, Float64, Date for dates at midnight, Datetime[ms], else String; `schemaOverrides` SHALL cast columns and `columns` keep only those. `readExcelSheets(path)` SHALL read every sheet into a table by sheet name. ```nim let path = getTempDir() / "bears.xlsx" newDataFrame(series("bear", @["Ada", "Bo"]), series("kg", @[410, 380]), series("seen", @[date(2024, 3, 1), date(2024, 3, 9)])).writeExcel(path, worksheet = "census") echo readExcel(path) echo readExcel(path, sheetName = "census", skipRows = 1, hasHeader = false) echo readExcel(path, skipRows = 1) echo readExcelSheets(path).len ``` ```text shape: (2, 3) ┌──────┬─────┬────────────┐ │ bear ┆ kg ┆ seen │ │ --- ┆ --- ┆ --- │ │ str ┆ i64 ┆ date │ ╞══════╪═════╪════════════╡ │ Ada ┆ 410 ┆ 2024-03-01 │ │ Bo ┆ 380 ┆ 2024-03-09 │ └──────┴─────┴────────────┘ shape: (2, 3) ┌──────────┬──────────┬────────────┐ │ column_1 ┆ column_2 ┆ column_3 │ │ --- ┆ --- ┆ --- │ │ str ┆ i64 ┆ date │ ╞══════════╪══════════╪════════════╡ │ Ada ┆ 410 ┆ 2024-03-01 │ │ Bo ┆ 380 ┆ 2024-03-09 │ └──────────┴──────────┴────────────┘ shape: (1, 3) ┌──────┬─────┬────────────┐ │ bear ┆ kg ┆ seen │ │ --- ┆ --- ┆ --- │ │ str ┆ i64 ┆ date │ ╞══════╪═════╪════════════╡ │ Bo ┆ 380 ┆ 2024-03-09 │ └──────┴─────┴────────────┘ 1TBD ``` Scenario: Missing sheet - **WHEN** `readExcel(path, sheetName = "nope")` is called - **THEN** `IOError` is raised Scenario: Round trip - **WHEN** a frame of strings, integers, floats, booleans and dates is written and read back - **THEN** the result equals the frame

                        Unchanged in this spec: Writing Excel, Reading OpenDocument

                        temporal-grouping modified +1

                        ADDED
                        Group keys by name

                        The groupBy parameter of rolling and groupByDynamic SHALL take a column name, several names, an expression or several expressions (groupBy = "store", ["store", "aisle"], [col("store")]).

                        let df = newDataFrame(series("day", @[1, 2, 3, 1, 2]), series("store", @["a", "a", "a", "b", "b"]),
                                              series("sales", @[1, 2, 3, 10, 20]))
                        echo df.rolling("day", "2i", groupBy = "store").agg(col("sales").sum)
                        TBD
                        Scenario: Expressions still work
                        • WHEN groupBy = [col("store")] is passed
                        • THEN the result is the same as with groupBy = "store"

                        Unchanged in this spec: Dynamic group-by, Rolling group-by, As-of join

                        Tasks3 of 3 done

                        1. Implementation 3/3

                        • 1.1readExcel header row and skipped rows as fastexcel; headerRow
                        • 1.2GroupKeys for groupBy of rolling and groupByDynamic
                        • 1.3Tests; nimble test and nimble specexamples pass; CHANGELOG
                        Revisions1 revision
                        r1 fdee4e0 2026-11-01 0.6: explainer needs (bin slicing, str.toInteger, full-range UInt64, CSV quoteChar/encoding/newColumns), book round 3 (readExcel headerRow/skipRows as fastexcel, GroupKeys), BACKLOG lean builds

                        First version: proposal.md, specs/excel-io/spec.md, specs/temporal-grouping/spec.md, tasks.md

                        ship-prebuilt-binaries Archived

                        created 2026-10-27 · openspec/changes/archive/2026-10-28-ship-prebuilt-binaries
                        1. Proposal
                        2. Specs
                        3. Design
                        4. Tasks
                        5. Implement 11/11
                        6. Archive
                        Proposal

                        Why

                        The first compile of a program that imports Nanuq builds Polars from source with cargo, which takes about ten minutes and needs a Rust toolchain. Before tagging 0.1, users should be able to nimble install nanuq and compile in seconds, on the common platforms, without Rust.

                        There is a second problem. nimble install copies only srcDir (src/) into the package directory, so an installed Nanuq has no rust/ crate and can't build the library at all (checked with nimble 0.18.2). Today Nanuq only works from a git checkout.

                        This takes up the BACKLOG.md entries "Prebuilt binaries for users" and "nimble install support" (Distribution). The research behind it is in the dev-log post "Shipping the Rust half" (docs/blog/shipping_rust_binaries.nim).

                        What Changes

                        • Release workflow. Pushing a lib-v<version> tag builds libnanuq_ffi.a for x86_64-unknown-linux-gnu, aarch64-unknown-linux-gnu, aarch64-apple-darwin and x86_64-pc-windows-gnu. Each x86_64 target also gets a legacy-cpu build. The archives and their SHA-256 sums are attached to a GitHub Release, and a PR commits the sums to the repository. Lib releases are tagged by hand.
                        • Compile-time download. When no library is available locally, importing nanuq downloads the archive for the target platform once into a per-user cache, verifies its checksum and links it. This is the default. A cargo build remains the fallback for any platform or version without a prebuilt library.
                        • CPU variants, as Explorer does them. On Linux x86_64 the CPU is checked at compile time, and the legacy build is picked if it lacks AVX2/FMA-era features. -d:nanuqLegacyCpu forces the legacy build everywhere.
                        • Lib versioning. The Rust library has its own version (rust/Cargo.toml), separate from the Nim package version. A version ending in -dev never downloads. CI fails if the Rust sources differ from the last released lib while the version still claims to be that release.
                        • Version check at startup. The library reports its version, and Nanuq refuses to run with a library that doesn't match the version it was compiled for.
                        • nimble install works. The Rust crate moves from rust/ to src/rust/ so that it ships with the installed package, and the source fallback works there too.
                        • Policy switch. -d:nanuqLib=auto|prebuilt|source picks where the library comes from. -d:nanuqNoCargo stays as an alias for prebuilt. -d:nanuqLibDir is unchanged.
                        • The README gets an install section.

                        Capabilities

                        New Capabilities
                        • binary-distribution: how prebuilt libraries are built, versioned, published, chosen for a platform and CPU, downloaded, verified and cached.
                        Modified Capabilities
                        • native-bridge: "Linking the static library" changes. The library can now come from the download cache, the policy define is new, the crate lives in src/rust/, and the library version is checked at runtime.
                        • ci: "Build Rust only when rust/ changes" moves to the new path, and there is a new check that lib versions are bumped when the Rust sources change.

                        Differences from Polars

                        The Nim API doesn't change. The differences are in how the native code reaches users:

                        • No wheels. Python Polars ships prebuilt wheels through PyPI at install time. Nanuq downloads its prebuilt library from GitHub Releases at compile time, the way Elixir's Explorer (rustler_precompiled) and r-polars do. The Rust crate polars is always built from source by cargo.
                        • CPU variants are picked automatically. Python publishes a separate package for old CPUs (polars-lts-cpu, now polars[rtcompat]) that users have to choose themselves. Nanuq picks the legacy build on Linux by checking the CPU, and otherwise takes a define.
                        • Fewer platforms. Python wheels cover more targets (Intel macOS, musl, Windows MSVC and arm64). Nanuq starts with four, and other platforms build from source.
                        • Windows uses MinGW. The Windows library targets x86_64-pc-windows-gnu to link with Nim's default C compiler. Python wheels use MSVC.

                        Impact

                        • rust/ moves to src/rust/. This touches ffi.nim, nanuq.nimble tasks, CI cache keys and paths, .gitignore, the OpenSpec config context and the docs that mention rust/.
                        • rust/src/lib.rs gains nq_version(), declared in ffi.nim. This rebuilds the library once in CI.
                        • New .github/workflows/release-lib.yml and a committed sums file under src/nanuq/.
                        • src/nanuq/ffi.nim: the source order, download, checksum, cache and CPU detection, all at compile time. The tools needed at compile time are curl and tar (present on Windows 10+, macOS and mainstream Linux) and the platform's SHA-256 tool.
                        • Contributors working from a git checkout with a built target/ see no change.
                        Spec changesbinary-distribution +6 · ci +1 ~1 · native-bridge +1 ~1

                        binary-distribution modified +6

                        Purpose: How users get a prebuilt libnanuq_ffi instead of compiling Polars: how libraries are built, versioned and published, and how a compile picks, downloads, verifies and caches the right one.

                        ADDED
                        Lib releases

                        Pushing a tag lib-v<version>, where <version> equals the version in the crate's Cargo.toml, SHALL publish a GitHub Release with one archive libnanuq_ffi-<version>-<target>.tar.gz per supported target, and a file of SHA-256 sums for all archives. The supported targets SHALL be x86_64-unknown-linux-gnu, x86_64-unknown-linux-gnu-legacy-cpu, aarch64-unknown-linux-gnu, aarch64-apple-darwin, x86_64-pc-windows-gnu and x86_64-pc-windows-gnu-legacy-cpu.

                        Scenario: Tag pushed
                        • WHEN a maintainer pushes lib-v0.1.0 and Cargo.toml says 0.1.0
                        • THEN a release lib-v0.1.0 appears with six archives and a sums file
                        • AND a pull request is opened that commits those sums to the repository
                        Scenario: Released from the Actions tab
                        • WHEN a maintainer runs the release workflow by hand on main with "publish"
                        • ticked, and no lib-v<version> tag exists for the Cargo.toml version
                        • THEN the same release and pull request are made, and the tag is created on the
                        • commit that was built
                        Scenario: Tag does not match the crate
                        • WHEN the tag's version differs from Cargo.toml
                        • THEN the workflow fails without publishing anything
                        ADDED
                        Archives are tested before release

                        Each archive SHALL be smoke-tested, by compiling and running a Nanuq test against it on its platform, before the release is published.

                        Scenario: Broken archive
                        • WHEN the smoke test fails for one target
                        • THEN no release is published for that tag
                        ADDED
                        Portable binaries

                        Linux libraries SHALL link against glibc 2.28 or older symbols, macOS libraries SHALL target macOS 11 or later, and the modern x86_64 builds SHALL require at most the x86-64-v3 instruction set. Legacy-cpu builds SHALL require only baseline x86-64.

                        Scenario: Older Linux distribution
                        • WHEN a program is linked with the Linux library on a system with glibc 2.28
                        • THEN it links and runs
                        ADDED
                        Committed checksums decide what can be downloaded

                        The package SHALL contain the lib version it expects and the SHA-256 of every archive for that version. A compile SHALL download only an archive listed there, and SHALL never download when the lib version ends in -dev.

                        Scenario: Development version
                        • WHEN the crate version is 0.2.0-dev
                        • THEN no download is attempted and the library is built from source
                        Scenario: Platform without a prebuilt library
                        • WHEN compiling for a target not listed in the sums (e.g. riscv64gc-unknown-linux-gnu)
                        • THEN no download is attempted and the library is built from source, with a hint
                        • saying why
                        ADDED
                        Download, verify and cache

                        When a prebuilt library is needed, the compile SHALL look in a per-user cache directory keyed by lib version and target, and otherwise download the archive, verify its SHA-256 against the committed sum, and unpack it into the cache. Every source the compile uses SHALL be reported with a compiler hint. A checksum mismatch SHALL stop the compile with an error and SHALL NOT fall back to building from source.

                        Scenario: First compile
                        • WHEN a program importing nanuq is compiled on Linux x86_64 with an empty cache
                        • and no local build
                        • THEN the archive is downloaded once, verified, cached and linked, and no cargo
                        • build runs
                        Scenario: Second project
                        • WHEN another project on the same machine imports the same Nanuq version
                        • THEN the cached library is linked without a download
                        Scenario: Tampered archive
                        • WHEN the downloaded archive's SHA-256 differs from the committed sum
                        • THEN compilation fails with an error naming the archive, the expected sum and the
                        • actual sum
                        Scenario: Offline
                        • WHEN the download fails (no network) and the lib policy is auto
                        • THEN the library is built from source, with a hint saying the download failed
                        ADDED
                        CPU variant selection

                        On x86_64 Linux, when the compile target is the host, the compile SHALL pick the legacy-cpu library if the host CPU lacks any feature the modern build needs. With -d:nanuqLegacyCpu the legacy-cpu library SHALL be picked on every x86_64 target. Otherwise the modern build SHALL be used.

                        Scenario: Old Linux CPU
                        • WHEN compiling on an x86_64 Linux host without AVX2
                        • THEN the legacy-cpu archive is used
                        Scenario: Forced legacy
                        • WHEN compiling for Windows x86_64 with -d:nanuqLegacyCpu
                        • THEN the x86_64-pc-windows-gnu-legacy-cpu archive is used

                        Unchanged in this spec: Release build configuration

                        ci modified +1 ~1

                        MODIFIED
                        Build Rust only when the crate changes
                        CI SHALL build `libnanuq_ffi.a` in a single job whose cache key is a hash of the crate sources in `src/rust/`, and SHALL share the library with the other jobs, which compile with `-d:nanuqNoCargo`. Scenario: Change that does not touch rust/ - **WHEN** a push changes only Nim code or docs - **THEN** the library comes from cache and no Rust toolchain or cargo build runs Scenario: Change to rust/ - **WHEN** a push changes files in `src/rust/` - **THEN** the library is rebuilt, reusing cached compiled dependencies
                        ADDED
                        Lib version follows the crate sources

                        CI SHALL fail when the crate sources differ from those at the tag lib-v<version> for the version in Cargo.toml, unless that version ends in -dev.

                        Scenario: Rust change without a version bump
                        • WHEN a pull request changes src/rust/src/lib.rs and Cargo.toml still says
                        • 0.1.0, which has a lib-v0.1.0 tag
                        • THEN CI fails and says to set the version to the next -dev version

                        Unchanged in this spec: Skip CI for non-code changes, Tests, example and dev log, Fast linking

                        native-bridge modified +1 ~1

                        MODIFIED
                        Linking the static library
                        Importing `nanuq` SHALL link `libnanuq_ffi.a` from the first of these sources that has it: the directory given with `-d:nanuqLibDir`, the local cargo output of the crate in `src/rust/`, the prebuilt library (see `binary-distribution`), and finally a cargo build of `src/rust/` run at compile time. `-d:nanuqLib=auto` (the default) allows all sources. `-d:nanuqLib=prebuilt` (or `-d:nanuqNoCargo`) never runs cargo. `-d:nanuqLib=source` never downloads. The crate SHALL ship inside the installed package, so the cargo fallback also works after `nimble install`. Scenario: Library missing, cargo allowed - **WHEN** no local library exists, no prebuilt library is available, and the policy is `auto` or `source` - **THEN** compilation runs `cargo build --release` for `src/rust/` and links the result Scenario: Library missing, cargo disabled - **WHEN** no local or prebuilt library is available and the policy is `prebuilt` - **THEN** compilation fails with an error naming the expected library path and how to get one Scenario: Installed with nimble - **WHEN** a user runs `nimble install nanuq` on a platform without a prebuilt library and has cargo - **THEN** compiling a program that imports `nanuq` builds the library from the installed package's sources and links it
                        ADDED
                        Library version check

                        The library SHALL report its version through the C ABI. At startup, Nanuq SHALL compare it with the lib version it was compiled for and stop with an error naming both versions if they differ.

                        Scenario: Stale library
                        • WHEN -d:nanuqLibDir points at a library built from an older crate version
                        • THEN the program stops at startup with an error naming both versions

                        Unchanged in this spec: C ABI over Polars with opaque handles, Errors and panics never cross the boundary, Nim declarations mirror the C ABI, Columns cross in bulk, Formatted cells, Polars version matches a py-polars release

                        Design

                        Design

                        Context

                        src/nanuq/ffi.nim finds libnanuq_ffi.a at compile time: -d:nanuqLibDir, else rust/target/release, else it runs cargo build through gorgeEx. CI already builds the library once per change of the crate and passes it to the other jobs.

                        nimble install copies only srcDir, and installDirs is resolved inside srcDir, so there is no way to ship a top-level rust/ with the package (both checked with nimble 0.18.2). Atlas and nimby clone the whole repository but don't run nimble hooks.

                        The research and the comparison with other ecosystems are in the dev-log post docs/blog/shipping_rust_binaries.nim. The requirements are in specs/binary-distribution, specs/native-bridge and specs/ci.

                        Goals / Non-Goals

                        Goals:

                        • A user on one of the four platforms compiles a first Nanuq program in seconds, without Rust, whether Nanuq came from nimble, Atlas, nimby or a git clone.
                        • Contributors who build the crate locally see no change.
                        • A binary that doesn't match the sources is never linked silently.

                        Non-Goals:

                        • A shared library option (it stays in the backlog).
                        • Intel macOS, musl, Windows MSVC or Windows arm64 builds.
                        • Automatic lib releases. Tags are pushed by hand.
                        • Signing the archives. The committed checksums are the trust anchor.

                        Decisions

                        The crate moves to src/rust/

                        This is the only layout nimble installs. ffi.nim finds the crate as currentSourcePath.parentDir.parentDir / "rust", which is src/rust in a checkout and <pkg>/rust in an installed package. Alternatives considered:

                        • Drop srcDir. This moves every Nim module and changes import paths for tests and docs.
                        • No source fallback for installed packages. Users on other platforms would have to clone the repository.

                        nanuq.nimble adds skipDirs for rust/target so that a local nimble install from a checkout doesn't copy gigabytes of build output.

                        Lib version comes from Cargo.toml; sums come from a committed file

                        ffi.nim reads the crate version from src/rust/Cargo.toml with staticRead. src/nanuq/lib-sums.txt holds the lib-v version it was generated for and one <sha256> <archive> line per archive, in sha256sum format. A download happens only when the two versions are equal and the version doesn't end in -dev. The release workflow generates the file, and a bot PR commits it. Between a version bump and the release the versions differ, so the library builds from source, which is the right behaviour for unreleased Rust code.

                        Alternative: one Nim constant per target in a .nim file. That's harder to diff against the release's sums file.

                        Download with curl, tar and the system SHA-256 tool, at compile time

                        Everything runs through gorgeEx during compilation: curl -fsSL --retry 2 -o <tmp> <url>, then the platform hash tool (sha256sum, shasum -a 256 or certutil -hashfile <f> SHA256), then tar -xzf into the cache directory, finally writing a .complete marker that later compiles look for, so that none of them links a half-unpacked file. (The plan was to rename a temporary directory into place, but moveDir isn't available in the compile-time VM.) Each compile downloads to its own temporary name. Hashing a 100 MB archive in the Nim VM would take too long.

                        -d:nanuqReleaseUrl replaces the GitHub releases URL with a mirror, for networks that block GitHub. The committed sums still apply.

                        Cache root: $XDG_CACHE_HOME or ~/.cache on Linux, ~/Library/Caches on macOS, %LOCALAPPDATA% on Windows, each plus nanuq/<libver>/<target>/. -d:nanuqCacheDir overrides it.

                        Alternative: a nimble before install hook. Atlas, nimby, submodules and nimble develop don't run it, so it could only warm the cache, which isn't worth a second code path.

                        Target triple from Nim's target defines

                        The triple comes from hostOS/hostCPU as seen by the compiler for the target (defined(linux), defined(amd64) and so on). So cross-compiling with --os/--cpu picks the archive for the target. CPU feature detection runs only when the target is x86_64 Linux and the compiler itself runs on x86_64 Linux. It reads the flags line of /proc/cpuinfo and requires avx avx2 bmi1 bmi2 fma f16c movbe (the x86-64-v3 set as listed there).

                        Building portable archives
                        • Linux is built inside the manylinux_2_28 container for each architecture. A static lib compiled on a glibc 2.39 runner can reference newer symbols from C dependencies (for example the __isoc23_* redirects), which would fail to link on older systems.
                        • macOS is built on macos-15 with MACOSX_DEPLOYMENT_TARGET=11.0.
                        • Windows is built on windows-latest with the MinGW toolchain that is preinstalled there.
                        • Modern x86_64 builds use RUSTFLAGS=-C target-cpu=x86-64-v3, and legacy-cpu builds use no CPU flags.
                        • Release profile: lto = "fat" and codegen-units = 1 if they make the archive smaller without making the build too slow. This is measured in the first task.

                        Every job smoke-tests its archive by running tests/test_basic.nim with -d:nanuqLibDir on its own runner. The Windows job runs the test under the default MinGW compiler, and ffi.nim gains the Windows system libraries Rust needs (ws2_32, userenv, bcrypt, ntdll).

                        Runtime version check

                        nq_version() returns CARGO_PKG_VERSION as a static C string. The top level of ffi.nim compares it with the compile-time version and raises a Defect with both versions in the message.

                        Policy define

                        const nanuqLib {.strdefine.} = "auto". nanuqNoCargo maps to prebuilt. Every branch emits a {.hint.} naming the source it used, and a {.error.} lists the ways out (install Rust, pass -d:nanuqLibDir, check the network).

                        Risks / Trade-offs

                        • [Corporate proxies block the download] curl honours HTTPS_PROXY. A failed download falls back to cargo under auto, and the hint names the URL so the archive can be fetched by hand and passed with -d:nanuqLibDir.
                        • [Release asset deleted or renamed] The download fails and the library builds from source. Assets are never replaced: a fix ships as a new lib version.
                        • [A cargo build inside the installed package dir] writes target/ into pkgs2/. Nimble doesn't re-verify package checksums after install. If that turns out to matter, the fallback can use the cache as --target-dir.
                        • [Archive size] About 300 MB unstripped before compression. GitHub allows 2 GiB per asset. It's measured in task 1, and LTO is applied if it helps.
                        • [/proc/cpuinfo misses a flag on some kernels] The legacy build is picked, which is slower but safe. -d:nanuqLegacyCpu is the manual override.

                        Migration Plan

                        1. Merge the implementation, with the crate at src/rust/ and version 0.1.0. Main builds from source until the first lib release, as it does today.
                        2. Pietro pushes lib-v0.1.0. The workflow publishes the release and opens the sums PR. Merging it turns on downloads for 0.1.0.
                        3. Pietro tags the package v0.1.0.

                        Rollback: delete src/nanuq/lib-sums.txt (or empty it), and every compile builds from source as before.

                        Tasks11 of 11 done

                        1. Move the crate and measure 2/2

                        • 1.1Move rust/ to src/rust/ (git mv). Update ffi.nim, nanuq.nimble tasks, .gitignore, ci.yml paths and cache keys, openspec/config.yaml context, README and the dev-log posts' mentions of rust/, and add skipDirs for rust/target. Verify nimble test passes and nimble install into a temporary --nimbleDir contains rust/Cargo.toml but no rust/target.
                        • 1.2Measure the archive (tar czf of libnanuq_ffi.a) with the current profile and with lto = "fat", codegen-units = 1. Keep the LTO settings if the archive is clearly smaller and the build stays under ~20 minutes. Record the numbers in the PR description.

                        2. Version in the library 1/1

                        • 2.1Add nq_version() to src/rust/src/lib.rs and ffi.nim, plus the startup check against the version parsed from Cargo.toml. Verify with a test that the versions match, and that a library built with a different crate version stops with an error naming both versions.

                        3. Release workflow 2/2

                        • 3.1Add .github/workflows/release-lib.yml (on lib-v* tags and workflow_dispatch without publishing): check the tag against Cargo.toml, run the 6-archive build matrix as in design.md (manylinux_2_28 for Linux, macos-15, windows-latest with MinGW, v3 / legacy-cpu for x86_64), smoke-test each archive with tests/test_basic.nim on its runner, then publish the release with the sums file and open a PR that updates src/nanuq/lib-sums.txt. Verify with a workflow_dispatch run that all six jobs build and pass their smoke tests.
                        • 3.2Add the Windows system libraries to ffi.nim's link flags. Verify via the Windows smoke test in 3.1.

                        4. Compile-time download 4/4

                        • 4.1In ffi.nim, add the nanuqLib policy (auto / prebuilt / source, with nanuqNoCargo as prebuilt), the target triple, the lib version from Cargo.toml, and reading lib-sums.txt. Verify that with -d:nanuqLib=source and no local build, cargo runs as before.
                        • 4.2Implement the cache lookup, the download (curl), checksum check (sha256sum / shasum / certutil), unpacking with a .complete marker (see design.md), and a hint for each source used. Verify against the workflow_dispatch archives from 3.1 (served from a local directory, or uploaded to a test pre-release): a clean cache downloads and links, a second compile uses the cache, a corrupted archive stops with the checksum error, and an unknown target falls back to cargo.
                        • 4.3Add CPU detection for x86_64 Linux and -d:nanuqLegacyCpu. Verify both choices, using a stubbed flags string for the old-CPU case.
                        • 4.4Document installing (nimble, Atlas, git), the defines and the cache location in the README, and update the ffi.nim module doc. Verify the README commands work in a clean container without Rust once a release exists (task 6.1).

                        5. CI check 1/1

                        • 5.1Add a CI step that fails when src/rust/ differs from tag lib-v<version> and the version doesn't end in -dev. Verify on a branch with a fake tag: changing lib.rs fails the step, and a -dev version passes.

                        6. End to end 1/1

                        • 6.1After Pietro pushes lib-v0.1.0 and the sums PR is merged: in a fresh container without Rust, nimble install the package from this branch and compile and run the README example. Verify that it finishes in under a minute with a download hint and no cargo hint.

                        Workflow follow-up 0/0

                          Revisions1 revision
                          r1 f2a95d3 2026-10-28 Archive ship-prebuilt-binaries and prepare the 0.1.0 changelog

                          First version: .openspec.yaml, design.md, proposal.md, specs/binary-distribution/spec.md, specs/ci/spec.md, specs/native-bridge/spec.md, tasks.md

                          use-how-for-method-params Archived

                          openspec/changes/archive/2026-11-01-use-how-for-method-params
                          1. Proposal
                          2. Specs
                          3. Tasks
                          4. Implement 3/3
                          5. Archive
                          Proposal

                          Why

                          Python Polars calls the "which variant" parameter of rank, corr and interpolate method, which is a Nim keyword. Nanuq worked around it three different ways: rankMethod, correlationMethod and interpolation. The names were long and inconsistent (Pietro, reviewing the 0.4 dev log: "not a fan of the long name correlationMethod").

                          Part of the 0.4 release (#51). There are no users yet, so the rename needs no deprecation.

                          What Changes

                          • BREAKING rank(rankMethod = ...) becomes rank(how = ...).
                          • corr(a, b, correlationMethod = ...) becomes corr(a, b, how = ...) (new in 0.4).
                          • interpolate(interpolation = ...) becomes interpolate(how = ...) (new in 0.4).
                          • api-conventions gains the rule: Python's method is how in Nanuq.
                          • Positional calls (rank(Min), corr(a, b, Spearman)) are unchanged.

                          Capabilities

                          Modified Capabilities
                          • api-conventions: the method → how rule.
                          • expressions: rank's parameter name.
                          • horizontal-functions: corr's parameter name.
                          • missing-values: interpolate's parameter name.

                          Differences from Polars

                          • Python: rank(method="dense"), pl.corr(a, b, method="spearman"), interpolate(method="nearest"). Nanuq: how = Dense, how = Spearman, how = Nearest.
                          • Rust Polars has separate pearson_corr and spearman_rank_corr functions, and takes RankOptions { method, .. } and InterpolationMethod as plain arguments.
                          • quantile keeps interpolation, which is Python's name there.

                          Impact

                          • src/nanuq.nim: three parameter names. No ABI change.
                          • Specs, the 0.4 dev-log post and the CHANGELOG mention the new names.
                          Spec changesapi-conventions +1 · expressions ~1 · horizontal-functions ~1 · missing-values ~1

                          api-conventions modified +1

                          ADDED
                          Python's method parameter is how

                          method is a Nim keyword, so no parameter can have that name. Where Python Polars has a method parameter that picks a variant from a closed set, Nanuq SHALL call it how, the name Polars itself uses for join and concat. This applies to rank, corr and interpolate. Where Python uses another name (quantile's interpolation), Nanuq SHALL keep Python's name.

                          let df = newDataFrame:
                            x: [1.0, 2.0, 2.0, 4.0]
                            y: [1.0, 4.0, 4.0, 16.0]
                          echo df.select(col.x.rank(how = Dense).alias("dense"),
                                         col.x.rank(Min).alias("min"))
                          echo df.select(corr("x", "y", how = Spearman).alias("spearman"))
                          shape: (4, 2)
                          ┌───────┬─────┐
                          │ dense ┆ min │
                          │ ---   ┆ --- │
                          │ u32   ┆ u32 │
                          ╞═══════╪═════╡
                          │ 1     ┆ 1   │
                          │ 2     ┆ 2   │
                          │ 2     ┆ 2   │
                          │ 3     ┆ 4   │
                          └───────┴─────┘
                          shape: (1, 1)
                          ┌──────────┐
                          │ spearman │
                          │ ---      │
                          │ f64      │
                          ╞══════════╡
                          │ 1.0      │
                          └──────────┘
                          Scenario: Named variant
                          • WHEN user code writes corr("x", "y", how = Spearman) or rank(how = Dense)
                          • THEN it compiles and picks that variant
                          Scenario: Positional variant
                          • WHEN user code writes rank(Min) or corr("x", "y", Spearman)
                          • THEN it means the same as naming how

                          Unchanged in this spec: Option values are pure enums with Rust Polars names, The conventions are documented, Parameters that take several types use converter types

                          expressions modified ~1

                          MODIFIED
                          Ranking
                          `Expr` SHALL support `rank(how = Average, descending = false, seed = none(int))` with a pure enum `RankMethod` (`Average`, `Min`, `Max`, `Dense`, `Ordinal`, `Random`), giving each value its rank from 1. Ties SHALL be handled as Polars does: `Average` gives tied values the mean of their ranks (f64), `Min` and `Max` the lowest or highest (u32), `Dense` leaves no gaps after ties, and `Ordinal` breaks ties by position. `seed` SHALL make `Random` repeatable. Nulls SHALL stay null. ```nim let roll = newDataFrame: rider: ["Merckx", "Pogačar", "De Vlaeminck", "Van Looy", "Kelly"] monuments: [19, 13, 11, 8, 9] echo roll.select(col.rider, col.monuments, col.monuments.rank(Min, descending = true).alias("place"), col.monuments.rank.alias("avg")) ``` ```text shape: (5, 4) ┌──────────────┬───────────┬───────┬─────┐ │ rider ┆ monuments ┆ place ┆ avg │ │ --- ┆ --- ┆ --- ┆ --- │ │ str ┆ i64 ┆ u32 ┆ f64 │ ╞══════════════╪═══════════╪═══════╪═════╡ │ Merckx ┆ 19 ┆ 1 ┆ 5.0 │ │ Pogačar ┆ 13 ┆ 2 ┆ 4.0 │ │ De Vlaeminck ┆ 11 ┆ 3 ┆ 3.0 │ │ Van Looy ┆ 8 ┆ 5 ┆ 1.0 │ │ Kelly ┆ 9 ┆ 4 ┆ 2.0 │ └──────────────┴───────────┴───────┴─────┘ ``` Scenario: Shared places - **WHEN** `rank(Min, descending = true)` runs over 9, 9, 7 - **THEN** the result is 1, 1, 3 Scenario: Dense - **WHEN** `rank(Dense)` runs over 9, 9, 7 - **THEN** the result is 2, 2, 1 Scenario: Average - **WHEN** `rank()` runs over 9, 9, 7 - **THEN** the result is 2.5, 2.5, 1.0 with dtype f64

                          Unchanged in this spec: Conditional expressions, choose macro, Membership and ranges, Arithmetic operators, Rounding, More aggregations, Null fill strategies, Window expressions, Filtering inside expressions, Shape and position aggregations, Boolean aggregations, Entropy, Row count expression, Several window keys and selector concatenation, Null-aware comparisons and closeness, More expression functions

                          horizontal-functions modified ~1

                          MODIFIED
                          Correlation
                          `corr(a, b, how = Pearson)` SHALL return the Pearson or Spearman correlation of two columns as an aggregation, and `cov(a, b, ddof = 1)` their covariance. ```nim let df = newDataFrame: oni: [-1.0, 0.0, 0.5, 2.0] world: [14.6, 14.8, 14.9, 15.2] echo df.select(corr("oni", "world").round(3).alias("pearson"), corr("oni", "world", how = Spearman).alias("spearman")) ``` ```text shape: (1, 2) ┌─────────┬──────────┐ │ pearson ┆ spearman │ │ --- ┆ --- │ │ f64 ┆ f64 │ ╞═════════╪══════════╡ │ 1.0 ┆ 1.0 │ └─────────┴──────────┘ ``` Scenario: Perfect correlation - **WHEN** `corr` runs on 1, 2, 3 and 2, 4, 6 - **THEN** the result is 1.0

                          Unchanged in this spec: Horizontal functions, Generated columns

                          missing-values modified ~1

                          MODIFIED
                          Interpolation
                          `e.interpolate()` SHALL fill nulls that lie between two values on a straight line between them, or with the nearest value for `interpolate(how = Nearest)`; `e.interpolateBy(by)` SHALL interpolate linearly using the distances in column `by`. Nulls before the first and after the last value SHALL stay null. ```nim let df = newDataFrame: day: [1, 2, 4, 5] temp: [10.0, nil, 16.0, nil] echo df.withColumns(col.temp.interpolate.alias("linear"), col.temp.interpolateBy("day").alias("by_day")) ``` ```text shape: (4, 4) ┌─────┬──────┬────────┬────────┐ │ day ┆ temp ┆ linear ┆ by_day │ │ --- ┆ --- ┆ --- ┆ --- │ │ i64 ┆ f64 ┆ f64 ┆ f64 │ ╞═════╪══════╪════════╪════════╡ │ 1 ┆ 10.0 ┆ 10.0 ┆ 10.0 │ │ 2 ┆ null ┆ 13.0 ┆ 12.0 │ │ 4 ┆ 16.0 ┆ 16.0 ┆ 16.0 │ │ 5 ┆ null ┆ null ┆ null │ └─────┴──────┴────────┴────────┘ ``` Scenario: Integer column - **WHEN** `interpolate` runs on 1, null, 3 - **THEN** the result is 1.0, 2.0, 3.0

                          Unchanged in this spec: Nulls are read as Option, Plain reads refuse nulls, Inspecting nulls, Building columns with nulls, CSV null markers, Null expressions, Dropping rows with nulls, Null literal, Filling nulls in whole frames

                          Tasks3 of 3 done

                          1. Rename 3/3

                          • 1.1rank, corr, interpolate: parameter how
                          • 1.2Tests, spec examples and the 0.4 dev-log post use the new names
                          • 1.3CHANGELOG entry
                          Revisions1 revision
                          r1 5803130 2026-11-01 Python's method parameter is how: rank, corr, interpolate

                          First version: proposal.md, specs/api-conventions/spec.md, specs/expressions/spec.md, specs/horizontal-functions/spec.md, specs/missing-values/spec.md, tasks.md

                          Specs

                          The current specs in openspec/specs, as archived changes left them. Changes still open are not applied here.

                          api-conventions4 requirements

                          Purpose: Naming conventions that every part of the Nanuq API follows: Polars names in camelCase, and closed sets of option values as pure enums with Rust Polars names.

                          Option values are pure enums with Rust Polars names

                          A parameter that takes one of a closed set of option values SHALL use a {.pure.} enum whose type name and PascalCase value names are those of the corresponding Rust Polars enum (e.g. JoinType.Left for JoinType::Left). When Rust Polars has no such enum, Nanuq SHALL name one after Python Polars' parameter strings, in PascalCase. Strings SHALL NOT be used for closed sets of options. Internal C ABI enums in ffi.nim keep their Nq/nq prefixes and are exempt.

                          let a = newDataFrame(series("k", [1, 2]))
                          let b = newDataFrame(series("k", [2, 3]))
                          echo a.join(b, on = ["k"], how = Left, maintainOrder = Left).shape   # JoinType.Left, MaintainOrderJoin.Left
                          let how = JoinType.Full    # outside a typed parameter, qualify the value
                          echo a.join(b, on = ["k"], how = how).shape
                          (2, 1)
                          (3, 2)
                          Scenario: Bare value in a typed context
                          • WHEN user code passes how = Left to join
                          • THEN it compiles and means JoinType.Left
                          Scenario: Shared value names
                          • WHEN user code passes how = Left, maintainOrder = Left
                          • THEN each resolves to its own enum's value, as in Rust
                          Scenario: Untyped context
                          • WHEN user code writes let x = Left with several enums exporting Left
                          • THEN compilation fails as ambiguous, and let x = JoinType.Left compiles
                          The conventions are documented

                          The README SHALL state the API conventions (camelCase Polars names, pure enums with Rust names for option values), and every OpenSpec proposal SHALL follow them, listing any exception in its "Differences from Polars" section.

                          Scenario: New option type
                          • WHEN a proposal adds a parameter with a closed set of values
                          • THEN it uses the Rust Polars enum name and values as a pure enum, or explains why not
                          Python's method parameter is how

                          method is a Nim keyword, so no parameter can have that name. Where Python Polars has a method parameter that picks a variant from a closed set, Nanuq SHALL call it how, the name Polars itself uses for join and concat. This applies to rank, corr and interpolate. Where Python uses another name (quantile's interpolation), Nanuq SHALL keep Python's name.

                          let df = newDataFrame:
                            x: [1.0, 2.0, 2.0, 4.0]
                            y: [1.0, 4.0, 4.0, 16.0]
                          echo df.select(col.x.rank(how = Dense).alias("dense"),
                                         col.x.rank(Min).alias("min"))
                          echo df.select(corr("x", "y", how = Spearman).alias("spearman"))
                          shape: (4, 2)
                          ┌───────┬─────┐
                          │ dense ┆ min │
                          │ ---   ┆ --- │
                          │ u32   ┆ u32 │
                          ╞═══════╪═════╡
                          │ 1     ┆ 1   │
                          │ 2     ┆ 2   │
                          │ 2     ┆ 2   │
                          │ 3     ┆ 4   │
                          └───────┴─────┘
                          shape: (1, 1)
                          ┌──────────┐
                          │ spearman │
                          │ ---      │
                          │ f64      │
                          ╞══════════╡
                          │ 1.0      │
                          └──────────┘
                          Scenario: Named variant
                          • WHEN user code writes corr("x", "y", how = Spearman) or rank(how = Dense)
                          • THEN it compiles and picks that variant
                          Scenario: Positional variant
                          • WHEN user code writes rank(Min) or corr("x", "y", Spearman)
                          • THEN it means the same as naming how
                          Parameters that take several types use converter types

                          Where Python Polars lets a parameter take values of different types (a name or a list of names, a duration string or a number) and the parameter needs a default, Nanuq SHALL use a small exported object type with a converter from each accepted type, instead of a generic union (string | openArray[string] = [] does not compile with a default in Nim) or one overload per combination. The existing types are ColumnNames (a name, a seq or an array of names), OptInterval (a std/times interval or a duration string), JoinKey (a column name or an expression) and AsofTolerance (an interval, a duration string, an int or a float). A new parameter of this kind SHALL reuse one of them when it fits, and a new type SHALL be listed here. Converters SHALL only convert into these types, so they apply only where such a parameter appears.

                          let df = newDataFrame:
                            year: [1997, 1997, 1998]
                            months: ["JJA", "SON", "JJA"]
                            anomaly: [1.5, 2.3, -0.2]
                          echo df.pivot("months", index = "year", values = "anomaly").columns
                          echo df.pivot(["months"], index = @["year"], values = "anomaly").columns
                          @["year", "JJA", "SON"]
                          @["year", "JJA", "SON"]
                          Scenario: One name or a list
                          • WHEN user code passes index = "year" or index = ["year", "month"] to pivot
                          • THEN both compile and mean one or two index columns
                          Scenario: Default left out
                          • WHEN user code calls joinAsof(other, on = "t") without tolerance
                          • THEN it compiles, and no tolerance is applied
                          arraymancer-interop2 requirements

                          Purpose: Copying numeric columns between Nanuq and Arraymancer tensors (nanuq/arraymancer), an optional module like nanuq/datamancer.

                          Columns to tensors

                          The optional module nanuq/arraymancer SHALL provide toTensor(series, T), toTensor(df, column, T) and toTensor(df, T, columns), copying values into an Arraymancer Tensor[T] for T in int, float and bool; the frame version SHALL give a 2-D tensor with one row per row of the frame. Nulls SHALL become NaN in float tensors and SHALL raise InvalidOperationError for int and bool.

                          import pkg/arraymancer, nanuq/arraymancer
                          let df = newDataFrame:
                            oni: [2.4, 2.6, 2.0]
                            temp: [14.7, 15.0, 15.2]
                          let t = df.toTensor(float)
                          echo t.shape[0], "x", t.shape[1], " ", t[1, 0]
                          3x2 2.6
                          Scenario: Nulls in a float tensor
                          • WHEN a float column with a null is copied with toTensor("a", float)
                          • THEN the tensor holds NaN at that position
                          Tensors to columns

                          toSeries(tensor, name) SHALL copy a 1-D tensor into a Series, and toDataFrame(tensor, columns) SHALL copy a 2-D tensor into a frame with one column per tensor column, named columns or column_0, column_1, ...

                          import pkg/arraymancer, nanuq/arraymancer
                          echo [[1.0, 2.0], [3.0, 4.0]].toTensor.toDataFrame(["a", "b"])
                          shape: (2, 2)
                          ┌─────┬─────┐
                          │ a   ┆ b   │
                          │ --- ┆ --- │
                          │ f64 ┆ f64 │
                          ╞═════╪═════╡
                          │ 1.0 ┆ 2.0 │
                          │ 3.0 ┆ 4.0 │
                          └─────┴─────┘
                          Scenario: Wrong rank
                          • WHEN toSeries is called on a 2-D tensor
                          • THEN ValueError is raised
                          arrow-interop3 requirements

                          Purpose: Exchanging columns and frames with other libraries through the Arrow C Data Interface, and zero-copy access to numeric columns from Nim.

                          Series through the Arrow C Data Interface

                          s.toArrow SHALL export a Series as an ArrowExport holding the standard ArrowSchema and ArrowArray C structs, without copying the values. Whatever a consumer did not take over SHALL be released when the export goes away. fromArrow(schema, array, name = "") SHALL import a Series from such structs, taking over the array.

                          var ex = series("kg", @[410, 380]).toArrow
                          echo ex.schema.format, " ", ex.array.length
                          let back = fromArrow(ex, name = "mass")
                          echo back
                          l 2
                          shape: (2,)
                          Series: 'mass' [i64]
                          [
                          	410
                          	380
                          ]
                          Scenario: Taken over
                          • WHEN an export's array is imported with fromArrow
                          • THEN the export's array.release is nil and the Series reads the same values
                          Frames through the Arrow C stream interface

                          df.toArrow SHALL export a frame as an ArrowArrayStream of record batches (struct arrays), and fromArrow(stream) SHALL read a whole stream into a frame and release it.

                          let df = newDataFrame(series("bear", @["Ada", "Bo"]), series("kg", @[410.0, 380.5]))
                          var stream = df.toArrow
                          echo fromArrow(stream)
                          shape: (2, 2)
                          ┌──────┬───────┐
                          │ bear ┆ kg    │
                          │ ---  ┆ ---   │
                          │ str  ┆ f64   │
                          ╞══════╪═══════╡
                          │ Ada  ┆ 410.0 │
                          │ Bo   ┆ 380.5 │
                          └──────┴───────┘
                          Scenario: Nested and temporal columns
                          • WHEN a frame with List, Struct and Datetime columns goes through toArrow and fromArrow
                          • THEN the result equals the frame
                          Zero-copy views

                          s.view(T) and df.view(column, T) SHALL give a ColumnView[T] over a numeric column's values without copying, with [], len, items and toOpenArray. T SHALL match the column's type exactly and the column SHALL have no nulls, else InvalidOperationError.

                          import std/math
                          let df = newDataFrame(series("kg", @[410.0, 380.5, 455.0]))
                          let v = df.view("kg", float)
                          echo v.len, " ", v[1], " ", sum(v.toOpenArray)
                          3 380.5 1245.5
                          Scenario: Wrong type
                          • WHEN an Int64 column is viewed as float
                          • THEN InvalidOperationError is raised
                          Scenario: Nulls
                          • WHEN a column with a null is viewed
                          • THEN InvalidOperationError is raised
                          binary-decimal6 requirements

                          Purpose: Binary (raw bytes) and Decimal (exact) columns, the bin namespace, string encodings and bitwise expressions.

                          Binary data

                          Binary SHALL be a data type of raw bytes. series(name, strings, Binary) SHALL build a Binary column whose values are the strings' bytes (any bytes), and toList(column, string) SHALL read them back unchanged.

                          let s = series("sig", ["\x00\xff", "bear"], Binary)
                          echo s.dtype
                          let df = newDataFrame(s)
                          echo df
                          echo df.toList("sig", string) == @["\x00\xff", "bear"]
                          Binary
                          shape: (2, 1)
                          ┌─────────────┐
                          │ sig         │
                          │ ---         │
                          │ binary      │
                          ╞═════════════╡
                          │ b"\x00\xff" │
                          │ b"bear"     │
                          └─────────────┘
                          true
                          Scenario: Cast from strings
                          • WHEN a String column is cast to Binary
                          • THEN its values read back as the same strings
                          Decimal data

                          Decimal(precision = 38, scale = 0) SHALL be the exact decimal type, with precision 1 to 38 and scale 0 to precision (else ValueError). Strings SHALL become decimals with series(name, strings, Decimal(p, s)) or str.toDecimal(scale), and Decimal columns SHALL read back as string (exact) or float.

                          let df = newDataFrame(series("price", ["1.25", "10.50", "0.10"], Decimal(10, 2)))
                          echo df
                          echo df.select(col("price").sum)
                          echo df.toList("price", float)
                          shape: (3, 1)
                          ┌───────────────┐
                          │ price         │
                          │ ---           │
                          │ decimal[10,2] │
                          ╞═══════════════╡
                          │ 1.25          │
                          │ 10.50         │
                          │ 0.10          │
                          └───────────────┘
                          shape: (1, 1)
                          ┌───────────────┐
                          │ price         │
                          │ ---           │
                          │ decimal[38,2] │
                          ╞═══════════════╡
                          │ 11.85         │
                          └───────────────┘
                          @[1.25, 10.5, 0.1]
                          Scenario: Bad precision
                          • WHEN Decimal(40, 2) is called
                          • THEN ValueError is raised
                          Binary functions

                          e.bin SHALL provide contains, startsWith, endsWith (with a string of bytes or an expression), encode(BinaryEncoding) (hex or base64 text), decode(BinaryEncoding) and size(unit = SizeUnit.Bytes); str.encode(BinaryEncoding) SHALL encode strings' UTF-8 bytes.

                          let df = newDataFrame(series("b", ["bear", "cub"], Binary))
                          echo df.select(col("b").bin.encode(BinaryEncoding.Hex).alias("hex"),
                                         col("b").bin.startsWith("be").alias("be"), col("b").bin.size.alias("n"))
                          echo newDataFrame(series("s", @["hi"])).select(col("s").str.encode(BinaryEncoding.Base64))
                          shape: (2, 3)
                          ┌──────────┬───────┬─────┐
                          │ hex      ┆ be    ┆ n   │
                          │ ---      ┆ ---   ┆ --- │
                          │ str      ┆ bool  ┆ u32 │
                          ╞══════════╪═══════╪═════╡
                          │ 62656172 ┆ true  ┆ 4   │
                          │ 637562   ┆ false ┆ 3   │
                          └──────────┴───────┴─────┘
                          shape: (1, 1)
                          ┌──────┐
                          │ s    │
                          │ ---  │
                          │ str  │
                          ╞══════╡
                          │ aGk= │
                          └──────┘
                          Scenario: Round trip
                          • WHEN a Binary column is encoded to hex, cast to Binary and decoded from hex
                          • THEN the values equal the original
                          Bitwise operations

                          Integer expressions SHALL provide bitwiseCountOnes, bitwiseCountZeros, bitwiseLeadingOnes, bitwiseLeadingZeros, bitwiseTrailingOnes, bitwiseTrailingZeros (per value) and bitwiseAnd, bitwiseOr, bitwiseXor (aggregations).

                          let df = newDataFrame(series("flags", @[0b0110'u8, 0b0011'u8]))
                          echo df.select(col("flags").bitwiseCountOnes.alias("ones"),
                                         col("flags").bitwiseTrailingZeros.alias("tz"))
                          echo df.select(col("flags").bitwiseAnd.alias("and"), col("flags").bitwiseOr.alias("or"))
                          shape: (2, 2)
                          ┌──────┬─────┐
                          │ ones ┆ tz  │
                          │ ---  ┆ --- │
                          │ u32  ┆ u32 │
                          ╞══════╪═════╡
                          │ 2    ┆ 1   │
                          │ 2    ┆ 0   │
                          └──────┴─────┘
                          shape: (1, 2)
                          ┌─────┬─────┐
                          │ and ┆ or  │
                          │ --- ┆ --- │
                          │ u8  ┆ u8  │
                          ╞═════╪═════╡
                          │ 2   ┆ 7   │
                          └─────┴─────┘
                          Scenario: Not integers
                          • WHEN bitwiseCountOnes is applied to a String column
                          • THEN PolarsError is raised
                          Binary slicing and bytes

                          The bin namespace SHALL provide slice(offset, length), head(n), tail(n) (negative values count from the end) and get(index, nullOnOob = false), which gives the byte as UInt8; index MAY be an expression. Reading a single Binary cell as string SHALL give its raw bytes, zero bytes included.

                          let df = newDataFrame(series("m", @["\x03\x04\x10\x11", "ab"], Binary))
                          echo df.select(col("m").bin.get(1).alias("second"),
                                         col("m").bin.slice(2, 2).bin.encode(BinaryEncoding.Hex).alias("tail_hex"))
                          shape: (2, 2)
                          ┌────────┬──────────┐
                          │ second ┆ tail_hex │
                          │ ---    ┆ ---      │
                          │ u8     ┆ str      │
                          ╞════════╪══════════╡
                          │ 4      ┆ 1011     │
                          │ 98     ┆          │
                          └────────┴──────────┘
                          Scenario: Out of bounds
                          • WHEN bin.get(9, nullOnOob = true) reads a 4-byte value
                          • THEN the result is null
                          Strings to integers

                          str.toInteger(base = 10, dtype = Int64, strict = true) SHALL parse strings as integers in base (2 to 36, or a column of bases); with strict = false, values that do not parse SHALL be null instead of raising.

                          let df = newDataFrame(series("k", @["zz", "10", "?"]))
                          echo df.select(col("k").str.toInteger(base = 36, strict = false))
                          shape: (3, 1)
                          ┌──────┐
                          │ k    │
                          │ ---  │
                          │ i64  │
                          ╞══════╡
                          │ 1295 │
                          │ 36   │
                          │ null │
                          └──────┘
                          Scenario: Strict
                          • WHEN a value does not parse and strict is true
                          • THEN a PolarsError is raised
                          binary-distribution7 requirements

                          Purpose: How users get a prebuilt libnanuq_ffi instead of compiling Polars: how libraries are built, versioned and published, and how a compile picks, downloads, verifies and caches the right one.

                          Lib releases

                          Pushing a tag lib-v<version>, where <version> equals the version in the crate's Cargo.toml, SHALL publish a GitHub Release with one archive libnanuq_ffi-<version>-<target>.tar.gz per supported target, and a file of SHA-256 sums for all archives. The supported targets SHALL be x86_64-unknown-linux-gnu, x86_64-unknown-linux-gnu-legacy-cpu, aarch64-unknown-linux-gnu, aarch64-apple-darwin, x86_64-pc-windows-gnu and x86_64-pc-windows-gnu-legacy-cpu.

                          Scenario: Tag pushed
                          • WHEN a maintainer pushes lib-v0.1.0 and Cargo.toml says 0.1.0
                          • THEN a release lib-v0.1.0 appears with six archives and a sums file
                          • AND a pull request is opened that commits those sums to the repository
                          Scenario: Released from the Actions tab
                          • WHEN a maintainer runs the release workflow by hand on main with "publish"
                          • ticked, and no lib-v<version> tag exists for the Cargo.toml version
                          • THEN the same release and pull request are made, and the tag is created on the
                          • commit that was built
                          Scenario: Tag does not match the crate
                          • WHEN the tag's version differs from Cargo.toml
                          • THEN the workflow fails without publishing anything
                          Archives are tested before release

                          Each archive SHALL be smoke-tested, by compiling and running a Nanuq test against it on its platform, before the release is published.

                          Scenario: Broken archive
                          • WHEN the smoke test fails for one target
                          • THEN no release is published for that tag
                          Portable binaries

                          Linux libraries SHALL link against glibc 2.28 or older symbols, macOS libraries SHALL target macOS 11 or later, and the modern x86_64 builds SHALL require at most the x86-64-v3 instruction set. Legacy-cpu builds SHALL require only baseline x86-64.

                          Scenario: Older Linux distribution
                          • WHEN a program is linked with the Linux library on a system with glibc 2.28
                          • THEN it links and runs
                          Committed checksums decide what can be downloaded

                          The package SHALL contain the lib version it expects and the SHA-256 of every archive for that version. A compile SHALL download only an archive listed there, and SHALL never download when the lib version ends in -dev.

                          Scenario: Development version
                          • WHEN the crate version is 0.2.0-dev
                          • THEN no download is attempted and the library is built from source
                          Scenario: Platform without a prebuilt library
                          • WHEN compiling for a target not listed in the sums (e.g. riscv64gc-unknown-linux-gnu)
                          • THEN no download is attempted and the library is built from source, with a hint
                          • saying why
                          Download, verify and cache

                          When a prebuilt library is needed, the compile SHALL look in a per-user cache directory keyed by lib version and target, and otherwise download the archive, verify its SHA-256 against the committed sum, and unpack it into the cache. Every source the compile uses SHALL be reported with a compiler hint. A checksum mismatch SHALL stop the compile with an error and SHALL NOT fall back to building from source.

                          Scenario: First compile
                          • WHEN a program importing nanuq is compiled on Linux x86_64 with an empty cache
                          • and no local build
                          • THEN the archive is downloaded once, verified, cached and linked, and no cargo
                          • build runs
                          Scenario: Second project
                          • WHEN another project on the same machine imports the same Nanuq version
                          • THEN the cached library is linked without a download
                          Scenario: Tampered archive
                          • WHEN the downloaded archive's SHA-256 differs from the committed sum
                          • THEN compilation fails with an error naming the archive, the expected sum and the
                          • actual sum
                          Scenario: Offline
                          • WHEN the download fails (no network) and the lib policy is auto
                          • THEN the library is built from source, with a hint saying the download failed
                          CPU variant selection

                          On x86_64 Linux, when the compile target is the host, the compile SHALL pick the legacy-cpu library if the host CPU lacks any feature the modern build needs. With -d:nanuqLegacyCpu the legacy-cpu library SHALL be picked on every x86_64 target. Otherwise the modern build SHALL be used.

                          Scenario: Old Linux CPU
                          • WHEN compiling on an x86_64 Linux host without AVX2
                          • THEN the legacy-cpu archive is used
                          Scenario: Forced legacy
                          • WHEN compiling for Windows x86_64 with -d:nanuqLegacyCpu
                          • THEN the x86_64-pc-windows-gnu-legacy-cpu archive is used
                          Release build configuration

                          Release archives SHALL be built with a pinned nightly Rust toolchain and the crate features nightly (Polars' nightly feature) and jemalloc (jemalloc as Rust's global allocator), except on Windows, where only nightly is used. Both features SHALL be off by default, so that a local build needs only stable Rust.

                          Scenario: Local build
                          • WHEN a contributor runs nimble buildRust with stable Rust
                          • THEN the library builds without either feature, and everything except str.toTitlecase works
                          Scenario: Release smoke test
                          • WHEN a release archive is smoke-tested
                          • THEN str.toTitlecase works with it
                          callbacks4 requirements

                          Purpose: Nim procs and closures called by Polars: element, batch, fold, name and group callbacks.

                          Typed element callbacks

                          e.mapElements(f) SHALL call the Nim proc or closure f: proc (x: T): U on each value of e, read as T (as toList reads it: objects and named tuples for structs, seqs for lists), and give a column of dataType(U). Nulls SHALL stay null without a call unless T is an Option. An exception in f SHALL raise ComputeError with its message when the query runs.

                          type Bear = object
                            name: string
                            kg: int
                          let df = newDataFrame:
                            name: ["Ada", "Bo", "Cy"]
                            kg: [410, nil, 500]
                          let tag = proc (b: Bear): string = b.name & " (" & $b.kg & " kg)"
                          echo df.select(col("kg").mapElements(proc (x: int): float = x / 1000).alias("t"),
                                         asStruct(col("name"), col("kg").fillNull(0)).mapElements(tag).alias("tag"))
                          shape: (3, 2)
                          ┌──────┬──────────────┐
                          │ t    ┆ tag          │
                          │ ---  ┆ ---          │
                          │ f64  ┆ str          │
                          ╞══════╪══════════════╡
                          │ 0.41 ┆ Ada (410 kg) │
                          │ null ┆ Bo (0 kg)    │
                          │ 0.5  ┆ Cy (500 kg)  │
                          └──────┴──────────────┘
                          Scenario: Error in the callback
                          • WHEN the callback raises ValueError("no bears")
                          • THEN collecting raises ComputeError whose message holds "no bears"
                          Batch callbacks

                          e.mapBatches(f) SHALL call f: proc (s: Series): Series with the whole column, or in a group-by with each group's values; the result SHALL keep the input type unless returnDtype is given, and with returnsScalar a group-by SHALL get one value per group instead of a list.

                          let df = newDataFrame:
                            cubs: [1, 0, 1]
                            kg: [410, 380, 500]
                          echo df.select(col("kg").mapBatches(proc (s: Series): Series = s * 2))
                          echo df.groupBy("cubs").agg(col("kg").mapBatches(proc (s: Series): Series = s.max,
                                                                            returnsScalar = true)).sort("cubs")
                          shape: (3, 1)
                          ┌──────┐
                          │ kg   │
                          │ ---  │
                          │ i64  │
                          ╞══════╡
                          │ 820  │
                          │ 760  │
                          │ 1000 │
                          └──────┘
                          shape: (2, 2)
                          ┌──────┬─────┐
                          │ cubs ┆ kg  │
                          │ ---  ┆ --- │
                          │ i64  ┆ i64 │
                          ╞══════╪═════╡
                          │ 0    ┆ 380 │
                          │ 1    ┆ 500 │
                          └──────┴─────┘
                          Scenario: Other result type
                          • WHEN mapBatches(proc (s: Series): Series = s / 10, Float64) runs on an integer column
                          • THEN the result is a f64 column
                          Folds

                          fold(acc, f, exprs) SHALL combine columns left to right with f: proc (acc, x: Series): Series, starting from acc; reduce(f, exprs) SHALL start from the first column, and cumFold and cumReduce SHALL keep each step as a struct field.

                          let df = newDataFrame:
                            a: [1, 2]
                            b: [10, 20]
                            c: [100, 200]
                          echo df.select(fold(lit(0), proc (acc, x: Series): Series = acc + x, col("*")).alias("sum"))
                          shape: (2, 1)
                          ┌─────┐
                          │ sum │
                          │ --- │
                          │ i32 │
                          ╞═════╡
                          │ 111 │
                          │ 222 │
                          └─────┘
                          Scenario: Reduce
                          • WHEN reduce with + runs on columns a and b
                          • THEN the result is 11 and 22
                          Name and group callbacks

                          name.map(f) SHALL rename outputs with f: proc (name: string): string, and groupBy(...).mapGroups(f) SHALL call f: proc (df: DataFrame): DataFrame on each group, in order of first occurrence, and concatenate the results.

                          let df = newDataFrame:
                            den: ["A", "B", "A"]
                            kg: [410, 380, 500]
                          echo df.select(col("*").name.map(proc (n: string): string = n.toUpperAscii))
                          echo df.groupBy("den").mapGroups(proc (g: DataFrame): DataFrame = g.sort("kg", descending = true).head(1))
                          shape: (3, 2)
                          ┌─────┬─────┐
                          │ DEN ┆ KG  │
                          │ --- ┆ --- │
                          │ str ┆ i64 │
                          ╞═════╪═════╡
                          │ A   ┆ 410 │
                          │ B   ┆ 380 │
                          │ A   ┆ 500 │
                          └─────┴─────┘
                          shape: (2, 2)
                          ┌─────┬─────┐
                          │ den ┆ kg  │
                          │ --- ┆ --- │
                          │ str ┆ i64 │
                          ╞═════╪═════╡
                          │ A   ┆ 500 │
                          │ B   ┆ 380 │
                          └─────┴─────┘
                          Scenario: Empty frame
                          • WHEN mapGroups runs on an empty frame
                          • THEN the result is an empty frame with the same columns
                          categoricals3 requirements

                          Purpose: Categorical and Enum columns: Nim enums as Polars Enums, run-time Enum and Categorical dtypes, and the cat namespace.

                          Nim enums as Enum columns

                          A Nim enum type SHALL map to a Polars Enum whose categories are $ of its values in order. series, the block form of newDataFrame, cast(T), toList, df[c, i, T], comparisons and isIn SHALL accept the enum type or its values. Reading a value that is not in the enum SHALL raise InvalidOperationError.

                          type Monument = enum
                            Sanremo = "Milano-Sanremo", Flanders = "Ronde van Vlaanderen",
                            Roubaix = "Paris-Roubaix", Liege = "Liège-Bastogne-Liège", Lombardia = "Il Lombardia"
                          let wins = newDataFrame:
                            race: ["Il Lombardia", "Milano-Sanremo", "Paris-Roubaix"]
                            winner: ["Pogačar", "Pogačar", "van der Poel"]
                          let byRace = wins.withColumns(col.race.cast(Monument)).sort("race")
                          echo byRace
                          echo byRace.toList("race", Monument)
                          echo byRace.filter(col.race == Roubaix).toList("winner", string)
                          shape: (3, 2)
                          ┌────────────────┬──────────────┐
                          │ race           ┆ winner       │
                          │ ---            ┆ ---          │
                          │ enum           ┆ str          │
                          ╞════════════════╪══════════════╡
                          │ Milano-Sanremo ┆ Pogačar      │
                          │ Paris-Roubaix  ┆ van der Poel │
                          │ Il Lombardia   ┆ Pogačar      │
                          └────────────────┴──────────────┘
                          @[Milano-Sanremo, Paris-Roubaix, Il Lombardia]
                          @["van der Poel"]
                          Scenario: Calendar order
                          • WHEN a column of Monument names is cast to Monument and sorted
                          • THEN the rows follow the order of the enum, not the alphabet
                          Scenario: Unknown value
                          • WHEN a string that is not a category is cast to Monument strictly
                          • THEN InvalidOperationError is raised
                          Run-time Enum and Categorical

                          Enum(categories) SHALL build an Enum dtype from strings, raising ValueError on duplicates, and Categorical SHALL be the dtype of strings with categories found in the data. Both SHALL read back as strings.

                          let df = newDataFrame:
                            team: ["UAE", "Visma", "UAE"]
                            level: ["high", "low", "high"]
                          let t = df.select(col.team.cast(Categorical), col.level.cast(Enum(["low", "high"])))
                          echo t.schema
                          echo t.sort("level").toList("level", string)
                          {"team": Categorical, "level": Enum(["low", "high"])}
                          @["low", "high", "high"]
                          Scenario: Categories of an Enum
                          • WHEN dtype(df, c).categories is read for a column cast to Enum(["low", "high"])
                          • THEN it is @["low", "high"]
                          The cat namespace

                          e.cat SHALL give access to lenBytes, lenChars, startsWith(prefix), endsWith(suffix) and slice(offset, length) on Categorical and Enum columns. e.toPhysical SHALL give the category indices. getCategories, removed in Polars 2.0, SHALL be a compile-time error pointing to unique() and the dtype's categories.

                          type Medal = enum Gold, Silver, Bronze
                          let df = newDataFrame:
                            medal: [Silver, Gold, Silver]
                          echo df.select(col.medal.cat.lenChars)
                          echo df.select(col.medal.toPhysical).toList("medal", int)
                          echo df.dtype("medal").categories
                          shape: (3, 1)
                          ┌───────┐
                          │ medal │
                          │ ---   │
                          │ u32   │
                          ╞═══════╡
                          │ 6     │
                          │ 4     │
                          │ 6     │
                          └───────┘
                          @[1, 0, 1]
                          @["Gold", "Silver", "Bronze"]
                          Scenario: All categories
                          • WHEN the categories of an Enum column holding only Silver and Gold are needed
                          • THEN dtype(df, c).categories gives Gold, Silver and Bronze
                          ci5 requirements

                          Purpose: Continuous integration and publishing for the repository (.github/workflows/ci.yml).

                          Build Rust only when the crate changes

                          CI SHALL build libnanuq_ffi.a in a single job whose cache key is a hash of the crate sources in src/rust/, and SHALL share the library with the other jobs, which compile with -d:nanuqNoCargo.

                          Scenario: Change that does not touch rust/
                          • WHEN a push changes only Nim code or docs
                          • THEN the library comes from cache and no Rust toolchain or cargo build runs
                          Scenario: Change to rust/
                          • WHEN a push changes files in src/rust/
                          • THEN the library is rebuilt, reusing cached compiled dependencies
                          Skip CI for non-code changes

                          CI SHALL NOT run for pushes or pull requests that only change Markdown files, LICENSE, .gitignore, openspec/ or .claude/, except openspec/specs/, whose examples CI runs. On main, CI SHALL also run for pushes that change openspec/, BACKLOG.md or tools/specview.nim, so the published OpenSpec page stays current.

                          Scenario: OpenSpec-only change
                          • WHEN a pull request only changes files under openspec/changes/
                          • THEN no CI run starts
                          Scenario: OpenSpec-only merge
                          • WHEN a commit that only changes files under openspec/changes/ lands on main
                          • THEN CI runs and the site is deployed with the updated OpenSpec page
                          Scenario: Main spec change
                          • WHEN a pull request changes openspec/specs/expressions/spec.md
                          • THEN CI runs, including the spec examples
                          Scenario: Dev log change
                          • WHEN a change touches docs/
                          • THEN CI runs, so the dev log is rebuilt
                          Tests, example and dev log

                          CI SHALL run the test suite, which includes the spec examples, as one program (tests/all.nim), and the example, and render the site as one program (docs/all.nim): the nimib dev-log posts in docs/blog, then the index page docs/index.nim and the living pages (the Polars coverage page and the OpenSpec page). On main, after these succeed, it SHALL deploy them to GitHub Pages, with the index as the site root.

                          Scenario: Merge to main
                          • WHEN a commit lands on main and the test and docs jobs pass
                          • THEN the dev log and the living pages are deployed to GitHub Pages, and the site root lists the posts
                          Scenario: Stale spec example
                          • WHEN a pull request changes behavior that a spec example shows
                          • THEN the test job fails until the example's output is updated
                          Scenario: New test file
                          • WHEN a pull request adds tests/test_x.nim
                          • THEN the test job runs it as part of tests/all.nim, with no list to update
                          Lib version follows the crate sources

                          CI SHALL fail when the crate sources differ from those at the tag lib-v<version> for the version in Cargo.toml, unless that version ends in -dev.

                          Scenario: Rust change without a version bump
                          • WHEN a pull request changes src/rust/src/lib.rs and Cargo.toml still says
                          • 0.1.0, which has a lib-v0.1.0 tag
                          • THEN CI fails and says to set the version to the next -dev version
                          Fast linking

                          Builds in the repository SHALL link with lld, without debug info, on Linux when ld.lld is installed, unless -d:nanuqKeepDebugInfo is given. CI SHALL make sure lld is installed.

                          Scenario: Linking a test program
                          • WHEN CI links a program against the static Polars library
                          • THEN it uses lld and the link takes about a second, not about nine
                          cloud-storage3 requirements

                          Purpose: Reading and writing object stores (S3, Google Cloud Storage, Azure, HTTP) by URI, with Python's storage options.

                          Cloud URIs

                          Every scan* and read* function for CSV, Parquet, IPC and NDJSON files SHALL accept a cloud URI (s3://, gs://, az://, abfss://, hf://, http://, https://) in place of a local path, globs included. isCloudPath(path) SHALL tell such URIs from local paths.

                          echo isCloudPath("s3://polar-bears/census.parquet")
                          echo isCloudPath("https://example.org/bears.csv")
                          echo isCloudPath("data/bears.csv")
                          true
                          true
                          false
                          Scenario: HTTP
                          • WHEN readParquet("http://127.0.0.1:<port>/bears.parquet") runs against a local
                          • HTTP server
                          • THEN the frame equals the file's
                          Storage options

                          The cloud-capable reads, scans, writes and sinks SHALL take storageOptions, key/value pairs as Python's storage_options (aws_region, aws_endpoint_url, google_service_account, azure_storage_account_name, ...). Without them, credentials SHALL come from the environment as in Polars. Unknown keys SHALL be ignored, as in Polars; a failed request SHALL raise IOError.

                          let opts = {"aws_region": "eu-west-1", "aws_skip_signature": "true"}
                          let lf = scanParquet("s3://polar-bears/census.parquet", storageOptions = opts)
                          echo lf is LazyFrame
                          true
                          Scenario: Missing bucket
                          • WHEN readParquet("s3://no-such-bucket/x.parquet", storageOptions = opts) runs
                          • against a local S3
                          • THEN IOError is raised
                          Writing to object stores

                          writeParquet, writeCsv, writeIpc, writeNdjson and the sinks (also partitioned) SHALL write to a cloud URI, with storageOptions; the eager writes SHALL go through a streaming sink.

                          let df = newDataFrame(series("bear", @["Ada", "Bo"]), series("kg", @[410, 380]))
                          let opts = {"aws_endpoint_url": "http://127.0.0.1:9000", "aws_allow_http": "true"}
                          let sink = df.lazy.sinkParquet("s3://polar-bears/out.parquet", lazy = true,
                                                         storageOptions = opts)
                          echo sink is LazyFrame  # collect(sink) writes the file
                          true
                          Scenario: S3 round trip
                          • WHEN a frame is written to s3://nanuq/bears.parquet on a local S3 (moto) and read
                          • back with the same storageOptions
                          • THEN the frames are equal
                          column-selectors6 requirements

                          Purpose: Selecting several columns at once, by Nim type, by name, by regex or all of them, minus excluded names, and renaming the outputs of such expressions.

                          Selecting by Nim type

                          col SHALL accept Nim types and typeclasses and return a Selector.

                          • SomeNumber, SomeInteger, SomeSignedInt, SomeUnsignedInt and SomeFloat SHALL select the matching Polars dtype category.
                          • A concrete type SHALL select the dtype dataType gives it.
                          • Several types SHALL select their union.
                          • A type without a dtype SHALL not compile.
                          let df = newDataFrame(series("station", ["N", "S"]), series("bears", [3, 5]),
                                                series("weight", [410.5, 380.0]))
                          echo df.select(col(SomeNumber)).columns
                          echo df.select(col(float, string)).columns
                          @["bears", "weight"]
                          @["station", "weight"]
                          Scenario: Numeric columns
                          • WHEN select(col(SomeNumber)) runs on columns station (str), bears (i64) and weight (f64)
                          • THEN the result has columns bears and weight
                          Scenario: Exact types
                          • WHEN select(col(float, string)) runs on the same frame
                          • THEN the result has columns station and weight
                          Scenario: Not a column type
                          • WHEN col(seq[int]) is compiled
                          • THEN compilation fails
                          Selecting by name

                          col(a, b, ...) with two or more names, and col(names) with an openArray[string], SHALL return a Selector for those columns in that order, and all() SHALL select every column. col with one name SHALL keep returning an Expr, and a name that starts with ^ and ends with $ SHALL be a regex.

                          let df = newDataFrame(series("weight_kg", [410.5]), series("weight_lb", [905.0]),
                                                series("name", ["Nanuq"]))
                          echo df.select(col("^weight_.*$")).columns    # regex
                          echo df.select(col("name", "weight_kg")).columns
                          echo df.select(all()).columns
                          let wanted = @["weight_lb", "name"]
                          echo df.select(col(wanted)).columns
                          @["weight_kg", "weight_lb"]
                          @["name", "weight_kg"]
                          @["weight_kg", "weight_lb", "name"]
                          @["weight_lb", "name"]
                          Scenario: Regex
                          • WHEN select(col("^weight_.*$")) runs on columns weight_kg, weight_lb and name
                          • THEN the result has columns weight_kg and weight_lb
                          Scenario: Names from a seq
                          • WHEN select(col(@["c", "a"])) runs on columns a, b and c
                          • THEN the result has columns c and a
                          Excluding columns

                          Selector SHALL support exclude(names: varargs[string]), which removes the named columns from the selection.

                          let df = newDataFrame(series("id", [1]), series("a", [2]), series("b", [3]))
                          echo df.select(all().exclude("id")).columns
                          @["a", "b"]
                          Scenario: All but one
                          • WHEN select(all().exclude("id")) runs on columns id, a and b
                          • THEN the result has columns a and b
                          Selectors as expressions

                          A Selector SHALL convert to Expr automatically. An expression built from it SHALL apply to every selected column and keep each column's name.

                          let df = newDataFrame(series("station", ["N", "N", "S"]), series("bears", [3, 5, 4]),
                                                series("cubs", [1, 0, 2]), series("weight", [410.5, 380.0, 300.0]))
                          echo df.lazy.groupBy(col("station"))
                            .agg(col(SomeNumber).exclude("cubs").mean)
                            .sort("station").collect
                          shape: (2, 3)
                          ┌─────────┬───────┬────────┐
                          │ station ┆ bears ┆ weight │
                          │ ---     ┆ ---   ┆ ---    │
                          │ str     ┆ f64   ┆ f64    │
                          ╞═════════╪═══════╪════════╡
                          │ N       ┆ 4.0   ┆ 395.25 │
                          │ S       ┆ 4.0   ┆ 300.0  │
                          └─────────┴───────┴────────┘
                          Scenario: Mean per group of every numeric column but one
                          • WHEN a frame is grouped by station and aggregated with col(SomeNumber).exclude("cubs").mean
                          • THEN the result has station and one mean column per remaining numeric column, with the original names
                          Output name suffix and prefix

                          Expr SHALL support name.suffix(s) and name.prefix(s), which append or prepend s to the name of every column the expression produces.

                          let df = newDataFrame(series("a", [1.0, 3.0]), series("b", [2.0, 4.0]))
                          echo df.select(col(SomeFloat).mean.name.suffix("_mean"),
                                         col(SomeFloat).max.name.prefix("max_"))
                          shape: (1, 4)
                          ┌────────┬────────┬───────┬───────┐
                          │ a_mean ┆ b_mean ┆ max_a ┆ max_b │
                          │ ---    ┆ ---    ┆ ---   ┆ ---   │
                          │ f64    ┆ f64    ┆ f64   ┆ f64   │
                          ╞════════╪════════╪═══════╪═══════╡
                          │ 2.0    ┆ 3.0    ┆ 3.0   ┆ 4.0   │
                          └────────┴────────┴───────┴───────┘
                          Scenario: Two aggregations of one selector
                          • WHEN agg(col(SomeFloat).mean.name.suffix("_mean"), col(SomeFloat).max.name.suffix("_max")) runs on float columns a and b
                          • THEN the result has columns a_mean, b_mean, a_max and b_max
                          Operators on selectors

                          Arithmetic, comparison and logical operators SHALL accept a selector (all(), col("a", "b"), col(SomeNumber)) on either side, applying to each selected column and keeping its name; a comparison with a value on the left SHALL be mirrored (0 < x is x > 0), so the result keeps the column's name.

                          let df = newDataFrame(series("a", @[1, -1]), series("b", @[0, 2]))
                          echo df.select((all() > 0).name.suffix(" > 0"))
                          echo df.select(0 < col("a"))
                          shape: (2, 2)
                          ┌───────┬───────┐
                          │ a > 0 ┆ b > 0 │
                          │ ---   ┆ ---   │
                          │ bool  ┆ bool  │
                          ╞═══════╪═══════╡
                          │ true  ┆ false │
                          │ false ┆ true  │
                          └───────┴───────┘
                          shape: (2, 1)
                          ┌───────┐
                          │ a     │
                          │ ---   │
                          │ bool  │
                          ╞═══════╡
                          │ true  │
                          │ false │
                          └───────┘
                          Scenario: Selector times a number
                          • WHEN all() * 2 is selected
                          • THEN every column is doubled and keeps its name
                          combining-frames3 requirements

                          Purpose: How Nanuq combines frames: joins of two frames on keys (or a cross join), and concatenation of several frames vertically, horizontally or diagonally.

                          Joins

                          The API SHALL join two LazyFrames or two DataFrames with join, with how one of a JoinType: Inner (default), Left, Right, Full, Semi, Anti or Cross. Keys SHALL be given as on (same names on both sides) or leftOn and rightOn, as column names or expressions. A cross join SHALL take no keys.

                          let bears = newDataFrame(series("k", [1, 2, 3]), series("bear", ["Nanuq", "Ursa", "Kuma"]))
                          let seen = newDataFrame(series("k", [1, 3]), series("where", ["ice", "shore"]))
                          echo bears.join(seen, on = ["k"], how = Left, maintainOrder = Left)
                          echo bears.join(seen, on = ["k"], how = Anti)
                          shape: (3, 3)
                          ┌─────┬───────┬───────┐
                          │ k   ┆ bear  ┆ where │
                          │ --- ┆ ---   ┆ ---   │
                          │ i64 ┆ str   ┆ str   │
                          ╞═════╪═══════╪═══════╡
                          │ 1   ┆ Nanuq ┆ ice   │
                          │ 2   ┆ Ursa  ┆ null  │
                          │ 3   ┆ Kuma  ┆ shore │
                          └─────┴───────┴───────┘
                          shape: (1, 2)
                          ┌─────┬──────┐
                          │ k   ┆ bear │
                          │ --- ┆ ---  │
                          │ i64 ┆ str  │
                          ╞═════╪══════╡
                          │ 2   ┆ Ursa │
                          └─────┴──────┘
                          Scenario: Left join
                          • WHEN a frame with keys 1, 2, 3 is left-joined on k to a frame with keys 1, 3
                          • THEN the result has three rows, and the right side's columns are null for key 2
                          Scenario: Semi and anti
                          • WHEN the same frames are semi-joined and anti-joined
                          • THEN the semi join keeps the rows with keys 1 and 3, and the anti join keeps the row with key 2, with only the left columns
                          Scenario: Different key names
                          • WHEN frames are joined with leftOn = ["id"] and rightOn = ["station_id"]
                          • THEN rows are matched on those columns
                          Scenario: Cross join
                          • WHEN a 2-row frame is joined to a 3-row frame with how = Cross
                          • THEN the result has 6 rows
                          Scenario: Keys missing
                          • WHEN join is called without keys and a join type other than Cross
                          • THEN PolarsError is raised
                          Join options

                          join SHALL accept, with Polars' defaults: suffix ("_right") for clashing column names, validate (JoinValidation: ManyToMany, or ManyToOne, OneToMany, OneToOne), nullsEqual (false), coalesce (none(bool) for Polars' per-join-type default) and maintainOrder (MaintainOrderJoin: None, or Left, Right, LeftRight, RightLeft).

                          let a = newDataFrame(series("k", [1, 2]), series("v", [10, 20]))
                          let b = newDataFrame(series("k", [1, 2]), series("v", [100, 200]))
                          echo a.join(b, on = ["k"], suffix = "_b", validate = OneToOne, maintainOrder = Left)
                          shape: (2, 3)
                          ┌─────┬─────┬─────┐
                          │ k   ┆ v   ┆ v_b │
                          │ --- ┆ --- ┆ --- │
                          │ i64 ┆ i64 ┆ i64 │
                          ╞═════╪═════╪═════╡
                          │ 1   ┆ 10  ┆ 100 │
                          │ 2   ┆ 20  ┆ 200 │
                          └─────┴─────┴─────┘
                          Scenario: Suffix
                          • WHEN both frames have a non-key column v and suffix = "_b"
                          • THEN the result has columns v and v_b
                          Scenario: Validation failure
                          • WHEN the right frame has a duplicate key and validate = ManyToOne
                          • THEN PolarsError is raised when the query runs
                          Scenario: Null keys
                          • WHEN both frames have a null key, joined with nullsEqual = true
                          • THEN the null keys match each other; with the default they don't
                          Scenario: Keep left order
                          • WHEN a left join runs with maintainOrder = Left
                          • THEN the result rows follow the left frame's order
                          Concatenation

                          The API SHALL concatenate a list of LazyFrames or DataFrames with concat, with how a ConcatMethod: Vertical (default, same schema), VerticalRelaxed (cast to common supertypes), Horizontal (side by side), Diagonal (union of columns, missing ones null) or DiagonalRelaxed. An empty list SHALL raise PolarsError.

                          let ab = newDataFrame(series("a", [1]), series("b", [2]))
                          let bc = newDataFrame(series("b", [3]), series("c", [4]))
                          echo concat([ab, bc], how = Diagonal)
                          shape: (2, 3)
                          ┌──────┬─────┬──────┐
                          │ a    ┆ b   ┆ c    │
                          │ ---  ┆ --- ┆ ---  │
                          │ i64  ┆ i64 ┆ i64  │
                          ╞══════╪═════╪══════╡
                          │ 1    ┆ 2   ┆ null │
                          │ null ┆ 3   ┆ 4    │
                          └──────┴─────┴──────┘
                          Scenario: Vertical
                          • WHEN two frames with the same columns and 2 and 3 rows are concatenated
                          • THEN the result has 5 rows in input order
                          Scenario: Vertical with different types
                          • WHEN frames whose column a is i64 in one and f64 in the other are concatenated
                          • THEN Vertical raises PolarsError and VerticalRelaxed returns a as f64
                          Scenario: Diagonal
                          • WHEN a frame with columns a, b and one with b, c are concatenated diagonally
                          • THEN the result has columns a, b, c, with nulls where a frame had no column
                          Scenario: Horizontal
                          • WHEN a frame with column a and one with column b are concatenated horizontally
                          • THEN the result has columns a and b
                          csv-io6 requirements

                          Purpose: Reading and writing CSV files: lazy scans of a file or a glob, eager reads, and the named read and write options, following Polars' names and defaults.

                          Scanning CSV

                          The API SHALL provide scanCsv(path, ...), which returns a LazyFrame without reading the file until the query runs. path SHALL accept a glob that matches several files with the same columns. A glob whose files have different columns SHALL raise PolarsError when the query runs.

                          let dir = getTempDir() / "census"
                          createDir dir
                          writeFile(dir / "week_01.csv", "station,bears\nNorth,3\nSouth,5\n")
                          writeFile(dir / "week_02.csv", "station,bears\nNorth,4\nSouth,2\nEast,1\n")
                          let weeks = scanCsv(dir / "*.csv")         # nothing is read yet
                          echo weeks.groupBy(col("station")).agg(col("bears").sum).sort("station").collect
                          shape: (3, 2)
                          ┌─────────┬───────┐
                          │ station ┆ bears │
                          │ ---     ┆ ---   │
                          │ str     ┆ i64   │
                          ╞═════════╪═══════╡
                          │ East    ┆ 1     │
                          │ North   ┆ 7     │
                          │ South   ┆ 7     │
                          └─────────┴───────┘
                          Scenario: A folder of logs
                          • WHEN scanCsv(dir / "*.csv").collect runs on two files with the same columns and 2 and 3 rows
                          • THEN the result has 5 rows
                          CSV read options

                          readCsv and scanCsv SHALL take these named options with Polars' defaults:

                          • separator = ',' and hasHeader = true
                          • nullValues and schemaOverrides ((string, DataType) pairs)
                          • skipRows = 0, nRows = none(int) and columns (all when empty)
                          • inferSchemaLength = some(100), where none scans all rows
                          • ignoreErrors = false and decimalComma = false
                          • tryParseDates = false, which reads ISO dates, datetimes and times as temporal columns

                          nRows and inferSchemaLength SHALL also accept a plain int.

                          let path = getTempDir() / "survey.csv"
                          writeFile(path, "Polar survey 2026\nexported by hand\nstation;bears;weight\n" &
                                          "North;3;410\nSouth;lots;380\nEast;1;355\n")
                          echo readCsv(path, separator = ';', skipRows = 2, nRows = 2, nullValues = ["lots"],
                                       schemaOverrides = {"weight": Float64}, columns = ["station", "weight", "bears"])
                          let stages = getTempDir() / "stages.csv"
                          writeFile(stages, "stage,day,start\n1,2026-07-04,13:10:00\n2,2026-07-05,12:45:00\n")
                          echo readCsv(stages, tryParseDates = true).schema
                          shape: (2, 3)
                          ┌─────────┬────────┬───────┐
                          │ station ┆ weight ┆ bears │
                          │ ---     ┆ ---    ┆ ---   │
                          │ str     ┆ f64    ┆ i64   │
                          ╞═════════╪════════╪═══════╡
                          │ North   ┆ 410.0  ┆ 3     │
                          │ South   ┆ 380.0  ┆ null  │
                          └─────────┴────────┴───────┘
                          {"stage": Int64, "day": Date, "start": TimeOfDay}
                          Scenario: Semicolons and null words
                          • WHEN a file with ; separators and the value "lots" is read with separator = ';', nullValues = ["lots"]
                          • THEN the columns are split at ; and "lots" is null
                          Scenario: Override a dtype
                          • WHEN a column of whole numbers is read with schemaOverrides = {"n": Float64}
                          • THEN dtype("n") == Float64
                          Scenario: Preamble and limit
                          • WHEN a file with two preamble lines and 10 data rows is read with skipRows = 2, nRows = 3
                          • THEN the header is the third line and the result has 3 rows
                          Scenario: Columns
                          • WHEN a file with columns a, b and c is read with columns = ["c", "a"]
                          • THEN the result has columns c and a
                          Scenario: Dates
                          • WHEN a column of ISO dates is read with and without tryParseDates = true
                          • THEN its dtype is Date and String
                          CSV write options

                          writeCsv(df, path, ...) SHALL take these named options:

                          • separator = ',' and includeHeader = true
                          • nullValue = ""
                          • quoteStyle = Necessary, a pure enum QuoteStyle (Necessary, Always, NonNumeric, Never)
                          • floatPrecision = none(int) (also a plain int)
                          • decimalComma = false
                          let df = newDataFrame(series("bear", ["Nanuq", "Ursa"]),
                                                series("weight", [some(410.256), none(float)]))
                          let path = getTempDir() / "out.csv"
                          df.writeCsv(path, separator = ';', nullValue = "NA", floatPrecision = 1,
                                      decimalComma = true, quoteStyle = NonNumeric)
                          echo readFile(path)
                          "bear";"weight"
                          "Nanuq";410,3
                          "Ursa";NA
                          Scenario: Spreadsheet in a comma-decimal locale
                          • WHEN a frame with 1.5 is written with separator = ';', decimalComma = true and read back with the same options
                          • THEN the file holds 1,5 and the value read back is 1.5
                          Scenario: Quote everything
                          • WHEN a frame is written with quoteStyle = Always
                          • THEN every field in the file is quoted
                          Scenario: Null marker and precision
                          • WHEN a frame with a null and 3.14159 is written with nullValue = "NA", floatPrecision = 2
                          • THEN the file holds NA and 3.14
                          Reading CSV from a stream

                          readCsv SHALL also take a Nim Stream instead of a path, read all of it when called, and take every CSV read option.

                          import std/streams
                          let text = "station;bears\nNorth;3\nSouth;NA\n"
                          echo readCsv(newStringStream(text), separator = ';', nullValues = ["NA"])
                          shape: (2, 2)
                          ┌─────────┬───────┐
                          │ station ┆ bears │
                          │ ---     ┆ ---   │
                          │ str     ┆ i64   │
                          ╞═════════╪═══════╡
                          │ North   ┆ 3     │
                          │ South   ┆ null  │
                          └─────────┴───────┘
                          Scenario: Same options
                          • WHEN CSV text with ; separators and "NA" is read from a stream with separator = ';', nullValues = ["NA"]
                          • THEN the result equals reading the same text from a file with those options
                          Scenario: Empty stream
                          • WHEN an empty stream is read
                          • THEN NoDataError is raised
                          Quoting, encoding and new column names

                          readCsv and scanCsv SHALL take quoteChar = some('"') (none(char) turns quoting off), encoding = CsvEncoding.Utf8 (Utf8Lossy replaces invalid UTF-8 instead of raising) and newColumns, which renames the first columns.

                          import std/os
                          let path = getTempDir() / "lines.txt"
                          writeFile(path, "a \"quoted, line\nplain\n")
                          echo readCsv(path, separator = '\x01', hasHeader = false, quoteChar = none(char),
                                       newColumns = ["line"])
                          shape: (2, 1)
                          ┌─────────────────┐
                          │ line            │
                          │ ---             │
                          │ str             │
                          ╞═════════════════╡
                          │ a "quoted, line │
                          │ plain           │
                          └─────────────────┘
                          Scenario: Invalid UTF-8
                          • WHEN a line holds the byte 0xFF and encoding = CsvEncoding.Utf8Lossy
                          • THEN the line is read, with a replacement character
                          Comment lines

                          readCsv and scanCsv SHALL skip lines starting with commentPrefix (none when empty).

                          import std/streams
                          echo readCsv(newStringStream("# measured 2026\nbear,kg\nAda,410\n"), commentPrefix = "#")
                          shape: (1, 2)
                          ┌──────┬─────┐
                          │ bear ┆ kg  │
                          │ ---  ┆ --- │
                          │ str  ┆ i64 │
                          ╞══════╪═════╡
                          │ Ada  ┆ 410 │
                          └──────┴─────┘
                          Scenario: No prefix
                          • WHEN a CSV starting with "# note" is read without commentPrefix
                          • THEN "# note" is the first column name
                          cumulative-functions4 requirements

                          Purpose: Functions that compare each row with the rows before it: shifting, differences, relative change, running totals and records, run ids and peaks.

                          Shifting

                          e.shift(n = 1) SHALL move values down by n rows (up when n is negative), filling the rows left empty with null, or with fillValue when it is given. Inside over, the shift SHALL happen within each group.

                          let df = newDataFrame:
                            month: ["Jan", "Feb", "Mar", "Apr"]
                            anomaly: [0.5, 0.8, 1.2, 0.9]
                          echo df.withColumns(col.anomaly.shift.alias("before"),
                                              col.anomaly.shift(-1, fillValue = 0.0).alias("after"))
                          shape: (4, 4)
                          ┌───────┬─────────┬────────┬───────┐
                          │ month ┆ anomaly ┆ before ┆ after │
                          │ ---   ┆ ---     ┆ ---    ┆ ---   │
                          │ str   ┆ f64     ┆ f64    ┆ f64   │
                          ╞═══════╪═════════╪════════╪═══════╡
                          │ Jan   ┆ 0.5     ┆ null   ┆ 0.8   │
                          │ Feb   ┆ 0.8     ┆ 0.5    ┆ 1.2   │
                          │ Mar   ┆ 1.2     ┆ 0.8    ┆ 0.9   │
                          │ Apr   ┆ 0.9     ┆ 1.2    ┆ 0.0   │
                          └───────┴─────────┴────────┴───────┘
                          Scenario: Shift within groups
                          • WHEN col.x.shift.over(col.g) runs on groups a = 1, 2 and b = 3, 4
                          • THEN the result is null, 1, null, 3
                          Differences

                          e.diff(n = 1, nullBehavior = NullBehavior.Ignore) SHALL subtract from each value the value n rows above, with null where there is none; NullBehavior.Drop SHALL leave out those rows. e.pctChange(n = 1) SHALL return the relative change from the value n rows above.

                          let df = newDataFrame:
                            year: [2021, 2022, 2023, 2024]
                            temp: [14.8, 14.9, 15.1, 15.3]
                          echo df.select(col.year, col.temp.diff.round(2).alias("diff"),
                                         col.temp.pctChange.round(4).alias("pct"))
                          shape: (4, 3)
                          ┌──────┬──────┬────────┐
                          │ year ┆ diff ┆ pct    │
                          │ ---  ┆ ---  ┆ ---    │
                          │ i64  ┆ f64  ┆ f64    │
                          ╞══════╪══════╪════════╡
                          │ 2021 ┆ null ┆ null   │
                          │ 2022 ┆ 0.1  ┆ 0.0068 │
                          │ 2023 ┆ 0.2  ┆ 0.0134 │
                          │ 2024 ┆ 0.2  ┆ 0.0132 │
                          └──────┴──────┴────────┘
                          Scenario: Drop the first row
                          • WHEN diff(nullBehavior = Drop) runs on 1, 4, 9
                          • THEN the result is 3, 5
                          Cumulative functions

                          cumSum, cumProd, cumMin, cumMax and cumCount SHALL return the running sum, product, minimum, maximum and count of non-null values from the first row, or from the last row with reverse = true.

                          let df = newDataFrame:
                            rain: [3, 0, 7, 2]
                          echo df.withColumns(col.rain.cumSum.alias("total"), col.rain.cumMax.alias("wettest"),
                                              col.rain.cumSum(reverse = true).alias("still_to_come"))
                          shape: (4, 4)
                          ┌──────┬───────┬─────────┬───────────────┐
                          │ rain ┆ total ┆ wettest ┆ still_to_come │
                          │ ---  ┆ ---   ┆ ---     ┆ ---           │
                          │ i64  ┆ i64   ┆ i64     ┆ i64           │
                          ╞══════╪═══════╪═════════╪═══════════════╡
                          │ 3    ┆ 3     ┆ 3       ┆ 12            │
                          │ 0    ┆ 3     ┆ 3       ┆ 9             │
                          │ 7    ┆ 10    ┆ 7       ┆ 9             │
                          │ 2    ┆ 12    ┆ 7       ┆ 2             │
                          └──────┴───────┴─────────┴───────────────┘
                          Scenario: Running record
                          • WHEN cumMax runs on 3, 1, 5, 2
                          • THEN the result is 3, 3, 5, 5
                          Scenario: Count skips nulls
                          • WHEN cumCount runs on 1, null, 3
                          • THEN the result is 1, 1, 2
                          Runs and peaks

                          e.rleId SHALL number the runs of equal consecutive values, starting at 0 and growing by one each time the value changes. peakMax and peakMin SHALL be true at local maxima and minima.

                          let df = newDataFrame:
                            season: ["DJF", "JFM", "FMA", "MAM", "AMJ", "MJJ"]
                            warm: [true, true, false, false, true, true]
                          echo df.withColumns(col.warm.rleId.alias("run"))
                          shape: (6, 3)
                          ┌────────┬───────┬─────┐
                          │ season ┆ warm  ┆ run │
                          │ ---    ┆ ---   ┆ --- │
                          │ str    ┆ bool  ┆ u32 │
                          ╞════════╪═══════╪═════╡
                          │ DJF    ┆ true  ┆ 0   │
                          │ JFM    ┆ true  ┆ 0   │
                          │ FMA    ┆ false ┆ 1   │
                          │ MAM    ┆ false ┆ 1   │
                          │ AMJ    ┆ true  ┆ 2   │
                          │ MJJ    ┆ true  ┆ 2   │
                          └────────┴───────┴─────┘
                          Scenario: Run lengths
                          • WHEN rows are grouped by rleId of true, true, false, true and counted
                          • THEN the runs have lengths 2, 1 and 1
                          data-types6 requirements

                          Purpose: How Nanuq represents Polars data types in Nim (DataType), reads schemas, and casts columns and expressions.

                          DataType values

                          The API SHALL provide a DataType value with a kind of type DataTypeKind (a pure enum, see api-conventions) covering Boolean, Int8, Int16, Int32, Int64, UInt8, UInt16, UInt32, UInt64, Float32, Float64, String, Null, Date, Datetime, Duration, Time, Categorical and Enum, plus DataTypeKind.Other carrying Polars' name for any other dtype. Datetime and Duration values SHALL carry a timeUnit (std/times' TimeUnit: Nanoseconds, Microseconds or Milliseconds), Datetime values a timeZone ("" when naive), and Enum values their categories. dtype(df, col) SHALL return a DataType. dtype == T with a Nim type SHALL compare with dataType(T), except that DateTime and Duration SHALL match any time unit and zone. $ SHALL print a data type as the Nanuq code that builds or names it: the constant (Int64), the constructor (Enum(["low", "high"])), or for temporal types the Nim type a column casts to (Date, TimeOfDay, DateTime(Milliseconds, "Europe/Rome"), Duration(Microseconds)). Table headers, glimpse and toHtml SHALL keep Polars' short names (i64).

                          let df = newDataFrame(series("a", [1, 2]))
                          echo df.dtype("a")                  # as Nanuq code
                          echo df.dtype("a") == Int64
                          echo df.dtype("a").kind
                          let t = newDataFrame(series("at", [dateTime(2026, mJul, 4, zone = utc())],
                                                      timeUnit = Milliseconds, timeZone = "Europe/Rome"))
                          echo t.dtype("at"), " ", t.dtype("at").timeZone, " ", t.dtype("at") == DateTime
                          Int64
                          true
                          Int64
                          DateTime(Milliseconds, "Europe/Rome") Europe/Rome true
                          Scenario: Column dtype
                          • WHEN a DataFrame is built from a Nim seq[int] column a
                          • THEN df.dtype("a") == Int64 and $df.dtype("a") == "Int64"
                          Scenario: Unmodelled dtype
                          • WHEN a column has a dtype Nanuq does not model
                          • THEN its kind is DataTypeKind.Other and $ returns Polars' name for it
                          Scenario: Zoned datetime
                          • WHEN a Datetime column has unit ms and zone Europe/Rome
                          • THEN $ gives DateTime(Milliseconds, "Europe/Rome") and it equals DateTime
                          Scenario: Enum categories
                          • WHEN a column is cast to Enum(["low", "high"])
                          • THEN $ of its dtype gives Enum(["low", "high"]) and categories is @["low", "high"]
                          Scenario: Tables keep short names
                          • WHEN a frame with an Int64 column is printed or turned into HTML
                          • THEN the column header shows i64
                          DataType constants and predicates

                          The API SHALL export DataType constants with Polars' names (Int64, String, ...), ==, $ printing the constant's name, and the predicates isInteger, isSignedInteger, isUnsignedInteger, isFloat and isNumeric.

                          echo UInt8.isNumeric, " ", Float32.isFloat, " ", String.isNumeric
                          true true false
                          Scenario: Predicates
                          • WHEN isNumeric is called on UInt8, Float32 and String
                          • THEN it returns true, true and false
                          Schemas

                          The API SHALL return the column names and dtypes of a DataFrame (schema) and of a LazyFrame without collecting it (collectSchema) as a Schema, an OrderedTable[string, DataType] in column order, and the dtypes alone with dtypes.

                          let df = newDataFrame(series("a", [1, 2]), series("b", ["x", "y"]))
                          echo df.schema
                          echo df.lazy.withColumns((col("a") * 1.5).alias("c")).collectSchema   # nothing runs
                          {"a": Int64, "b": String}
                          {"a": Int64, "b": String, "c": Float64}
                          Scenario: Schema in column order
                          • WHEN schema is called on a DataFrame with columns a (i64) and b (str)
                          • THEN the keys are a, b in that order and the values are Int64, String
                          Scenario: Lazy schema
                          • WHEN collectSchema is called on a LazyFrame that adds (col("a") * 1.5).alias("c")
                          • THEN the schema has c with Float64, and the query is not executed
                          Casting

                          The API SHALL cast expressions (e.cast(target, strict = true)), all columns of a DataFrame or LazyFrame (cast(target, strict = true)), where target is a Nim type or a DataType, and named columns (cast({"a": Int32}, strict = true)) with DataType values. Temporal Nim targets (Date, DateTime, Duration, TimeOfDay) SHALL take timeUnit = Microseconds and, for DateTime, timeZone = "". A strict cast SHALL raise PolarsError (when the query runs) if a value cannot be converted; a non-strict cast SHALL turn such values into nulls. Casting to a DataTypeKind.Other dtype SHALL raise PolarsError.

                          let df = newDataFrame(series("a", [1, 2]), series("s", ["1", "x"]))
                          echo df.cast({"a": Int32}).dtype("a")
                          echo df.select(col("a").cast(float32)).dtype("a")
                          echo df.select(col("s").cast(Int64, strict = false))
                          echo df.select(col("a").cast(DateTime, timeUnit = Milliseconds, timeZone = "UTC")).dtype("a")
                          Int32
                          Float32
                          shape: (2, 1)
                          ┌──────┐
                          │ s    │
                          │ ---  │
                          │ i64  │
                          ╞══════╡
                          │ 1    │
                          │ null │
                          └──────┘
                          DateTime(Milliseconds, "UTC")
                          Scenario: Narrow an integer column
                          • WHEN df.cast({"a": Int32}) runs on an i64 column
                          • THEN dtype("a") == Int32 and toList(df, "a", int) returns the same values
                          Scenario: Nim type as target
                          • WHEN col("a").cast(float32) is selected from an i64 column
                          • THEN the result column has dtype Float32
                          Scenario: Strict failure
                          • WHEN a string column holding "1" and "x" is cast to Int64 with strict = true
                          • THEN PolarsError is raised
                          Scenario: Non-strict cast
                          • WHEN the same column is cast with strict = false
                          • THEN the result is 1 and null
                          Scenario: Integers to dates
                          • WHEN a column of microseconds [0, 86_400_000_000] is cast to DateTime and then to Date
                          • THEN the result is 1970-01-01 and 1970-01-02
                          Nim types map to DataType

                          dataType(T) SHALL map int8 to int64, uint8 to uint64, float32, float64, bool and string to their dtypes, int to Int64 and float to Float64. dataType(T, timeUnit = Microseconds, timeZone = "") SHALL map Date, DateTime, std/times' Duration and TimeOfDay to Date, Datetime, Duration and Time. A Nim enum SHALL map to an Enum of $ of its values. seq[T] SHALL map to a List, array[N, T] to an Array and objects and named tuples to a Struct of their fields, at any depth. Other types SHALL not compile.

                          type Medal = enum Gold, Silver, Bronze
                          echo dataType(int), " ", dataType(float32), " ", dataType(uint8), " ", dataType(string)
                          echo dataType(Date), " ", dataType(DateTime), " ", dataType(Duration, Nanoseconds), " ", dataType(TimeOfDay)
                          echo dataType(Medal), " ", dataType(Medal).categories
                          echo dataType(seq[string]), " ", dataType(array[3, float]), " ", dataType(tuple[x: int, tags: seq[string]]).fields
                          Int64 Float32 UInt8 String
                          Date DateTime(Microseconds) Duration(Nanoseconds) TimeOfDay
                          Enum(["Gold", "Silver", "Bronze"]) @["Gold", "Silver", "Bronze"]
                          List(String) Array(Float64, 3) @[(name: "x", dtype: Int64), (name: "tags", dtype: List(String))]
                          Scenario: Platform int
                          • WHEN dataType(int) is evaluated
                          • THEN it equals Int64, the dtype series builds from seq[int]
                          Scenario: Unsupported type
                          • WHEN col("a").cast(ref int) is compiled
                          • THEN compilation fails
                          Scenario: Unsupported unit
                          • WHEN dataType(DateTime, Seconds) is evaluated
                          • THEN ValueError is raised
                          Scenario: Nim enum
                          • WHEN dataType(Medal) is evaluated for enum Gold, Silver, Bronze
                          • THEN it equals Enum(["Gold", "Silver", "Bronze"])
                          Scenario: Nested Nim types
                          • WHEN dataType(seq[seq[int]]) is evaluated
                          • THEN it equals List(List(Int64))
                          Full-range UInt64

                          UInt64 columns SHALL keep all 64 bits between Nim and Polars: series(name, seq[uint64]) (with or without Option) and toList(uint64) SHALL handle values above high(int64).

                          let df = newDataFrame(series("key", @[1'u64, 9223372036854775809'u64]))
                          echo df.toList("key", uint64)
                          echo df.select(col("key").bitwiseXor)
                          @[1, 9223372036854775809]
                          shape: (1, 1)
                          ┌─────────────────────┐
                          │ key                 │
                          │ ---                 │
                          │ u64                 │
                          ╞═════════════════════╡
                          │ 9223372036854775808 │
                          └─────────────────────┘
                          Scenario: Nulls
                          • WHEN series("u", [some(x), none(uint64)]) is built
                          • THEN the second value is null
                          database-io2 requirements

                          Purpose: Reading query results from SQLite and writing frames to it, in the optional module nanuq/database (on db_connector).

                          Writing to a database

                          writeDatabase(df, tableName, connection, ifTableExists = IfTableExists.Fail) in nanuq/database SHALL write the frame's rows to a SQLite table, creating it with column types from the frame (integers and booleans INTEGER, floats REAL, Binary BLOB, the rest TEXT), and return the number of rows written. An existing table SHALL raise ValueError with Fail, be dropped first with Replace, and receive the rows with Append.

                          import nanuq/database, db_connector/db_sqlite
                          let db = open(":memory:", "", "", "")
                          let df = newDataFrame(series("bear", @["Ada", "Bo"]), series("kg", @[410, 380]))
                          echo df.writeDatabase("bears", db)
                          echo df.writeDatabase("bears", db, IfTableExists.Append)
                          2
                          2
                          Scenario: Table exists
                          • WHEN a frame is written to an existing table with IfTableExists.Fail
                          • THEN ValueError is raised and the table is unchanged
                          Reading from a database

                          readDatabase(query, connection, schemaOverrides = []) SHALL run a query on an open SQLite connection and return its rows, with INTEGER values as Int64, REAL (or mixed numbers) as Float64, TEXT as String and BLOB as Binary, and a column of only nulls typed from its declared type. readDatabaseUri(query, "sqlite:///path") SHALL open the database for the query and close it.

                          import nanuq/database, db_connector/db_sqlite
                          let db = open(":memory:", "", "", "")
                          discard newDataFrame(series("bear", @["Ada", "Bo"]), series("kg", @[410.5, 380.0])).writeDatabase("bears", db)
                          echo readDatabase("select bear, kg * 2 as double from bears where kg > 400", db)
                          shape: (1, 2)
                          ┌──────┬────────┐
                          │ bear ┆ double │
                          │ ---  ┆ ---    │
                          │ str  ┆ f64    │
                          ╞══════╪════════╡
                          │ Ada  ┆ 821.0  │
                          └──────┴────────┘
                          Scenario: Bad query
                          • WHEN the query names a table that does not exist
                          • THEN IOError is raised
                          Scenario: Other URIs
                          • WHEN readDatabaseUri gets a postgres:// URI
                          • THEN ValueError is raised
                          dataframe-api9 requirements

                          Purpose: The Nim-facing API in src/nanuq.nim: DataFrame, LazyFrame and Expr values backed by Polars, with automatic memory management and Nim exceptions.

                          Automatic memory management

                          DataFrame, LazyFrame, Expr and Series SHALL be Nim ref types whose destructors free the underlying Rust object when the last reference goes away. Copying the inner objects SHALL be a compile-time error.

                          var a = newDataFrame(series("n", [1, 2]))
                          let b = a          # same Polars frame, no copy
                          a = nil            # still alive through b
                          echo b.shape       # freed when b goes out of scope
                          (2, 1)
                          Scenario: Shared value
                          • WHEN two Nim variables refer to the same DataFrame
                          • THEN the Rust object is freed once, after both go out of scope
                          Building and reading data

                          The API SHALL build a DataFrame from Nim arrays of int, float, bool and string (series, newDataFrame), read and write CSV with a header row, and expose shape, columns, dtype, head, $ (Polars' table format), single cells and whole columns (toList).

                          let df = newDataFrame(series("bear", ["Nanuq", "Ursa"]), series("weight", [410.5, 380.0]))
                          echo df
                          echo df.shape, " ", df.columns, " ", df["bear", 0, string], " ", df.toList("weight", float)
                          shape: (2, 2)
                          ┌───────┬────────┐
                          │ bear  ┆ weight │
                          │ ---   ┆ ---    │
                          │ str   ┆ f64    │
                          ╞═══════╪════════╡
                          │ Nanuq ┆ 410.5  │
                          │ Ursa  ┆ 380.0  │
                          └───────┴────────┘
                          (2, 2) @["bear", "weight"] Nanuq @[410.5, 380.0]
                          Scenario: Columns of different lengths
                          • WHEN newDataFrame gets series of different lengths
                          • THEN PolarsError is raised
                          Scenario: No clash with sequtils
                          • WHEN a module imports nanuq and std/[os, sequtils] and calls toSeq(walkFiles("*.csv"))
                          • THEN it compiles and returns the matching paths
                          Reading columns by type

                          Reading as float SHALL accept any integer or float column; as string, any column, formatted as Polars does; as int, only integer columns; as bool, only boolean columns. A dtype that does not match SHALL raise PolarsError.

                          let df = newDataFrame(series("a", [1, 2]))
                          echo df.toList("a", float)     # integers widen to float
                          echo df.toList("a", string)    # any column formats as text
                          @[1.0, 2.0]
                          @["1", "2"]
                          Scenario: Integers read as floats
                          • WHEN an i64 column holding 1, 2 is read with toList(df, "a", float)
                          • THEN the result is @[1.0, 2.0]
                          Scenario: Floats are not truncated to int
                          • WHEN an f64 column is read with toList(df, "a", int)
                          • THEN PolarsError is raised
                          Scenario: Bool column
                          • WHEN a bool column is read with toList(df, "d", bool)
                          • THEN the result holds the column's values
                          Expressions and lazy queries

                          The API SHALL provide col, lit, arithmetic, comparison and boolean operators on Expr (lifting Nim literals automatically), the aggregations sum, mean, min, max, count, first, last, nUnique and std, and alias. LazyFrame SHALL support select, withColumns, filter, groupBy/agg, sort, limit, explain and collect. select and groupBy SHALL take expressions or column names (select("a", "b"), groupBy("species")); groupBy SHALL keep the groups in the order their keys first appear (Python's maintain_order=True, always on). On a DataFrame, groupBy, groupByDynamic and rolling followed by agg SHALL return a DataFrame, as in Python; on a LazyFrame they return a LazyFrame. DataFrame SHALL offer eager shortcuts for select, withColumns, filter and sort.

                          let query = penguins().lazy
                            .filter(col("body_mass_g").isNotNull)
                            .groupBy(col("species"))
                            .agg(col("body_mass_g").mean.alias("mass"), col("species").count.alias("n"))
                            .sort("mass", descending = true)
                          echo query.collect          # nothing runs before collect
                          shape: (3, 3)
                          ┌───────────┬─────────────┬─────┐
                          │ species   ┆ mass        ┆ n   │
                          │ ---       ┆ ---         ┆ --- │
                          │ str       ┆ f64         ┆ u32 │
                          ╞═══════════╪═════════════╪═════╡
                          │ Gentoo    ┆ 5076.01626  ┆ 123 │
                          │ Chinstrap ┆ 3733.088235 ┆ 68  │
                          │ Adelie    ┆ 3700.662252 ┆ 151 │
                          └───────────┴─────────────┴─────┘
                          Scenario: Eager group by
                          • WHEN df.groupBy("a").agg(col.v.sum) runs on a DataFrame
                          • THEN the result is a DataFrame, with no collect needed
                          Scenario: Select by name
                          • WHEN df.select("c", "a") runs
                          • THEN the result has columns c and a, in that order
                          Scenario: Keys by name
                          • WHEN df.groupBy("a", "b") is followed by agg
                          • THEN it groups as df.groupBy(col.a, col.b) does
                          Scenario: Group order
                          • WHEN a frame with keys b, a, b, c is grouped by the key
                          • THEN the groups come out as b, a, c
                          Scenario: Lazy group by
                          • WHEN a LazyFrame is filtered, grouped, aggregated and sorted
                          • THEN nothing runs until collect, which returns the resulting DataFrame
                          HTML tables

                          toHtml(df, maxRows = 10, maxCols = 75) SHALL return the HTML that Python Polars' DataFrame._repr_html_ returns for the same data and limits: shape line, names and dtypes header rows, cells formatted by Polars, and … rows and columns when truncated.

                          Scenario: Same as Python
                          • WHEN toHtml is called on penguins()
                          • THEN the result equals what Python Polars' _repr_html_ returns for the same CSV read with null_values="NA"
                          Scenario: Truncation
                          • WHEN a DataFrame with 344 rows is rendered with maxRows = 10
                          • THEN the body shows rows 0 to 4, a … row, and rows 339 to 343
                          Scenario: Escaping and nulls
                          • WHEN a string cell holds <b> and another cell is null
                          • THEN the first is shown as "&lt;b&gt;" and the second as null
                          Block syntax for building a DataFrame

                          newDataFrame SHALL accept a block of name: [values] lines and build one column per line, in order, as series(name, values) would. A name SHALL be a Nim identifier or a string literal. A nil inside the brackets SHALL be a missing value, and the column SHALL then have the type of its other values. newDataFrame SHALL keep accepting series (newDataFrame(series(...), ...), a seq of series, or none at all).

                          let df = newDataFrame:
                            rider: ["Pogačar", "Seixas", "Vingegaard"]
                            wins: [22, 8, nil]
                            "win %": [0.31, 0.12, 0.05]
                          echo df
                          shape: (3, 3)
                          ┌────────────┬──────┬───────┐
                          │ rider      ┆ wins ┆ win % │
                          │ ---        ┆ ---  ┆ ---   │
                          │ str        ┆ i64  ┆ f64   │
                          ╞════════════╪══════╪═══════╡
                          │ Pogačar    ┆ 22   ┆ 0.31  │
                          │ Seixas     ┆ 8    ┆ 0.12  │
                          │ Vingegaard ┆ null ┆ 0.05  │
                          └────────────┴──────┴───────┘
                          Scenario: Same frame as series
                          • WHEN a frame is built with the block syntax and the same frame with series calls
                          • THEN both have the same columns, dtypes and values
                          Scenario: nil is a null
                          • WHEN a line reads wins: [22, nil]
                          • THEN column "wins" is i64 with values 22 and null
                          Scenario: Only nil
                          • WHEN a line reads wins: [nil, nil]
                          • THEN the program fails to compile
                          Scenario: Empty frame
                          • WHEN newDataFrame() is called
                          • THEN the result has shape (0, 0)
                          Column shorthand

                          col.name SHALL be the same expression as col("name") for any column name that is a Nim identifier and not taken by Nim first (type, and generic system procs such as repr). Every other form of col SHALL keep working: col("a"), col("a", "b"), col(SomeNumber) and col(float, int). User code SHALL need no pragma to use them.

                          let df = newDataFrame:
                            race: ["Sanremo", "Lombardia"]
                            "end": [1, 2]
                          echo df.select(col.race, col.end, col("race", "end").count.name.suffix("_n"))
                          shape: (2, 4)
                          ┌───────────┬─────┬────────┬───────┐
                          │ race      ┆ end ┆ race_n ┆ end_n │
                          │ ---       ┆ --- ┆ ---    ┆ ---   │
                          │ str       ┆ i64 ┆ u32    ┆ u32   │
                          ╞═══════════╪═════╪════════╪═══════╡
                          │ Sanremo   ┆ 1   ┆ 2      ┆ 2     │
                          │ Lombardia ┆ 2   ┆ 2      ┆ 2     │
                          └───────────┴─────┴────────┴───────┘
                          Scenario: Same plan
                          • WHEN $col.race and $col("race") are compared
                          • THEN they are equal
                          Scenario: Names that are procs
                          • WHEN col.len and col.min are used
                          • THEN they select the columns "len" and "min"
                          True division

                          / on expressions SHALL be Polars' true division: the result SHALL be a float column even when both sides are integers, and a division by zero SHALL give inf or NaN, not null. div SHALL stay floor division.

                          let df = newDataFrame:
                            seconds: [7200, 5400, 0]
                          echo df.select(col.seconds, (col.seconds / 3600).alias("hours"),
                                         (col.seconds div 3600).alias("whole"), (col.seconds / 0).alias("by_zero"))
                          shape: (3, 4)
                          ┌─────────┬───────┬───────┬─────────┐
                          │ seconds ┆ hours ┆ whole ┆ by_zero │
                          │ ---     ┆ ---   ┆ ---   ┆ ---     │
                          │ i64     ┆ f64   ┆ i64   ┆ f64     │
                          ╞═════════╪═══════╪═══════╪═════════╡
                          │ 7200    ┆ 2.0   ┆ 2     ┆ inf     │
                          │ 5400    ┆ 1.5   ┆ 1     ┆ inf     │
                          │ 0       ┆ 0.0   ┆ 0     ┆ NaN     │
                          └─────────┴───────┴───────┴─────────┘
                          Scenario: Integers divide to a float
                          • WHEN lit(7) / 2 is evaluated
                          • THEN the result is 3.5 with dtype f64
                          Scenario: Floor division unchanged
                          • WHEN lit(7) div 2 is evaluated
                          • THEN the result is 3 with dtype i64
                          Errors as PolarsError

                          Any failing FFI call SHALL raise a PolarsError, or Nim's IOError for IO failures, carrying the message from Rust. The type SHALL follow the Rust PolarsError variant: ColumnNotFoundError, ComputeError, DuplicateError, InvalidOperationError, NoDataError, OutOfBoundsError, SchemaError, SchemaFieldNotFoundError, ShapeError, StructFieldNotFoundError and SqlError, all subtypes of PolarsError.

                          let df = newDataFrame(series("a", [1]), series("s", ["x"]))
                          try:
                            discard df.select(col("nope"))
                          except ColumnNotFoundError as e:
                            echo e.msg.splitLines[0]
                          try:
                            discard df.select(col("s").cast(int))
                          except PolarsError as e:
                            echo e.name
                          try:
                            discard readCsv("no/such/file.csv")
                          except IOError:
                            echo "IOError"
                          not found: unable to find column "nope"; valid columns: ["a", "s"]
                          InvalidOperationError
                          IOError
                          Scenario: Bad column
                          • WHEN a query selects a column that does not exist
                          • THEN ColumnNotFoundError is raised with the Polars error message
                          Scenario: Subtypes are PolarsErrors
                          • WHEN a strict cast fails and the code catches PolarsError
                          • THEN the handler runs, with an InvalidOperationError
                          Scenario: Missing file
                          • WHEN readCsv gets a path that does not exist
                          • THEN IOError is raised, and it is not a PolarsError
                          datamancer-interop4 requirements

                          Purpose: Converting DataFrames between Nanuq and Datamancer (nanuq/datamancer), so Datamancer and ggplotnim code can use Polars for queries. Datamancer stays an optional dependency.

                          To Datamancer

                          toDatamancer SHALL copy every column, in order and with its name, into a Datamancer DataFrame: integers as int, floats as float, booleans as bool, strings as string, and any other dtype as string formatted by Polars.

                          import nanuq/datamancer
                          let dm = penguins().dropNulls.toDatamancer    # a Datamancer DataFrame
                          echo dm.len
                          333
                          Scenario: Penguins without nulls
                          • WHEN penguins().dropNulls().toDatamancer is called
                          • THEN the result has 333 rows, the same column names in order, and body_mass_g is an int column
                          Nulls to Datamancer

                          A column with nulls SHALL become an object column whose missing entries are Datamancer null values and whose other entries hold the values.

                          Scenario: Body mass with nulls
                          • WHEN penguins().toDatamancer is called
                          • THEN body_mass_g is an object column with 2 null values, and drop_null on it leaves 342 rows
                          From Datamancer

                          fromDatamancer SHALL copy every column back in order: int to i64, float to f64, bool to bool, string to str, constant columns repeated, and object columns of one value kind plus nulls to that dtype with nulls. Other object columns SHALL raise PolarsError.

                          import nanuq/datamancer
                          let back = penguins().toDatamancer.fromDatamancer
                          echo back.shape, " ", back.nullCount("body_mass_g")
                          (344, 8) 2
                          Scenario: Round trip
                          • WHEN a Nanuq DataFrame is converted with toDatamancer and back with fromDatamancer
                          • THEN it has the same shape, columns, dtypes (for i64, f64, bool, str) and null counts
                          Scenario: Mixed object column
                          • WHEN a Datamancer object column holds both an int and a string
                          • THEN fromDatamancer raises PolarsError naming the column
                          Optional dependency

                          Importing nanuq SHALL NOT require Datamancer; only importing nanuq/datamancer does.

                          Scenario: Without Datamancer
                          • WHEN a program imports only nanuq on a machine without Datamancer
                          • THEN it compiles
                          datasets3 requirements

                          Purpose: Small, well-known datasets loadable with one call and no file path, for examples, tests and documentation. They are bundled for convenience during early development and are expected to move out of the library later.

                          Penguins dataset

                          nanuq/datasets SHALL provide penguins() returning the palmerpenguins table: 344 rows and the columns species, island, bill_length_mm, bill_depth_mm, flipper_length_mm, body_mass_g, sex and year, with "NA" fields as nulls.

                          let df = penguins()
                          echo df.shape
                          echo df.columns
                          echo df.nullCount("body_mass_g"), " ", df.nullCount("sex")
                          (344, 8)
                          @["species", "island", "bill_length_mm", "bill_depth_mm", "flipper_length_mm", "body_mass_g", "sex", "year"]
                          2 11
                          Scenario: Shape and columns
                          • WHEN penguins() is called
                          • THEN the result has shape (344, 8) and the columns listed above, in that order
                          Scenario: Missing values
                          • WHEN penguins() is called
                          • THEN nullCount is 2 for body_mass_g and 11 for sex, and body_mass_g is an integer column
                          Loading from any working directory

                          Bundled datasets SHALL load with no path from the caller and without using the network, whatever the program's working directory.

                          Scenario: Different working directory
                          • WHEN a compiled program calls penguins() from any working directory
                          • THEN the dataset loads
                          Licensing

                          Every bundled dataset SHALL ship with its source, credit and license in the repository, and SHALL be under a license that allows redistribution.

                          Scenario: Penguins credit
                          • WHEN someone looks for where penguins comes from
                          • THEN the data folder names palmerpenguins, its authors and CC0
                          dev-log6 requirements

                          Purpose: The Nanuq dev log: dated nimib posts in docs/blog, an index page, and the Nanuq theme they share. It is published with GitHub Pages and is separate from the official documentation that will come later.

                          Index of posts

                          The site root SHALL be an index page listing every rendered post in docs/blog, newest first, each with its date, title, one-line summary and a link to the post. Adding a post SHALL NOT require editing the index.

                          Scenario: New post
                          • WHEN a post docs/blog/x.nim writing 2026-11-02-x.html is added and CI renders the site
                          • THEN the index lists it first, dated 2 November 2026, with its title and summary
                          Scenario: Post without a summary
                          • WHEN a post does not set a summary
                          • THEN the index still lists it, with date and title only
                          Dated post files

                          Each post SHALL render to a file in docs/blog named YYYY-MM-DD-<slug>.html, and its URL SHALL stay the same once published.

                          Scenario: Existing links
                          • WHEN the index is introduced
                          • THEN the existing post URLs under blog/ keep working
                          Polars coverage page

                          The site SHALL publish a Polars coverage page at polars_coverage.html, linked from the index and the README, rendered from the data file docs/coverage/polars.json. The page SHALL describe the latest Nanuq release only: the data names that release and lists Polars feature groups by area with their Polars names, a status (has it, partly, missing, not planned), a note naming what is still missing, a priority for open groups, and a mark on the groups whose status changed in that release. When the next release has a plan, the data MAY name it and mark the open groups it plans; the page SHALL then show them. The page SHALL show the release totals, counts by area, the open groups by priority and the full catalogue, with the dev log's header and footer. Each release PR SHALL refresh the data for that release. The page is not a dated post and is not listed among the posts.

                          Scenario: A release refreshes the data
                          • WHEN the 0.7 release PR sets the release to 0.7, clears the old new-marks, and updates and marks the rows that 0.7 changed
                          • THEN the page shows only 0.7 statuses, with the changed groups marked as new in 0.7
                          Scenario: No plan for the next release
                          • WHEN the data names no next release
                          • THEN the page shows no Planned column
                          Scenario: Index link
                          • WHEN the site is rendered
                          • THEN the index links to the coverage page, and the page does not appear in the list of posts
                          OpenSpec page

                          The site SHALL publish an OpenSpec page at openspec.html, linked from the index, the coverage page and the README's "How development works", rendered by tools/specview.nim with the dev log's header and footer: every change (archived ones hidden until the reader asks for them) and every spec in openspec/specs/ in full. The page is rebuilt from the repository each time the site is, so it shows the specs and changes on main. It is not a dated post and is not listed among the posts.

                          Scenario: A change is archived
                          • WHEN a pull request that archives a change into openspec/specs/ is merged
                          • THEN the published OpenSpec page shows the updated spec and lists the change as archived
                          Scenario: Index link
                          • WHEN the site is rendered
                          • THEN the index links to the OpenSpec page, and the page does not appear in the list of posts
                          Review mode

                          Every page rendered with the Nanuq theme SHALL have the review mode of docs/review.nim (from tabelline, until nimib has it), unless the page passes review = false: a version line in the masthead (Version N · updated D, N being the commits that touched the page's source) with ✎ Review, which opens a mode where the reader selects text, comments on it, and exports the comments as Markdown with a YAML block (nimib-review format) naming the page, its source, its version and commit. The page SHALL stay readable at phone width in both modes, light and dark.

                          Scenario: Reviewing a post on a phone
                          • WHEN a reader opens a post on a phone, taps ✎ Review, selects a sentence and writes a note
                          • THEN the sentence is marked, the note is kept in the browser, and Export gives a text
                          • naming the post's source (docs/blog/<post>.nim), its version and the quoted sentence
                          Scenario: A new commit
                          • WHEN a commit changes a post's source and the site is built again
                          • THEN the post's version goes up by one, and its comments start empty
                          Source files

                          A page that mentions source files of the repository SHALL fold them (whole, or the part it discusses) in a "Source files" section at its end, made with nbSourceFiles and nbFoldCode (from tabelline): each under its path or a title, with its number of lines. The top of the page SHALL point to the section, every file name shown as code in the text SHALL link to its fold, and following such a link SHALL open the fold.

                          Scenario: Reading a file a post names
                          • WHEN a reader taps ffi.nim in the text of a post
                          • THEN the page goes to the fold of src/nanuq/ffi.nim in "Source files", opened
                          excel-io3 requirements

                          Purpose: Reading and writing Excel workbooks with pure-Rust crates compiled into the Nanuq library (no Python, no system dependency).

                          Writing Excel

                          writeExcel(df, path, worksheet = "Sheet1", includeHeader = true, autofit = false, floatPrecision = none(int)) SHALL write the frame to one worksheet of a new .xlsx file: a header row, then numbers, booleans, dates and datetimes as Excel values and other values as text; nulls SHALL be empty cells.

                          let path = getTempDir() / "bears.xlsx"
                          let df = newDataFrame(series("bear", @["Ada", "Bo"]), series("kg", @[410.5, 380.0]),
                                                series("seen", @[date(2024, 3, 1), date(2024, 3, 9)]))
                          df.writeExcel(path, worksheet = "census")
                          echo fileExists(path)
                          true
                          Scenario: Missing directory
                          • WHEN the target directory does not exist
                          • THEN IOError is raised
                          Reading Excel

                          readExcel(path, sheetName = "", sheetId = 1, hasHeader = true, headerRow = 0, skipRows = 0, columns = [], schemaOverrides = []) SHALL read one sheet (by name, else by position from 1) of an .xlsx, .xlsm, .xlsb, .xls or .ods file. Row headerRow SHALL hold the column names, and skipRows rows SHALL be skipped after it (from the top when hasHeader = false), as Python's default engine (fastexcel) does. Column types SHALL be inferred from the cells: Boolean, Int64 for whole numbers, Float64, Date for dates at midnight, Datetime[ms], else String; schemaOverrides SHALL cast columns and columns keep only those. readExcelSheets(path) SHALL read every sheet into a table by sheet name.

                          let path = getTempDir() / "bears.xlsx"
                          newDataFrame(series("bear", @["Ada", "Bo"]), series("kg", @[410, 380]),
                                       series("seen", @[date(2024, 3, 1), date(2024, 3, 9)])).writeExcel(path, worksheet = "census")
                          echo readExcel(path)
                          echo readExcel(path, sheetName = "census", skipRows = 1, hasHeader = false)
                          echo readExcel(path, skipRows = 1)
                          echo readExcelSheets(path).len
                          shape: (2, 3)
                          ┌──────┬─────┬────────────┐
                          │ bear ┆ kg  ┆ seen       │
                          │ ---  ┆ --- ┆ ---        │
                          │ str  ┆ i64 ┆ date       │
                          ╞══════╪═════╪════════════╡
                          │ Ada  ┆ 410 ┆ 2024-03-01 │
                          │ Bo   ┆ 380 ┆ 2024-03-09 │
                          └──────┴─────┴────────────┘
                          shape: (2, 3)
                          ┌──────────┬──────────┬────────────┐
                          │ column_1 ┆ column_2 ┆ column_3   │
                          │ ---      ┆ ---      ┆ ---        │
                          │ str      ┆ i64      ┆ date       │
                          ╞══════════╪══════════╪════════════╡
                          │ Ada      ┆ 410      ┆ 2024-03-01 │
                          │ Bo       ┆ 380      ┆ 2024-03-09 │
                          └──────────┴──────────┴────────────┘
                          shape: (1, 3)
                          ┌──────┬─────┬────────────┐
                          │ bear ┆ kg  ┆ seen       │
                          │ ---  ┆ --- ┆ ---        │
                          │ str  ┆ i64 ┆ date       │
                          ╞══════╪═════╪════════════╡
                          │ Bo   ┆ 380 ┆ 2024-03-09 │
                          └──────┴─────┴────────────┘
                          1
                          Scenario: Missing sheet
                          • WHEN readExcel(path, sheetName = "nope") is called
                          • THEN IOError is raised
                          Scenario: Round trip
                          • WHEN a frame of strings, integers, floats, booleans and dates is written and read back
                          • THEN the result equals the frame
                          Reading OpenDocument

                          readOds SHALL read a sheet of an .ods file with the options of readExcel.

                          echo readOds("tests/data/bears.ods")
                          shape: (2, 2)
                          ┌──────┬─────┐
                          │ bear ┆ kg  │
                          │ ---  ┆ --- │
                          │ str  ┆ i64 │
                          ╞══════╪═════╡
                          │ Ada  ┆ 410 │
                          │ Bo   ┆ 380 │
                          └──────┴─────┘
                          Scenario: Numbers
                          • WHEN an .ods sheet with numeric cells is read
                          • THEN those columns are Float64
                          expression-plugins1 requirements

                          Purpose: Calling Polars expression plugins (shared libraries implementing the Polars plugin ABI) from Nanuq, as register_plugin_function does in Python Polars.

                          Calling an expression plugin

                          registerPluginFunction(pluginPath, functionName, args) SHALL give an expression that calls the function functionName of the Polars expression plugin at pluginPath (a shared library implementing the Polars plugin ABI 0.1) on the columns of args, with the options of Python's register_plugin_function (kwargs as pickled bytes, isElementwise, changesLength, returnsScalar, castToSupertype, inputWildcardExpansion, passNameToApply, isDeterministic). The output name and data type SHALL be the ones the plugin reports, extension types included. The expression SHALL compose like any other, lazily and in group-bys.

                          # tests/data/plugins/double_it.nim, built as a library
                          let lib = "tests/data/plugins/" & (DynlibFormat % "double_it")
                          let df = newDataFrame(series("x", [1.5, 2.0, 4.0]))
                          echo df.select(registerPluginFunction(lib, "double_it", [col"x"], isElementwise = true))
                          shape: (3, 1)
                          ┌─────┐
                          │ x   │
                          │ --- │
                          │ f64 │
                          ╞═════╡
                          │ 3.0 │
                          │ 4.0 │
                          │ 8.0 │
                          └─────┘
                          Scenario: Plugin error
                          • WHEN the plugin reports an error for a call (it returns no column and sets its last error message)
                          • THEN running the query raises ComputeError with the plugin's message
                          Scenario: Missing library
                          • WHEN pluginPath is not a loadable library
                          • THEN running the query raises ComputeError naming the path
                          Scenario: Extension type output
                          • WHEN the plugin's output field carries ARROW:extension:name
                          • THEN the column has that extension type, shown as ext[<name>]
                          expressions17 requirements

                          Purpose: Expressions beyond the basics: conditionals, membership and range tests, extra arithmetic, rounding and aggregations, null fill strategies, and window expressions.

                          Conditional expressions

                          The API SHALL build conditional expressions with the chain when(cond).then(value) , optionally followed by more .when(cond).then(value) pairs and .otherwise(value). Rows matching no condition SHALL be null when there is no otherwise. A chain SHALL be usable wherever an Expr is expected. Values SHALL be expressions or Nim literals, and strings SHALL be literal values.

                          let bears = newDataFrame(series("w", [100, 300, 900]))
                          echo bears.select(
                            `when`(col("w") < 150).then("cub")
                            .when(col("w") < 500).then("adult")
                            .otherwise("chonk")
                            .alias("size"))
                          shape: (3, 1)
                          ┌───────┐
                          │ size  │
                          │ ---   │
                          │ str   │
                          ╞═══════╡
                          │ cub   │
                          │ adult │
                          │ chonk │
                          └───────┘
                          Scenario: Three-way label
                          • WHEN when(col("w") < 150).then("cub").when(col("w") < 500).then("adult").otherwise("chonk") is selected over weights 100, 300 and 900
                          • THEN the result is "cub", "adult" and "chonk"
                          Scenario: No otherwise
                          • WHEN when(col("w") < 150).then(1) is selected over weights 100 and 900
                          • THEN the result is 1 and null
                          choose macro

                          The API SHALL provide a choose macro that turns an if/elif/else expression with expression conditions into the same chain. A missing else SHALL mean null. Any other body SHALL fail to compile.

                          let bears = newDataFrame(series("w", [100, 300, 900]))
                          let size = choose:
                            if col("w") < 150: "cub"
                            elif col("w") < 500: "adult"
                            else: "chonk"
                          echo bears.select(col("w"), size.alias("size"))
                          shape: (3, 2)
                          ┌─────┬───────┐
                          │ w   ┆ size  │
                          │ --- ┆ ---   │
                          │ i64 ┆ str   │
                          ╞═════╪═══════╡
                          │ 100 ┆ cub   │
                          │ 300 ┆ adult │
                          │ 900 ┆ chonk │
                          └─────┴───────┘
                          Scenario: Same plan as the chain
                          • WHEN a choose block and the equivalent chain are built
                          • THEN their $ strings are equal
                          Scenario: One line
                          • WHEN choose(if col("collared"): "tracked" else: "free") is selected
                          • THEN each row is "tracked" or "free"
                          Membership and ranges

                          Expr SHALL support isIn(values) for a list of Nim values or an expression, with nullsEqual = false, and isBetween(lower, upper, closed = Both) with a pure enum ClosedInterval (Both, Left, Right, None).

                          let df = newDataFrame(series("a", [1, 2, 3]))
                          echo df.select(
                            col("a"),
                            col("a").isIn([1, 3]).alias("in_1_3"),
                            col("a").isBetween(1, 3, closed = Left).alias("in_[1,3)"))
                          shape: (3, 3)
                          ┌─────┬────────┬──────────┐
                          │ a   ┆ in_1_3 ┆ in_[1,3) │
                          │ --- ┆ ---    ┆ ---      │
                          │ i64 ┆ bool   ┆ bool     │
                          ╞═════╪════════╪══════════╡
                          │ 1   ┆ true   ┆ true     │
                          │ 2   ┆ false  ┆ true     │
                          │ 3   ┆ true   ┆ false    │
                          └─────┴────────┴──────────┘
                          Scenario: isIn
                          • WHEN col("a").isIn([1, 3]) is selected over 1, 2 and 3
                          • THEN the result is true, false and true
                          Scenario: Half-open range
                          • WHEN col("a").isBetween(1, 3, closed = Left) is selected over 1, 2 and 3
                          • THEN the result is true, true and false
                          Arithmetic operators

                          Expr SHALL support mod, div (floor division), ^ and pow, abs and unary -, with Nim literals on either side of a binary operator. mod and div SHALL follow Polars' floor semantics.

                          let df = newDataFrame(series("a", [-7, 3]))
                          echo df.select(col("a"), (col("a") mod 3).alias("mod"), (col("a") div 3).alias("div"),
                                         (col("a") ^ 2).alias("sq"), abs(col("a")).alias("abs"))
                          shape: (2, 5)
                          ┌─────┬─────┬─────┬─────┬─────┐
                          │ a   ┆ mod ┆ div ┆ sq  ┆ abs │
                          │ --- ┆ --- ┆ --- ┆ --- ┆ --- │
                          │ i64 ┆ i64 ┆ i64 ┆ i64 ┆ i64 │
                          ╞═════╪═════╪═════╪═════╪═════╡
                          │ -7  ┆ 2   ┆ -3  ┆ 49  ┆ 7   │
                          │ 3   ┆ 0   ┆ 1   ┆ 9   ┆ 3   │
                          └─────┴─────┴─────┴─────┴─────┘
                          Scenario: Floor semantics
                          • WHEN lit(-7) mod 3 and lit(-7) div 3 are evaluated
                          • THEN the results are 2 and -3
                          Scenario: Power
                          • WHEN col("a") ^ 2 is selected over 3
                          • THEN the result is 9
                          Rounding

                          Expr SHALL support round(decimals = 0, mode = HalfToEven) with a pure enum RoundMode (HalfToEven, HalfAwayFromZero, ToZero).

                          let df = newDataFrame(series("w", [1.23456, 2.5]))
                          echo df.select(col("w").round(2).alias("r2"), col("w").round.alias("even"),
                                         col("w").round(mode = HalfAwayFromZero).alias("away"))
                          shape: (2, 3)
                          ┌──────┬──────┬──────┐
                          │ r2   ┆ even ┆ away │
                          │ ---  ┆ ---  ┆ ---  │
                          │ f64  ┆ f64  ┆ f64  │
                          ╞══════╪══════╪══════╡
                          │ 1.23 ┆ 1.0  ┆ 1.0  │
                          │ 2.5  ┆ 2.0  ┆ 3.0  │
                          └──────┴──────┴──────┘
                          Scenario: Two decimals
                          • WHEN col("w").round(2) is selected over 1.23456
                          • THEN the result is 1.23
                          Scenario: Half to even by default
                          • WHEN col("w").round and col("w").round(mode = HalfAwayFromZero) are selected over 2.5
                          • THEN the results are 2.0 and 3.0
                          More aggregations

                          Expr SHALL support median, var(ddof = 1), std(ddof = 1), quantile(q, interpolation = Nearest) with a pure enum QuantileMethod (Nearest, Lower, Higher, Midpoint, Linear, Equiprobable), and len, which counts rows including nulls.

                          let df = newDataFrame(series("a", [some(1), some(2), none(int), some(4)]))
                          echo df.select(col("a").median.alias("median"),
                                         col("a").quantile(0.5, interpolation = Linear).alias("q50"),
                                         col("a").len.alias("len"), col("a").count.alias("count"))
                          shape: (1, 4)
                          ┌────────┬─────┬─────┬───────┐
                          │ median ┆ q50 ┆ len ┆ count │
                          │ ---    ┆ --- ┆ --- ┆ ---   │
                          │ f64    ┆ f64 ┆ u32 ┆ u32   │
                          ╞════════╪═════╪═════╪═══════╡
                          │ 2.0    ┆ 2.0 ┆ 4   ┆ 3     │
                          └────────┴─────┴─────┴───────┘
                          Scenario: Median and quantile
                          • WHEN median and quantile(0.25, interpolation = Linear) are computed over 1, 2, 3 and 4
                          • THEN the results are 2.5 and 1.75
                          Scenario: len vs count
                          • WHEN len and count are computed over 1, null and 3
                          • THEN the results are 3 and 2
                          Null fill strategies

                          Expr SHALL support fillNull(strategy, limit = none(int)) with a pure enum FillNullStrategy (Forward, Backward, Mean, Min, Max, Zero, One), and the shortcuts forwardFill(limit) and backwardFill(limit). limit SHALL also accept a plain int. A limit SHALL bound how many consecutive nulls are filled.

                          let df = newDataFrame(series("a", [some(1), none(int), none(int), some(4)]))
                          echo df.select(col("a"), col("a").forwardFill(1).alias("ffill1"),
                                         col("a").backwardFill.alias("bfill"), col("a").fillNull(Mean).alias("mean"))
                          shape: (4, 4)
                          ┌──────┬────────┬───────┬──────┐
                          │ a    ┆ ffill1 ┆ bfill ┆ mean │
                          │ ---  ┆ ---    ┆ ---   ┆ ---  │
                          │ i64  ┆ i64    ┆ i64   ┆ i64  │
                          ╞══════╪════════╪═══════╪══════╡
                          │ 1    ┆ 1      ┆ 1     ┆ 1    │
                          │ null ┆ 1      ┆ 4     ┆ 2    │
                          │ null ┆ null   ┆ 4     ┆ 2    │
                          │ 4    ┆ 4      ┆ 4     ┆ 4    │
                          └──────┴────────┴───────┴──────┘
                          Scenario: Forward with limit
                          • WHEN col("a").forwardFill(1) is selected over 1, null, null and 4
                          • THEN the result is 1, 1, null and 4
                          Scenario: Mean
                          • WHEN col("a").fillNull(Mean) is selected over 1, null and 3
                          • THEN the result is 1, 2 and 3
                          Window expressions

                          Expr SHALL support over(partitionBy) with one column name, a list of names, or a list of expressions. It SHALL compute the expression per group and return one value per row.

                          let df = newDataFrame(series("g", ["x", "x", "y"]), series("v", [1, 3, 10]))
                          echo df.withColumns(col("v").mean.over("g").alias("group_mean"))
                          shape: (3, 3)
                          ┌─────┬─────┬────────────┐
                          │ g   ┆ v   ┆ group_mean │
                          │ --- ┆ --- ┆ ---        │
                          │ str ┆ i64 ┆ f64        │
                          ╞═════╪═════╪════════════╡
                          │ x   ┆ 1   ┆ 2.0        │
                          │ x   ┆ 3   ┆ 2.0        │
                          │ y   ┆ 10  ┆ 10.0       │
                          └─────┴─────┴────────────┘
                          Scenario: Group mean per row
                          • WHEN col("v").mean.over("g") is selected over groups x, x, y with values 1, 3, 10
                          • THEN the result is 2, 2 and 10
                          Scenario: Forward fill within groups
                          • WHEN col("r").forwardFill.over("g") runs where group y starts with a null
                          • THEN that null stays null, instead of taking the last value of group x
                          Ranking

                          Expr SHALL support rank(how = Average, descending = false, seed = none(int)) with a pure enum RankMethod (Average, Min, Max, Dense, Ordinal, Random), giving each value its rank from 1. Ties SHALL be handled as Polars does: Average gives tied values the mean of their ranks (f64), Min and Max the lowest or highest (u32), Dense leaves no gaps after ties, and Ordinal breaks ties by position. seed SHALL make Random repeatable. Nulls SHALL stay null.

                          let roll = newDataFrame:
                            rider: ["Merckx", "Pogačar", "De Vlaeminck", "Van Looy", "Kelly"]
                            monuments: [19, 13, 11, 8, 9]
                          echo roll.select(col.rider, col.monuments,
                                           col.monuments.rank(Min, descending = true).alias("place"),
                                           col.monuments.rank.alias("avg"))
                          shape: (5, 4)
                          ┌──────────────┬───────────┬───────┬─────┐
                          │ rider        ┆ monuments ┆ place ┆ avg │
                          │ ---          ┆ ---       ┆ ---   ┆ --- │
                          │ str          ┆ i64       ┆ u32   ┆ f64 │
                          ╞══════════════╪═══════════╪═══════╪═════╡
                          │ Merckx       ┆ 19        ┆ 1     ┆ 5.0 │
                          │ Pogačar      ┆ 13        ┆ 2     ┆ 4.0 │
                          │ De Vlaeminck ┆ 11        ┆ 3     ┆ 3.0 │
                          │ Van Looy     ┆ 8         ┆ 5     ┆ 1.0 │
                          │ Kelly        ┆ 9         ┆ 4     ┆ 2.0 │
                          └──────────────┴───────────┴───────┴─────┘
                          Scenario: Shared places
                          • WHEN rank(Min, descending = true) runs over 9, 9, 7
                          • THEN the result is 1, 1, 3
                          Scenario: Dense
                          • WHEN rank(Dense) runs over 9, 9, 7
                          • THEN the result is 2, 2, 1
                          Scenario: Average
                          • WHEN rank() runs over 9, 9, 7
                          • THEN the result is 2.5, 2.5, 1.0 with dtype f64
                          Filtering inside expressions

                          e.filter(predicate) SHALL keep the values of e where predicate is true, so that an aggregation can run over part of each group.

                          let df = newDataFrame:
                            rider: ["Pogačar", "Pogačar", "Vingegaard", "Vingegaard"]
                            stage: ["TT", "road", "TT", "road"]
                            secs: [3120, 15400, 3150, 15390]
                          echo df.groupBy(col.rider).agg(col.secs.filter(col.stage == "TT").sum.alias("tt_secs"))
                            .sort("rider")
                          shape: (2, 2)
                          ┌────────────┬─────────┐
                          │ rider      ┆ tt_secs │
                          │ ---        ┆ ---     │
                          │ str        ┆ i64     │
                          ╞════════════╪═════════╡
                          │ Pogačar    ┆ 3120    │
                          │ Vingegaard ┆ 3150    │
                          └────────────┴─────────┘
                          Scenario: Conditional sum
                          • WHEN col.secs.filter(col.stage == "TT").sum is aggregated per rider
                          • THEN each rider's sum counts only the TT rows
                          Shape and position aggregations

                          Expressions SHALL have the aggregations product, mode (every most frequent value, in order of appearance), argMin and argMax (the row index of the first minimum or maximum), skew(bias = true) and kurtosis(fisher = true, bias = true).

                          let df = newDataFrame:
                            year: [2020, 2021, 2022, 2023]
                            oni: [0.5, -1.0, -0.9, 1.9]
                          echo df.select(col.oni.argMax.alias("warmest_row"),
                                         col.oni.argMin.alias("coldest_row"), col.oni.skew.round(3).alias("skew"))
                          shape: (1, 3)
                          ┌─────────────┬─────────────┬───────┐
                          │ warmest_row ┆ coldest_row ┆ skew  │
                          │ ---         ┆ ---         ┆ ---   │
                          │ u32         ┆ u32         ┆ f64   │
                          ╞═════════════╪═════════════╪═══════╡
                          │ 3           ┆ 1           ┆ 0.474 │
                          └─────────────┴─────────────┴───────┘
                          Scenario: Product
                          • WHEN product runs on 2, 3, 4
                          • THEN the result is 24
                          Scenario: Several modes
                          • WHEN mode runs on 1, 2, 2, 3, 3
                          • THEN the result holds 2 and 3
                          Boolean aggregations

                          Expr SHALL support any(ignoreNulls = true) and all(ignoreNulls = true) on boolean columns, as aggregations: whether any value, or every value, is true. With ignoreNulls = false they SHALL follow Kleene logic: any is null when there are nulls and no true value, all is null when there are nulls and no false value. The all() selector (no arguments) SHALL keep working.

                          let df = newDataFrame:
                            team: ["a", "a", "b", "b"]
                            won: [true, false, true, true]
                          echo df.groupBy("team").agg(col.won.all.alias("always"), col.won.any.alias("ever"))
                          shape: (2, 3)
                          ┌──────┬────────┬──────┐
                          │ team ┆ always ┆ ever │
                          │ ---  ┆ ---    ┆ ---  │
                          │ str  ┆ bool   ┆ bool │
                          ╞══════╪════════╪══════╡
                          │ a    ┆ false  ┆ true │
                          │ b    ┆ true   ┆ true │
                          └──────┴────────┴──────┘
                          Scenario: Kleene logic
                          • WHEN any(ignoreNulls = false) runs on false and null
                          • THEN the result is null
                          Entropy

                          Expr SHALL support entropy(base = E, normalize = true), an aggregation giving -sum(p * ln(p)) / ln(base), where p are the values (divided by their sum when normalize is true).

                          let df = newDataFrame:
                            votes: [@[1, 1, 2], @[5]]
                          echo df.select(col.votes.list.agg(element().entropy).alias("entropy"))
                          shape: (2, 1)
                          ┌──────────┐
                          │ entropy  │
                          │ ---      │
                          │ f64      │
                          ╞══════════╡
                          │ 1.039721 │
                          │ 0.0      │
                          └──────────┘
                          Scenario: One value
                          • WHEN the entropy of a single positive value is computed
                          • THEN the result is 0.0
                          Row count expression

                          len() with no argument SHALL be an expression counting rows, named len (Python's pl.len()); in a group-by it SHALL count the rows of each group.

                          let df = newDataFrame:
                            team: ["a", "a", "b"]
                          echo df.groupBy("team").agg(len())
                          shape: (2, 2)
                          ┌──────┬─────┐
                          │ team ┆ len │
                          │ ---  ┆ --- │
                          │ str  ┆ u32 │
                          ╞══════╪═════╡
                          │ a    ┆ 2   │
                          │ b    ┆ 1   │
                          └──────┴─────┘
                          Scenario: Whole frame
                          • WHEN df.select(len()) runs on 4 rows
                          • THEN the result is one row with len = 4
                          Several window keys and selector concatenation

                          over SHALL take several column names as separate arguments, and concatStr SHALL take selectors, expanding them to their columns.

                          let df = newDataFrame(series("c", @["x", "x", "y"]), series("b", @["p", "p", "q"]))
                          echo df.select(concatStr([all()], "-").alias("s"), lit(1).sum.over("c", "b").alias("n"))
                          shape: (3, 2)
                          ┌─────┬─────┐
                          │ s   ┆ n   │
                          │ --- ┆ --- │
                          │ str ┆ i32 │
                          ╞═════╪═════╡
                          │ x-p ┆ 1   │
                          │ x-p ┆ 1   │
                          │ y-q ┆ 1   │
                          └─────┴─────┘
                          Scenario: Two keys
                          • WHEN col("v").sum.over("c", "b") is selected
                          • THEN each row gets the sum of its (c, b) group
                          Null-aware comparisons and closeness

                          eqMissing(other) and neMissing(other) SHALL compare as == and != with null equal to null, never giving null. isClose(other, absTol = 0.0, relTol = 1e-9, nansEqual = false) SHALL be true where abs(a - b) <= max(relTol * max(abs(a), abs(b)), absTol).

                          let df = newDataFrame(series("a", [some(1.0), none(float)]), series("b", [some(1.05), none(float)]))
                          echo df.select(col("a").eqMissing(col("b")).alias("eq"),
                                         col("a").isClose(col("b"), absTol = 0.1).alias("close"))
                          shape: (2, 2)
                          ┌───────┬───────┐
                          │ eq    ┆ close │
                          │ ---   ┆ ---   │
                          │ bool  ┆ bool  │
                          ╞═══════╪═══════╡
                          │ false ┆ true  │
                          │ true  ┆ null  │
                          └───────┴───────┘
                          Scenario: Nulls
                          • WHEN eqMissing compares null with null
                          • THEN the result is true
                          More expression functions

                          nth(indices) SHALL select columns by position (negative from the end). cumulativeEval(expr, minSamples = 1) SHALL run expr on the growing window up to each row, roundSigFigs(digits) SHALL round to significant figures, reinterpret(signed) SHALL read 64-bit integer bits as Int64 or UInt64, and concatArr(exprs) SHALL build fixed-size arrays per row.

                          let df = newDataFrame(series("x", @[1.0, 22.0, 333.0]), series("y", @[4.0, 5.0, 6.0]))
                          echo df.select(nth(-1), col("x").cumulativeEval(element().sum).alias("cum"),
                                         col("x").roundSigFigs(1).alias("sig"), concatArr(col("x"), col("y")).alias("xy"))
                          shape: (3, 4)
                          ┌─────┬───────┬───────┬───────────────┐
                          │ y   ┆ cum   ┆ sig   ┆ xy            │
                          │ --- ┆ ---   ┆ ---   ┆ ---           │
                          │ f64 ┆ f64   ┆ f64   ┆ array[f64, 2] │
                          ╞═════╪═══════╪═══════╪═══════════════╡
                          │ 4.0 ┆ 1.0   ┆ 1.0   ┆ [1.0, 4.0]    │
                          │ 5.0 ┆ 23.0  ┆ 20.0  ┆ [22.0, 5.0]   │
                          │ 6.0 ┆ 356.0 ┆ 300.0 ┆ [333.0, 6.0]  │
                          └─────┴───────┴───────┴───────────────┘
                          Scenario: Cumulative sum
                          • WHEN cumulativeEval(element().sum) runs on 1, 2, 3
                          • THEN the result is 1, 3, 6
                          frame-utilities16 requirements

                          Purpose: Smaller expression and frame functions: sampling, hashing, meta, comparing, stacking, updating and upsampling.

                          Smaller expression functions

                          Expressions SHALL have shuffle(seed), sample(n or fraction), hash(seed), get(i), argTrue, upperBound, lowerBound, extendConstant(value, n), rle (a struct of len and value) and reshape(dims), and over(partitionBy, mappingStrategy) with MappingStrategy.GroupToRows, Join or Explode.

                          let df = newDataFrame:
                            den: ["A", "A", "B"]
                            kg: [410, 380, 500]
                          echo df.select(col("kg").get(1).alias("second"), col("kg").upperBound.alias("max"))
                          echo df.select((col("kg") > 400).argTrue.alias("heavy"))
                          echo df.select(col("den"), col("kg").over("den", MappingStrategy.Join).alias("all"))
                          echo df.select(col("den").rle).unnest("den")
                          shape: (1, 2)
                          ┌────────┬─────────────────────┐
                          │ second ┆ max                 │
                          │ ---    ┆ ---                 │
                          │ i64    ┆ i64                 │
                          ╞════════╪═════════════════════╡
                          │ 380    ┆ 9223372036854775807 │
                          └────────┴─────────────────────┘
                          shape: (2, 1)
                          ┌───────┐
                          │ heavy │
                          │ ---   │
                          │ u32   │
                          ╞═══════╡
                          │ 0     │
                          │ 2     │
                          └───────┘
                          shape: (3, 2)
                          ┌─────┬────────────┐
                          │ den ┆ all        │
                          │ --- ┆ ---        │
                          │ str ┆ list[i64]  │
                          ╞═════╪════════════╡
                          │ A   ┆ [410, 380] │
                          │ A   ┆ [410, 380] │
                          │ B   ┆ [500]      │
                          └─────┴────────────┘
                          shape: (2, 2)
                          ┌─────┬───────┐
                          │ len ┆ value │
                          │ --- ┆ ---   │
                          │ u32 ┆ str   │
                          ╞═════╪═══════╡
                          │ 2   ┆ A     │
                          │ 1   ┆ B     │
                          └─────┴───────┘
                          Scenario: Seeded shuffle
                          • WHEN shuffle(seed = 1) is evaluated twice
                          • THEN both results are the same permutation
                          Names and meta

                          name.toLowercase and name.toUppercase SHALL change output names, and e.meta SHALL give outputName, rootNames, hasMultipleOutputs, isColumn, isLiteral and undoAliases.

                          let e = (col("kg") * 2).alias("double")
                          echo e.meta.outputName, " ", e.meta.rootNames, " ", col("*").meta.hasMultipleOutputs
                          let df = newDataFrame:
                            Bear: ["Ada"]
                          echo df.select(col("Bear").name.toUppercase).columns
                          double @["kg"] true
                          @["BEAR"]
                          Scenario: No output name
                          • WHEN outputName is asked of col("*")
                          • THEN ComputeError is raised
                          Comparing and stacking frames

                          a.equals(b, nullEqual = true) SHALL tell whether two frames (or Series) have the same names, types and values; vstack and extend SHALL append the rows of a frame with the same schema, and hstack SHALL add Series or the columns of another frame.

                          let a = newDataFrame:
                            bear: ["Ada"]
                            kg: [410]
                          let b = newDataFrame:
                            bear: ["Bo"]
                            kg: [380]
                          echo a.vstack(b).hstack([series("den", ["A", "B"])])
                          echo a.equals(a), " ", a.equals(b)
                          shape: (2, 3)
                          ┌──────┬─────┬─────┐
                          │ bear ┆ kg  ┆ den │
                          │ ---  ┆ --- ┆ --- │
                          │ str  ┆ i64 ┆ str │
                          ╞══════╪═════╪═════╡
                          │ Ada  ┆ 410 ┆ A   │
                          │ Bo   ┆ 380 ┆ B   │
                          └──────┴─────┴─────┘
                          true false
                          Scenario: Nulls
                          • WHEN two frames with a null in the same place are compared with nullEqual = false
                          • THEN equals is false
                          Updating, upsampling and partitions

                          df.update(other, on, how) SHALL replace values of df with the non-null values of other in matching rows; df.upsample(timeColumn, every, groupBy) SHALL insert rows for missing times at a regular interval; estimatedSize SHALL give the frame's size; partitionBy(by, asDict = true) SHALL give a table from key values to frames; and collectAll(lfs) SHALL collect several LazyFrames.

                          let df = newDataFrame:
                            bear: ["Ada", "Bo"]
                            kg: [410, 380]
                          let fix = newDataFrame:
                            bear: ["Bo"]
                            kg: [395]
                          echo df.update(fix, on = "bear")
                          let t = newDataFrame:
                            day: [date(2026, 3, 1), date(2026, 3, 4)]
                            seen: [3, 1]
                          echo t.upsample("day", every = "1d")
                          echo df.partitionBy("bear", asDict = true).len, " ", collectAll([df.lazy, fix.lazy]).len
                          shape: (2, 2)
                          ┌──────┬─────┐
                          │ bear ┆ kg  │
                          │ ---  ┆ --- │
                          │ str  ┆ i64 │
                          ╞══════╪═════╡
                          │ Ada  ┆ 410 │
                          │ Bo   ┆ 395 │
                          └──────┴─────┘
                          shape: (4, 2)
                          ┌────────────┬──────┐
                          │ day        ┆ seen │
                          │ ---        ┆ ---  │
                          │ date       ┆ i64  │
                          ╞════════════╪══════╡
                          │ 2026-03-01 ┆ 3    │
                          │ 2026-03-02 ┆ null │
                          │ 2026-03-03 ┆ null │
                          │ 2026-03-04 ┆ 1    │
                          └────────────┴──────┘
                          2 2
                          Scenario: Upsample by group
                          • WHEN upsample is called with groupBy
                          • THEN each group is filled between its own first and last time
                          Operator methods and xor

                          Expressions SHALL have the method spellings add, sub, mul, truediv, floordiv, eq, ne, lt, le, gt, ge (with an expression, number, string or bool) and neg, giving the same result as the operators, and xor SHALL be logical on booleans and bitwise on integers.

                          let df = newDataFrame(series("a", @[6, 3]), series("ok", @[true, false]))
                          echo df.select(col("a").mul(2).alias("m"), col("a").floordiv(4).alias("f"),
                                         (col("a") xor 5).alias("x"), (col("ok") xor true).alias("nx"))
                          shape: (2, 4)
                          ┌─────┬─────┬─────┬───────┐
                          │ m   ┆ f   ┆ x   ┆ nx    │
                          │ --- ┆ --- ┆ --- ┆ ---   │
                          │ i64 ┆ i64 ┆ i64 ┆ bool  │
                          ╞═════╪═════╪═════╪═══════╡
                          │ 12  ┆ 1   ┆ 3   ┆ false │
                          │ 6   ┆ 0   ┆ 6   ┆ true  │
                          └─────┴─────┴─────┴───────┘
                          Scenario: Same as operators
                          • WHEN col("a").sub(1) and col("a") - 1 are selected
                          • THEN both columns are equal
                          Ranges per row

                          intRanges(start, stop, step = 1, dtype = Int64), dateRanges(start, stop, interval) and datetimeRanges(start, stop, interval, closed, timeUnit, timeZone) SHALL give one list per row, with columns or values as bounds; arange SHALL be intRange.

                          let df = newDataFrame(series("lo", @[1, 3]), series("hi", @[3, 6]))
                          echo df.select(intRanges(col("lo"), col("hi")).alias("r"))
                          shape: (2, 1)
                          ┌───────────┐
                          │ r         │
                          │ ---       │
                          │ list[i64] │
                          ╞═══════════╡
                          │ [1, 2]    │
                          │ [3, 4, 5] │
                          └───────────┘
                          Scenario: Dates
                          • WHEN dateRanges runs from 2024-01-01 to 2024-01-03
                          • THEN the list holds 3 dates
                          Inequality joins

                          joinWhere(other, predicates..., suffix = "_right") on DataFrames and LazyFrames SHALL join the rows of both frames for which every predicate holds; clashing columns of other SHALL get suffix.

                          let east = newDataFrame(series("id", @[100, 101]), series("dur", @[140, 100]))
                          let west = newDataFrame(series("t_id", @[404, 498]), series("time", @[90, 130]))
                          echo east.joinWhere(west, col("dur") < col("time"))
                          shape: (1, 4)
                          ┌─────┬─────┬──────┬──────┐
                          │ id  ┆ dur ┆ t_id ┆ time │
                          │ --- ┆ --- ┆ ---  ┆ ---  │
                          │ i64 ┆ i64 ┆ i64  ┆ i64  │
                          ╞═════╪═════╪══════╪══════╡
                          │ 101 ┆ 100 ┆ 498  ┆ 130  │
                          └─────┴─────┴──────┴──────┘
                          Scenario: No match
                          • WHEN no pair of rows satisfies the predicates
                          • THEN the result has no rows
                          Frame and Series helpers

                          The API SHALL provide append (rows of another frame, in place), remove(predicate) (rows where it is not true), setSorted, Series.isSorted(descending, nullsLast), explainAll(lfs), threadPoolSize(), readParquetSchema(path), fromEpoch(column, unit), hist(bins, binCount, includeCategory, includeBreakpoint) on Expr and Series, Series.scatter(indices, values) and set(mask, value) .

                          var df = newDataFrame(series("a", @[1, 2]))
                          df.append(newDataFrame(series("a", @[3])))
                          echo df.remove(col("a") == 2)
                          echo series("x", @[1.0, 2.0, 2.5, 4.0]).hist(bins = [0.0, 2.0, 4.0])
                          echo series("x", @[1, 2, 3]).scatter([0, 2], [10, 30])
                          shape: (2, 1)
                          ┌─────┐
                          │ a   │
                          │ --- │
                          │ i64 │
                          ╞═════╡
                          │ 1   │
                          │ 3   │
                          └─────┘
                          shape: (2, 3)
                          ┌────────────┬────────────┬───────┐
                          │ breakpoint ┆ category   ┆ count │
                          │ ---        ┆ ---        ┆ ---   │
                          │ f64        ┆ cat        ┆ u32   │
                          ╞════════════╪════════════╪═══════╡
                          │ 2.0        ┆ [0.0, 2.0] ┆ 2     │
                          │ 4.0        ┆ (2.0, 4.0] ┆ 2     │
                          └────────────┴────────────┴───────┘
                          shape: (3,)
                          Series: 'x' [i64]
                          [
                          	10
                          	2
                          	30
                          ]
                          Scenario: Remove keeps nulls
                          • WHEN remove(col("a") > 1) runs on a column with a null
                          • THEN the null row stays
                          Unstack

                          unstack(step, how = UnstackDirection.Vertical, columns = [], fillValues = nil) SHALL reshape each column into columns <name>_<i> of step values each (Vertical) or with step values per row (Horizontal), padding the end with nulls or fillValues.

                          let df = newDataFrame(series("x", @["a", "b", "c", "d", "e"]))
                          echo df.unstack(2)
                          shape: (2, 3)
                          ┌─────┬─────┬──────┐
                          │ x_0 ┆ x_1 ┆ x_2  │
                          │ --- ┆ --- ┆ ---  │
                          │ str ┆ str ┆ str  │
                          ╞═════╪═════╪══════╡
                          │ a   ┆ c   ┆ e    │
                          │ b   ┆ d   ┆ null │
                          └─────┴─────┴──────┘
                          Scenario: Horizontal
                          • WHEN 5 values are unstacked horizontally with step 2 and fill 0
                          • THEN column _0 holds values 1, 3, 5 and column _1 holds 2, 4, 0
                          Rolling Nim functions

                          rollingMap(f, windowSize, minPeriods = windowSize, center = false) SHALL apply a typed Nim proc to each window's non-null values, giving null when a window has fewer than minPeriods values.

                          import std/sequtils
                          let df = newDataFrame(series("x", @[1.0, 2.0, 3.0, 4.0]))
                          echo df.select(col("x").rollingMap(proc (w: seq[float]): float = w.foldl(a + b), windowSize = 2))
                          shape: (4, 1)
                          ┌──────┐
                          │ x    │
                          │ ---  │
                          │ f64  │
                          ╞══════╡
                          │ null │
                          │ 3.0  │
                          │ 5.0  │
                          │ 7.0  │
                          └──────┘
                          Scenario: Centered
                          • WHEN center = true with window 3
                          • THEN each value's window is the value and its two neighbours
                          Data type of an expression

                          dtypeOf(expr or column) SHALL stand for the type of an expression at run time: cast(e, dtypeOf(...)) casts to it, display gives its short name as a string value, innerDtype the inner type of a List or Array.

                          let df = newDataFrame(series("a", @[1.5, 2.5]), series("b", @[1'i32, 2'i32]))
                          echo df.select(col("a").cast(dtypeOf("b"), strict = false), dtypeOf("b").display.alias("type"))
                          shape: (2, 2)
                          ┌─────┬──────┐
                          │ a   ┆ type │
                          │ --- ┆ ---  │
                          │ i32 ┆ str  │
                          ╞═════╪══════╡
                          │ 1   ┆ i32  │
                          │ 2   ┆ i32  │
                          └─────┴──────┘
                          Scenario: Unknown column
                          • WHEN dtypeOf("nope") is used
                          • THEN ColumnNotFoundError is raised when the query runs
                          Empty frames

                          newDataFrame(schema = {...}) SHALL build a frame with those columns and types and no rows (a Schema works too). clear(n = 0) on a DataFrame or LazyFrame SHALL keep the columns and types with no rows, or n rows of nulls. isEmpty on a DataFrame or Series SHALL be true when it has no rows.

                          let empty = newDataFrame(schema = {"bear": String, "kg": Int64})
                          echo empty
                          echo empty.isEmpty
                          echo newDataFrame(series("kg", @[410, 380])).clear(1)
                          shape: (0, 2)
                          ┌──────┬─────┐
                          │ bear ┆ kg  │
                          │ ---  ┆ --- │
                          │ str  ┆ i64 │
                          ╞══════╪═════╡
                          └──────┴─────┘
                          true
                          shape: (1, 1)
                          ┌──────┐
                          │ kg   │
                          │ ---  │
                          │ i64  │
                          ╞══════╡
                          │ null │
                          └──────┘
                          Scenario: Same schema
                          • WHEN df.clear runs
                          • THEN its schema equals df.schema and its height is 0
                          Frame shortcuts

                          getColumnIndex(name) SHALL give a column's position (raising ColumnNotFoundError). rowsByKey(key, K, T, unique = false) SHALL group the rows, as T objects or tuples, by the values of key in order of appearance (with unique, the last row per key). shift(n, fillValue) and dropNans(subset) SHALL work on frames as on each column; LazyFrame first and last SHALL keep the first or last row. rechunk SHALL put each column in one chunk, shrinkToFit SHALL drop spare capacity, and nChunks SHALL count chunks.

                          import std/tables
                          let df = newDataFrame(series("station", @["A", "B", "A"]), series("rain", @[1.5, NaN, 3.0]))
                          echo df.getColumnIndex("rain")
                          echo df.rowsByKey("station", string, tuple[rain: float])
                          echo df.dropNans.shift(1)
                          1
                          {"A": @[(rain: 1.5), (rain: 3.0)], "B": @[(rain: nan)]}
                          shape: (2, 2)
                          ┌─────────┬──────┐
                          │ station ┆ rain │
                          │ ---     ┆ ---  │
                          │ str     ┆ f64  │
                          ╞═════════╪══════╡
                          │ null    ┆ null │
                          │ A       ┆ 1.5  │
                          └─────────┴──────┘
                          Scenario: Unknown column
                          • WHEN getColumnIndex("nope") runs
                          • THEN ColumnNotFoundError is raised
                          Schema matching

                          matchToSchema(schema, missingColumns, extraColumns, integerCast, floatCast) SHALL put the columns in the schema's order and types. A missing column SHALL raise unless missingColumns = Insert (nulls), an extra column SHALL raise unless extraColumns = Ignore, and integers and floats SHALL change type only with CastPolicy.Upcast.

                          let df = newDataFrame(series("b", @[1'i32]), series("a", @["x"]))
                          echo df.matchToSchema({"a": String, "b": Int64, "c": Float64},
                                                missingColumns = MissingColumns.Insert, integerCast = CastPolicy.Upcast)
                          shape: (1, 3)
                          ┌─────┬─────┬──────┐
                          │ a   ┆ b   ┆ c    │
                          │ --- ┆ --- ┆ ---  │
                          │ str ┆ i64 ┆ f64  │
                          ╞═════╪═════╪══════╡
                          │ x   ┆ 1   ┆ null │
                          └─────┴─────┴──────┘
                          Scenario: Missing column
                          • WHEN the schema has a column the frame lacks and missingColumns is Raise
                          • THEN PolarsError is raised
                          Merging sorted frames

                          mergeSorted(other, key) SHALL merge two frames sorted by key into one sorted frame.

                          let a = newDataFrame(series("k", @[1, 4]))
                          let b = newDataFrame(series("k", @[2, 3, 5]))
                          echo a.mergeSorted(b, "k").toList("k", int)
                          @[1, 2, 3, 4, 5]
                          Scenario: Same columns
                          • WHEN both frames have the same columns, sorted by key
                          • THEN the result has all their rows, sorted
                          Query optimizations

                          cache SHALL mark part of a query to compute once. QueryOptFlags SHALL hold the optimization switches (all on by default; QueryOptFlags.none turns off all but type coercion and checks), applied with withOptimizations or collect(optimizations, engine).

                          let lf = newDataFrame(series("x", @[1, 2, 3])).lazy.filter(col("x") > 1)
                          echo lf.collect(QueryOptFlags.none).height
                          echo lf.cache.collect(QueryOptFlags(predicatePushdown: false)).height
                          2
                          2
                          Scenario: Same rows
                          • WHEN a query is collected with every optimization on and with QueryOptFlags.none
                          • THEN the rows are the same
                          frame-verbs15 requirements

                          Purpose: Column and row verbs on DataFrames and LazyFrames: dropping and renaming columns, row windows, unique rows, row indexes, sorting by several keys, and sampling.

                          Dropping and renaming columns

                          LazyFrame and DataFrame SHALL support drop(columns, strict = true), with one column name or a list of names, and rename(mapping: openArray[(string, string)], strict = true). With strict = true, a column that does not exist SHALL raise PolarsError. With strict = false, it SHALL be ignored.

                          let df = newDataFrame(series("a", [1]), series("b", [2]), series("c", [3]))
                          echo df.drop("b").columns                  # one name
                          echo df.drop(["a", "b"]).columns           # several
                          echo df.drop("zzz", strict = false).columns
                          echo df.rename({"a": "x"}).columns
                          @["a", "c"]
                          @["c"]
                          @["a", "b", "c"]
                          @["x", "b", "c"]
                          Scenario: Drop
                          • WHEN df.drop("b") runs on columns a, b, c
                          • THEN the columns are a, c, and df.drop(["a", "b"]) leaves c
                          Scenario: Rename
                          • WHEN df.rename({"a": "x"}) runs on columns a, b
                          • THEN the columns are x, b
                          Scenario: Strict
                          • WHEN df.drop("zzz") runs
                          • THEN PolarsError is raised, and df.drop("zzz", strict = false) returns the frame unchanged
                          Row windows

                          LazyFrame and DataFrame SHALL support head(n = 5), tail(n = 5), slice(offset) and slice(offset, length). A negative offset SHALL count from the end. reverse() SHALL reverse the row order.

                          let df = newDataFrame(series("n", [1, 2, 3, 4, 5]))
                          echo df.tail(2).toList("n", int)
                          echo df.slice(-3, 2).toList("n", int)       # negative offset counts from the end
                          echo df.slice(1).toList("n", int)           # to the end
                          echo df.reverse.toList("n", int)
                          @[4, 5]
                          @[3, 4]
                          @[2, 3, 4, 5]
                          @[5, 4, 3, 2, 1]
                          Scenario: Tail
                          • WHEN tail(2) runs on rows 1 to 5
                          • THEN the result is rows 4 and 5
                          Scenario: Slice from the end
                          • WHEN slice(-3, 2) runs on rows 1 to 5
                          • THEN the result is rows 3 and 4
                          Scenario: Slice to the end
                          • WHEN slice(1) runs on rows 1 to 5
                          • THEN the result is rows 2 to 5
                          Unique rows

                          LazyFrame and DataFrame SHALL support unique(subset = [], keep, maintainOrder = false), with one column name or a list of names, judging duplicates on all columns when the subset is empty. keep is a pure enum UniqueKeepStrategy (Any (default), First, Last, None). With maintainOrder = true, the rows SHALL keep their original order.

                          let df = newDataFrame(series("k", ["a", "b", "a"]), series("v", [1, 2, 3]))
                          echo df.unique("k", keep = First, maintainOrder = true)
                          echo df.unique("k", keep = None)
                          shape: (2, 2)
                          ┌─────┬─────┐
                          │ k   ┆ v   │
                          │ --- ┆ --- │
                          │ str ┆ i64 │
                          ╞═════╪═════╡
                          │ a   ┆ 1   │
                          │ b   ┆ 2   │
                          └─────┴─────┘
                          shape: (1, 2)
                          ┌─────┬─────┐
                          │ k   ┆ v   │
                          │ --- ┆ --- │
                          │ str ┆ i64 │
                          ╞═════╪═════╡
                          │ b   ┆ 2   │
                          └─────┴─────┘
                          Scenario: Keep first
                          • WHEN unique("k", keep = First, maintainOrder = true) runs on keys a, b, a with values 1, 2, 3
                          • THEN the result is (a, 1), (b, 2)
                          Scenario: Keep none
                          • WHEN the same frame is made unique on k with keep = None
                          • THEN only (b, 2) remains
                          Row index

                          LazyFrame and DataFrame SHALL support withRowIndex(name = "index", offset = 0), which adds an unsigned integer column with that name as the first column, counting from offset.

                          let df = newDataFrame(series("bear", ["Nanuq", "Ursa", "Kuma"]))
                          echo df.withRowIndex("n", offset = 1)
                          shape: (3, 2)
                          ┌─────┬───────┐
                          │ n   ┆ bear  │
                          │ --- ┆ ---   │
                          │ u32 ┆ str   │
                          ╞═════╪═══════╡
                          │ 1   ┆ Nanuq │
                          │ 2   ┆ Ursa  │
                          │ 3   ┆ Kuma  │
                          └─────┴───────┘
                          Scenario: Offset
                          • WHEN withRowIndex("n", offset = 1) runs on three rows
                          • THEN the first column is n with values 1, 2, 3
                          Sorting by several keys

                          LazyFrame and DataFrame SHALL sort by several column names or expressions with sort(by, descending: openArray[bool] = [], nullsLast: openArray[bool] = [], maintainOrder = false). An empty list SHALL mean false for every key, and one value SHALL apply to every key. Another length SHALL raise PolarsError. The one-column sort(by: string, descending = false, nullsLast = false, maintainOrder = false) SHALL remain.

                          let df = newDataFrame(series("g", ["b", "a", "b", "a"]), series("v", [1, 2, 3, 4]))
                          echo df.sort(["g", "v"], descending = [false, true])
                          shape: (4, 2)
                          ┌─────┬─────┐
                          │ g   ┆ v   │
                          │ --- ┆ --- │
                          │ str ┆ i64 │
                          ╞═════╪═════╡
                          │ a   ┆ 4   │
                          │ a   ┆ 2   │
                          │ b   ┆ 3   │
                          │ b   ┆ 1   │
                          └─────┴─────┘
                          Scenario: Two keys
                          • WHEN a frame is sorted by ["g", "v"] with descending = [false, true]
                          • THEN rows are ordered by g ascending and, within each g, by v descending
                          Scenario: Nulls last
                          • WHEN a column holding null, 2, 1 is sorted with nullsLast = true
                          • THEN the order is 1, 2, null
                          Scenario: Length mismatch
                          • WHEN a sort by three keys gets descending = [true, false]
                          • THEN PolarsError is raised
                          Sampling rows

                          DataFrame SHALL support sample(n, withReplacement = false, shuffle = none(bool), seed = none(int)) and sample(fraction, ...) with the same options. shuffle SHALL also accept a plain bool: true shuffles the rows, false keeps their order and none gives no order guarantee, as in Polars. Asking for more rows than there are without replacement SHALL raise PolarsError. The same seed SHALL give the same rows. seed SHALL also accept a plain int (seed = 42), and setRandomSeed(seed) SHALL seed Polars' global generator, used when no seed is passed.

                          let df = newDataFrame(series("n", [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
                          echo df.sample(3, seed = 42) == df.sample(3, seed = 42)   # same seed, same rows
                          echo df.sample(fraction = 0.5).shape
                          setRandomSeed(42)
                          let a = df.sample(4)
                          setRandomSeed(42)
                          echo a == df.sample(4)
                          false
                          (5, 1)
                          false
                          Scenario: Seeded sample
                          • WHEN sample(3, seed = some(42)) runs twice on the same 10-row frame
                          • THEN both results have 3 rows and are equal
                          Scenario: Global seed
                          • WHEN setRandomSeed(42) is called before each of two sample(4) calls on the same frame
                          • THEN both results are equal
                          Scenario: Fraction
                          • WHEN sample(fraction = 0.5) runs on 10 rows
                          • THEN the result has 5 rows
                          Scenario: Too many rows
                          • WHEN sample(11) runs on 10 rows
                          • THEN PolarsError is raised
                          Every n-th row

                          LazyFrame and DataFrame SHALL support gatherEvery(n, offset = 0), keeping rows offset, offset + n, offset + 2n, ... (Python's gather_every).

                          let df = newDataFrame:
                            month: [1, 2, 3, 4, 5, 6]
                          echo df.gatherEvery(3, offset = 2)
                          shape: (2, 1)
                          ┌───────┐
                          │ month │
                          │ ---   │
                          │ i64   │
                          ╞═══════╡
                          │ 3     │
                          │ 6     │
                          └───────┘
                          Scenario: Offset past the end
                          • WHEN gatherEvery(2, offset = 10) runs on 6 rows
                          • THEN the result has no rows
                          Frame interpolation

                          DataFrame and LazyFrame SHALL support interpolate(how = InterpolationMethod.Linear), filling the nulls of every column as Expr.interpolate does (Python's DataFrame.interpolate).

                          let df = newDataFrame:
                            day: [1, 2, 3]
                            temp: [some(-2.0), none(float), some(1.0)]
                          echo df.interpolate
                          shape: (3, 2)
                          ┌─────┬──────┐
                          │ day ┆ temp │
                          │ --- ┆ ---  │
                          │ f64 ┆ f64  │
                          ╞═════╪══════╡
                          │ 1.0 ┆ -2.0 │
                          │ 2.0 ┆ -0.5 │
                          │ 3.0 ┆ 1.0  │
                          └─────┴──────┘
                          Scenario: Integer column
                          • WHEN an integer column with a null between 1 and 5 is interpolated
                          • THEN it becomes a float column holding 1.0, 3.0, 5.0
                          Casting by data type

                          DataFrame and LazyFrame cast SHALL also take a mapping from data types, or from selectors, to data types: cast({Float64: Float32}) casts every Float64 column, cast({col(SomeNumber): Float32}) every column the selector picks; other columns are kept.

                          let df = newDataFrame:
                            kg: [410.5, 380.0]
                            cubs: [1, 0]
                            bear: ["Ada", "Bo"]
                          echo df.cast({Float64: Float32}).schema
                          echo df.cast({col(SomeNumber): Float32}).schema
                          {"kg": Float32, "cubs": Int64, "bear": String}
                          {"kg": Float32, "cubs": Float32, "bear": String}
                          Scenario: Other columns kept
                          • WHEN cast({Float64: Float32}) runs on a frame with an Int64 column
                          • THEN the Int64 column is unchanged
                          Several filter predicates

                          DataFrame and LazyFrame filter SHALL take several predicates, filter(a, b, ...), keeping the rows where all of them hold (Python's filter(a, b)).

                          let df = newDataFrame:
                            peak: ["Mont Blanc", "Monte Rosa", "Gran Paradiso"]
                            m: [4806, 4634, 4061]
                            italy: [true, true, true]
                          echo df.filter(col.m > 4500, col.italy)
                          shape: (2, 3)
                          ┌────────────┬──────┬───────┐
                          │ peak       ┆ m    ┆ italy │
                          │ ---        ┆ ---  ┆ ---   │
                          │ str        ┆ i64  ┆ bool  │
                          ╞════════════╪══════╪═══════╡
                          │ Mont Blanc ┆ 4806 ┆ true  │
                          │ Monte Rosa ┆ 4634 ┆ true  │
                          └────────────┴──────┴───────┘
                          Scenario: All must hold
                          • WHEN a row meets one predicate but not the other
                          • THEN it is dropped
                          Group order parameter

                          groupBy on DataFrame and LazyFrame SHALL accept maintainOrder (Python's maintain_order), with names or expressions; the groups SHALL keep the order their keys first appear whatever its value.

                          let df = newDataFrame:
                            country: ["CH", "IT", "CH"]
                            m: [4634, 4061, 4506]
                          echo df.groupBy("country", maintainOrder = true).agg(col.m.max)
                          shape: (2, 2)
                          ┌─────────┬──────┐
                          │ country ┆ m    │
                          │ ---     ┆ ---  │
                          │ str     ┆ i64  │
                          ╞═════════╪══════╡
                          │ CH      ┆ 4634 │
                          │ IT      ┆ 4061 │
                          └─────────┴──────┘
                          Scenario: Order kept
                          • WHEN keys appear as CH, IT, CH and maintainOrder = false is passed
                          • THEN the groups come out as CH, IT
                          Frame aggregations

                          DataFrames and LazyFrames SHALL provide sum, mean, median, product, min, max, std(ddof = 1), var(ddof = 1), quantile(q, interpolation), nUnique, count and nullCount(), each giving one row with the aggregation of every column; columns of a type the aggregation does not apply to (strings for sum) SHALL give null.

                          let df = newDataFrame(series("bear", @["Ada", "Bo", "Cy"]), series("kg", @[410, 380, 455]))
                          echo df.sum
                          echo df.max
                          echo df.nullCount
                          shape: (1, 2)
                          ┌──────┬──────┐
                          │ bear ┆ kg   │
                          │ ---  ┆ ---  │
                          │ str  ┆ i64  │
                          ╞══════╪══════╡
                          │ null ┆ 1245 │
                          └──────┴──────┘
                          shape: (1, 2)
                          ┌──────┬─────┐
                          │ bear ┆ kg  │
                          │ ---  ┆ --- │
                          │ str  ┆ i64 │
                          ╞══════╪═════╡
                          │ Cy   ┆ 455 │
                          └──────┴─────┘
                          shape: (1, 2)
                          ┌──────┬─────┐
                          │ bear ┆ kg  │
                          │ ---  ┆ --- │
                          │ u32  ┆ u32 │
                          ╞══════╪═════╡
                          │ 0    ┆ 0   │
                          └──────┴─────┘
                          Scenario: Lazy
                          • WHEN df.lazy.mean.collect runs
                          • THEN it equals df.mean
                          Group-by shortcuts

                          GroupBy and LazyGroupBy SHALL provide len(name = "len"), count, head(n = 5), tail(n = 5), first, last, sum, mean, median, min, max, nUnique, quantile(q) and all, each aggregating every non-key column per group, with groups in order of appearance.

                          let df = newDataFrame(series("den", @["N", "S", "N"]), series("kg", @[410, 380, 455]))
                          echo df.groupBy("den").max
                          echo df.groupBy("den").len
                          echo df.groupBy("den").head(1)
                          shape: (2, 2)
                          ┌─────┬─────┐
                          │ den ┆ kg  │
                          │ --- ┆ --- │
                          │ str ┆ i64 │
                          ╞═════╪═════╡
                          │ N   ┆ 455 │
                          │ S   ┆ 380 │
                          └─────┴─────┘
                          shape: (2, 2)
                          ┌─────┬─────┐
                          │ den ┆ len │
                          │ --- ┆ --- │
                          │ str ┆ u32 │
                          ╞═════╪═════╡
                          │ N   ┆ 2   │
                          │ S   ┆ 1   │
                          └─────┴─────┘
                          shape: (2, 2)
                          ┌─────┬─────┐
                          │ den ┆ kg  │
                          │ --- ┆ --- │
                          │ str ┆ i64 │
                          ╞═════╪═════╡
                          │ N   ┆ 410 │
                          │ S   ┆ 380 │
                          └─────┴─────┘
                          Scenario: Not a plain group-by
                          • WHEN head is called on a groupByDynamic
                          • THEN InvalidOperationError is raised
                          Iterating over groups

                          for key, part in df.groupBy(columns) SHALL yield each group's key values (as strings, in by order) and its rows, groups in order of appearance.

                          let df = newDataFrame(series("den", @["N", "S", "N"]), series("kg", @[410, 380, 455]))
                          for key, part in df.groupBy("den"):
                            echo key, " ", part.height
                          @["N"] 2
                          @["S"] 1
                          Scenario: Several keys
                          • WHEN a frame is grouped by two columns and iterated
                          • THEN each key holds two values
                          Frame fillNan and select without a frame

                          fillNan(value) on DataFrames and LazyFrames SHALL replace NaN in float columns (nil for null), and select(exprs...) SHALL evaluate expressions without a frame.

                          echo newDataFrame(series("x", @[1.0, NaN])).fillNan(0.0)
                          echo select(lit(1).alias("one"), intRange(0, 3).alias("i"))
                          shape: (2, 1)
                          ┌─────┐
                          │ x   │
                          │ --- │
                          │ f64 │
                          ╞═════╡
                          │ 1.0 │
                          │ 0.0 │
                          └─────┘
                          shape: (3, 2)
                          ┌─────┬─────┐
                          │ one ┆ i   │
                          │ --- ┆ --- │
                          │ i32 ┆ i64 │
                          ╞═════╪═════╡
                          │ 1   ┆ 0   │
                          │ 1   ┆ 1   │
                          │ 1   ┆ 2   │
                          └─────┴─────┘
                          Scenario: Other columns
                          • WHEN a frame with an integer and a float column gets fillNan(0.0)
                          • THEN the integer column is unchanged
                          horizontal-functions3 requirements

                          Purpose: Functions that compute across the columns of a row, columns generated from ranges and repeated values, and correlation between columns.

                          Horizontal functions

                          sumHorizontal, meanHorizontal, minHorizontal, maxHorizontal, allHorizontal, anyHorizontal and coalesce SHALL compute row by row over their arguments, which SHALL be expressions, literals, selectors (expanded to their columns) or a list of column names. sumHorizontal and meanHorizontal SHALL skip nulls unless ignoreNulls = false, and coalesce SHALL return the first non-null value.

                          let df = newDataFrame:
                            station: ["Lima", "Piura", "Tumbes"]
                            jan: [1.0, 4.0, nil]
                            feb: [2.0, 30.0, 61.0]
                            mar: [1.0, 80.0, 95.0]
                          echo df.select(col.station, sumHorizontal(col(float)).alias("total"),
                                         maxHorizontal("jan", "feb", "mar").alias("wettest"),
                                         coalesce(col.jan, col.feb).alias("first_reading"))
                          shape: (3, 4)
                          ┌─────────┬───────┬─────────┬───────────────┐
                          │ station ┆ total ┆ wettest ┆ first_reading │
                          │ ---     ┆ ---   ┆ ---     ┆ ---           │
                          │ str     ┆ f64   ┆ str     ┆ f64           │
                          ╞═════════╪═══════╪═════════╪═══════════════╡
                          │ Lima    ┆ 4.0   ┆ mar     ┆ 1.0           │
                          │ Piura   ┆ 114.0 ┆ mar     ┆ 4.0           │
                          │ Tumbes  ┆ 156.0 ┆ mar     ┆ 61.0          │
                          └─────────┴───────┴─────────┴───────────────┘
                          Scenario: Nulls in a sum
                          • WHEN sumHorizontal([col.a, col.b], ignoreNulls = false) runs on a row where b is null
                          • THEN that row's sum is null
                          Scenario: All and any
                          • WHEN allHorizontal and anyHorizontal run on a row holding true and false
                          • THEN they give false and true
                          Generated columns

                          intRange(start, stop, step = 1, dtype = Int64) (or intRange(stop)) SHALL produce the integers from start up to stop excluded, linearSpace(start, stop, numSamples, closed) SHALL produce evenly spaced floats, and repeat(value, n) SHALL repeat a value n times. A string value SHALL be wrapped in lit, since std/strutils' repeat takes plain strings.

                          echo newDataFrame().select(intRange(1950, 2026, 25).alias("year"),
                                                     linearSpace(0, 1, 4).alias("share"),
                                                     repeat(lit("ENSO"), 4).alias("index"))
                          shape: (4, 3)
                          ┌──────┬──────────┬───────┐
                          │ year ┆ share    ┆ index │
                          │ ---  ┆ ---      ┆ ---   │
                          │ i64  ┆ f64      ┆ str   │
                          ╞══════╪══════════╪═══════╡
                          │ 1950 ┆ 0.0      ┆ ENSO  │
                          │ 1975 ┆ 0.333333 ┆ ENSO  │
                          │ 2000 ┆ 0.666667 ┆ ENSO  │
                          │ 2025 ┆ 1.0      ┆ ENSO  │
                          └──────┴──────────┴───────┘
                          Scenario: Zero step
                          • WHEN intRange(0, 5, step = 0) is built
                          • THEN ValueError is raised
                          Correlation

                          corr(a, b, how = Pearson) SHALL return the Pearson or Spearman correlation of two columns as an aggregation, and cov(a, b, ddof = 1) their covariance.

                          let df = newDataFrame:
                            oni: [-1.0, 0.0, 0.5, 2.0]
                            world: [14.6, 14.8, 14.9, 15.2]
                          echo df.select(corr("oni", "world").round(3).alias("pearson"),
                                         corr("oni", "world", how = Spearman).alias("spearman"))
                          shape: (1, 2)
                          ┌─────────┬──────────┐
                          │ pearson ┆ spearman │
                          │ ---     ┆ ---      │
                          │ f64     ┆ f64      │
                          ╞═════════╪══════════╡
                          │ 1.0     ┆ 1.0      │
                          └─────────┴──────────┘
                          Scenario: Perfect correlation
                          • WHEN corr runs on 1, 2, 3 and 2, 4, 6
                          • THEN the result is 1.0
                          inspection6 requirements

                          Purpose: Looking at a frame: glimpse, describe, and the display configuration (setTbl*, setConfig, withConfig).

                          glimpse

                          glimpse(df, maxItemsPerColumn = 10, maxColnameLength = 50) SHALL return, as a string, the lines Rows: <height> and Columns: <width>, then one line per column: $ <name> <<dtype>> <values>, with names left-aligned and dtypes right-aligned to a common width, and the first maxItemsPerColumn values joined by ", ". Nulls SHALL be null, booleans True/False, and strings quoted as Python's repr quotes them. Names longer than maxColnameLength SHALL be cut and end with ….

                          let df = newDataFrame:
                            rider: ["Pogačar", "Seixas", "Van der Poel"]
                            wins: [22, 8, nil]
                            pro: [true, false, true]
                            race: ["Giro d'Italia", "Tour", "Vuelta"]
                          echo df.glimpse
                          Rows: 3
                          Columns: 4
                          $ rider  <str> 'Pogačar', 'Seixas', 'Van der Poel'
                          $ wins   <i64> 22, 8, null
                          $ pro   <bool> True, False, True
                          $ race   <str> "Giro d'Italia", 'Tour', 'Vuelta'
                          
                          Scenario: Long frame
                          • WHEN a column of 100 rows is glimpsed with maxItemsPerColumn = 3
                          • THEN its line shows the first 3 values only
                          Scenario: Long name
                          • WHEN a column named with 60 characters is glimpsed
                          • THEN its line shows the first 49 characters followed by …
                          describe

                          describe(percentiles = [0.25, 0.5, 0.75], interpolation = Nearest) on DataFrame and LazyFrame SHALL return a DataFrame with a statistic column holding count, null_count, mean, std, min, one row per percentile (labelled as 25%) and max, followed by one column per input column: f64 for numeric and boolean columns, str for the others, and null where a statistic does not apply.

                          let df = newDataFrame:
                            rider: ["Pogačar", "Seixas", "Van der Poel"]
                            wins: [22, 8, nil]
                            pro: [true, false, true]
                          echo df.describe
                          shape: (9, 4)
                          ┌────────────┬──────────────┬──────────┬──────────┐
                          │ statistic  ┆ rider        ┆ wins     ┆ pro      │
                          │ ---        ┆ ---          ┆ ---      ┆ ---      │
                          │ str        ┆ str          ┆ f64      ┆ f64      │
                          ╞════════════╪══════════════╪══════════╪══════════╡
                          │ count      ┆ 3            ┆ 2.0      ┆ 3.0      │
                          │ null_count ┆ 0            ┆ 1.0      ┆ 0.0      │
                          │ mean       ┆ null         ┆ 15.0     ┆ 0.666667 │
                          │ std        ┆ null         ┆ 9.899495 ┆ null     │
                          │ min        ┆ Pogačar      ┆ 8.0      ┆ 0.0      │
                          │ 25%        ┆ null         ┆ 8.0      ┆ null     │
                          │ 50%        ┆ null         ┆ 22.0     ┆ null     │
                          │ 75%        ┆ null         ┆ 22.0     ┆ null     │
                          │ max        ┆ Van der Poel ┆ 22.0     ┆ 1.0      │
                          └────────────┴──────────────┴──────────┴──────────┘
                          Scenario: Custom percentiles
                          • WHEN describe(percentiles = [0.1, 0.9]) runs
                          • THEN the statistic column holds count, null_count, mean, std, min, 10%, 90% and max
                          Scenario: Statistics that do not apply
                          • WHEN a frame with a string and a boolean column is described
                          • THEN mean, std and percentiles are null for the string column, and std and percentiles for the boolean one
                          Scenario: No columns
                          • WHEN newDataFrame().describe runs
                          • THEN PolarsError is raised
                          Display config

                          The API SHALL set how tables print with setTblRows(n), setTblCols(n), setTblWidthChars(n) and setFmtStrLengths(n), where -1 means no limit and none(int) restores Polars' default; with setFloatPrecision(n), the number of decimal places floats print with (none(int) for Polars' default); with setConfig(tblRows, tblCols, tblWidthChars, fmtStrLengths, floatPrecision), where options left out are unchanged; and with resetConfig(), which restores every default. The settings SHALL apply to every later $ of a DataFrame.

                          let df = newDataFrame(series("n", [1, 2, 3, 4, 5, 6]))
                          setTblRows(4); setFmtStrLengths(10)
                          echo df
                          setConfig(tblRows = 2, tblCols = 5)
                          echo df
                          resetConfig()
                          shape: (6, 1)
                          ┌─────┐
                          │ n   │
                          │ --- │
                          │ i64 │
                          ╞═════╡
                          │ 1   │
                          │ 2   │
                          │ …   │
                          │ 5   │
                          │ 6   │
                          └─────┘
                          shape: (6, 1)
                          ┌─────┐
                          │ n   │
                          │ --- │
                          │ i64 │
                          ╞═════╡
                          │ 1   │
                          │ …   │
                          │ 6   │
                          └─────┘
                          Scenario: Float precision
                          • WHEN setConfig(floatPrecision = 2) is called and a frame holding 0.05333 prints
                          • THEN the value shows as 0.05
                          Scenario: No limit
                          • WHEN setTblRows(-1) is called and a frame of 50 rows is printed
                          • THEN all 50 rows are shown
                          Scenario: Reset
                          • WHEN setTblRows(2) and then resetConfig() are called
                          • THEN a frame of 10 rows prints all 10 rows again
                          Scoped display config

                          withConfig(options): body SHALL apply the named options (tblRows, tblCols, tblWidthChars, fmtStrLengths, floatPrecision) while body runs, and SHALL restore the previous settings afterwards, also when body raises.

                          let df = newDataFrame(series("n", [1, 2, 3, 4, 5, 6]))
                          withConfig(tblRows = 2):
                            echo df
                          echo df.shape, " ", ($df).count('\n')
                          shape: (6, 1)
                          ┌─────┐
                          │ n   │
                          │ --- │
                          │ i64 │
                          ╞═════╡
                          │ 1   │
                          │ …   │
                          │ 6   │
                          └─────┘
                          (6, 1) 12
                          Scenario: Restored after an exception
                          • WHEN the body of withConfig(tblRows = 2) raises
                          • THEN the exception propagates and the row limit is back to its previous value
                          Describe prints temporal values as Python

                          describe SHALL print Datetime statistics and the mean of a Date column as YYYY-MM-DD HH:MM:SS, with a fraction only when it is not zero.

                          let df = newDataFrame(series("d", @[date(1986, 9, 1), date(1986, 9, 7)]))
                          echo df.describe
                          shape: (9, 2)
                          ┌────────────┬─────────────────────┐
                          │ statistic  ┆ d                   │
                          │ ---        ┆ ---                 │
                          │ str        ┆ str                 │
                          ╞════════════╪═════════════════════╡
                          │ count      ┆ 2                   │
                          │ null_count ┆ 0                   │
                          │ mean       ┆ 1986-09-04 00:00:00 │
                          │ std        ┆ null                │
                          │ min        ┆ 1986-09-01          │
                          │ 25%        ┆ 1986-09-01          │
                          │ 50%        ┆ 1986-09-07          │
                          │ 75%        ┆ 1986-09-07          │
                          │ max        ┆ 1986-09-07          │
                          └────────────┴─────────────────────┘
                          Scenario: Date mean
                          • WHEN the mean of 1986-09-01 and 1986-09-07 is described
                          • THEN it reads 1986-09-04 00:00:00
                          Table formatting options

                          setTblFormatting(TableFormat, roundedCorners), setAsciiTables, setTblHideColumnDataTypes, setTblHideColumnNames, setTblHideDataframeShape, setTblHideColumnSeparator, setTblDataframeShapeBelow, setTblColumnDataTypeInline, setTblCellAlignment, setTblCellNumericAlignment and setFmtTableCellListLen SHALL change how frames print; setConfig and withConfig SHALL take tblFormatting, asciiTables, tblHideColumnDataTypes, tblHideColumnNames, tblHideDataframeShape and tblCellAlignment, and resetConfig SHALL undo them all.

                          let df = newDataFrame(series("bear", @["Ada"]), series("kg", @[410]))
                          withConfig(tblFormatting = TableFormat.Markdown, tblHideDataframeShape = true):
                            echo df
                          | bear | kg  |
                          | ---  | --- |
                          | str  | i64 |
                          |------|-----|
                          | Ada  | 410 |
                          Scenario: ASCII
                          • WHEN a frame prints inside withConfig(asciiTables = true)
                          • THEN its borders use +, - and |
                          json-io3 requirements

                          Purpose: Reading and writing JSON and NDJSON.

                          Reading JSON

                          readJson(source) SHALL read a JSON array of objects (one row each) from a file path or a Stream, and readNdjson(source) newline-delimited JSON, with nested values becoming List and Struct columns. schema SHALL fix all column types, schemaOverrides some of them, inferSchemaLength SHALL bound the rows used to infer the rest, and ignoreErrors SHALL read values that do not parse as null.

                          import std/streams
                          let json = """[{"bear": "Ada", "cubs": ["Bo"], "den": {"lat": 78.2}},
                                         {"bear": "Cy", "cubs": [], "den": {"lat": 79.0}}]"""
                          let df = readJson(newStringStream(json))
                          echo df
                          echo readNdjson(newStringStream("{\"a\": 1}\n{\"a\": 2}\n"), schemaOverrides = {"a": Float64})
                          shape: (2, 3)
                          ┌──────┬───────────┬───────────┐
                          │ bear ┆ cubs      ┆ den       │
                          │ ---  ┆ ---       ┆ ---       │
                          │ str  ┆ list[str] ┆ struct[1] │
                          ╞══════╪═══════════╪═══════════╡
                          │ Ada  ┆ ["Bo"]    ┆ {78.2}    │
                          │ Cy   ┆ []        ┆ {79.0}    │
                          └──────┴───────────┴───────────┘
                          shape: (2, 1)
                          ┌─────┐
                          │ a   │
                          │ --- │
                          │ f64 │
                          ╞═════╡
                          │ 1.0 │
                          │ 2.0 │
                          └─────┘
                          Scenario: Not JSON
                          • WHEN a file that is not JSON is read with readJson
                          • THEN ComputeError is raised
                          Scanning NDJSON

                          scanNdjson(path) SHALL read newline-delimited JSON files lazily (a path or a glob), with nRows, rowIndexName and rowIndexOffset and the schema options of readNdjson.

                          let path = getTempDir() / "bears.ndjson"
                          writeFile(path, "{\"bear\": \"Ada\", \"kg\": 410}\n{\"bear\": \"Bo\", \"kg\": 380}\n")
                          echo scanNdjson(path, rowIndexName = "i").filter(col("kg") > 400).collect
                          shape: (1, 3)
                          ┌─────┬──────┬─────┐
                          │ i   ┆ bear ┆ kg  │
                          │ --- ┆ ---  ┆ --- │
                          │ u32 ┆ str  ┆ i64 │
                          ╞═════╪══════╪═════╡
                          │ 0   ┆ Ada  ┆ 410 │
                          └─────┴──────┴─────┘
                          Scenario: Limit rows
                          • WHEN a file of 3 lines is scanned with nRows = 2
                          • THEN the frame has 2 rows
                          Writing JSON

                          writeJson(dest) SHALL write a frame as a JSON array of row objects to a path or a Stream, writeNdjson(dest) one object per line, and toJson/toNdjson SHALL return the same text; reading it back SHALL give the same frame.

                          let df = newDataFrame:
                            bear: ["Ada", "Bo"]
                            cubs: [@["Cy"], @[]]
                          echo df.toJson
                          echo df.toNdjson
                          [{"bear":"Ada","cubs":["Cy"]},{"bear":"Bo","cubs":[]}]
                          {"bear":"Ada","cubs":["Cy"]}
                          {"bear":"Bo","cubs":[]}
                          Scenario: Round trip
                          • WHEN a frame with list and struct columns is written with writeNdjson and read with readNdjson
                          • THEN the result equals the frame
                          list-functions7 requirements

                          Purpose: Functions on list columns: the list namespace, explode, implode and concatList.

                          List aggregations and access

                          e.list SHALL give a namespace whose methods work on each list of a List (or Array) column: len, sum, min, max, mean, median, std, var, first, last, argMin, argMax, nUnique, any, all give one value per list; get(i) (negative from the end), gather, gatherEvery, slice, head, tail pick values; contains(x), countMatches(x) and join(separator) compare or join them.

                          let df = newDataFrame:
                            cubs: [@[2, 1, 3], @[], @[4]]
                            names: [@["Ada", "Bo"], @["Cy"], @[]]
                          echo df.select(col("cubs").list.len.alias("n"), col("cubs").list.sum.alias("sum"),
                                         col("cubs").list.get(0, nullOnOob = true).alias("first"),
                                         col("cubs").list.contains(3).alias("has3"),
                                         col("names").list.join(", ").alias("names"))
                          shape: (3, 5)
                          ┌─────┬─────┬───────┬───────┬─────────┐
                          │ n   ┆ sum ┆ first ┆ has3  ┆ names   │
                          │ --- ┆ --- ┆ ---   ┆ ---   ┆ ---     │
                          │ u32 ┆ i64 ┆ i64   ┆ bool  ┆ str     │
                          ╞═════╪═════╪═══════╪═══════╪═════════╡
                          │ 3   ┆ 6   ┆ 2     ┆ true  ┆ Ada, Bo │
                          │ 0   ┆ 0   ┆ null  ┆ false ┆ Cy      │
                          │ 1   ┆ 4   ┆ 4     ┆ false ┆         │
                          └─────┴─────┴───────┴───────┴─────────┘
                          Scenario: Index out of bounds
                          • WHEN list.get(5) is evaluated on a list of 3 values without nullOnOob
                          • THEN ComputeError is raised; with nullOnOob = true the value is null
                          List transforms

                          e.list SHALL have sort, reverse, unique, dropNulls, diff, shift, sample, filter(predicate), the set operations union, setDifference, setIntersection and setSymmetricDifference with another list expression, toArray(width) and toStruct(fields), each giving a list (array or struct) per row.

                          let df = newDataFrame:
                            a: [@[3, 1, 3], @[2]]
                            b: [@[1, 5], @[2, 4]]
                          echo df.select(col("a").list.sort.alias("sorted"), col("a").list.unique(maintainOrder = true).alias("unique"),
                                         col("a").list.union(col("b")).alias("union"),
                                         col("a").list.filter(element() > 1).alias("gt1"))
                          shape: (2, 4)
                          ┌───────────┬───────────┬───────────┬───────────┐
                          │ sorted    ┆ unique    ┆ union     ┆ gt1       │
                          │ ---       ┆ ---       ┆ ---       ┆ ---       │
                          │ list[i64] ┆ list[i64] ┆ list[i64] ┆ list[i64] │
                          ╞═══════════╪═══════════╪═══════════╪═══════════╡
                          │ [1, 3, 3] ┆ [3, 1]    ┆ [3, 1, 5] ┆ [3, 3]    │
                          │ [2]       ┆ [2]       ┆ [2, 4]    ┆ [2]       │
                          └───────────┴───────────┴───────────┴───────────┘
                          Scenario: Lists to structs
                          • WHEN list.toStruct(["x", "y"]) is evaluated on lists of two values
                          • THEN the result is a struct column with fields x and y
                          Expressions on list elements

                          list.eval(e) SHALL evaluate e on the values of each list, with element() standing for them, and give a list per row; list.agg(e) SHALL do the same for an aggregation and give one value per row.

                          let df = newDataFrame:
                            weights: [@[410.0, 380.0], @[450.0, 470.0, 455.0]]
                          echo df.select(col("weights").list.eval(element().rank).alias("rank"),
                                         col("weights").list.agg(element().max - element().min).alias("spread"))
                          shape: (2, 2)
                          ┌─────────────────┬────────┐
                          │ rank            ┆ spread │
                          │ ---             ┆ ---    │
                          │ list[f64]       ┆ f64    │
                          ╞═════════════════╪════════╡
                          │ [2.0, 1.0]      ┆ 30.0   │
                          │ [1.0, 3.0, 2.0] ┆ 20.0   │
                          └─────────────────┴────────┘
                          Scenario: Element outside a list
                          • WHEN element() is used in a select that is not inside list.eval
                          • THEN evaluating it raises a Polars error
                          Explode and implode

                          e.explode and e.list.explode SHALL give one row per list value, df.explode(columns) SHALL do the same for whole rows (eager and lazy; emptyAsNull and keepNulls default to true, as in Polars), e.implode SHALL collect a column into one list, and concatList(exprs) SHALL join values and lists of several columns into one list per row.

                          let df = newDataFrame:
                            den: ["A", "B", "C"]
                            cubs: [@["Ada", "Bo"], @[], @["Cy"]]
                          echo df.explode("cubs")
                          echo df.select(concatList(col("den"), col("cubs")).alias("all"))
                          echo df.select(col("den").implode)
                          shape: (4, 2)
                          ┌─────┬──────┐
                          │ den ┆ cubs │
                          │ --- ┆ ---  │
                          │ str ┆ str  │
                          ╞═════╪══════╡
                          │ A   ┆ Ada  │
                          │ A   ┆ Bo   │
                          │ B   ┆ null │
                          │ C   ┆ Cy   │
                          └─────┴──────┘
                          shape: (3, 1)
                          ┌────────────────────┐
                          │ all                │
                          │ ---                │
                          │ list[str]          │
                          ╞════════════════════╡
                          │ ["A", "Ada", "Bo"] │
                          │ ["B"]              │
                          │ ["C", "Cy"]        │
                          └────────────────────┘
                          shape: (1, 1)
                          ┌─────────────────┐
                          │ den             │
                          │ ---             │
                          │ list[str]       │
                          ╞═════════════════╡
                          │ ["A", "B", "C"] │
                          └─────────────────┘
                          Scenario: Empty lists
                          • WHEN a frame with an empty list is exploded with emptyAsNull = false
                          • THEN that row is dropped instead of giving a null
                          Exploding several columns by name

                          DataFrame and LazyFrame explode SHALL also take several column names as separate arguments: explode("a", "b") is explode(["a", "b"]).

                          let df = newDataFrame:
                            peak: ["Mont Blanc", "Monte Rosa"]
                            huts: [@["Goûter", "Cosmiques"], @["Margherita", "Gnifetti"]]
                            m: [@[3835, 3613], @[4554, 3647]]
                          echo df.explode("huts", "m")
                          shape: (4, 3)
                          ┌────────────┬────────────┬──────┐
                          │ peak       ┆ huts       ┆ m    │
                          │ ---        ┆ ---        ┆ ---  │
                          │ str        ┆ str        ┆ i64  │
                          ╞════════════╪════════════╪══════╡
                          │ Mont Blanc ┆ Goûter     ┆ 3835 │
                          │ Mont Blanc ┆ Cosmiques  ┆ 3613 │
                          │ Monte Rosa ┆ Margherita ┆ 4554 │
                          │ Monte Rosa ┆ Gnifetti   ┆ 3647 │
                          └────────────┴────────────┴──────┘
                          Scenario: Lists of equal length
                          • WHEN two list columns with lists of the same lengths are exploded together
                          • THEN each row holds the matching elements of both
                          Repeating values into lists

                          Expr.repeatBy(by) SHALL repeat each value by times into a list, where by is an int, a column name or an expression (Python's repeat_by).

                          let df = newDataFrame:
                            hut: ["Goûter", "Margherita"]
                            nights: [2, 1]
                          echo df.select(col.hut.repeatBy("nights"))
                          shape: (2, 1)
                          ┌──────────────────────┐
                          │ hut                  │
                          │ ---                  │
                          │ list[str]            │
                          ╞══════════════════════╡
                          │ ["Goûter", "Goûter"] │
                          │ ["Margherita"]       │
                          └──────────────────────┘
                          Scenario: Constant count
                          • WHEN repeatBy(2) runs on "x"
                          • THEN the result is the list ["x", "x"]
                          Seeds as plain ints

                          sample on expressions and on list SHALL take the seed as a plain int, sample(3, seed = 42), as shuffle and frame sample do; the same seed SHALL give the same values.

                          let df = newDataFrame:
                            m: [4806, 4634, 4061, 4506, 4478]
                          echo df.select(col.m.sample(3, seed = 42)).height
                          3
                          Scenario: Same seed
                          • WHEN sample(3, seed = 42) runs twice on the same column
                          • THEN both runs give the same values
                          math-functions5 requirements

                          Purpose: Elementwise math on expressions: roots, exponentials and logarithms, rounding to integers, clipping, trigonometry, the dot product, and NaN and infinity, which Polars keeps apart from null.

                          Elementwise math

                          Expressions SHALL have sqrt, cbrt, exp, log(base = E), log10, log1p, sign, floor and ceil, computed value by value as in Polars, with nulls staying null. sqrt, cbrt, exp and the logarithms SHALL return Float64 for integer input.

                          let df = newDataFrame:
                            x: [1.0, 4.0, 10.0, nil]
                          echo df.select(col.x.sqrt.alias("sqrt"), col.x.log10.alias("log10"),
                                         col.x.log(2.0).alias("log2"), col.x.exp.round(1).alias("exp"))
                          shape: (4, 4)
                          ┌──────────┬─────────┬──────────┬─────────┐
                          │ sqrt     ┆ log10   ┆ log2     ┆ exp     │
                          │ ---      ┆ ---     ┆ ---      ┆ ---     │
                          │ f64      ┆ f64     ┆ f64      ┆ f64     │
                          ╞══════════╪═════════╪══════════╪═════════╡
                          │ 1.0      ┆ 0.0     ┆ 0.0      ┆ 2.7     │
                          │ 2.0      ┆ 0.60206 ┆ 2.0      ┆ 54.6    │
                          │ 3.162278 ┆ 1.0     ┆ 3.321928 ┆ 22026.5 │
                          │ null     ┆ null    ┆ null     ┆ null    │
                          └──────────┴─────────┴──────────┴─────────┘
                          Scenario: Integer input
                          • WHEN sqrt runs on an Int64 column holding 4 and 9
                          • THEN the result is a Float64 column holding 2.0 and 3.0
                          Scenario: Sign, floor and ceil
                          • WHEN sign, floor and ceil run on -2.5 and 1.5
                          • THEN they give -1 and 1, -3.0 and 1.0, -2.0 and 2.0
                          Clipping

                          clip(lowerBound, upperBound) SHALL limit values to the range, and clip(lowerBound = v) or clip(upperBound = v) SHALL limit them on one side. Bounds SHALL be literals or expressions.

                          let df = newDataFrame:
                            anomaly: [-2.1, -0.3, 0.4, 2.6]
                          echo df.select(col.anomaly.clip(-1.0, 1.0).alias("both"),
                                         col.anomaly.clip(lowerBound = 0.0).alias("warm_only"))
                          shape: (4, 2)
                          ┌──────┬───────────┐
                          │ both ┆ warm_only │
                          │ ---  ┆ ---       │
                          │ f64  ┆ f64       │
                          ╞══════╪═══════════╡
                          │ -1.0 ┆ 0.0       │
                          │ -0.3 ┆ 0.0       │
                          │ 0.4  ┆ 0.4       │
                          │ 1.0  ┆ 2.6       │
                          └──────┴───────────┘
                          Scenario: Both bounds
                          • WHEN clip(-1.0, 1.0) runs on -2.1 and 2.6
                          • THEN the result is -1.0 and 1.0
                          Trigonometry

                          Expressions SHALL have sin, cos, tan, cot, arcsin, arccos, arctan, sinh, cosh, tanh, arcsinh, arccosh, arctanh, degrees and radians, working in radians, and arctan2(y, x) SHALL return the angle of the point (x, y).

                          let df = newDataFrame:
                            deg: [0.0, 90.0, 180.0]
                          echo df.select(col.deg.radians.sin.round(3).alias("sin"),
                                         arctan2(lit(1.0), lit(1.0)).degrees.alias("atan2"))
                          shape: (3, 2)
                          ┌─────┬───────┐
                          │ sin ┆ atan2 │
                          │ --- ┆ ---   │
                          │ f64 ┆ f64   │
                          ╞═════╪═══════╡
                          │ 0.0 ┆ 45.0  │
                          │ 1.0 ┆ 45.0  │
                          │ 0.0 ┆ 45.0  │
                          └─────┴───────┘
                          Scenario: Degrees round trip
                          • WHEN radians and then degrees run on 90.0
                          • THEN the result is 90.0
                          NaN and infinity

                          isNan, isNotNan, isFinite and isInfinite SHALL test float values (nulls give null), fillNan(value) SHALL replace NaN with a literal or expression, dropNans SHALL remove NaN values and Expr.dropNulls SHALL remove nulls. NaN SHALL stay distinct from null, as in Polars.

                          import std/math
                          let df = newDataFrame:
                            x: [1.0, NaN, Inf, nil]
                          echo df.select(col.x.isNan.alias("nan"), col.x.isFinite.alias("finite"),
                                         col.x.fillNan(0.0).alias("filled"))
                          echo df.select(col.x.dropNans.dropNulls)
                          shape: (4, 3)
                          ┌───────┬────────┬────────┐
                          │ nan   ┆ finite ┆ filled │
                          │ ---   ┆ ---    ┆ ---    │
                          │ bool  ┆ bool   ┆ f64    │
                          ╞═══════╪════════╪════════╡
                          │ false ┆ true   ┆ 1.0    │
                          │ true  ┆ false  ┆ 0.0    │
                          │ false ┆ false  ┆ inf    │
                          │ null  ┆ null   ┆ null   │
                          └───────┴────────┴────────┘
                          shape: (2, 1)
                          ┌─────┐
                          │ x   │
                          │ --- │
                          │ f64 │
                          ╞═════╡
                          │ 1.0 │
                          │ inf │
                          └─────┘
                          Scenario: NaN is not null
                          • WHEN isNull runs on a column holding NaN
                          • THEN the result is false
                          Scenario: fillNan leaves nulls
                          • WHEN fillNan(0.0) runs on NaN and null
                          • THEN the result is 0.0 and null
                          Dot product

                          a.dot(b) SHALL return the sum of the elementwise products of two columns, as an aggregation.

                          let df = newDataFrame:
                            a: [1, 2, 3]
                            b: [4, 5, 6]
                          echo df.select(col.a.dot(col.b))
                          shape: (1, 1)
                          ┌─────┐
                          │ a   │
                          │ --- │
                          │ i64 │
                          ╞═════╡
                          │ 32  │
                          └─────┘
                          Scenario: Dot of two integer columns
                          • WHEN col.a.dot(col.b) runs on a = 1, 2, 3 and b = 4, 5, 6
                          • THEN the result is one row holding 32
                          missing-values10 requirements

                          Purpose: How Nanuq represents missing values (Polars nulls) in its Nim API: building data with gaps, reading it back, and testing, filling and dropping nulls in queries.

                          Nulls are read as Option

                          Reading a column or a cell with the type Option[T] SHALL return none(T) for each null and some(value) otherwise, for T in int, float, bool and string.

                          let df = newDataFrame(series("a", [some(1), none(int), some(3)]))
                          echo df.toList("a", Option[int])
                          echo df["a", 1, Option[int]]
                          @[some(1), none(int), some(3)]
                          none(int)
                          Scenario: Column with gaps
                          • WHEN a column holds 1, null, 3 and is read with toList(df, "a", Option[int])
                          • THEN the result is @[some(1), none(int), some(3)]
                          Scenario: Single cell
                          • WHEN the null cell is read with df["a", 1, Option[int]]
                          • THEN the result is none(int)
                          Plain reads refuse nulls

                          Reading a column or a cell with a plain type T SHALL raise InvalidOperationError if the values read include a null, and the message SHALL name the column.

                          let df = newDataFrame(series("a", [some(1), none(int)]))
                          try:
                            discard df.toList("a", int)
                          except PolarsError as e:
                            echo e.name
                          InvalidOperationError
                          Scenario: Column with a null read as int
                          • WHEN a column with one null is read with toList(df, "a", int)
                          • THEN InvalidOperationError is raised before any value is returned, naming column "a"
                          Inspecting nulls

                          The API SHALL report the number of nulls in a column and whether it has any, and SHALL provide nullCount on expressions as an aggregation (u32), usable in select and agg.

                          let df = newDataFrame(series("a", [some(1), none(int), some(3)]))
                          echo df.nullCount("a"), " ", df.hasNulls("a")
                          echo df.select(col.a.nullCount.alias("missing"))
                          1 true
                          shape: (1, 1)
                          ┌─────────┐
                          │ missing │
                          │ ---     │
                          │ u32     │
                          ╞═════════╡
                          │ 1       │
                          └─────────┘
                          Scenario: Counting
                          • WHEN a column of 3 values has 1 null
                          • THEN nullCount(df, "a") is 1 and hasNulls(df, "a") is true
                          Scenario: No nulls
                          • WHEN a column has no nulls
                          • THEN nullCount is 0 and hasNulls is false
                          Scenario: Null count per group
                          • WHEN groupBy(col.g).agg(col.a.nullCount) runs on groups with 1 and 0 nulls
                          • THEN the result has 1 and 0 for those groups
                          Building columns with nulls

                          series SHALL accept openArray[Option[T]] for int, float, bool and string, storing none as null with the same dtype as the plain version.

                          let df = newDataFrame(series("a", [some(1), none(int)]), series("s", [none(string), some("x")]))
                          echo df
                          shape: (2, 2)
                          ┌──────┬──────┐
                          │ a    ┆ s    │
                          │ ---  ┆ ---  │
                          │ i64  ┆ str  │
                          ╞══════╪══════╡
                          │ 1    ┆ null │
                          │ null ┆ x    │
                          └──────┴──────┘
                          Scenario: Round trip
                          • WHEN a DataFrame is built from series("a", [some(1), none(int)])
                          • THEN dtype(df, "a") is "i64", nullCount(df, "a") is 1, and reading it as Option[int] gives back the input
                          CSV null markers

                          readCsv SHALL accept a list of strings to read as null. Without it, behavior is unchanged: only empty fields are null.

                          let path = getTempDir() / "bears.csv"
                          writeFile(path, "bear,weight\nNanuq,410\nUrsa,NA\n")
                          echo readCsv(path, nullValues = ["NA"])
                          shape: (2, 2)
                          ┌───────┬────────┐
                          │ bear  ┆ weight │
                          │ ---   ┆ ---    │
                          │ str   ┆ i64    │
                          ╞═══════╪════════╡
                          │ Nanuq ┆ 410    │
                          │ Ursa  ┆ null   │
                          └───────┴────────┘
                          Scenario: NA marker
                          • WHEN a CSV file with "NA" in a numeric column is read with nullValues = @["NA"]
                          • THEN that column is numeric and the "NA" fields are null
                          Null expressions

                          The API SHALL provide isNull and isNotNull on expressions (giving booleans), and fillNull replacing nulls with a literal or an expression.

                          let df = newDataFrame(series("a", [some(1), none(int), some(3)]))
                          echo df.select(col("a").isNull.alias("missing"), col("a").fillNull(0).alias("filled"))
                          echo df.filter(col("a").isNotNull).toList("a", int)
                          shape: (3, 2)
                          ┌─────────┬────────┐
                          │ missing ┆ filled │
                          │ ---     ┆ ---    │
                          │ bool    ┆ i64    │
                          ╞═════════╪════════╡
                          │ false   ┆ 1      │
                          │ true    ┆ 0      │
                          │ false   ┆ 3      │
                          └─────────┴────────┘
                          @[1, 3]
                          Scenario: Filter out nulls
                          • WHEN a LazyFrame is filtered with col("a").isNotNull and collected
                          • THEN the result has no nulls in column "a"
                          Scenario: Fill nulls
                          • WHEN withColumns(col("a").fillNull(0)) is applied to a column 1, null, 3
                          • THEN column "a" becomes 1, 0, 3
                          Dropping rows with nulls

                          LazyFrame and DataFrame SHALL provide dropNulls, removing rows with a null in any column, or only in the named columns when a subset is given.

                          let df = newDataFrame(series("a", [some(1), none(int), some(3)]),
                                                series("b", [some("x"), some("y"), none(string)]))
                          echo df.dropNulls.shape          # any column
                          echo df.dropNulls("a")           # only column a
                          (1, 2)
                          shape: (2, 2)
                          ┌─────┬──────┐
                          │ a   ┆ b    │
                          │ --- ┆ ---  │
                          │ i64 ┆ str  │
                          ╞═════╪══════╡
                          │ 1   ┆ x    │
                          │ 3   ┆ null │
                          └─────┴──────┘
                          Scenario: Subset
                          • WHEN dropNulls(["a"]) is applied to rows where "a" has one null and "b" another, in different rows
                          • THEN only the row with the null in "a" is removed
                          Interpolation

                          e.interpolate() SHALL fill nulls that lie between two values on a straight line between them, or with the nearest value for interpolate(how = Nearest); e.interpolateBy(by) SHALL interpolate linearly using the distances in column by. Nulls before the first and after the last value SHALL stay null.

                          let df = newDataFrame:
                            day: [1, 2, 4, 5]
                            temp: [10.0, nil, 16.0, nil]
                          echo df.withColumns(col.temp.interpolate.alias("linear"),
                                              col.temp.interpolateBy("day").alias("by_day"))
                          shape: (4, 4)
                          ┌─────┬──────┬────────┬────────┐
                          │ day ┆ temp ┆ linear ┆ by_day │
                          │ --- ┆ ---  ┆ ---    ┆ ---    │
                          │ i64 ┆ f64  ┆ f64    ┆ f64    │
                          ╞═════╪══════╪════════╪════════╡
                          │ 1   ┆ 10.0 ┆ 10.0   ┆ 10.0   │
                          │ 2   ┆ null ┆ 13.0   ┆ 12.0   │
                          │ 4   ┆ 16.0 ┆ 16.0   ┆ 16.0   │
                          │ 5   ┆ null ┆ null   ┆ null   │
                          └─────┴──────┴────────┴────────┘
                          Scenario: Integer column
                          • WHEN interpolate runs on 1, null, 3
                          • THEN the result is 1.0, 2.0, 3.0
                          Null literal

                          lit(nil) SHALL be a null literal (Python's pl.lit(None)), usable wherever an expression is, and fillNan(nil) SHALL turn NaN values into nulls.

                          let df = newDataFrame:
                            x: [1.0, NaN, 3.0]
                          echo df.select(col.x.fillNan(nil).alias("x"), col.x.fillNan(nil).nullCount.alias("nulls"))
                          shape: (3, 2)
                          ┌──────┬───────┐
                          │ x    ┆ nulls │
                          │ ---  ┆ ---   │
                          │ f64  ┆ u32   │
                          ╞══════╪═══════╡
                          │ 1.0  ┆ 1     │
                          │ null ┆ 1     │
                          │ 3.0  ┆ 1     │
                          └──────┴───────┘
                          Scenario: Null column
                          • WHEN select(lit(nil).alias("n")) runs with another column of 3 rows
                          • THEN n holds 3 nulls
                          Filling nulls in whole frames

                          DataFrame and LazyFrame SHALL support fillNull(value), filling the columns the value fits (a number: numeric columns, where a float turns integer columns into Float64; a string: String columns; a bool: Boolean columns), and fillNull(strategy, limit) on every column (Python's df.fill_null).

                          let df = newDataFrame:
                            peak: ["Dom", "Täschhorn"]
                            m: [some(4545), none(int)]
                            first_ascent: [some(1858), none(int)]
                          echo df.fillNull(0)
                          shape: (2, 3)
                          ┌───────────┬──────┬──────────────┐
                          │ peak      ┆ m    ┆ first_ascent │
                          │ ---       ┆ ---  ┆ ---          │
                          │ str       ┆ i64  ┆ i64          │
                          ╞═══════════╪══════╪══════════════╡
                          │ Dom       ┆ 4545 ┆ 1858         │
                          │ Täschhorn ┆ 0    ┆ 0            │
                          └───────────┴──────┴──────────────┘
                          Scenario: Float value
                          • WHEN fillNull(0.5) runs on a frame with an Int64 column with nulls
                          • THEN that column becomes Float64 and its nulls hold 0.5
                          Scenario: String value
                          • WHEN fillNull("x") runs on a frame with Int64 and String columns
                          • THEN only the String column is filled
                          native-bridge8 requirements

                          Purpose: How Nanuq reaches Polars: a Rust crate (rust/, nanuq_ffi) exports a C ABI, it is linked as a static library, and src/nanuq/ffi.nim declares it to Nim.

                          C ABI over Polars with opaque handles

                          The nanuq_ffi crate SHALL expose Polars objects (DataFrame, LazyFrame, Expr, Series) only as opaque heap pointers through extern "C" functions, each type with a matching *_free function. Functions SHALL borrow their pointer arguments and return newly allocated objects.

                          Scenario: Ownership stays with the caller
                          • WHEN Nim passes a DataFrame pointer to an FFI function
                          • THEN the pointer stays valid and owned by Nim after the call
                          • AND any object the function returns is a new pointer that Nim must free exactly once
                          Errors and panics never cross the boundary

                          Every FFI function SHALL catch Polars errors and Rust panics, signal failure with a NULL (or false / -1) return, and make the message available through nq_last_error and its kind through nq_last_error_kind.

                          Scenario: Polars error
                          • WHEN an operation fails in Polars (e.g. a missing column)
                          • THEN the function returns NULL and nq_last_error returns the Polars message
                          Scenario: Rust panic
                          • WHEN Polars panics inside an FFI call
                          • THEN the panic is caught, the call returns NULL, and no unwinding reaches Nim
                          Scenario: Error kind
                          • WHEN an operation fails with a Polars ColumnNotFound error, possibly wrapped in context
                          • THEN nq_last_error_kind returns ColumnNotFound
                          Nim declarations mirror the C ABI

                          src/nanuq/ffi.nim SHALL declare every exported function with matching signatures, and the enums NqBinOp, NqUnary, NqDtype, NqDtypeClass, NqJoinType, NqJoinValidation, NqMaintainOrderJoin, NqConcat, NqUniqueKeepStrategy, NqClosedInterval, NqQuantileMethod, NqFillNullStrategy, NqRoundMode, NqQuoteStyle, NqRankMethod, NqErrorKind, NqStrOp, NqTimeUnit, NqClosedWindow, NqDtOp, NqCatOp, NqParquetCompression and NqIpcCompression SHALL keep the same order as in Rust. NqDtype SHALL also keep the order of DataTypeKind, and the option enums the order of their Nim API enums. Data types SHALL cross the ABI as an NqDtypeSpec struct (code, time unit, time zone, categories) with the same field order on both sides.

                          Scenario: ABI change
                          • WHEN a function is added or changed in rust/src/lib.rs
                          • THEN src/nanuq/ffi.nim is updated in the same change
                          Linking the static library

                          Importing nanuq SHALL link libnanuq_ffi.a from the first of these sources that has it: the directory given with -d:nanuqLibDir, the local cargo output of the crate in src/rust/, the prebuilt library (see binary-distribution), and finally a cargo build of src/rust/ run at compile time. -d:nanuqLib=auto (the default) allows all sources. -d:nanuqLib=prebuilt (or -d:nanuqNoCargo) never runs cargo. -d:nanuqLib=source never downloads. The crate SHALL ship inside the installed package, so the cargo fallback also works after nimble install.

                          Scenario: Library missing, cargo allowed
                          • WHEN no local library exists, no prebuilt library is available, and the policy is
                          • auto or source
                          • THEN compilation runs cargo build --release for src/rust/ and links the result
                          Scenario: Library missing, cargo disabled
                          • WHEN no local or prebuilt library is available and the policy is prebuilt
                          • THEN compilation fails with an error naming the expected library path and how to
                          • get one
                          Scenario: Installed with nimble
                          • WHEN a user runs nimble install nanuq on a platform without a prebuilt library
                          • and has cargo
                          • THEN compiling a program that imports nanuq builds the library from the
                          • installed package's sources and links it
                          Columns cross in bulk

                          Reading a whole column into Nim SHALL take a constant number of FFI calls, independent of the number of rows, and SHALL transfer a validity mask alongside the values so nulls are not lost or replaced by placeholder values.

                          Scenario: Large column
                          • WHEN a 1,000,000-row float column is read into a Nim seq
                          • THEN at most two FFI calls are made for that column
                          Scenario: Validity
                          • WHEN a column with nulls crosses the boundary
                          • THEN Nim receives, for every row, whether the value is valid
                          Library version check

                          The library SHALL report its version through the C ABI. At startup, Nanuq SHALL compare it with the lib version it was compiled for and stop with an error naming both versions if they differ.

                          Scenario: Stale library
                          • WHEN -d:nanuqLibDir points at a library built from an older crate version
                          • THEN the program stops at startup with an error naming both versions
                          Formatted cells

                          The bridge SHALL return a single cell as text formatted by Polars, as Python Polars' get_fmt does: the value's display form, with strings in quotes and cut to a given number of characters followed by ….

                          Scenario: Float cell
                          • WHEN a cell holding 5076.016260162602 is formatted
                          • THEN the text is the same as in Polars' text table, 5076.01626
                          Scenario: Long string
                          • WHEN a string of 40 characters is formatted with a limit of 30
                          • THEN the text is a quote, its first 30 characters and …
                          Polars version matches a py-polars release

                          The nanuq_ffi crate SHALL depend on Polars by the git tag of a py-polars release (py-X.Y.Z), the same version the Nanuq Book and the explainers use as their Python oracle, with the [patch.crates-io] entries of Polars' workspace at that tag; release builds SHALL use that tag's Rust toolchain. Moving to a new py-polars release SHALL move the tag, the patches, the toolchain and the Python oracle together.

                          Scenario: Same results as Python
                          • WHEN a book chapter runs the same query in Nanuq and in the pinned py-polars
                          • THEN the outputs agree, including SQL table functions and seeded hash/sample
                          nested-data4 requirements

                          Purpose: List, Array and Struct data types, and nested values between Nim and Polars.

                          Nested data types

                          DataType SHALL have the kinds List, Array and Struct, built by List(inner), Array(inner, width) (or a shape, Array(Int64, [2, 3])) and Struct(fields) (from {"name": dtype} pairs or a seq of Field). inner, width, shape and fields SHALL read them back, $ SHALL print the constructor call (List(Int64), Array(Int64, [2, 3]), Struct({"x": Float64})) and == SHALL compare the whole type.

                          let point = Struct({"x": Float64, "y": Float64})
                          echo List(Int64), " ", Array(Float64, 3), " ", Array(Int64, [2, 3]), " ", point
                          echo List(point).inner == point, " ", Array(Int64, [2, 3]).shape, " ", point.fields[1].name
                          List(Int64) Array(Float64, 3) Array(Int64, [2, 3]) Struct({"x": Float64, "y": Float64})
                          true @[2, 3] y
                          Scenario: Schema of nested columns
                          • WHEN the schema of a frame with a list of strings column is read
                          • THEN its dtype is List(String) and $ gives List(String)
                          Scenario: Struct field types
                          • WHEN fields is read from the dtype of a struct column built from (x: 1, y: 2.0)
                          • THEN it holds x: Int64 and y: Float64, in order
                          Nested columns from Nim

                          series(name, values) SHALL build a List column from seqs, an Array column from Nim arrays, and a Struct column from objects or named tuples, at any depth (seqs of objects, objects with seq fields). Option values SHALL be null rows, and Option elements null values inside a list. The newDataFrame block and toDataFrame(rows) SHALL take the same values; in the block nil SHALL be a null row. lit(seq) SHALL be a list literal.

                          let df = newDataFrame:
                            tags: [@["polar", "bear"], @[], nil]
                            point: [(x: 1, y: 2.0), (x: 3, y: 4.0), (x: 5, y: 6.0)]
                            rgb: [[255, 0, 0], [0, 255, 0], [0, 0, 255]]
                          echo df
                          echo df.select(lit(@[1, 2]).alias("lit"))
                          shape: (3, 3)
                          ┌───────────────────┬───────────┬───────────────┐
                          │ tags              ┆ point     ┆ rgb           │
                          │ ---               ┆ ---       ┆ ---           │
                          │ list[str]         ┆ struct[2] ┆ array[i64, 3] │
                          ╞═══════════════════╪═══════════╪═══════════════╡
                          │ ["polar", "bear"] ┆ {1,2.0}   ┆ [255, 0, 0]   │
                          │ []                ┆ {3,4.0}   ┆ [0, 255, 0]   │
                          │ null              ┆ {5,6.0}   ┆ [0, 0, 255]   │
                          └───────────────────┴───────────┴───────────────┘
                          shape: (1, 1)
                          ┌───────────┐
                          │ lit       │
                          │ ---       │
                          │ list[i64] │
                          ╞═══════════╡
                          │ [1, 2]    │
                          └───────────┘
                          Scenario: Empty lists keep their type
                          • WHEN series("a", newSeq[seq[int]](2)) is built
                          • THEN its dtype is List(Int64) and both values are empty lists
                          Scenario: Null values inside a list
                          • WHEN series("a", @[@[some(1), none(int)]]) is built
                          • THEN the list holds 1 and null
                          Nested values to Nim

                          toList(column, T) SHALL read a List column as seq[U], an Array column as array[N, U] or seq[U], and a Struct column as an object or named tuple matching fields by name, on frames and Series, at any depth; Option[T] SHALL read null rows as none. Cell reads df[column, row, T] and rows(T) SHALL take the same types. A null read into a plain type SHALL raise InvalidOperationError, and an object field without a struct field ColumnNotFoundError.

                          type Point = object
                            x: int
                            y: float
                          let df = newDataFrame:
                            tags: [@["polar", "bear"], @[]]
                            point: [Point(x: 1, y: 2.0), Point(x: 3, y: 4.0)]
                          echo df.toList("tags", seq[string])
                          echo df.toList("point", Point)
                          echo df["point", 1, tuple[x: int]]
                          for r in df.rows(tuple[tags: seq[string], point: Point]):
                            echo r.tags.len, " ", r.point.y
                          @[@["polar", "bear"], @[]]
                          @[(x: 1, y: 2.0), (x: 3, y: 4.0)]
                          (x: 3)
                          2 2.0
                          0 4.0
                          Scenario: Round trip
                          • WHEN a seq of objects with seq and object fields is turned into a frame and read back with rows
                          • THEN the result equals the original seq
                          Scenario: Null row
                          • WHEN a list column with a null row is read as seq[int] rows
                          • THEN InvalidOperationError is raised; read as Option[seq[int]] it gives none
                          Casting to nested types

                          cast(dtype) and castTo SHALL accept nested data types, and cast(T) nested Nim types.

                          let df = newDataFrame(series("a", @[@[1, 2], @[3]]))
                          echo df.select(col("a").cast(List(Float64)), col("a").cast(seq[string]).alias("s"))
                          shape: (2, 2)
                          ┌────────────┬────────────┐
                          │ a          ┆ s          │
                          │ ---        ┆ ---        │
                          │ list[f64]  ┆ list[str]  │
                          ╞════════════╪════════════╡
                          │ [1.0, 2.0] ┆ ["1", "2"] │
                          │ [3.0]      ┆ ["3"]      │
                          └────────────┴────────────┘
                          Scenario: List to array
                          • WHEN a list column whose lists all have 2 values is cast to Array(Int64, 2)
                          • THEN the result is an array column
                          parquet-ipc6 requirements

                          Purpose: Reading and writing Parquet and Arrow IPC (Feather v2) files, lazily or eagerly, from paths or Nim streams.

                          Reading Parquet

                          The API SHALL provide scanParquet(path, ...), a lazy scan of a file or a glob, and readParquet(path, ...), which is scanParquet(...).collect. Both SHALL take nRows, columns, rowIndexName with rowIndexOffset = 0, and lowMemory = false. Every dtype Nanuq models SHALL round-trip through Parquet unchanged.

                          let path = getTempDir() / "riders.parquet"
                          let df = newDataFrame:
                            rider: ["Seixas", "Pogačar", "Evenepoel"]
                            born: [date(2006, 9, 24), date(1998, 9, 21), date(2000, 1, 25)]
                            wins: [3, 22, nil]
                          df.writeParquet(path)
                          echo readParquet(path, columns = ["rider", "born"], nRows = 2, rowIndexName = "nr")
                          shape: (2, 3)
                          ┌─────┬─────────┬────────────┐
                          │ nr  ┆ rider   ┆ born       │
                          │ --- ┆ ---     ┆ ---        │
                          │ u32 ┆ str     ┆ date       │
                          ╞═════╪═════════╪════════════╡
                          │ 0   ┆ Seixas  ┆ 2006-09-24 │
                          │ 1   ┆ Pogačar ┆ 1998-09-21 │
                          └─────┴─────────┴────────────┘
                          Scenario: Round trip
                          • WHEN a DataFrame with string, date and nullable integer columns is written and read back
                          • THEN the result equals the original, dtypes included
                          Scenario: Not Parquet
                          • WHEN bytes that are not Parquet are read
                          • THEN PolarsError is raised
                          Writing Parquet

                          writeParquet(df, path, compression = ParquetCompression.Zstd, compressionLevel = none(int), statistics = true, rowGroupSize = none(int)) SHALL write a Parquet file. compressionLevel SHALL apply to Gzip, Brotli and Zstd; with another codec it SHALL raise ValueError, and an out-of-range level SHALL raise PolarsError.

                          import std/sequtils
                          let path = getTempDir() / "sizes.parquet"
                          let df = newDataFrame(series("n", toSeq(1..1000)))
                          for c in [ParquetCompression.Uncompressed, ParquetCompression.Zstd]:
                            df.writeParquet(path, compression = c)
                            echo c, " ", getFileSize(path) < 5000
                          Uncompressed false
                          Zstd true
                          Scenario: Every codec
                          • WHEN a DataFrame is written with each ParquetCompression value
                          • THEN each file reads back with the same rows
                          Scenario: Level without a level
                          • WHEN writeParquet(path, compression = ParquetCompression.Snappy, compressionLevel = 3) is called
                          • THEN ValueError is raised
                          Scenario: Missing directory
                          • WHEN the target directory does not exist
                          • THEN IOError is raised
                          Arrow IPC

                          The API SHALL provide scanIpc and readIpc with the read options of Parquet, and writeIpc(df, path, compression = IpcCompression.Uncompressed) with Lz4 and Zstd.

                          let path = getTempDir() / "riders.arrow"
                          let df = newDataFrame:
                            rider: ["Seixas", "Pogačar"]
                            start: [timeOfDay(13, 10), timeOfDay(13, 12)]
                          df.writeIpc(path, compression = IpcCompression.Lz4)
                          echo readIpc(path).schema
                          {"rider": String, "start": TimeOfDay}
                          Scenario: Round trip
                          • WHEN a DataFrame is written with each IpcCompression and read back
                          • THEN the result equals the original
                          Reading from streams

                          readParquet and readIpc SHALL also take a Nim Stream instead of a path, read all of it when called, and take the same options.

                          import std/streams
                          let path = getTempDir() / "one.parquet"
                          newDataFrame(series("a", [1, 2])).writeParquet(path)
                          echo readParquet(newStringStream(readFile(path))).shape
                          (2, 1)
                          Scenario: Bytes in memory
                          • WHEN the bytes of a Parquet file are read with readParquet(newStringStream(bytes))
                          • THEN the result equals reading the file
                          Hive partitioning switch

                          scanParquet and readParquet SHALL take hivePartitioning: true reads key=value directories as columns, false does not, none(bool) (default) decides by the path.

                          let base = getTempDir() / "nanuq-hive"
                          let df = newDataFrame(series("year", @[2024, 2025]), series("n", @[1, 2]))
                          df.lazy.sinkParquet(PartitionBy(basePath: base, key: @["year"], includeKey: false), mkdir = true)
                          echo scanParquet(base / "**/*.parquet", hivePartitioning = false).collect.columns
                          @["n"]
                          Scenario: On
                          • WHEN the same files are scanned with hivePartitioning = true
                          • THEN the frame has a year column
                          Arrow IPC streams

                          writeIpcStream(path, compression) SHALL write the Arrow IPC stream format, and readIpcStream SHALL read it from a path or a stream.

                          let path = getTempDir() / "bears.arrows"
                          newDataFrame(series("kg", @[410, 380])).writeIpcStream(path)
                          echo readIpcStream(path).toList("kg", int)
                          @[410, 380]
                          Scenario: Compressed
                          • WHEN a frame is written with IpcCompression.Zstd and read back
                          • THEN the frames are equal
                          plan-serialization3 requirements

                          Purpose: Saving and loading query plans and expressions (binary or JSON), and inspecting expressions with the meta namespace.

                          Serializing query plans

                          lf.serialize(format = SerializationFormat.Binary) SHALL return the LazyFrame's plan as bytes (in a string), Json as JSON text, and lf.serialize(path, format) SHALL write it to a file. deserialize(LazyFrame, data, format) and deserializeFile(LazyFrame, path, format) SHALL rebuild a LazyFrame that collects to the same result. In-memory frames in the plan SHALL travel with it.

                          let lf = newDataFrame(series("kg", @[410, 380, 455])).lazy.filter(col("kg") > 400)
                          let bytes = lf.serialize
                          echo deserialize(LazyFrame, bytes).collect
                          echo lf.serialize(SerializationFormat.Json).len > 0
                          shape: (2, 1)
                          ┌─────┐
                          │ kg  │
                          │ --- │
                          │ i64 │
                          ╞═════╡
                          │ 410 │
                          │ 455 │
                          └─────┘
                          true
                          Scenario: Not a plan
                          • WHEN deserialize(LazyFrame, "garbage") is called
                          • THEN PolarsError is raised
                          Scenario: Nim callbacks
                          • WHEN a plan with mapElements is serialized
                          • THEN PolarsError is raised
                          Serializing expressions

                          e.meta.serialize(format) SHALL return an expression as bytes or JSON, and deserialize(Expr, data, format) SHALL rebuild it.

                          let e = (col("kg") * 2).alias("double")
                          let back = deserialize(Expr, e.meta.serialize)
                          echo back.meta.eq(e)
                          echo newDataFrame(series("kg", @[1, 2])).select(back)
                          true
                          shape: (2, 1)
                          ┌────────┐
                          │ double │
                          │ ---    │
                          │ i64    │
                          ╞════════╡
                          │ 2      │
                          │ 4      │
                          └────────┘
                          Scenario: JSON round trip
                          • WHEN an expression is serialized with Json and deserialized with Json
                          • THEN meta.eq with the original is true
                          Expression metadata

                          The meta namespace SHALL also provide eq(other) and ne(other) (same expression tree), pop (the inputs of the outermost node), isRegexProjection, isColumnSelection(allowAliasing = false), isLiteral(allowAliasing) and treeFormat (the tree as text).

                          let e = (col("a") + col("b")).alias("c")
                          echo e.meta.undoAliases.meta.outputName
                          echo e.meta.pop.len
                          echo col("^x.*$").meta.isRegexProjection, " ", col("a").alias("b").meta.isColumnSelection(allowAliasing = true)
                          echo (col("a") + 1).meta.treeFormat
                          a
                          1
                          true true
                                         0               1
                             ┌─────────────────────────────────
                             │
                             │     ╭───────────╮
                           0 │     │ binary: + │
                             │     ╰─────┬┬────╯
                             │           ││
                             │           │╰──────────────╮
                             │           │               │
                             │  ╭────────┴────────╮  ╭───┴────╮
                           1 │  │ lit(dyn int: 1) │  │ col(a) │
                             │  ╰─────────────────╯  ╰────────╯
                          Scenario: Different trees
                          • WHEN col("a").meta.eq(col("b")) is called
                          • THEN it is false
                          reshaping5 requirements

                          Purpose: Changing the shape of a frame: long to wide (pivot), wide to long (unpivot), rows to columns (transpose), splitting by key (partitionBy) and dummy columns.

                          Pivot

                          df.pivot(on, index, values, aggregateFunction = PivotAgg.Item, maintainOrder = true, sortColumns = false, separator = "_") SHALL turn each distinct value of the on columns into a column (in order of appearance, or sorted), with one row per distinct index value and cells from values combined by aggregateFunction, a PivotAgg or an expression on element(). When index or values is left out it SHALL mean every other column. lf.pivot(on, onColumns, ...) SHALL do the same lazily with the new columns listed in the DataFrame onColumns.

                          let df = newDataFrame:
                            year: [2023, 2023, 2024, 2024]
                            season: ["DJF", "JJA", "DJF", "JJA"]
                            oni: [-0.7, 1.1, 1.8, 0.0]
                          echo df.pivot("season", index = "year", values = "oni")
                          shape: (2, 3)
                          ┌──────┬──────┬─────┐
                          │ year ┆ DJF  ┆ JJA │
                          │ ---  ┆ ---  ┆ --- │
                          │ i64  ┆ f64  ┆ f64 │
                          ╞══════╪══════╪═════╡
                          │ 2023 ┆ -0.7 ┆ 1.1 │
                          │ 2024 ┆ 1.8  ┆ 0.0 │
                          └──────┴──────┴─────┘
                          Scenario: Aggregating duplicates
                          • WHEN two rows share an index and an on value and aggregateFunction = Sum
                          • THEN their cell holds the sum of both values
                          Scenario: Duplicates without an aggregation
                          • WHEN two rows share an index and an on value and no aggregation is given
                          • THEN pivot raises a PolarsError
                          Unpivot

                          unpivot(on, index, variableName = "variable", valueName = "value") on a DataFrame or LazyFrame SHALL turn the on columns (by default every column not in index) into rows, one per index value and on column, holding the column's name and value.

                          let df = newDataFrame:
                            year: [2023, 2024]
                            DJF: [-0.7, 1.8]
                            JJA: [1.1, 0.0]
                          echo df.unpivot(index = "year", variableName = "season", valueName = "oni")
                          shape: (4, 3)
                          ┌──────┬────────┬──────┐
                          │ year ┆ season ┆ oni  │
                          │ ---  ┆ ---    ┆ ---  │
                          │ i64  ┆ str    ┆ f64  │
                          ╞══════╪════════╪══════╡
                          │ 2023 ┆ DJF    ┆ -0.7 │
                          │ 2024 ┆ DJF    ┆ 1.8  │
                          │ 2023 ┆ JJA    ┆ 1.1  │
                          │ 2024 ┆ JJA    ┆ 0.0  │
                          └──────┴────────┴──────┘
                          Scenario: Round trip
                          • WHEN a long frame is pivoted and the result unpivoted on the new columns
                          • THEN the rows are the original rows
                          Transpose

                          df.transpose(includeHeader = false, headerName = "column", columnNames) SHALL turn rows into columns, naming them columnNames or column_0, column_1, ..., and with includeHeader SHALL put the old column names in a first column headerName.

                          let df = newDataFrame:
                            lima: [22.1, 24.3]
                            quito: [14.0, 14.2]
                          echo df.transpose(includeHeader = true, headerName = "station", columnNames = ["jan", "feb"])
                          shape: (2, 3)
                          ┌─────────┬──────┬──────┐
                          │ station ┆ jan  ┆ feb  │
                          │ ---     ┆ ---  ┆ ---  │
                          │ str     ┆ f64  ┆ f64  │
                          ╞═════════╪══════╪══════╡
                          │ lima    ┆ 22.1 ┆ 24.3 │
                          │ quito   ┆ 14.0 ┆ 14.2 │
                          └─────────┴──────┴──────┘
                          Scenario: Default names
                          • WHEN a frame with two rows is transposed without names
                          • THEN its columns are column_0 and column_1
                          Partition

                          df.partitionBy(by, maintainOrder = true, includeKey = true) SHALL return one DataFrame per distinct value of the by columns, in order of appearance with maintainOrder, and without the by columns when includeKey is false.

                          let df = newDataFrame:
                            phase: ["El Niño", "La Niña", "El Niño"]
                            year: [2015, 2020, 2023]
                          for part in df.partitionBy("phase", includeKey = false):
                            echo part.toList("year", int)
                          @[2015, 2023]
                          @[2020]
                          Scenario: Several keys
                          • WHEN partitionBy(["a", "b"]) runs on rows with three distinct (a, b) pairs
                          • THEN the result has three frames
                          Dummy columns

                          df.toDummies(columns, separator = "_", dropFirst = false, dropNulls = false) SHALL replace each listed column (all by default) by one 0/1 column per distinct value, named column, separator and value.

                          let df = newDataFrame:
                            phase: ["warm", "cold", "warm"]
                          echo df.toDummies()
                          shape: (3, 2)
                          ┌────────────┬────────────┐
                          │ phase_cold ┆ phase_warm │
                          │ ---        ┆ ---        │
                          │ u8         ┆ u8         │
                          ╞════════════╪════════════╡
                          │ 0          ┆ 1          │
                          │ 1          ┆ 0          │
                          │ 0          ┆ 1          │
                          └────────────┴────────────┘
                          Scenario: Drop first
                          • WHEN toDummies(dropFirst = true) runs on a column with values a and b
                          • THEN only one dummy column remains
                          rolling-windows3 requirements

                          Purpose: Statistics over moving windows: a fixed number of rows, or a time span of a sorted column, and exponentially weighted statistics.

                          Fixed rolling windows

                          rollingSum, rollingMean, rollingMin, rollingMax, rollingMedian, rollingStd, rollingVar and rollingQuantile SHALL compute their statistic over the last windowSize rows, or over a window centred on each row with center = true. A row SHALL get null until minSamples non-null values are in its window (by default windowSize), and weights, when given, SHALL multiply the values of each window.

                          let df = newDataFrame:
                            season: ["NDJ", "DJF", "JFM", "FMA", "MAM"]
                            anomaly: [1.9, 2.1, 1.6, 1.0, 0.4]
                          echo df.withColumns(col.anomaly.rollingMean(3).round(2).alias("mean3"),
                                              col.anomaly.rollingMean(3, center = true).round(2).alias("centred"),
                                              col.anomaly.rollingMax(2, minSamples = 1).alias("max2"))
                          shape: (5, 5)
                          ┌────────┬─────────┬───────┬─────────┬──────┐
                          │ season ┆ anomaly ┆ mean3 ┆ centred ┆ max2 │
                          │ ---    ┆ ---     ┆ ---   ┆ ---     ┆ ---  │
                          │ str    ┆ f64     ┆ f64   ┆ f64     ┆ f64  │
                          ╞════════╪═════════╪═══════╪═════════╪══════╡
                          │ NDJ    ┆ 1.9     ┆ null  ┆ null    ┆ 1.9  │
                          │ DJF    ┆ 2.1     ┆ null  ┆ 1.87    ┆ 2.1  │
                          │ JFM    ┆ 1.6     ┆ 1.87  ┆ 1.57    ┆ 2.1  │
                          │ FMA    ┆ 1.0     ┆ 1.57  ┆ 1.0     ┆ 1.6  │
                          │ MAM    ┆ 0.4     ┆ 1.0   ┆ null    ┆ 1.0  │
                          └────────┴─────────┴───────┴─────────┴──────┘
                          Scenario: Window not full yet
                          • WHEN rollingSum(3) runs on 1, 2, 3, 4
                          • THEN the result is null, null, 6, 9
                          Scenario: Weights
                          • WHEN rollingSum(2, weights = [0.5, 1.0]) runs on 2.0, 4.0
                          • THEN the second value is 5.0
                          Scenario: Invalid window
                          • WHEN rollingMean(0) is built
                          • THEN ValueError is raised
                          Time rolling windows

                          The same functions with a By suffix SHALL take a sorted column by (temporal or integer) and a window size as a std/times interval or Polars duration string; the window of each row SHALL span windowSize back from its by value, with ends included as closed (ClosedWindow, default Right) says, and rows SHALL need minSamples values (default 1).

                          let df = newDataFrame:
                            day: [date(2026, 7, 1), date(2026, 7, 2), date(2026, 7, 5), date(2026, 7, 6)]
                            rain: [4, 0, 10, 2]
                          echo df.withColumns(col.rain.rollingSumBy("day", 3.days).alias("last_3_days"))
                          shape: (4, 3)
                          ┌────────────┬──────┬─────────────┐
                          │ day        ┆ rain ┆ last_3_days │
                          │ ---        ┆ ---  ┆ ---         │
                          │ date       ┆ i64  ┆ i64         │
                          ╞════════════╪══════╪═════════════╡
                          │ 2026-07-01 ┆ 4    ┆ 4           │
                          │ 2026-07-02 ┆ 0    ┆ 4           │
                          │ 2026-07-05 ┆ 10   ┆ 10          │
                          │ 2026-07-06 ┆ 2    ┆ 12          │
                          └────────────┴──────┴─────────────┘
                          Scenario: Gaps in the dates
                          • WHEN rollingSumBy("day", 3.days) runs on July 1, 2, 5, 6 with 4, 0, 10, 2
                          • THEN the result is 4, 4, 10, 12
                          Exponentially weighted functions

                          ewmMean, ewmStd and ewmVar SHALL compute exponentially weighted statistics with the decay given by exactly one of com, span, halfLife or alpha, converted to alpha as Python Polars does, and SHALL take adjust, minSamples and ignoreNulls (and bias for std and var). Giving none or more than one decay parameter SHALL raise ValueError.

                          let df = newDataFrame:
                            temp: [14.0, 15.0, 13.0, 16.0]
                          echo df.withColumns(col.temp.ewmMean(alpha = 0.5).round(3).alias("ewm"),
                                              col.temp.ewmMean(span = 3, adjust = false).round(3).alias("span3"))
                          shape: (4, 3)
                          ┌──────┬────────┬────────┐
                          │ temp ┆ ewm    ┆ span3  │
                          │ ---  ┆ ---    ┆ ---    │
                          │ f64  ┆ f64    ┆ f64    │
                          ╞══════╪════════╪════════╡
                          │ 14.0 ┆ 14.0   ┆ 14.0   │
                          │ 15.0 ┆ 14.667 ┆ 14.5   │
                          │ 13.0 ┆ 13.714 ┆ 13.75  │
                          │ 16.0 ┆ 14.933 ┆ 14.875 │
                          └──────┴────────┴────────┘
                          Scenario: Span and alpha agree
                          • WHEN ewmMean(span = 3) and ewmMean(alpha = 0.5) run on the same column
                          • THEN the results are equal
                          Scenario: Two decay parameters
                          • WHEN ewmMean(com = 1, alpha = 0.5) is built
                          • THEN ValueError is raised
                          row-objects2 requirements

                          Purpose: Reading the rows of a frame as typed Nim objects or named tuples, and building a frame from a seq of objects.

                          Rows as objects

                          df.rows(T) SHALL return the rows as a seq[T] and df.iterRows(T) SHALL iterate them, for T an object or named tuple whose fields are named after columns, and df.row(i, T) SHALL return row i (negative from the end). Fields SHALL be int, float, bool, string, temporal values, Nim enums, or Option of these; a null read into a plain field SHALL raise InvalidOperationError, and a field without a column ColumnNotFoundError.

                          type Reading = object
                            station: string
                            rain: float
                          let df = newDataFrame:
                            station: ["Lima", "Piura", "Tumbes"]
                            rain: [1.5, 80.0, 95.0]
                            year: [1998, 1998, 1998]
                          for r in df.iterRows(Reading):
                            echo r.station, ": ", r.rain
                          echo df.row(-1, tuple[station: string, year: int])
                          Lima: 1.5
                          Piura: 80.0
                          Tumbes: 95.0
                          (station: "Tumbes", year: 1998)
                          Scenario: Missing column
                          • WHEN rows is called with a type that has a field wind and the frame has no column wind
                          • THEN ColumnNotFoundError is raised
                          Objects to a frame

                          toDataFrame(rows) SHALL build a frame from a seq or array of objects or named tuples, with one column per field in field order; Option fields SHALL give columns with nulls.

                          type Event = object
                            year: int
                            peak: Option[float]
                          let events = @[Event(year: 1997, peak: some(2.4)), Event(year: 2014, peak: none(float))]
                          echo events.toDataFrame
                          shape: (2, 2)
                          ┌──────┬──────┐
                          │ year ┆ peak │
                          │ ---  ┆ ---  │
                          │ i64  ┆ f64  │
                          ╞══════╪══════╡
                          │ 1997 ┆ 2.4  │
                          │ 2014 ┆ null │
                          └──────┴──────┘
                          Scenario: Round trip
                          • WHEN a seq of objects is turned into a frame and read back with rows
                          • THEN the result equals the original seq
                          series8 requirements

                          Purpose: Single columns as Series: getting them from frames, reading them, operating on them through the expression methods of the same name, and putting them back into frames.

                          Getting a Series

                          df["name"] and df.getColumn("name") SHALL return the column as a Series, and df.toSeries(index = 0) the column at a position (negative from the end); a missing column SHALL raise ColumnNotFoundError. A Series SHALL have name, len, dtype, nullCount and $, which shows Polars' Series display.

                          let df = newDataFrame:
                            year: [1997, 2015, 2023]
                            oni: [2.4, 2.6, 2.0]
                          let s = df["oni"]
                          echo s
                          echo s.name, " ", s.len, " ", s.dtype
                          shape: (3,)
                          Series: 'oni' [f64]
                          [
                          	2.4
                          	2.6
                          	2.0
                          ]
                          oni 3 Float64
                          Scenario: Missing column
                          • WHEN df["nope"] runs on a frame without that column
                          • THEN ColumnNotFoundError is raised
                          Reading a Series

                          s.toList(T) and s.toList(Option[T]) SHALL return the values, s[i, T] one value, and s.item(T) the only value of a one-value Series (raising InvalidOperationError otherwise). toFrame SHALL return a one-column frame, and alias/rename and cast SHALL return a renamed or converted Series.

                          let s = series("oni", [2.4, 2.6, 2.0])
                          echo s.toList(float), " ", s[1, float]
                          echo s.toFrame.columns
                          @[2.4, 2.6, 2.0] 2.6
                          @["oni"]
                          Scenario: item on a longer Series
                          • WHEN item(float) is called on a Series of three values
                          • THEN InvalidOperationError is raised
                          Series operations

                          Series SHALL support the arithmetic, comparison and boolean operators with literals and other Series of the same length, filter(mask), and the expression methods that take no other column (aggregations, math, cumulative, rolling, ranking, distinct values, recoding, binning), each SHALL give the same values as the expression of the same name on a one-column frame. Aggregations SHALL return a Series of one value.

                          let s = series("oni", [0.5, -1.0, 2.0, 1.2])
                          echo s.max.item(float)
                          echo ((s - s.mean.item(float)) / s.std.item(float)).round(2).toList(float)
                          echo s.filter(s > 0.5).toList(float)
                          echo s.rollingMean(2).toList(Option[float])
                          2.0
                          @[-0.14, -1.31, 1.04, 0.41]
                          @[2.0, 1.2]
                          @[none(float), some(-0.25), some(0.5), some(1.6)]
                          Scenario: Two Series
                          • WHEN a + b runs on Series a = 1, 2 and b = 10, 20
                          • THEN the result is 11, 22 named like a
                          Series in frames

                          df.withColumns(series...) SHALL add or replace columns with Series of the frame's height, and lit(series) SHALL use a Series as a column in an expression.

                          let df = newDataFrame:
                            year: [1997, 2015, 2023]
                          let peak = series("peak", [2.4, 2.6, 2.0])
                          echo df.withColumns(peak, (peak * 10).alias("tenths"))
                          shape: (3, 3)
                          ┌──────┬──────┬────────┐
                          │ year ┆ peak ┆ tenths │
                          │ ---  ┆ ---  ┆ ---    │
                          │ i64  ┆ f64  ┆ f64    │
                          ╞══════╪══════╪════════╡
                          │ 1997 ┆ 2.4  ┆ 24.0   │
                          │ 2015 ┆ 2.6  ┆ 26.0   │
                          │ 2023 ┆ 2.0  ┆ 20.0   │
                          └──────┴──────┴────────┘
                          Scenario: Expression with a Series
                          • WHEN select(col.year + lit(series("d", [1, 1, 1]))) runs
                          • THEN each year grows by one
                          Series namespaces

                          A Series SHALL have the namespaces list, arr, struct, str, dt and cat, each offering every function of the Expr namespace of the same name: s.ns.f(args) SHALL return the Series s.eval(col(s.name).ns.f(args)). The result keeps the name the expression gives (so s.struct.field("x") is named x).

                          let df = newDataFrame:
                            p: [(x: 1, y: 2.0), (x: 3, y: 4.0)]
                            l: [@[1, 2], @[3]]
                          echo df["p"].struct.field("x")
                          echo df["l"].list.len
                          shape: (2,)
                          Series: 'x' [i64]
                          [
                          	1
                          	3
                          ]
                          shape: (2,)
                          Series: 'l' [u32]
                          [
                          	2
                          	1
                          ]
                          Scenario: String function on a Series
                          • WHEN s.str.toUppercase runs on a String Series holding "ab" and "c"
                          • THEN the result holds "AB" and "C"
                          Series as HTML

                          toHtml(s: Series, maxRows = 10) SHALL return the HTML that Python Polars shows for a Series in notebooks: the table of its one column, with the shape written (n,).

                          let s = series("kg", [410, 380])
                          echo s.toHtml
                          <div><style>
                          .dataframe > thead > tr,
                          .dataframe > tbody > tr {
                            text-align: right;
                            white-space: pre-wrap;
                          }
                          </style>
                          <small>shape: (2,)</small><table border="1" class="dataframe"><thead><tr><th>kg</th></tr><tr><td>i64</td></tr></thead><tbody><tr><td>410</td></tr><tr><td>380</td></tr></tbody></table></div>
                          Scenario: Shape of a Series
                          • WHEN a Series of 3 values is turned into HTML
                          • THEN the HTML shows shape: (3,)
                          Columns from sized numbers

                          series, newDataFrame, lists and arrays SHALL accept int8, int16, int32, int64, uint8, uint16, uint32, uint64 and float32 values (and Option of them), giving the Polars type of the same size, and toList SHALL read columns back as those types.

                          let df = newDataFrame:
                            rgb: [[255'u8, 0, 0], [0'u8, 128, 255]]
                            temp: [-1.5'f32, 2.0]
                          echo df
                          echo df.toList("temp", float32)
                          shape: (2, 2)
                          ┌───────────────┬──────┐
                          │ rgb           ┆ temp │
                          │ ---           ┆ ---  │
                          │ array[u8, 3]  ┆ f32  │
                          ╞═══════════════╪══════╡
                          │ [255, 0, 0]   ┆ -1.5 │
                          │ [0, 128, 255] ┆ 2.0  │
                          └───────────────┴──────┘
                          @[-1.5, 2.0]
                          Scenario: Int32 column
                          • WHEN series("a", [1'i32, 2]) is built
                          • THEN its data type is Int32 and toList(int32) gives @[1'i32, 2]
                          Binary functions on a Series

                          s.bin SHALL give the bin namespace on a Series, as on an expression.

                          let s = newDataFrame(series("b", @["ab", "c"])).select(col("b").cast(Binary)).getColumn("b")
                          echo s.bin.size
                          shape: (2,)
                          Series: 'b' [u32]
                          [
                          	2
                          	1
                          ]
                          Scenario: Same as the expression
                          • WHEN s.bin.size runs
                          • THEN it equals s.eval(col(s.name).bin.size)
                          spec-examples2 requirements

                          Purpose: Runnable Nim examples in the OpenSpec specs: where they go, how they are checked against the code, and how specview shows them.

                          API requirements have examples

                          Every requirement in openspec/specs/ that describes Nim API SHALL include an example: a

                          allowed use; failures stay in scenarios. Requirements about process (CI, releases, the dev log, the C ABI) need none.

                          let df = newDataFrame(series("a", [1, 2, 3]))
                          echo df.select(col("a").isIn([1, 3]))
                          shape: (3, 1)
                          ┌───────┐
                          │ a     │
                          │ ---   │
                          │ bool  │
                          ╞═══════╡
                          │ true  │
                          │ false │
                          │ true  │
                          └───────┘
                          Scenario: New API requirement
                          • WHEN a change adds or modifies a requirement that describes Nim API
                          • THEN its delta includes the example and the expected output
                          Scenario: Process requirement
                          • WHEN a requirement describes CI or the release process
                          • THEN it has no example
                          Examples are run

                          Every nim block in openspec/specs/ SHALL be a unittest test of the test suite (tests/test_specs*.nim, named <capability>:<line>), with nanuq, nanuq/datasets and std/[options, os, strutils]` imported, that fails when the example does not compile, fails at run time, or prints something other than its

                          their own. `nimble specexamples` SHALL check the same examples, and with `--update`
                          write the actual output into the text blocks instead. Change deltas SHALL NOT be run.
                          

                          nim r tests/test_specs.nim "spec expressions::*" # check one spec nimble specexamples # check every spec nim r tools/specexamples.nim --update expressions # refresh one spec's outputs

                          spec-review2 requirements

                          Purpose: What the specview review page (tools/specview.nim) shows.

                          Full specs in specview

                          specview SHALL render every spec in openspec/specs/ in full, with its purpose, requirements, examples and scenarios, and SHALL mark the specs that an open change modifies or that changed since --base.

                          Scenario: Reading a spec
                          • WHEN a reviewer opens the Specs section and expands temporal
                          • THEN every requirement of openspec/specs/temporal/spec.md is shown with its example and scenarios
                          Archived changes are hidden by default

                          specview SHALL hide archived changes until the reader ticks "Show archived changes", except archived changes that changed since --base. A link to a hidden change SHALL reveal it.

                          Scenario: No base
                          • WHEN specview runs without --base on a repository whose changes are all archived
                          • THEN no change is shown until the checkbox is ticked
                          Scenario: A PR that archives changes
                          • WHEN specview runs with --base:origin/main on a branch that archived three changes
                          • THEN those three changes are shown and the other archived ones are hidden
                          sql3 requirements

                          Purpose: Running SQL queries on frames: contexts, frames by variable name, and SQL on a frame.

                          SQL contexts

                          newSQLContext() SHALL make an empty context and newSQLContext({"name": frame}) one with frames registered; register(name, frame) SHALL add a LazyFrame or DataFrame, unregister(name) remove it and tables list the names in sorted order; execute(query) SHALL run a SQL query on the registered frames and give a LazyFrame, or a DataFrame with eager = true.

                          let bears = newDataFrame:
                            bear: ["Ada", "Bo", "Cy"]
                            kg: [410, 380, 500]
                          let ctx = newSQLContext({"bears": bears.lazy})
                          echo ctx.tables
                          echo ctx.execute("SELECT bear, kg FROM bears WHERE kg > 400 ORDER BY kg DESC", eager = true)
                          @["bears"]
                          shape: (2, 2)
                          ┌──────┬─────┐
                          │ bear ┆ kg  │
                          │ ---  ┆ --- │
                          │ str  ┆ i64 │
                          ╞══════╪═════╡
                          │ Cy   ┆ 500 │
                          │ Ada  ┆ 410 │
                          └──────┴─────┘
                          Scenario: Unknown table
                          • WHEN a query reads a table that is not registered
                          • THEN SqlError is raised
                          Frames by variable name

                          sqlContext(a, b, ...) SHALL make a context with each frame registered under the name of the variable passed.

                          let bears = newDataFrame:
                            bear: ["Ada", "Bo"]
                            den: [1, 2]
                          let dens = newDataFrame:
                            den: [1, 2]
                            site: ["Kong Karls Land", "Hopen"]
                          let ctx = sqlContext(bears, dens)
                          echo ctx.execute("SELECT bear, site FROM bears JOIN dens USING (den) ORDER BY bear").collect
                          shape: (2, 2)
                          ┌──────┬─────────────────┐
                          │ bear ┆ site            │
                          │ ---  ┆ ---             │
                          │ str  ┆ str             │
                          ╞══════╪═════════════════╡
                          │ Ada  ┆ Kong Karls Land │
                          │ Bo   ┆ Hopen           │
                          └──────┴─────────────────┘
                          Scenario: Not a variable
                          • WHEN sqlContext(bears.lazy) is compiled
                          • THEN compilation fails with a message asking for a variable
                          SQL on a frame

                          df.sql(query) and lf.sql(query) SHALL run a query on the frame, which the query calls self (or tableName), and sql(query, {"name": frame}) SHALL run a query on the given frames.

                          let df = newDataFrame:
                            island: ["Biscoe", "Dream", "Biscoe"]
                            kg: [4.5, 3.7, 5.1]
                          echo df.sql("SELECT island, AVG(kg) AS kg FROM self GROUP BY island ORDER BY island")
                          shape: (2, 2)
                          ┌────────┬─────┐
                          │ island ┆ kg  │
                          │ ---    ┆ --- │
                          │ str    ┆ f64 │
                          ╞════════╪═════╡
                          │ Biscoe ┆ 4.8 │
                          │ Dream  ┆ 3.7 │
                          └────────┴─────┘
                          Scenario: Other table name
                          • WHEN df.sql("SELECT * FROM penguins", tableName = "penguins") is run
                          • THEN the result is the frame
                          streaming3 requirements

                          Purpose: Running lazy queries on Polars' streaming engine and writing results straight to files (sinks), whole or partitioned by key, without holding them in memory.

                          Choosing the engine

                          collect(lf, engine) SHALL run the query with the given Engine: Auto (Polars picks, today the in-memory engine), InMemory or Streaming, which processes the data in batches. Every engine SHALL give the same rows; collectAll(lfs, engine) SHALL take the same choice.

                          let lf = newDataFrame(series("kg", @[410, 380, 455])).lazy
                          echo lf.filter(col("kg") > 400).collect(engine = Engine.Streaming)
                          shape: (2, 1)
                          ┌─────┐
                          │ kg  │
                          │ --- │
                          │ i64 │
                          ╞═════╡
                          │ 410 │
                          │ 455 │
                          └─────┘
                          Scenario: Same result
                          • WHEN a group-by query is collected with Engine.InMemory and with Engine.Streaming
                          • THEN both frames are equal after sorting
                          Sinks

                          sinkParquet, sinkIpc, sinkCsv and sinkNdjson SHALL run a LazyFrame with the streaming engine and write the result to a file, with the options of writeParquet, writeIpc, writeCsv and writeNdjson, plus maintainOrder = true and mkdir = false (create missing directories). With lazy = true they SHALL return the sink as a LazyFrame, which writes the file when collected; collectAll SHALL run several such sinks together.

                          let dir = getTempDir() / "nanuq-sinks"
                          let lf = newDataFrame(series("bear", @["Ada", "Bo"]), series("kg", @[410, 380])).lazy
                          lf.sinkCsv(dir / "bears.csv", mkdir = true)
                          echo readFile(dir / "bears.csv")
                          let sinks = [lf.sinkParquet(dir / "bears.parquet", lazy = true),
                                       lf.filter(col("kg") > 400).sinkNdjson(dir / "big.ndjson", lazy = true)]
                          discard collectAll(sinks)
                          echo readParquet(dir / "bears.parquet").height, " ", readFile(dir / "big.ndjson")
                          bear,kg
                          Ada,410
                          Bo,380
                          
                          2 {"bear":"Ada","kg":410}
                          Scenario: Missing directory
                          • WHEN a sink targets a directory that does not exist and mkdir is false
                          • THEN IOError is raised and no file is written
                          Partitioned sinks

                          A sink SHALL accept a PartitionBy(basePath, key, includeKey = true, maxRowsPerFile) target instead of a path: with key it SHALL write one Hive-style directory per key value (basePath/key=value/...), without it files of at most maxRowsPerFile rows.

                          let base = getTempDir() / "nanuq-by-year"
                          let df = newDataFrame(series("year", @[2024, 2024, 2025]), series("n", @[1, 2, 3]))
                          df.lazy.sinkParquet(PartitionBy(basePath: base, key: @["year"]), mkdir = true)
                          echo scanParquet(base / "**/*.parquet").sort("n").collect
                          shape: (3, 2)
                          ┌──────┬─────┐
                          │ year ┆ n   │
                          │ ---  ┆ --- │
                          │ i64  ┆ i64 │
                          ╞══════╪═════╡
                          │ 2024 ┆ 1   │
                          │ 2024 ┆ 2   │
                          │ 2025 ┆ 3   │
                          └──────┴─────┘
                          Scenario: Rows per file
                          • WHEN 10 rows are sunk with PartitionBy(basePath: dir, maxRowsPerFile: 4)
                          • THEN reading every file in dir gives the 10 rows back
                          strings11 requirements

                          Purpose: String expressions: the str namespace, concatStr and format.

                          The str namespace

                          e.str SHALL give access to string functions that return expressions: lenChars, lenBytes, toUppercase, toLowercase and reverse. Nulls SHALL stay null in every string function, unless stated otherwise.

                          let df = newDataFrame:
                            rider: ["Pogačar", "Seixas", nil]
                          echo df.select(col.rider, col.rider.str.toUppercase.alias("upper"),
                                         col.rider.str.lenChars.alias("chars"), col.rider.str.lenBytes.alias("bytes"))
                          shape: (3, 4)
                          ┌─────────┬─────────┬───────┬───────┐
                          │ rider   ┆ upper   ┆ chars ┆ bytes │
                          │ ---     ┆ ---     ┆ ---   ┆ ---   │
                          │ str     ┆ str     ┆ u32   ┆ u32   │
                          ╞═════════╪═════════╪═══════╪═══════╡
                          │ Pogačar ┆ POGAČAR ┆ 7     ┆ 8     │
                          │ Seixas  ┆ SEIXAS  ┆ 6     ┆ 6     │
                          │ null    ┆ null    ┆ null  ┆ null  │
                          └─────────┴─────────┴───────┴───────┘
                          Scenario: Characters and bytes
                          • WHEN str.lenChars and str.lenBytes run over "Pogačar"
                          • THEN the results are 7 and 8
                          Scenario: Not a string column
                          • WHEN str.toUppercase runs over an i64 column
                          • THEN PolarsError is raised when the query runs
                          Matching

                          The namespace SHALL provide startsWith(prefix), endsWith(suffix), contains(pattern, literal = false, strict = true), find(pattern, literal = false, strict = true), countMatches(pattern, literal = false) and extract(pattern, groupIndex = 1). Patterns SHALL be Rust regular expressions unless literal = true. With strict = false, an invalid regex SHALL give null instead of raising.

                          let df = newDataFrame:
                            race: ["Paris–Nice", "Milano-Sanremo", "Tour de France"]
                          echo df.select(col.race,
                                         col.race.str.contains("–", literal = true).alias("en_dash"),
                                         col.race.str.startsWith("Tour").alias("tour"),
                                         col.race.str.extract(r"^(\w+)", 1).alias("first"),
                                         col.race.str.countMatches("[aeiou]").alias("vowels"))
                          shape: (3, 5)
                          ┌────────────────┬─────────┬───────┬────────┬────────┐
                          │ race           ┆ en_dash ┆ tour  ┆ first  ┆ vowels │
                          │ ---            ┆ ---     ┆ ---   ┆ ---    ┆ ---    │
                          │ str            ┆ bool    ┆ bool  ┆ str    ┆ u32    │
                          ╞════════════════╪═════════╪═══════╪════════╪════════╡
                          │ Paris–Nice     ┆ true    ┆ false ┆ Paris  ┆ 4      │
                          │ Milano-Sanremo ┆ false   ┆ false ┆ Milano ┆ 6      │
                          │ Tour de France ┆ false   ┆ true  ┆ Tour   ┆ 5      │
                          └────────────────┴─────────┴───────┴────────┴────────┘
                          Scenario: Literal vs regex
                          • WHEN str.contains(".") and str.contains(".", literal = true) run over "abc"
                          • THEN the results are true and false
                          Scenario: No match
                          • WHEN str.extract(r"(\d+)'") runs over "73h"
                          • THEN the result is null
                          Scenario: Invalid regex
                          • WHEN str.contains("(") runs, and then str.contains("(", strict = false)
                          • THEN the first raises PolarsError and the second gives null
                          Replacing and stripping

                          The namespace SHALL provide replace(pattern, value, literal = false, n = 1), replaceAll(pattern, value, literal = false), stripChars, stripCharsStart and stripCharsEnd (whitespace without an argument, otherwise the given characters), stripPrefix(prefix) and stripSuffix(suffix). In a regex replacement, $1 SHALL refer to a capture group.

                          let df = newDataFrame:
                            race: ["  Paris–Nice ", "Tirreno–Adriatico", "Strade Bianche"]
                          echo df.select(col.race.str.stripChars.str.replaceAll("–", "-", literal = true).alias("clean"),
                                         col.race.str.replace(r"(\w+) (\w+)", "$2 $1").alias("swapped"))
                          shape: (3, 2)
                          ┌───────────────────┬───────────────────┐
                          │ clean             ┆ swapped           │
                          │ ---               ┆ ---               │
                          │ str               ┆ str               │
                          ╞═══════════════════╪═══════════════════╡
                          │ Paris-Nice        ┆   Paris–Nice      │
                          │ Tirreno-Adriatico ┆ Tirreno–Adriatico │
                          │ Strade Bianche    ┆ Bianche Strade    │
                          └───────────────────┴───────────────────┘
                          Scenario: Replace the first n
                          • WHEN str.replace("a", "o", n = 2) runs over "banana"
                          • THEN the result is "bonona"
                          Scenario: Strip given characters
                          • WHEN str.stripChars("*") runs over "win"
                          • THEN the result is "win"
                          Slicing and padding

                          The namespace SHALL provide slice(offset) and slice(offset, length) (a negative offset counts from the end), head(n), tail(n), padStart(length, fillChar = ' '), padEnd(length, fillChar = ' ') and zfill(length), counting characters.

                          let df = newDataFrame:
                            bib: ["1", "21", "141"]
                            nat: ["SLO", "FRA", "DEN"]
                          echo df.select(col.bib.str.zfill(3).alias("bib"), col.bib.str.padStart(4, '.').alias("dots"),
                                         col.nat.str.head(2).alias("head"), col.nat.str.slice(-2).alias("last2"))
                          shape: (3, 4)
                          ┌─────┬──────┬──────┬───────┐
                          │ bib ┆ dots ┆ head ┆ last2 │
                          │ --- ┆ ---  ┆ ---  ┆ ---   │
                          │ str ┆ str  ┆ str  ┆ str   │
                          ╞═════╪══════╪══════╪═══════╡
                          │ 001 ┆ ...1 ┆ SL   ┆ LO    │
                          │ 021 ┆ ..21 ┆ FR   ┆ RA    │
                          │ 141 ┆ .141 ┆ DE   ┆ EN    │
                          └─────┴──────┴──────┴───────┘
                          Scenario: Slice with a length
                          • WHEN str.slice(1, 2) runs over "Pogačar"
                          • THEN the result is "og"
                          Joining strings in an aggregation

                          str.join(delimiter = "", ignoreNulls = true) SHALL aggregate a column into one string, in row order, per group in agg. With ignoreNulls = false, a null SHALL make the result null.

                          let wins = newDataFrame:
                            rider: ["Pogačar", "Seixas", "Pogačar"]
                            race: ["Strade Bianche", "Flèche Wallonne", "Il Lombardia"]
                          echo wins.groupBy(col.rider).agg(col.race.str.join(", ").alias("races")).sort("rider")
                          shape: (2, 2)
                          ┌─────────┬──────────────────────────────┐
                          │ rider   ┆ races                        │
                          │ ---     ┆ ---                          │
                          │ str     ┆ str                          │
                          ╞═════════╪══════════════════════════════╡
                          │ Pogačar ┆ Strade Bianche, Il Lombardia │
                          │ Seixas  ┆ Flèche Wallonne              │
                          └─────────┴──────────────────────────────┘
                          Scenario: Whole column
                          • WHEN select(col.race.str.join("|")) runs over "a", null, "b"
                          • THEN the result is one row holding "a|b"
                          Building strings from columns

                          concatStr(exprs, separator = "", ignoreNulls = false) SHALL concatenate expressions row by row into a string column, and format(template, args...) SHALL replace each {} in template by the next argument. Non-string arguments SHALL be formatted as Polars casts them to strings. A null argument SHALL make the row null, unless ignoreNulls = true in concatStr. A template whose placeholders don't match the number of arguments SHALL raise ValueError.

                          let gaps = newDataFrame:
                            rider: ["Vingegaard", "Pogačar"]
                            minutes: [4, 0]
                            seconds: [23, 7]
                          echo gaps.select(format("{}: {}′ {}″", col.rider, col.minutes, col.seconds).alias("gap"),
                                           concatStr([col.rider, lit("UAE")], separator = " / ").alias("team"))
                          shape: (2, 2)
                          ┌────────────────────┬──────────────────┐
                          │ gap                ┆ team             │
                          │ ---                ┆ ---              │
                          │ str                ┆ str              │
                          ╞════════════════════╪══════════════════╡
                          │ Vingegaard: 4′ 23″ ┆ Vingegaard / UAE │
                          │ Pogačar: 0′ 7″     ┆ Pogačar / UAE    │
                          └────────────────────┴──────────────────┘
                          Scenario: Wrong number of arguments
                          • WHEN format("{} {}", col.a) is called
                          • THEN ValueError is raised
                          Scenario: Next to strutils
                          • WHEN a module imports std/strutils and nanuq and calls format("{}", col.a) and "$1".format("x")
                          • THEN both compile, the first giving an expression and the second "x"
                          Title case

                          str.toTitlecase SHALL upper-case the first letter of each word and lower-case the rest, when the native library is built with the nightly feature, as the release libraries are. With a library built without it, it SHALL raise InvalidOperationError when the expression is built.

                          Scenario: Release library
                          • WHEN str.toTitlecase runs over "tour de france" with a release library
                          • THEN the result is "Tour De France"
                          Scenario: Stable build
                          • WHEN str.toTitlecase is called with a library built on stable Rust
                          • THEN InvalidOperationError is raised
                          Splitting and extracting into lists and structs

                          str.split(by) SHALL split each string into a list[str] (keeping by with inclusive = true), str.extractAll(pattern) SHALL give all regex matches as a list, str.splitExact(by, n) and str.splitn(by, n) SHALL give a struct of n + 1 or n fields named field_0, ..., and str.extractGroups(pattern) SHALL give a struct with one field per capture group, named after named groups or numbered from 1.

                          let df = newDataFrame:
                            station: ["Lima, Peru", "Piura, Peru", "Darwin"]
                          echo df.select(col("station").str.split(", ").alias("parts"),
                                         col("station").str.splitExact(", ", 1).alias("exact"),
                                         col("station").str.extractGroups(r"(?<city>\w+)(, (?<country>\w+))?").alias("groups"))
                          shape: (3, 3)
                          ┌───────────────────┬──────────────────┬───────────────────────────┐
                          │ parts             ┆ exact            ┆ groups                    │
                          │ ---               ┆ ---              ┆ ---                       │
                          │ list[str]         ┆ struct[2]        ┆ struct[3]                 │
                          ╞═══════════════════╪══════════════════╪═══════════════════════════╡
                          │ ["Lima", "Peru"]  ┆ {"Lima","Peru"}  ┆ {"Lima",", Peru","Peru"}  │
                          │ ["Piura", "Peru"] ┆ {"Piura","Peru"} ┆ {"Piura",", Peru","Peru"} │
                          │ ["Darwin"]        ┆ {"Darwin",null}  ┆ {"Darwin",null,null}      │
                          └───────────────────┴──────────────────┴───────────────────────────┘
                          Scenario: Missing parts
                          • WHEN splitExact(", ", 1) is evaluated on a string without a comma
                          • THEN the second field is null
                          Many patterns at once

                          str.containsAny(patterns), str.replaceMany(patterns, replaceWith) (or a mapping), str.extractMany(patterns) and str.findMany(patterns) SHALL match many literal patterns in one pass, with asciiCaseInsensitive and, for extract and find, overlapping.

                          let df = newDataFrame:
                            note: ["sea ice thin", "no ice", "open water"]
                          echo df.select(col("note").str.containsAny(["ice", "water"]).alias("any"),
                                         col("note").str.replaceMany({"ice": "ICE", "water": "WATER"}).alias("loud"),
                                         col("note").str.extractMany(["ice", "sea", "water"]).alias("found"))
                          shape: (3, 3)
                          ┌──────┬──────────────┬────────────────┐
                          │ any  ┆ loud         ┆ found          │
                          │ ---  ┆ ---          ┆ ---            │
                          │ bool ┆ str          ┆ list[str]      │
                          ╞══════╪══════════════╪════════════════╡
                          │ true ┆ sea ICE thin ┆ ["sea", "ice"] │
                          │ true ┆ no ICE       ┆ ["ice"]        │
                          │ true ┆ open WATER   ┆ ["water"]      │
                          └──────┴──────────────┴────────────────┘
                          Scenario: One replacement for all
                          • WHEN replaceMany(["a", "b"], "_") is evaluated on "abc"
                          • THEN the result is "__c"
                          JSON in strings

                          str.jsonDecode(dtype) (or jsonDecode(T) with a Nim type) SHALL parse each string as JSON into a value of dtype, and str.jsonPathMatch(path) SHALL give the string at a JSONPath, null when there is none.

                          let df = newDataFrame:
                            json: ["""{"bear": "Ada", "kg": 410}""", """{"bear": "Bo", "kg": null}"""]
                          echo df.select(col("json").str.jsonDecode(tuple[bear: string, kg: Option[int]]).alias("v"),
                                         col("json").str.jsonPathMatch("$.bear").alias("bear"))
                          shape: (2, 2)
                          ┌─────────────┬──────┐
                          │ v           ┆ bear │
                          │ ---         ┆ ---  │
                          │ struct[2]   ┆ str  │
                          ╞═════════════╪══════╡
                          │ {"Ada",410} ┆ Ada  │
                          │ {"Bo",null} ┆ Bo   │
                          └─────────────┴──────┘
                          Scenario: Invalid JSON
                          • WHEN a string that is not JSON is decoded
                          • THEN ComputeError is raised
                          Escaping and normalizing

                          str.escapeRegex SHALL escape regex metacharacters, and str.normalize(form = UnicodeForm.NFC) SHALL give the Unicode normal form (NFC, NFKC, NFD, NFKD).

                          let df = newDataFrame(series("s", @["a.b*c", "é"]))
                          echo df.select(col("s").str.escapeRegex.alias("escaped"),
                                         col("s").str.normalize.str.lenChars.alias("chars"))
                          shape: (2, 2)
                          ┌─────────┬───────┐
                          │ escaped ┆ chars │
                          │ ---     ┆ ---   │
                          │ str     ┆ u32   │
                          ╞═════════╪═══════╡
                          │ a\.b\*c ┆ 5     │
                          │ é       ┆ 1     │
                          └─────────┴───────┘
                          Scenario: Composed form
                          • WHEN "e" followed by a combining acute accent is normalized to NFC
                          • THEN the result is the one character "é"
                          struct-functions6 requirements

                          Purpose: Struct construction, the struct and arr namespaces, unnest and expression valueCounts.

                          Building structs

                          asStruct(exprs) SHALL build a struct column with one field per expression, named after its output name.

                          let df = newDataFrame:
                            bear: ["Ada", "Bo"]
                            kg: [410, 380]
                          echo df.select(asStruct(col("bear"), col("kg") * 2).alias("s"))
                          shape: (2, 1)
                          ┌─────────────┐
                          │ s           │
                          │ ---         │
                          │ struct[2]   │
                          ╞═════════════╡
                          │ {"Ada",820} │
                          │ {"Bo",760}  │
                          └─────────────┘
                          Scenario: Duplicate names
                          • WHEN two expressions with the same output name are put in one struct
                          • THEN DuplicateError is raised
                          Struct fields

                          e.struct.field(name) (also e.struct[name]) SHALL give one field as a column, field(names) several, field(index) one by position, and e.struct.unnest all of them; renameFields(names) SHALL rename the fields in order, withFields(exprs) add or replace fields, and jsonEncode give each struct as a JSON string.

                          let df = newDataFrame:
                            p: [(x: 1, y: 2.0), (x: 3, y: 4.0)]
                          echo df.select(col("p").struct.field("x"), col("p").struct["y"].alias("y"),
                                         col("p").struct.jsonEncode.alias("json"))
                          echo df.select(col("p").struct.renameFields(["a", "b"]).struct.unnest)
                          shape: (2, 3)
                          ┌─────┬─────┬─────────────────┐
                          │ x   ┆ y   ┆ json            │
                          │ --- ┆ --- ┆ ---             │
                          │ i64 ┆ f64 ┆ str             │
                          ╞═════╪═════╪═════════════════╡
                          │ 1   ┆ 2.0 ┆ {"x":1,"y":2.0} │
                          │ 3   ┆ 4.0 ┆ {"x":3,"y":4.0} │
                          └─────┴─────┴─────────────────┘
                          shape: (2, 2)
                          ┌─────┬─────┐
                          │ a   ┆ b   │
                          │ --- ┆ --- │
                          │ i64 ┆ f64 │
                          ╞═════╪═════╡
                          │ 1   ┆ 2.0 │
                          │ 3   ┆ 4.0 │
                          └─────┴─────┘
                          Scenario: Unknown field
                          • WHEN struct.field("z") is evaluated on a struct without z
                          • THEN StructFieldNotFoundError is raised
                          Unnesting frames

                          df.unnest(columns) SHALL replace each struct column by its fields (eager and lazy); with separator, the new columns SHALL be named <column><separator><field>.

                          let df = newDataFrame:
                            bear: ["Ada", "Bo"]
                            den: [(lat: 78.2, lon: 15.6), (lat: 79.0, lon: 16.1)]
                          echo df.unnest("den")
                          echo df.unnest("den", separator = "_").columns
                          shape: (2, 3)
                          ┌──────┬──────┬──────┐
                          │ bear ┆ lat  ┆ lon  │
                          │ ---  ┆ ---  ┆ ---  │
                          │ str  ┆ f64  ┆ f64  │
                          ╞══════╪══════╪══════╡
                          │ Ada  ┆ 78.2 ┆ 15.6 │
                          │ Bo   ┆ 79.0 ┆ 16.1 │
                          └──────┴──────┴──────┘
                          @["bear", "den_lat", "den_lon"]
                          Scenario: Not a struct
                          • WHEN a list column is unnested
                          • THEN InvalidOperationError or SchemaError is raised
                          Value counts as an expression

                          e.valueCounts(sort, parallel, name, normalize) SHALL give a struct column with the distinct values and their counts (or fractions with normalize), named count (or proportion) unless name is given.

                          let df = newDataFrame:
                            island: ["Biscoe", "Dream", "Biscoe"]
                          echo df.select(col("island").valueCounts(sort = true)).unnest("island")
                          shape: (2, 2)
                          ┌────────┬───────┐
                          │ island ┆ count │
                          │ ---    ┆ ---   │
                          │ str    ┆ u32   │
                          ╞════════╪═══════╡
                          │ Biscoe ┆ 2     │
                          │ Dream  ┆ 1     │
                          └────────┴───────┘
                          Scenario: Sorted counts
                          • WHEN valueCounts(sort = true) is evaluated
                          • THEN the most frequent value comes first
                          Array functions

                          e.arr SHALL give a namespace of functions on each array of an Array column: len, sum, min, max, mean, median, std, var, argMin, argMax, first, last, get, join, contains, countMatches, sort, slice, head, tail, shift, toList, toStruct, explode, eval and agg.

                          let df = newDataFrame:
                            rgb: [[255, 0, 0], [10, 20, 30]]
                          echo df.select(col("rgb").arr.sum.alias("sum"), col("rgb").arr.get(1).alias("g"),
                                         col("rgb").arr.toList.alias("list"))
                          shape: (2, 3)
                          ┌─────┬─────┬──────────────┐
                          │ sum ┆ g   ┆ list         │
                          │ --- ┆ --- ┆ ---          │
                          │ i64 ┆ i64 ┆ list[i64]    │
                          ╞═════╪═════╪══════════════╡
                          │ 255 ┆ 0   ┆ [255, 0, 0]  │
                          │ 60  ┆ 20  ┆ [10, 20, 30] │
                          └─────┴─────┴──────────────┘
                          Scenario: Array to struct
                          • WHEN arr.toStruct is evaluated on arrays of width 3
                          • THEN the result is a struct with fields field_0, field_1 and field_2
                          Structs from column names

                          asStruct SHALL also take column names: asStruct("a", "b") is asStruct(col("a"), col("b")) (Python's pl.struct("a", "b")).

                          let df = newDataFrame:
                            bear: ["Ada", "Bo"]
                            kg: [410, 380]
                          echo df.select(asStruct("bear", "kg").alias("s"))
                          shape: (2, 1)
                          ┌─────────────┐
                          │ s           │
                          │ ---         │
                          │ struct[2]   │
                          ╞═════════════╡
                          │ {"Ada",410} │
                          │ {"Bo",380}  │
                          └─────────────┘
                          Scenario: Field names
                          • WHEN asStruct("bear", "kg") is selected
                          • THEN the struct has the fields bear and kg
                          temporal10 requirements

                          Purpose: Dates, datetimes, durations and times of day: Nim values, constructors, parsing strings, and the dt namespace.

                          Temporal values

                          The API SHALL provide Date (date(y, m, d)) and TimeOfDay (timeOfDay(h, m, s, ns)), and SHALL accept them and std/times' DateTime and Duration wherever Nim values build columns or literals. toList and df[c, i, T] SHALL read them back, as Option for nulls. DateTime values SHALL be stored and read back as UTC instants. nanuq SHALL export std/times.

                          let df = newDataFrame:
                            rider: ["Seixas", "Pogačar"]
                            born: [date(2006, 9, 24), date(1998, 9, 21)]
                            start: [timeOfDay(13, 10), timeOfDay(13, 12)]
                            gap: [initDuration(minutes = 4, seconds = 23), initDuration()]
                            finish: [dateTime(2026, mJul, 4, 17, 21, zone = utc()), nil]
                          echo df
                          echo df.filter(col.born > date(2000, 1, 1)).toList("rider", string)
                          echo df.toList("born", Date)[0].year, " ", df["finish", 1, Option[DateTime]].isNone
                          shape: (2, 5)
                          ┌─────────┬────────────┬──────────┬──────────────┬─────────────────────┐
                          │ rider   ┆ born       ┆ start    ┆ gap          ┆ finish              │
                          │ ---     ┆ ---        ┆ ---      ┆ ---          ┆ ---                 │
                          │ str     ┆ date       ┆ time     ┆ duration[μs] ┆ datetime[μs]        │
                          ╞═════════╪════════════╪══════════╪══════════════╪═════════════════════╡
                          │ Seixas  ┆ 2006-09-24 ┆ 13:10:00 ┆ 4m 23s       ┆ 2026-07-04 17:21:00 │
                          │ Pogačar ┆ 1998-09-21 ┆ 13:12:00 ┆ 0µs          ┆ null                │
                          └─────────┴────────────┴──────────┴──────────────┴─────────────────────┘
                          @["Seixas"]
                          2006 true
                          Scenario: Round trip
                          • WHEN a column built from [date(2026, 7, 4), nil] is read with toList(df, c, Option[Date])
                          • THEN the result is @[some(date(2026, 7, 4)), none(Date)]
                          Scenario: Out of range
                          • WHEN timeOfDay(24) is called
                          • THEN ValueError is raised
                          Scenario: Wrong reader
                          • WHEN a Date column is read with toList(df, c, DateTime)
                          • THEN InvalidOperationError is raised
                          Temporal ranges and durations

                          dateRange(start, stop, interval = "1d", closed = ClosedWindow.Both) and datetimeRange(..., timeUnit, timeZone) SHALL return expressions. interval SHALL be a Polars interval string or a TimeInterval, converted by toPolarsInterval, which raises ValueError on mixed signs. duration(weeks, days, hours, ..., nanoseconds) SHALL build a Duration from ints or expressions.

                          let months = newDataFrame().select(dateRange(date(2026, 1, 31), date(2026, 4, 30), 1.months).alias("day"))
                          echo months.toList("day", Date)
                          echo toPolarsInterval(1.years + 2.days)
                          let gaps = newDataFrame:
                            h: [73, 0]
                            m: [56, 4]
                          echo gaps.select(duration(hours = col.h, minutes = col.m, seconds = 26).alias("gap"))
                          @[2026-01-31, 2026-02-28, 2026-03-31, 2026-04-30]
                          1y2d
                          shape: (2, 1)
                          ┌───────────────┐
                          │ gap           │
                          │ ---           │
                          │ duration[μs]  │
                          ╞═══════════════╡
                          │ 3d 1h 56m 26s │
                          │ 4m 26s        │
                          └───────────────┘
                          Scenario: Calendar steps
                          • WHEN dateRange(date(2026, 1, 31), date(2026, 4, 30), 1.months) is selected
                          • THEN the dates are the last days of January to April
                          Scenario: Half-open range
                          • WHEN dateRange(date(2026, 1, 1), date(2026, 1, 15), "1w", closed = ClosedWindow.Left) is selected
                          • THEN the result has 2 rows
                          Scenario: Mixed signs
                          • WHEN toPolarsInterval(1.days - 2.hours) is called
                          • THEN ValueError is raised
                          Parsing strings

                          e.str SHALL provide strptime(T, format, strict = true, exact = true, cache = true) for T in Date, DateTime and TimeOfDay, and the shorthands toDate(format), toDatetime(format, timeUnit, timeZone, ambiguous) and toTime(format). Formats SHALL use chrono's codes; an empty format SHALL let Polars infer it. A strict parse SHALL raise PolarsError when a value does not match; a non-strict one SHALL give null. exact = false SHALL allow the format to match part of the string.

                          let df = newDataFrame:
                            born: ["17 July 1993", "24 September 2006", "smudged"]
                          echo df.select(col.born.str.toDate("%d %B %Y", strict = false))
                          shape: (3, 1)
                          ┌────────────┐
                          │ born       │
                          │ ---        │
                          │ date       │
                          ╞════════════╡
                          │ 1993-07-17 │
                          │ 2006-09-24 │
                          │ null       │
                          └────────────┘
                          Scenario: Strict failure
                          • WHEN str.toDate("%d %B %Y") runs over a value "smudged"
                          • THEN PolarsError is raised
                          Scenario: Zoned datetimes
                          • WHEN str.toDatetime("%Y-%m-%d %H:%M", timeZone = "Australia/Adelaide") is selected
                          • THEN the dtype is datetime[μs, Australia/Adelaide]
                          Date and time parts

                          e.dt SHALL return a DtNameSpace with year, isoYear, quarter, month, week, weekday (Monday 1 to Sunday 7), day, ordinalDay, hour, minute, second, millisecond, microsecond, nanosecond, date, time, isLeapYear, daysInMonth, monthStart and monthEnd, each returning an expression with Polars' result dtype.

                          let df = newDataFrame:
                            at: [dateTime(2026, mJul, 4, 13, 10, zone = utc()), dateTime(2024, mFeb, 29, zone = utc())]
                          echo df.select(col.at.dt.year.alias("y"), col.at.dt.weekday.alias("wd"),
                                         col.at.dt.ordinalDay.alias("od"), col.at.dt.date.alias("d"),
                                         col.at.dt.time.alias("t"), col.at.dt.isLeapYear.alias("leap"))
                          shape: (2, 6)
                          ┌──────┬─────┬─────┬────────────┬──────────┬───────┐
                          │ y    ┆ wd  ┆ od  ┆ d          ┆ t        ┆ leap  │
                          │ ---  ┆ --- ┆ --- ┆ ---        ┆ ---      ┆ ---   │
                          │ i32  ┆ i8  ┆ i16 ┆ date       ┆ time     ┆ bool  │
                          ╞══════╪═════╪═════╪════════════╪══════════╪═══════╡
                          │ 2026 ┆ 6   ┆ 185 ┆ 2026-07-04 ┆ 13:10:00 ┆ false │
                          │ 2024 ┆ 4   ┆ 60  ┆ 2024-02-29 ┆ 00:00:00 ┆ true  │
                          └──────┴─────┴─────┴────────────┴──────────┴───────┘
                          Scenario: Parts of a datetime
                          • WHEN dt.day and dt.hour run over 2026-07-04 13:10
                          • THEN the results are 4 and 13
                          Scenario: Not temporal
                          • WHEN dt.year runs over a string column
                          • THEN PolarsError is raised when the query runs
                          Formatting temporal values

                          dt.toString(format) and its alias dt.strftime(format) SHALL format dates, datetimes and times with chrono's codes. dt.toString(DurationFormat.Iso) and dt.toString(DurationFormat.Polars) SHALL format durations as ISO 8601 or Polars' short form.

                          let df = newDataFrame:
                            at: [dateTime(2026, mJul, 4, 13, 10, zone = utc())]
                            gap: [initDuration(minutes = 4, seconds = 23)]
                          echo df.select(col.at.dt.toString("%d %B %Y"), col.gap.dt.toString(DurationFormat.Iso).alias("iso"),
                                         col.gap.dt.toString(DurationFormat.Polars).alias("short"))
                          shape: (1, 3)
                          ┌──────────────┬─────────┬────────┐
                          │ at           ┆ iso     ┆ short  │
                          │ ---          ┆ ---     ┆ ---    │
                          │ str          ┆ str     ┆ str    │
                          ╞══════════════╪═════════╪════════╡
                          │ 04 July 2026 ┆ PT4M23S ┆ 4m 23s │
                          └──────────────┴─────────┴────────┘
                          Scenario: Duration formats
                          • WHEN a 4 min 23 s duration is formatted with DurationFormat.Iso and DurationFormat.Polars
                          • THEN the results are "PT4M23S" and "4m 23s"
                          Temporal arithmetic

                          Subtracting dates or datetimes SHALL give a Duration. dt SHALL provide truncate(every), round(every), offsetBy(by) (intervals as strings or TimeIntervals), timestamp(timeUnit), castTimeUnit(timeUnit), and on durations totalDays … totalNanoseconds, whole numbers unless fractional = true.

                          let df = newDataFrame:
                            born: [date(2006, 9, 24), date(1998, 9, 21)]
                            race: [date(2026, 3, 21), date(2026, 3, 21)]
                          echo df.select((col.race - col.born).dt.totalDays.alias("days"),
                                         col.born.dt.offsetBy(19.years).alias("turns_19"),
                                         col.race.dt.truncate(1.months).alias("month"))
                          shape: (2, 3)
                          ┌───────┬────────────┬────────────┐
                          │ days  ┆ turns_19   ┆ month      │
                          │ ---   ┆ ---        ┆ ---        │
                          │ i64   ┆ date       ┆ date       │
                          ╞═══════╪════════════╪════════════╡
                          │ 7118  ┆ 2025-09-24 ┆ 2026-03-01 │
                          │ 10043 ┆ 2017-09-21 ┆ 2026-03-01 │
                          └───────┴────────────┴────────────┘
                          Scenario: Leap day
                          • WHEN 2024-02-29 is offset by 1.years
                          • THEN the result is 2025-02-28
                          Scenario: Fractional totals
                          • WHEN dt.totalDays(fractional = true) runs over 36 hours
                          • THEN the result is 1.5
                          Time zones

                          dt.replaceTimeZone(timeZone, ambiguous = Ambiguous.Raise, nonExistent = NonExistent.Raise) SHALL attach a zone to wall-clock times (or remove it with ""), dt.convertTimeZone(timeZone) SHALL show the same instants in another zone, and dt.combine(time) SHALL join a date and a time of day into a datetime.

                          let stage = newDataFrame:
                            day: [date(2026, 1, 20)]
                            finish: [timeOfDay(14, 3)]
                          let local = col.day.dt.combine(col.finish).dt.replaceTimeZone("Australia/Adelaide")
                          echo stage.select(local.alias("adelaide"), local.dt.convertTimeZone("Europe/Paris").alias("paris"))
                          shape: (1, 2)
                          ┌─────────────────────────────────┬────────────────────────────┐
                          │ adelaide                        ┆ paris                      │
                          │ ---                             ┆ ---                        │
                          │ datetime[μs,                    ┆ datetime[μs, Europe/Paris] │
                          │ Australia/Adelaide]             ┆                            │
                          ╞═════════════════════════════════╪════════════════════════════╡
                          │ 2026-01-20 14:03:00 ACDT        ┆ 2026-01-20 04:33:00 CET    │
                          └─────────────────────────────────┴────────────────────────────┘
                          Scenario: Same instant
                          • WHEN 14:03 in Adelaide on 2026-01-20 is converted to Europe/Paris
                          • THEN the time is 04:33 and the value read back equals 03:33 UTC
                          Scenario: Unknown zone
                          • WHEN dt.convertTimeZone("Mars/Olympus") runs
                          • THEN PolarsError is raised
                          Dates from parts

                          date(year, month, day) SHALL build a Date column when at least one part is an expression; each part SHALL be an integer expression or a number, as Polars' date. Invalid dates (month 13, 30 February) SHALL raise when the query runs. With three numbers date SHALL keep returning a Date value.

                          let seasons = newDataFrame:
                            year: [1982, 1997, 2015]
                            month: [12, 11, 11]
                          echo seasons.select(date(col.year, col.month, 15).alias("mid"))
                          echo date(2026, 2, 1)
                          shape: (3, 1)
                          ┌────────────┐
                          │ mid        │
                          │ ---        │
                          │ date       │
                          ╞════════════╡
                          │ 1982-12-15 │
                          │ 1997-11-15 │
                          │ 2015-11-15 │
                          └────────────┘
                          2026-02-01
                          Scenario: Mixed parts
                          • WHEN date(col.year, 1, 1) runs on years 1950 and 1951
                          • THEN the result is the dates 1950-01-01 and 1951-01-01
                          Scenario: Invalid date
                          • WHEN date(col.year, 2, 30) runs
                          • THEN a PolarsError is raised
                          More date parts and time ranges

                          dt.epoch(EpochUnit) SHALL give the time since 1970-01-01 (whole seconds and days for Seconds and Days), dt.century and dt.millennium the century and millennium, dt.dstOffset and dt.baseUtcOffset the offsets of zoned datetimes as Durations. timeRange(start, stop, interval, closed) SHALL give times of day, timeRanges one list per row.

                          let df = newDataFrame(series("d", @[date(2000, 6, 1), date(2001, 1, 1)]))
                          echo df.select(col("d").dt.epoch(EpochUnit.Days).alias("days"),
                                         col("d").dt.century.alias("century"))
                          echo select(timeRange(timeOfDay(9), timeOfDay(11), "1h").alias("t"))
                          shape: (2, 2)
                          ┌───────┬─────────┐
                          │ days  ┆ century │
                          │ ---   ┆ ---     │
                          │ i32   ┆ i32     │
                          ╞═══════╪═════════╡
                          │ 11109 ┆ 20      │
                          │ 11323 ┆ 21      │
                          └───────┴─────────┘
                          shape: (3, 1)
                          ┌──────────┐
                          │ t        │
                          │ ---      │
                          │ time     │
                          ╞══════════╡
                          │ 09:00:00 │
                          │ 10:00:00 │
                          │ 11:00:00 │
                          └──────────┘
                          Scenario: Daylight saving
                          • WHEN dt.dstOffset runs on 2026-07-01 12:00 in Europe/Rome
                          • THEN the result is 1 hour
                          Business days

                          dt.addBusinessDays(n, weekMask, holidays, roll), dt.isBusinessDay(weekMask, holidays) and businessDayCount(start, stop, weekMask, holidays) SHALL count business days: Monday to Friday by default (weekMask, Monday first), minus holidays. roll SHALL say what a start date that is not a business day does (Raise, Forward, Backward).

                          let df = newDataFrame(series("d", @[date(2026, 10, 30)]))
                          echo df.select(col("d").dt.addBusinessDays(1).alias("next"),
                                         col("d").dt.isBusinessDay.alias("business"))
                          echo select(businessDayCount(date(2026, 11, 2), date(2026, 11, 9)).alias("n")).toList("n", int)
                          shape: (1, 2)
                          ┌────────────┬──────────┐
                          │ next       ┆ business │
                          │ ---        ┆ ---      │
                          │ date       ┆ bool     │
                          ╞════════════╪══════════╡
                          │ 2026-11-02 ┆ true     │
                          └────────────┴──────────┘
                          @[5]
                          Scenario: Holiday
                          • WHEN one business day is added to Friday 2026-10-30 with Monday 2026-11-02 a holiday
                          • THEN the result is 2026-11-03
                          temporal-grouping4 requirements

                          Purpose: Grouping rows by time windows (dynamic and rolling group-by) and joining each row to the nearest row of another frame by a sorted key (as-of join).

                          Dynamic group-by

                          groupByDynamic(indexColumn, every, period, offset, ...) on a DataFrame or LazyFrame SHALL group the rows of the sorted indexColumn into windows that start every every, span period (default every) and are shifted by offset, labelled as label says, and agg SHALL aggregate each window. Intervals SHALL be std/times intervals or Polars duration strings; groupBy SHALL group within the windows.

                          let df = newDataFrame:
                            day: [date(2026, 1, 1), date(2026, 1, 20), date(2026, 2, 3), date(2026, 3, 30)]
                            rain: [12, 3, 40, 7]
                          echo df.groupByDynamic("day", every = 1.months).agg(col.rain.sum)
                          shape: (3, 2)
                          ┌────────────┬──────┐
                          │ day        ┆ rain │
                          │ ---        ┆ ---  │
                          │ date       ┆ i64  │
                          ╞════════════╪══════╡
                          │ 2026-01-01 ┆ 15   │
                          │ 2026-02-01 ┆ 40   │
                          │ 2026-03-01 ┆ 7    │
                          └────────────┴──────┘
                          Scenario: Overlapping windows
                          • WHEN groupByDynamic("day", every = 1.months, period = 3.months) aggregates monthly rows
                          • THEN each window sums three months of rows
                          Scenario: Boundaries
                          • WHEN includeBoundaries = true
                          • THEN the result has _lower_boundary and _upper_boundary columns
                          Rolling group-by

                          rolling(indexColumn, period, offset, closed = Right, groupBy) SHALL make one group per row, holding the rows whose indexColumn lies in the period up to that row's value (shifted by offset), and agg SHALL aggregate each group.

                          let df = newDataFrame:
                            day: [date(2026, 7, 1), date(2026, 7, 2), date(2026, 7, 5)]
                            rain: [4, 0, 10]
                          echo df.rolling("day", period = 3.days).agg(col.rain.sum.alias("rain_3d"))
                          shape: (3, 2)
                          ┌────────────┬─────────┐
                          │ day        ┆ rain_3d │
                          │ ---        ┆ ---     │
                          │ date       ┆ i64     │
                          ╞════════════╪═════════╡
                          │ 2026-07-01 ┆ 4       │
                          │ 2026-07-02 ┆ 4       │
                          │ 2026-07-05 ┆ 10      │
                          └────────────┴─────────┘
                          Scenario: Gap in the dates
                          • WHEN rows on July 1, 2 and 5 are grouped with period = 3.days
                          • THEN the July 5 group holds only the July 5 row
                          As-of join

                          joinAsof(other, on, ...) (or leftOn and rightOn) SHALL join each left row to one right row by a sorted key: the last one at or before it (Backward), the first one at or after it (Forward) or the closest (Nearest), only within tolerance when given and only among rows with equal by columns; rows without a match SHALL get nulls. With coalesce = false the right key column SHALL be kept (with suffix if its name is taken), showing which right row matched.

                          let events = newDataFrame:
                            day: [date(2026, 1, 15), date(2026, 3, 2)]
                            event: ["flood", "drought"]
                          let oni = newDataFrame:
                            month: [date(2026, 1, 1), date(2026, 2, 1), date(2026, 3, 1)]
                            oni: [1.8, 1.5, 1.1]
                          echo events.joinAsof(oni, leftOn = "day", rightOn = "month")
                          shape: (2, 4)
                          ┌────────────┬─────────┬────────────┬─────┐
                          │ day        ┆ event   ┆ month      ┆ oni │
                          │ ---        ┆ ---     ┆ ---        ┆ --- │
                          │ date       ┆ str     ┆ date       ┆ f64 │
                          ╞════════════╪═════════╪════════════╪═════╡
                          │ 2026-01-15 ┆ flood   ┆ 2026-01-01 ┆ 1.8 │
                          │ 2026-03-02 ┆ drought ┆ 2026-03-01 ┆ 1.1 │
                          └────────────┴─────────┴────────────┴─────┘
                          Scenario: Tolerance
                          • WHEN the nearest earlier right row is 2 days before and tolerance = 1.days
                          • THEN the left row gets nulls
                          Scenario: Keep the right key
                          • WHEN joinAsof(other, on = "t", coalesce = false) runs
                          • THEN the result has both t and t_right
                          Scenario: Missing keys
                          • WHEN joinAsof is called without on and without leftOn and rightOn
                          • THEN ValueError is raised
                          Group keys by name

                          The groupBy parameter of rolling and groupByDynamic SHALL take a column name, several names, an expression or several expressions (groupBy = "store", ["store", "aisle"], [col("store")]).

                          let df = newDataFrame(series("day", @[1, 2, 3, 1, 2]), series("store", @["a", "a", "a", "b", "b"]),
                                                series("sales", @[1, 2, 3, 10, 20]))
                          echo df.rolling("day", "2i", groupBy = "store").agg(col("sales").sum)
                          shape: (5, 3)
                          ┌───────┬─────┬───────┐
                          │ store ┆ day ┆ sales │
                          │ ---   ┆ --- ┆ ---   │
                          │ str   ┆ i64 ┆ i64   │
                          ╞═══════╪═════╪═══════╡
                          │ a     ┆ 1   ┆ 1     │
                          │ a     ┆ 2   ┆ 3     │
                          │ a     ┆ 3   ┆ 5     │
                          │ b     ┆ 1   ┆ 10    │
                          │ b     ┆ 2   ┆ 30    │
                          └───────┴─────┴───────┘
                          Scenario: Expressions still work
                          • WHEN groupBy = [col("store")] is passed
                          • THEN the result is the same as with groupBy = "store"
                          testing-helpers2 requirements

                          Purpose: Assertions for tests that compare frames and series, in the module nanuq/testing, as polars.testing.

                          Comparing frames in tests

                          assertFrameEqual(left, right, checkRowOrder = true, checkColumnOrder = true, checkDtypes = true, checkExact = false, rtol = 1e-5, atol = 1e-8) in nanuq/testing SHALL return when the frames (or collected LazyFrames) have the same columns, types and rows, with nulls equal to nulls and floats equal within atol + rtol * abs(right) unless checkExact, and raise AssertionDefect naming the first difference otherwise. assertFrameNotEqual SHALL do the opposite.

                          import nanuq/testing
                          let df = newDataFrame(series("bear", @["Ada", "Bo"]), series("kg", @[410.0, 380.5]))
                          assertFrameEqual(df, newDataFrame(series("bear", @["Ada", "Bo"]), series("kg", @[410.0, 380.5000001])))
                          try:
                            assertFrameEqual(df, newDataFrame(series("bear", @["Ada", "Cy"]), series("kg", @[410.0, 380.5])))
                          except AssertionDefect as e:
                            echo e.msg
                          DataFrame column "bear" values differ at row 1: Bo != Cy
                          Scenario: Ignoring order
                          • WHEN two frames hold the same rows and columns in another order and both order checks are off
                          • THEN assertFrameEqual returns
                          Comparing Series in tests

                          assertSeriesEqual(left, right, checkDtypes = true, checkNames = true, checkOrder = true, checkExact = false, rtol = 1e-5, atol = 1e-8) SHALL compare two Series the same way, also checking their names unless checkNames = false; assertSeriesNotEqual SHALL do the opposite.

                          import nanuq/testing
                          let a = series("kg", @[410, 380])
                          assertSeriesEqual(a, series("mass", @[410, 380]), checkNames = false)
                          assertSeriesNotEqual(a, series("kg", @[410, 381]))
                          echo "ok"
                          ok
                          Scenario: NaN
                          • WHEN both Series hold NaN at the same row
                          • THEN assertSeriesEqual returns
                          value-functions7 requirements

                          Purpose: Expressions that treat the values of a column as a sequence or a set: ordering, picking values by position or rank, distinct values, recoding, binning and counting.

                          Ordering values

                          e.sort(descending, nullsLast) SHALL sort the values of e, e.argSort SHALL return the row indices that sort them, e.sortBy(by, descending) SHALL order e by one or more other columns, and e.reverse SHALL reverse it, so that these work inside agg and over.

                          let df = newDataFrame:
                            basin: ["Pacific", "Pacific", "Atlantic", "Atlantic"]
                            storm: ["Ana", "Bud", "Cleo", "Dan"]
                            wind: [120, 185, 150, 95]
                          echo df.groupBy(col.basin).agg(col.storm.sortBy(col.wind, descending = true).first
                                                         .alias("strongest")).sort("basin")
                          shape: (2, 2)
                          ┌──────────┬───────────┐
                          │ basin    ┆ strongest │
                          │ ---      ┆ ---       │
                          │ str      ┆ str       │
                          ╞══════════╪═══════════╡
                          │ Atlantic ┆ Cleo      │
                          │ Pacific  ┆ Bud       │
                          └──────────┴───────────┘
                          Scenario: Sorted column
                          • WHEN col.x.sort(descending = true) is selected on 2, 3, 1
                          • THEN the result is 3, 2, 1
                          Picking values

                          e.head(n = 10), e.tail(n = 10), e.slice(offset, length), e.gather(indices), e.gatherEvery(n, offset = 0), e.topK(k = 5), e.bottomK(k = 5), e.topKBy(by, k = 5, reverse) and e.bottomKBy(...) SHALL return those values of e (the k ones in no particular order, as in Polars); e.indexOf(value) SHALL return the index of the first occurrence of value (or null), and e.searchSorted(element, side) the index at which element would be inserted to keep e sorted.

                          let df = newDataFrame:
                            year: [1982, 1997, 2015, 2023]
                            oni: [2.2, 2.4, 2.6, 2.0]
                          echo df.select(col.year.topKBy(col.oni, k = 2).sort.alias("top2"),
                                         col.oni.topK(2).sort.alias("peak"))
                          shape: (2, 2)
                          ┌──────┬──────┐
                          │ top2 ┆ peak │
                          │ ---  ┆ ---  │
                          │ i64  ┆ f64  │
                          ╞══════╪══════╡
                          │ 1997 ┆ 2.4  │
                          │ 2015 ┆ 2.6  │
                          └──────┴──────┘
                          Scenario: Gather by position
                          • WHEN col.x.gather([0, 2]) is selected on 10, 20, 30
                          • THEN the result is 10, 30
                          Scenario: Insertion point
                          • WHEN searchSorted(2) runs on 1, 2, 2, 3 with side Left and Right
                          • THEN the results are 1 and 3
                          Distinct values

                          e.unique(maintainOrder = false) SHALL return the distinct values, isUnique, isDuplicated, isFirstDistinct and isLastDistinct SHALL flag rows by how their value repeats, argUnique SHALL return the index of each value's first occurrence, uniqueCounts the number of occurrences of each distinct value in order of appearance, and approxNUnique an estimate of the number of distinct values.

                          let df = newDataFrame:
                            station: ["Lima", "Quito", "Lima", "Paita"]
                          echo df.withColumns(col.station.isDuplicated.alias("dup"),
                                              col.station.isFirstDistinct.alias("first"))
                          shape: (4, 3)
                          ┌─────────┬───────┬───────┐
                          │ station ┆ dup   ┆ first │
                          │ ---     ┆ ---   ┆ ---   │
                          │ str     ┆ bool  ┆ bool  │
                          ╞═════════╪═══════╪═══════╡
                          │ Lima    ┆ true  ┆ true  │
                          │ Quito   ┆ false ┆ true  │
                          │ Lima    ┆ true  ┆ false │
                          │ Paita   ┆ false ┆ true  │
                          └─────────┴───────┴───────┘
                          Scenario: Unique in order
                          • WHEN unique(maintainOrder = true) runs on b, a, b, c
                          • THEN the result is b, a, c
                          Recoding values

                          e.replace(old, new) and e.replace({old: new, ...}) SHALL replace each listed value and keep the others and the data type; e.replaceStrict(...) SHALL require every value to be listed, unless a default is given, and SHALL take the data type of the new values.

                          let df = newDataFrame:
                            phase: ["N", "EN", "LN", "EN"]
                          echo df.withColumns(col.phase.replaceStrict({"EN": "El Niño", "LN": "La Niña"},
                                                                      default = "neutral").alias("name"))
                          shape: (4, 2)
                          ┌───────┬─────────┐
                          │ phase ┆ name    │
                          │ ---   ┆ ---     │
                          │ str   ┆ str     │
                          ╞═══════╪═════════╡
                          │ N     ┆ neutral │
                          │ EN    ┆ El Niño │
                          │ LN    ┆ La Niña │
                          │ EN    ┆ El Niño │
                          └───────┴─────────┘
                          Scenario: Value not listed
                          • WHEN replaceStrict({"a": 1}) runs on a column holding "a" and "b"
                          • THEN collecting raises InvalidOperationError
                          Scenario: Unequal lists
                          • WHEN replace([1, 2], [10]) is built
                          • THEN ValueError is raised
                          Binning

                          e.cut(breaks, labels, leftClosed = false) SHALL put each value in the interval between breaks it falls into, as an Enum labelled like "(-0.5, 0.5]" or with labels (one more than breaks), and e.qcut(quantiles, ...) SHALL do the same at the quantiles of the values, given as probabilities or as a number of equal groups.

                          let df = newDataFrame:
                            oni: [-1.6, -0.2, 0.3, 0.9, 2.4]
                          echo df.withColumns(col.oni.cut([-0.5, 0.5], labels = ["La Niña", "neutral", "El Niño"])
                                              .alias("phase"))
                          shape: (5, 2)
                          ┌──────┬─────────┐
                          │ oni  ┆ phase   │
                          │ ---  ┆ ---     │
                          │ f64  ┆ enum    │
                          ╞══════╪═════════╡
                          │ -1.6 ┆ La Niña │
                          │ -0.2 ┆ neutral │
                          │ 0.3  ┆ neutral │
                          │ 0.9  ┆ El Niño │
                          │ 2.4  ┆ El Niño │
                          └──────┴─────────┘
                          Scenario: Default labels
                          • WHEN cut([0.0]) runs on -1.0 and 1.0
                          • THEN the labels are "(-inf, 0]" and "(0, inf]"
                          Value counts

                          valueCounts(column, sort = false, normalize = false, name) on a DataFrame or LazyFrame SHALL return each distinct value of column with its number of occurrences in a column count (or its share in proportion with normalize, or the column name), most frequent first with sort.

                          let df = newDataFrame:
                            phase: ["neutral", "El Niño", "neutral", "La Niña", "neutral", "El Niño"]
                          echo df.valueCounts("phase", sort = true)
                          shape: (3, 2)
                          ┌─────────┬───────┐
                          │ phase   ┆ count │
                          │ ---     ┆ ---   │
                          │ str     ┆ u32   │
                          ╞═════════╪═══════╡
                          │ neutral ┆ 3     │
                          │ El Niño ┆ 2     │
                          │ La Niña ┆ 1     │
                          └─────────┴───────┘
                          Scenario: Proportions
                          • WHEN valueCounts("x", normalize = true) runs on a, a, b, b
                          • THEN each value has proportion 0.5
                          Top k rows

                          LazyFrame and DataFrame SHALL support topK(k, by, reverse = false) and bottomK(k, by, reverse = false), returning the k whole rows with the largest (topK) or smallest (bottomK) values of by, in that order. by SHALL be a column name, a list of names, an expression or a list of expressions; with several keys the later ones break ties. reverse = true SHALL swap the direction. Nulls SHALL come last and ties SHALL keep their original order.

                          let events = newDataFrame:
                            start: ["1972 MJJ", "1982 AMJ", "1997 AMJ", "2015 MAM", "2023 MJJ"]
                            peak: [2.1, 2.2, 2.4, 2.6, 2.0]
                          echo events.topK(3, by = "peak")
                          echo events.bottomK(1, by = col.peak)
                          shape: (3, 2)
                          ┌──────────┬──────┐
                          │ start    ┆ peak │
                          │ ---      ┆ ---  │
                          │ str      ┆ f64  │
                          ╞══════════╪══════╡
                          │ 2015 MAM ┆ 2.6  │
                          │ 1997 AMJ ┆ 2.4  │
                          │ 1982 AMJ ┆ 2.2  │
                          └──────────┴──────┘
                          shape: (1, 2)
                          ┌──────────┬──────┐
                          │ start    ┆ peak │
                          │ ---      ┆ ---  │
                          │ str      ┆ f64  │
                          ╞══════════╪══════╡
                          │ 2023 MJJ ┆ 2.0  │
                          └──────────┴──────┘
                          Scenario: Reverse
                          • WHEN topK(2, by = "peak", reverse = true) runs
                          • THEN it returns the same rows as bottomK(2, by = "peak")
                          Scenario: k larger than the frame
                          • WHEN topK(10, by = "peak") runs on 5 rows
                          • THEN all 5 rows are returned, largest first

                          Source files

                          Every source file this page mentions, folded: tap one to read it. A file's name in the text leads here.

                          tools/specview.nim: the report on this page 843 lines
                          ## specview: a review page for the OpenSpec changes in this repository.
                          ##
                          ## Reads `openspec/` (changes, archive, main specs), `BACKLOG.md` and, with `--base`,
                          ## git, and writes one self-contained HTML page:
                          ## - where each change is in the process (proposal → specs → design → tasks →
                          ##   implementation → archive),
                          ## - its proposal, design and tasks, and its revisions (each commit that touched it,
                          ##   shown as word diffs of the changed paragraphs),
                          ## - its spec deltas as requirement cards, with MODIFIED requirements shown as a word
                          ##   diff against the current spec,
                          ## - with `--base`, a line diff of every OpenSpec, backlog and changelog file changed
                          ##   since that git ref,
                          ## - every main spec in full (`openspec/specs/`), with its requirements, examples and
                          ##   scenarios, marking the specs that active changes touch.
                          ##
                          ## Archived changes are hidden until "Show archived changes" is ticked, except those
                          ## changed since `--base`.
                          ##
                          ## Usage:
                          ##   nim r tools/specview.nim [--base:origin/main] [--out:specview.html] [--md:summary.md]
                          ##
                          ## Only the standard library is used, so it runs without the Rust build.
                          
                          import std/[os, osproc, strutils, tables, algorithm, parseopt, sequtils, times]
                          import experimental/diff
                          
                          # ---------------------------------------------------------------------------
                          # Model and parsing
                          # ---------------------------------------------------------------------------
                          
                          type
                            Scenario = object
                              name: string
                              lines: seq[string]
                          
                            Requirement = object
                              name: string
                              body: string
                              scenarios: seq[Scenario]
                          
                            Section = object
                              title: string           ## "Requirements", "ADDED Requirements", ...
                              reqs: seq[Requirement]
                          
                            SpecDoc = object
                              purpose: string
                              sections: seq[Section]
                          
                            Task = object
                              id, text: string
                              done: bool
                          
                            TaskGroup = object
                              title: string
                              tasks: seq[Task]
                          
                            CapDelta = object
                              name: string
                              delta: SpecDoc
                              current: SpecDoc
                              isNew: bool
                          
                            Change = object
                              name, dir: string
                              archived: bool
                              created: string
                              proposal, design: string
                              hasProposal, hasDesign, hasTasks: bool
                              tasks: seq[TaskGroup]
                              caps: seq[CapDelta]
                              backlog: seq[string]    ## titles of BACKLOG.md entries naming this change
                              touched: bool           ## changed since --base
                          
                          proc readOr(path: string, default = ""): string =
                            if fileExists(path): readFile(path) else: default
                          
                          proc parseSpec(text: string): SpecDoc =
                            var section = -1
                            var inPurpose = false
                            var purpose: seq[string]
                            template curReq: untyped = result.sections[section].reqs[^1]
                            var inFence = false
                            for raw in text.splitLines:
                              let line = raw.strip(leading = false)
                              if line.strip.startsWith("```"): inFence = not inFence
                              if inFence or line.strip.startsWith("```"):
                                # code examples: kept verbatim, never read as headings
                                if section >= 0 and result.sections[section].reqs.len > 0 and curReq.scenarios.len == 0:
                                  curReq.body.add line & "\n"
                                elif inPurpose: purpose.add line
                              elif line.startsWith("## "):
                                let title = line[3..^1].strip
                                inPurpose = title == "Purpose"
                                if not inPurpose:
                                  result.sections.add Section(title: title)
                                  section = result.sections.high
                              elif line.startsWith("### Requirement:"):
                                if section < 0:
                                  result.sections.add Section(title: "Requirements")
                                  section = 0
                                result.sections[section].reqs.add Requirement(name: line["### Requirement:".len..^1].strip)
                              elif line.startsWith("#### Scenario:"):
                                if section >= 0 and result.sections[section].reqs.len > 0:
                                  curReq.scenarios.add Scenario(name: line["#### Scenario:".len..^1].strip)
                              elif line.startsWith("# "):
                                discard
                              elif inPurpose:
                                purpose.add line
                              elif section >= 0 and result.sections[section].reqs.len > 0:
                                if curReq.scenarios.len > 0:
                                  if line.len > 0: curReq.scenarios[^1].lines.add line
                                else:
                                  curReq.body.add line & "\n"
                            result.purpose = purpose.join("\n").strip
                            for s in result.sections.mitems:
                              for r in s.reqs.mitems: r.body = r.body.strip
                          
                          proc parseTasks(text: string): seq[TaskGroup] =
                            for raw in text.splitLines:
                              let line = raw.strip
                              if line.startsWith("## "):
                                result.add TaskGroup(title: line[3..^1].strip)
                              elif line.startsWith("- [") and line.len > 4:
                                let close = line.find(']')
                                if close < 0: continue
                                if result.len == 0: result.add TaskGroup(title: "Tasks")
                                let mark = line[3 ..< close].strip
                                var rest = line[close + 1 .. ^1].strip
                                var id = ""
                                let sp = rest.find(' ')
                                if sp > 0 and rest[0].isDigit:
                                  id = rest[0 ..< sp]
                                  rest = rest[sp + 1 .. ^1]
                                result[^1].tasks.add Task(id: id, text: rest, done: mark.toLowerAscii == "x")
                          
                          proc sectionsOf(md: string): OrderedTable[string, string] =
                            var cur = ""
                            for line in md.splitLines:
                              if line.startsWith("## "):
                                cur = line[3..^1].strip
                                result[cur] = ""
                              elif cur.len > 0:
                                result[cur].add line & "\n"
                          
                          proc backlogEntries(backlog: string): seq[(string, string)] =
                            ## (title, full text) of every top-level "- **Title**" entry.
                            var title, body: string
                            for line in backlog.splitLines:
                              if line.startsWith("- **") or line.startsWith("## "):
                                if title.len > 0: result.add (title, body)
                                title = ""; body = ""
                                if line.startsWith("- **"):
                                  let e = line.find("**", 4)
                                  title = if e > 4: line[4 ..< e] else: line
                              if title.len > 0: body.add line & "\n"
                            if title.len > 0: result.add (title, body)
                          
                          proc loadChange(root, dir: string, archived: bool, backlog: seq[(string, string)]): Change =
                            result.dir = dir.relativePath(root).replace('\\', '/')
                            result.archived = archived
                            result.name = dir.lastPathPart
                            if archived and result.name.len > 11 and result.name[10] == '-':
                              result.name = result.name[11..^1]   # archive dirs are prefixed with a date
                            for line in readOr(dir / ".openspec.yaml").splitLines:
                              if line.startsWith("created:"): result.created = line[8..^1].strip
                            result.proposal = readOr(dir / "proposal.md")
                            result.design = readOr(dir / "design.md")
                            result.hasProposal = result.proposal.len > 0
                            result.hasDesign = result.design.len > 0
                            result.hasTasks = fileExists(dir / "tasks.md")
                            result.tasks = parseTasks(readOr(dir / "tasks.md"))
                            if dirExists(dir / "specs"):
                              for f in walkDirRec(dir / "specs"):
                                if f.endsWith("spec.md"):
                                  let cap = f.parentDir.relativePath(dir / "specs")
                                  let mainPath = root / "openspec" / "specs" / cap / "spec.md"
                                  result.caps.add CapDelta(name: cap, delta: parseSpec(readFile(f)),
                                                           current: parseSpec(readOr(mainPath)),
                                                           isNew: not fileExists(mainPath))
                            result.caps.sort(proc (a, b: CapDelta): int = cmp(a.name, b.name))
                            for (title, body) in backlog:
                              if result.name in body: result.backlog.add title
                          
                          proc taskCounts(c: Change): (int, int) =
                            for g in c.tasks:
                              for t in g.tasks:
                                inc result[1]
                                if t.done: inc result[0]
                          
                          proc stage(c: Change): string =
                            let (done, total) = c.taskCounts
                            if c.archived: "Archived"
                            elif not (c.hasProposal and c.caps.len > 0 and c.hasTasks): "Planning"
                            elif done == 0: "Ready to apply"
                            elif done < total: "Implementing"
                            else: "Ready to archive"
                          
                          # ---------------------------------------------------------------------------
                          # HTML helpers: escaping, a small Markdown subset, word and line diffs
                          # ---------------------------------------------------------------------------
                          
                          proc esc(s: string): string =
                            result = newStringOfCap(s.len)
                            for ch in s:
                              case ch
                              of '&': result.add "&amp;"
                              of '<': result.add "&lt;"
                              of '>': result.add "&gt;"
                              of '"': result.add "&quot;"
                              else: result.add ch
                          
                          proc inline(s: string): string =
                            ## `code`, **bold**, *em*, [text](url); everything else escaped.
                            var i = 0
                            while i < s.len:
                              if s[i] == '`':
                                let e = s.find('`', i + 1)
                                if e > i:
                                  result.add "<code>" & esc(s[i+1 ..< e]) & "</code>"; i = e + 1; continue
                              elif s[i] == '*' and i + 1 < s.len and s[i+1] == '*':
                                let e = s.find("**", i + 2)
                                if e > i:
                                  result.add "<strong>" & inline(s[i+2 ..< e]) & "</strong>"; i = e + 2; continue
                              elif s[i] == '*' and i + 1 < s.len and s[i+1] != ' ':
                                let e = s.find('*', i + 1)
                                if e > i + 1:
                                  result.add "<em>" & inline(s[i+1 ..< e]) & "</em>"; i = e + 1; continue
                              elif s[i] == '[':
                                let m = s.find("](", i)
                                let e = if m > 0: s.find(')', m) else: -1
                                if m > i and e > m and '\n' notin s[i..e]:
                                  result.add "<a href=\"" & esc(s[m+2 ..< e]) & "\">" & inline(s[i+1 ..< m]) & "</a>"
                                  i = e + 1; continue
                              result.add esc($s[i])
                              inc i
                          
                          proc md(text: string): string =
                            ## Headings, paragraphs, bullet/numbered lists (one level), fenced code.
                            var para: seq[string]
                            var list: seq[string]
                            var listTag = ""
                            var code: seq[string]
                            var inCode = false
                            var lang = ""
                            template flushPara() =
                              if para.len > 0: result.add "<p>" & inline(para.join(" ")) & "</p>\n"; para = @[]
                            template flushList() =
                              if list.len > 0:
                                result.add "<" & listTag & ">"
                                for it in list: result.add "<li>" & inline(it) & "</li>"
                                result.add "</" & listTag & ">\n"
                                list = @[]
                            for raw in text.splitLines:
                              let line = raw.strip(leading = false)
                              let s = line.strip
                              if s.startsWith("```"):
                                if inCode:
                                  # a ```text block shows an example's output
                                  let cls = if lang == "text": " class=\"out\"" else: ""
                                  result.add "<pre" & cls & "><code>" & esc(code.join("\n")) & "</code></pre>\n"; code = @[]
                                else:
                                  flushPara(); flushList()
                                  lang = s[3..^1].strip
                                inCode = not inCode
                              elif inCode: code.add raw
                              elif s.startsWith("<!--"): discard
                              elif s.len == 0: flushPara(); flushList()
                              elif s.startsWith("#"):
                                flushPara(); flushList()
                                let level = min(s.len - s.strip(chars = {'#'}).len + 2, 6)
                                result.add "<h" & $level & ">" & inline(s.strip(chars = {'#', ' '})) & "</h" & $level & ">\n"
                              elif s.startsWith("- ") or s.startsWith("* ") or
                                   (s.len > 2 and s[0].isDigit and (s.find(". ") in 1..3)):
                                flushPara()
                                let ordered = s[0].isDigit
                                let tag = if ordered: "ol" else: "ul"
                                if list.len > 0 and tag != listTag: flushList()
                                listTag = tag
                                list.add(if ordered: s[s.find(". ") + 2 .. ^1] else: s[2..^1])
                              elif list.len > 0 and raw.startsWith(" "): list[^1].add " " & s
                              else: para.add s
                            flushPara(); flushList()
                          
                          proc tokens(s: string): seq[string] =
                            ## Words and whitespace runs, so a diff can be rejoined exactly.
                            var cur = ""
                            for ch in s:
                              if cur.len > 0 and (ch in Whitespace) != (cur[^1] in Whitespace):
                                result.add cur; cur = ""
                              cur.add ch
                            if cur.len > 0: result.add cur
                          
                          proc wordDiff(a, b: string): string =
                            let ta = tokens(a)
                            let tb = tokens(b)
                            var ids: Table[string, int]
                            proc idsOf(ts: seq[string]): seq[int] =
                              for t in ts: result.add ids.mgetOrPut(t, ids.len)
                            let items = diffInt(idsOf(ta), idsOf(tb))
                            var ia, ib = 0
                            for it in items:
                              while ia < it.startA: result.add esc(ta[ia]); inc ia; inc ib
                              if it.deletedA > 0: result.add "<del>" & esc(ta[it.startA ..< it.startA + it.deletedA].join) & "</del>"
                              if it.insertedB > 0: result.add "<ins>" & esc(tb[it.startB ..< it.startB + it.insertedB].join) & "</ins>"
                              ia = it.startA + it.deletedA
                              ib = it.startB + it.insertedB
                            while ia < ta.len: result.add esc(ta[ia]); inc ia
                          
                          proc reqText(r: Requirement): string =
                            result = r.body
                            for s in r.scenarios:
                              result.add "\n\nScenario: " & s.name
                              for l in s.lines: result.add "\n" & l
                          
                          proc lineDiff(a, b: string, context = 3): (string, int, int) =
                            ## Unified diff rendered as table rows, plus added and removed line counts.
                            let la = if a.len == 0: @[] else: a.splitLines
                            let lb = if b.len == 0: @[] else: b.splitLines
                            let items = diffText(la.join("\n"), lb.join("\n"))
                            var rows = ""
                            var added, removed = 0
                            proc row(kind, na, nb, text: string): string =
                              "<tr class=\"" & kind & "\"><td class=\"ln\">" & na & "</td><td class=\"ln\">" & nb &
                                "</td><td class=\"tx\">" & esc(text) & "</td></tr>\n"
                            var ia = 0
                            var ib = 0
                            var lastShown = -1
                            for idx, it in items:
                              let from0 = max(ia, it.startA - context)
                              if from0 > lastShown + 1 and lastShown >= 0 or (lastShown < 0 and from0 > 0):
                                rows.add "<tr class=\"gap\"><td class=\"ln\"></td><td class=\"ln\"></td><td class=\"tx\">⋯</td></tr>\n"
                              ib += from0 - ia
                              ia = from0
                              while ia < it.startA:
                                rows.add row("eq", $(ia + 1), $(ib + 1), la[ia]); inc ia; inc ib
                              for k in 0 ..< it.deletedA:
                                rows.add row("rm", $(it.startA + k + 1), "", la[it.startA + k]); inc removed
                              for k in 0 ..< it.insertedB:
                                rows.add row("ad", "", $(it.startB + k + 1), lb[it.startB + k]); inc added
                              ia = it.startA + it.deletedA
                              ib = it.startB + it.insertedB
                              let nextStart = if idx < items.high: items[idx + 1].startA else: la.len
                              let upto = min(ia + context, nextStart)
                              while ia < upto:
                                rows.add row("eq", $(ia + 1), $(ib + 1), la[ia]); inc ia; inc ib
                              lastShown = ia - 1
                            if lastShown >= 0 and lastShown < la.len - 1:
                              rows.add "<tr class=\"gap\"><td class=\"ln\"></td><td class=\"ln\"></td><td class=\"tx\">⋯</td></tr>\n"
                            (rows, added, removed)
                          
                          # ---------------------------------------------------------------------------
                          # Rendering
                          # ---------------------------------------------------------------------------
                          
                          const varsCss = """
                          :root{--ice:#f3f7f9;--floe:#fff;--ink:#12222e;--mute:#5a6b77;--rule:#d5e1e8;--fjord:#0d6f86;
                          --add:#e3f4e6;--add-ink:#1f6b2c;--del:#fbe7e4;--del-ink:#a2321f;--mod:#fff2d6;--mod-ink:#8a5a00;
                          --display:"Familjen Grotesk","Helvetica Neue",Arial,sans-serif;--body:"Literata",Georgia,serif;
                          --mono:"JetBrains Mono",ui-monospace,Menlo,Consolas,monospace;color-scheme:light}
                          @media (prefers-color-scheme:dark){:root:not([data-theme="light"]){--ice:#0d161d;--floe:#121e27;
                          --ink:#e3ecf1;--mute:#93a6b3;--rule:#22323e;--fjord:#5cc4dc;--add:#12301b;--add-ink:#8fd19a;
                          --del:#3a1a16;--del-ink:#f0a092;--mod:#33290f;--mod-ink:#f0c868;color-scheme:dark}}
                          """
                          
                          ## The page frame of the standalone page: ground, column, header, headings.
                          const pageCss = """
                          *{box-sizing:border-box}
                          body{margin:0;background:var(--ice);color:var(--ink);font:16px/1.6 var(--body);
                          padding:0 max(16px,env(safe-area-inset-left,0px))}
                          main,header.mast{max-width:62rem;margin:0 auto}
                          header.mast{padding:2.5rem 0 1.5rem;border-bottom:1px solid var(--rule)}
                          .eyebrow{font:600 .75rem/1 var(--mono);letter-spacing:.12em;text-transform:uppercase;color:var(--fjord)}
                          h1{font:700 clamp(2rem,6vw,3rem)/1.05 var(--display);margin:.5rem 0}
                          h2,h3,h4,h5{font-family:var(--display);line-height:1.2}
                          h2{font-size:1.6rem;margin:2.5rem 0 .5rem}
                          h3{font-size:1.2rem;margin:1.6rem 0 .4rem}
                          .meta{font:.8rem/1.4 var(--mono);color:var(--mute)}
                          a{color:var(--fjord)}
                          footer{max-width:62rem;margin:3rem auto;color:var(--mute);font:.8rem var(--mono)}
                          """
                          
                          ## The report itself (changes, requirements, diffs, specs). docs/openspec.nim reuses it
                          ## inside the dev-log theme, scoped to `.specview`.
                          const reportCss* = """
                          code,pre{font-family:var(--mono);font-size:.85em}
                          p code,li code,td code{background:var(--rule);padding:.05em .3em;border-radius:3px}
                          pre{background:var(--floe);border:1px solid var(--rule);border-radius:6px;padding:.8rem;overflow-x:auto;line-height:1.25}
                          pre + pre.out{margin-top:-.4rem;border-top-left-radius:0;border-top-right-radius:0}
                          pre.out{background:var(--ice);border-style:dashed;position:relative}
                          pre.out::before{content:"output";position:absolute;top:.3rem;right:.6rem;font-size:.7rem;color:var(--mute);font-family:var(--display)}
                          table.overview{border-collapse:collapse;width:100%;font-size:.9rem;margin:1rem 0}
                          table.overview th,table.overview td{text-align:left;padding:.4rem .6rem;border-bottom:1px solid var(--rule);vertical-align:top}
                          table.overview th{font:600 .7rem/1 var(--mono);text-transform:uppercase;letter-spacing:.08em;color:var(--mute)}
                          .change{background:var(--floe);border:1px solid var(--rule);border-radius:10px;padding:1.2rem 1.4rem;margin:1.5rem 0}
                          .change>h2{margin-top:0}
                          .pill{display:inline-block;font:600 .7rem/1 var(--mono);letter-spacing:.06em;text-transform:uppercase;
                          padding:.35rem .55rem;border-radius:99px;border:1px solid var(--rule);color:var(--mute);vertical-align:middle;white-space:nowrap}
                          .pill.stage{background:var(--fjord);color:var(--floe);border-color:var(--fjord)}
                          .pill.touched{color:var(--mod-ink);background:var(--mod);border-color:transparent}
                          .steps{display:flex;flex-wrap:wrap;gap:.3rem;margin:1rem 0;padding:0;list-style:none}
                          .steps li{font:600 .72rem/1 var(--mono);padding:.5rem .7rem;border-radius:6px;border:1px solid var(--rule);color:var(--mute)}
                          .steps li.done{background:var(--add);color:var(--add-ink);border-color:transparent}
                          .steps li.now{background:var(--fjord);color:var(--floe);border-color:var(--fjord)}
                          .steps li.skip{border-style:dashed}
                          .bar{height:6px;background:var(--rule);border-radius:3px;overflow:hidden;margin:.3rem 0 .8rem}
                          .bar>span{display:block;height:100%;background:var(--fjord)}
                          details{border-top:1px solid var(--rule);padding:.5rem 0}
                          details>summary{cursor:pointer;font:700 1.05rem/1.4 var(--display);list-style-position:outside}
                          details>summary .meta{font-weight:400;margin-left:.5rem}
                          .cap{margin:1rem 0 1.5rem}
                          .cap>h4{margin:0 0 .5rem;font-size:1.05rem}
                          .req{border:1px solid var(--rule);border-left:4px solid var(--rule);border-radius:6px;padding:.7rem 1rem;margin:.6rem 0;background:var(--ice)}
                          .req.ADDED{border-left-color:var(--add-ink)}.req.MODIFIED{border-left-color:var(--mod-ink)}
                          .req.REMOVED{border-left-color:var(--del-ink)}.req.RENAMED{border-left-color:var(--fjord)}
                          .req .op{font:700 .65rem/1 var(--mono);letter-spacing:.08em;margin-right:.5rem}
                          .ADDED .op{color:var(--add-ink)}.MODIFIED .op{color:var(--mod-ink)}.REMOVED .op{color:var(--del-ink)}
                          .req h5{display:inline;font-size:1rem;margin:0}
                          .req p{margin:.4rem 0}
                          .scn{margin:.5rem 0 0;padding:.5rem .8rem;border-radius:4px;background:var(--floe);font-size:.92rem}
                          .scn b{font-family:var(--display)}
                          .scn ul{margin:.2rem 0;padding-left:1.1rem}
                          .wdiff{white-space:pre-wrap;font-size:.92rem;margin:.4rem 0}
                          ins{background:var(--add);color:var(--add-ink);text-decoration:none}
                          del{background:var(--del);color:var(--del-ink)}
                          .unchanged{color:var(--mute);font-size:.9rem}
                          .tasks{list-style:none;padding:0;margin:.3rem 0 1rem}
                          .tasks li{padding:.15rem 0 .15rem 1.7rem;position:relative}
                          .tasks li::before{content:"○";position:absolute;left:.3rem;color:var(--mute)}
                          .tasks li.done::before{content:"✓";color:var(--add-ink);font-weight:700}
                          .tasks li.done{color:var(--mute)}
                          .tid{font:.75rem var(--mono);color:var(--mute);margin-right:.3rem}
                          table.diff{border-collapse:collapse;width:100%;font:.78rem/1.45 var(--mono);background:var(--floe)}
                          table.diff td{padding:0 .5rem;vertical-align:top}
                          table.diff td.ln{color:var(--mute);text-align:right;width:3rem;user-select:none;border-right:1px solid var(--rule)}
                          table.diff td.tx{white-space:pre-wrap;word-break:break-word}
                          tr.ad{background:var(--add)}tr.ad td.tx::before{content:"+ ";color:var(--add-ink)}
                          tr.rm{background:var(--del)}tr.rm td.tx::before{content:"− ";color:var(--del-ink)}
                          tr.eq td.tx::before{content:"  "}
                          tr.gap td{color:var(--mute);text-align:center}
                          .diffwrap{overflow-x:auto;border:1px solid var(--rule);border-radius:6px;margin:.5rem 0}
                          .count .a{color:var(--add-ink)}.count .r{color:var(--del-ink)}
                          .rev{margin:.8rem 0 1.2rem}
                          .revhead{margin-bottom:.4rem}
                          .revfile{margin:.6rem 0 .2rem;font-size:.9rem}
                          .hunk{border:1px solid var(--rule);border-radius:6px;padding:.5rem .8rem;margin:.4rem 0;background:var(--ice)}
                          .where{font:600 .7rem/1.2 var(--mono);color:var(--mute);text-transform:uppercase;letter-spacing:.06em;margin-bottom:.2rem}
                          .nav{display:flex;flex-wrap:wrap;gap:1rem;align-items:center;margin:1rem 0 0;font:600 .8rem/1 var(--mono)}
                          .nav label{color:var(--mute);cursor:pointer;display:inline-flex;gap:.4rem;align-items:center}
                          .archived{display:none}
                          body:has(#show-archived:checked) .archived,body.show-archived .archived{display:revert}
                          .hint{font:.8rem/1.4 var(--mono);color:var(--mute)}
                          .spec{background:var(--floe);border:1px solid var(--rule);border-radius:10px;padding:.6rem 1.4rem;margin:.8rem 0}
                          .spec>summary{font-size:1.15rem}
                          .req.CURRENT{border-left-color:var(--fjord)}
                          .speclist{columns:2 16rem;font-size:.9rem;padding-left:1.1rem}
                          """
                          
                          const css = varsCss & pageCss & reportCss
                          
                          const toggleJs* = """<script>
                          (function(){
                            var box = document.getElementById("show-archived"), key = "specview-show-archived";
                            function apply(on){ document.body.classList.toggle("show-archived", on); box.checked = on; }
                            var saved = false;
                            try { saved = localStorage.getItem(key) === "1"; } catch(e) {}
                            apply(saved);
                            box.addEventListener("change", function(){
                              apply(box.checked);
                              try { localStorage.setItem(key, box.checked ? "1" : "0"); } catch(e) {}
                            });
                            // a link to an archived change or a spec opens it
                            function reveal(){
                              var id = decodeURIComponent(location.hash.slice(1)); if (!id) return;
                              var el = document.getElementById(id); if (!el) return;
                              if (el.classList.contains("archived")) apply(true);
                              if (el.tagName === "DETAILS") el.open = true;
                              el.scrollIntoView();
                            }
                            window.addEventListener("hashchange", reveal); reveal();
                          })();
                          </script>"""
                          
                          proc deltaCounts(c: CapDelta): Table[string, int] =
                            for s in c.delta.sections:
                              result[s.title.split(' ')[0]] = result.getOrDefault(s.title.split(' ')[0]) + s.reqs.len
                          
                          proc countsLabel(c: CapDelta): string =
                            var parts: seq[string]
                            let t = c.deltaCounts
                            for (k, sym) in [("ADDED", "+"), ("MODIFIED", "~"), ("REMOVED", "−"), ("RENAMED", "→")]:
                              if t.getOrDefault(k) > 0: parts.add sym & $t[k]
                            parts.join(" ")
                          
                          proc renderScenarios(r: Requirement): string =
                            for s in r.scenarios:
                              result.add "<div class=\"scn\"><b>Scenario: " & inline(s.name) & "</b><ul>"
                              for l in s.lines:
                                result.add "<li>" & inline(l.strip(chars = {'-', ' '})) & "</li>"
                              result.add "</ul></div>"
                          
                          proc renderReq(op: string, r: Requirement, current: SpecDoc): string =
                            result.add "<div class=\"req " & op & "\">" &
                              (if op == "CURRENT": "" else: "<span class=\"op\">" & op & "</span>") & "<h5>" &
                              inline(r.name) & "</h5>"
                            if op == "MODIFIED":
                              var before: Requirement
                              var found = false
                              for s in current.sections:
                                for cr in s.reqs:
                                  if cr.name.toLowerAscii.strip == r.name.toLowerAscii.strip:
                                    before = cr; found = true
                              if found:
                                result.add "<div class=\"wdiff\">" & wordDiff(reqText(before), reqText(r)) & "</div>"
                              else:
                                result.add "<p class=\"unchanged\">⚠ No requirement with this name in the current spec, so archiving will fail.</p>" &
                                  md(r.body) & renderScenarios(r)
                            else:
                              result.add md(r.body) & renderScenarios(r)
                            result.add "</div>\n"
                          
                          proc renderCap(c: CapDelta): string =
                            result.add "<div class=\"cap\"><h4><code>" & esc(c.name) & "</code> " &
                              (if c.isNew: "<span class=\"pill touched\">new capability</span>" else: "<span class=\"pill\">modified</span>") &
                              " <span class=\"meta\">" & c.countsLabel & "</span></h4>"
                            if c.delta.purpose.len > 0: result.add "<p><em>Purpose:</em> " & inline(c.delta.purpose) & "</p>"
                            var changed: seq[string]
                            for s in c.delta.sections:
                              let op = s.title.split(' ')[0]
                              for r in s.reqs:
                                changed.add r.name.toLowerAscii
                                result.add renderReq(op, r, c.current)
                            if not c.isNew:
                              var same: seq[string]
                              for s in c.current.sections:
                                for r in s.reqs:
                                  if r.name.toLowerAscii notin changed: same.add r.name
                              if same.len > 0:
                                result.add "<p class=\"unchanged\">Unchanged in this spec: " & same.mapIt(inline(it)).join(", ") & "</p>"
                            result.add "</div>"
                          
                          proc renderSteps(c: Change): string =
                            let (done, total) = c.taskCounts
                            type St = tuple[label, cls: string]
                            let implCls = if c.archived or (total > 0 and done == total): "done"
                                          elif done > 0: "now" else: ""
                            var steps: seq[St] = @[
                              ("Proposal", if c.hasProposal: "done" else: "now"),
                              ("Specs", if c.caps.len > 0: "done" elif c.hasProposal: "now" else: ""),
                              ("Design", if c.hasDesign: "done" elif c.hasTasks: "skip" else: ""),
                              ("Tasks", if c.hasTasks: "done" elif c.caps.len > 0: "now" else: ""),
                              ("Implement " & $done & "/" & $total, implCls),
                              ("Archive", if c.archived: "done" elif total > 0 and done == total: "now" else: "")]
                            if c.hasProposal and c.caps.len > 0 and c.hasTasks and done == 0 and not c.archived:
                              steps[4].cls = "now"
                            result = "<ol class=\"steps\">"
                            for s in steps: result.add "<li class=\"" & s.cls & "\">" & esc(s.label) & "</li>"
                            result.add "</ol>"
                          
                          proc git(root: string, args: varargs[string]): (string, int) =
                            execCmdEx("git -C " & quoteShell(root) & " " & args.mapIt(quoteShell(it)).join(" "))
                          
                          proc paragraphs(text: string): seq[string] =
                            for p in text.replace("\r\n", "\n").split("\n\n"):
                              if p.strip.len > 0: result.add p.strip(chars = {'\n'})
                          
                          proc paraDiff(a, b: string): string =
                            ## Changed paragraphs only, each as a word diff, labelled with the nearest heading.
                            let pa = paragraphs(a)
                            let pb = paragraphs(b)
                            var ids: Table[string, int]
                            proc idsOf(ps: seq[string]): seq[int] =
                              for p in ps: result.add ids.mgetOrPut(p, ids.len)
                            for it in diffInt(idsOf(pa), idsOf(pb)):
                              var where = ""
                              let first = if it.startB < pb.len and pb[it.startB].startsWith("#"): it.startB else: it.startB - 1
                              for k in countdown(min(first, pb.high), 0):
                                if pb[k].startsWith("#"):
                                  where = pb[k].strip(chars = {'#', ' '}).splitLines[0]; break
                              let before = pa[it.startA ..< it.startA + it.deletedA].join("\n\n")
                              let after = pb[it.startB ..< it.startB + it.insertedB].join("\n\n")
                              result.add "<div class=\"hunk\">" &
                                (if where.len > 0: "<div class=\"where\">§ " & esc(where) & "</div>" else: "") &
                                "<div class=\"wdiff\">" & wordDiff(before, after) & "</div></div>"
                          
                          type Revision = object
                            label, sha, date, subject: string
                          
                          proc revisions(root, dir: string): seq[Revision] =
                            let (log, code) = git(root, "log", "--reverse", "--format=%h%x09%ad%x09%s", "--date=short", "--", dir)
                            if code != 0: return
                            for line in log.splitLines:
                              let f = line.split('\t', 2)
                              if f.len == 3: result.add Revision(sha: f[0], date: f[1], subject: f[2])
                            let (dirty, _) = git(root, "status", "--porcelain", "--", dir)
                            if dirty.strip.len > 0:
                              result.add Revision(sha: "", date: "", subject: "uncommitted changes in the working tree")
                            for i, r in result.mpairs: r.label = "r" & $(i + 1)
                          
                          proc fileAt(root, sha, path: string): string =
                            if sha.len == 0: return readOr(root / path)
                            let (s, code) = git(root, "show", sha & ":" & path)
                            if code == 0: s else: ""
                          
                          proc renderRevisions(root: string, c: Change): string =
                            let revs = revisions(root, c.dir)
                            if revs.len == 0: return
                            result.add "<details" & (if revs.len > 1: " open" else: "") & "><summary>Revisions<span class=\"meta\">" &
                              $revs.len & (if revs.len == 1: " revision" else: " revisions") & "</span></summary>"
                            for i, r in revs:
                              result.add "<div class=\"rev\"><div class=\"revhead\"><span class=\"pill stage\">" & r.label &
                                "</span> <code>" & esc(if r.sha.len > 0: r.sha else: "working tree") & "</code> <span class=\"meta\">" &
                                esc(r.date) & "</span> " & inline(r.subject) & "</div>"
                              if i == 0:
                                let (files, _) = git(root, "ls-tree", "-r", "--name-only", (if r.sha.len > 0: r.sha else: "HEAD"), "--", c.dir)
                                let names = files.splitLines.filterIt(it.len > 0).mapIt(it.relativePath(c.dir))
                                result.add "<p class=\"unchanged\">First version: " & names.mapIt("<code>" & esc(it) & "</code>").join(", ") & "</p>"
                              else:
                                let prev = revs[i - 1].sha
                                let (files, _) = if r.sha.len > 0: git(root, "diff", "--name-only", prev, r.sha, "--", c.dir)
                                                 else: git(root, "diff", "--name-only", prev, "--", c.dir)
                                for f in files.splitLines:
                                  if f.strip.len == 0: continue
                                  result.add "<div class=\"revfile\"><code>" & esc(f.relativePath(c.dir)) & "</code></div>" &
                                    paraDiff(fileAt(root, prev, f), fileAt(root, r.sha, f))
                              result.add "</div>"
                            result.add "</details>"
                          
                          proc renderChange(c: Change, root: string): string =
                            let (done, total) = c.taskCounts
                            let hidden = c.archived and not c.touched
                            result.add "<section class=\"change" & (if hidden: " archived" else: "") & "\" id=\"" &
                              esc(c.name) & "\"><h2>" & esc(c.name) &
                              " <span class=\"pill stage\">" & c.stage & "</span>" &
                              (if c.touched: " <span class=\"pill touched\">changed in this diff</span>" else: "") & "</h2>"
                            result.add "<div class=\"meta\">" & (if c.created.len > 0: "created " & esc(c.created) & " · " else: "") &
                              esc(c.dir) & "</div>"
                            result.add renderSteps(c)
                            if c.backlog.len > 0:
                              result.add "<p><strong>From the backlog:</strong> " & c.backlog.mapIt(inline(it)).join("; ") & "</p>"
                            let ps = sectionsOf(c.proposal)
                            if c.hasProposal:
                              result.add "<details open><summary>Proposal</summary>"
                              for key in ["Why", "What Changes"]:
                                if key in ps: result.add "<h3>" & key & "</h3>" & md(ps[key])
                              for key, val in ps:
                                if key notin ["Why", "What Changes"]: result.add "<h3>" & esc(key) & "</h3>" & md(val)
                              result.add "</details>"
                            if c.caps.len > 0:
                              result.add "<details open><summary>Spec changes<span class=\"meta\">" &
                                c.caps.mapIt(esc(it.name) & " " & it.countsLabel).join(" · ") & "</span></summary>"
                              for cap in c.caps: result.add renderCap(cap)
                              result.add "</details>"
                            if c.hasDesign:
                              result.add "<details><summary>Design</summary>" & md(c.design) & "</details>"
                            if c.hasTasks:
                              result.add "<details " & (if done > 0 and done < total: "open" else: "") &
                                "><summary>Tasks<span class=\"meta\">" & $done & " of " & $total & " done</span></summary>"
                              for g in c.tasks:
                                let gd = g.tasks.countIt(it.done)
                                result.add "<h4>" & inline(g.title) & " <span class=\"meta\">" & $gd & "/" & $g.tasks.len & "</span></h4>"
                                if g.tasks.len > 0:
                                  result.add "<div class=\"bar\"><span style=\"width:" & $(gd * 100 div g.tasks.len) & "%\"></span></div>"
                                result.add "<ul class=\"tasks\">"
                                for t in g.tasks:
                                  result.add "<li class=\"" & (if t.done: "done" else: "") & "\"><span class=\"tid\">" & esc(t.id) &
                                    "</span>" & inline(t.text) & "</li>"
                                result.add "</ul>"
                              result.add "</details>"
                            result.add renderRevisions(root, c)
                            result.add "</section>\n"
                          
                          
                          proc changedFiles(root, base: string): seq[string] =
                            let scope = ["openspec", "BACKLOG.md", "CHANGELOG.md"]
                            let (tracked, code) = git(root, @["diff", "--name-only", base, "--"] & @scope)
                            if code != 0: quit "git diff against " & base & " failed:\n" & tracked
                            let (untracked, _) = git(root, @["ls-files", "--others", "--exclude-standard", "--"] & @scope)
                            for l in (tracked & "\n" & untracked).splitLines:
                              if l.strip.len > 0 and l.strip notin result: result.add l.strip
                            result.sort
                          
                          proc renderRawDiff(root, base: string, files: seq[string]): string =
                            result.add "<h2 id=\"raw-diff\">Files changed since <code>" & esc(base) & "</code></h2>"
                            if files.len == 0:
                              return result & "<p class=\"unchanged\">No OpenSpec, backlog or changelog files changed.</p>"
                            for f in files:
                              let (old, code) = git(root, "show", base & ":" & f)
                              let before = if code == 0: old else: ""
                              let after = readOr(root / f)
                              let (rows, added, removed) = lineDiff(before, after)
                              let tag = if code != 0: " <span class=\"pill touched\">new</span>"
                                        elif not fileExists(root / f): " <span class=\"pill\">deleted</span>" else: ""
                              result.add "<details><summary><code>" & esc(f) & "</code>" & tag &
                                "<span class=\"meta count\"><span class=\"a\">+" & $added & "</span> <span class=\"r\">−" & $removed &
                                "</span></span></summary><div class=\"diffwrap\"><table class=\"diff\">" & rows & "</table></div></details>"
                          
                          proc renderMarkdown(changes: seq[Change], base: string, files: seq[string]): string =
                            result = "## OpenSpec review\n\n"
                            let active = changes.filterIt(not it.archived)
                            if active.len == 0: result.add "No active changes.\n"
                            else:
                              result.add "| Change | Stage | Tasks | Specs |\n|---|---|---|---|\n"
                              for c in active:
                                let (done, total) = c.taskCounts
                                result.add "| " & (if c.touched: "**" & c.name & "**" else: c.name) & " | " & c.stage & " | " &
                                  $done & "/" & $total & " | " &
                                  c.caps.mapIt("`" & it.name & "` " & (if it.isNew: "(new) " else: "") & it.countsLabel).join(", ") & " |\n"
                            if base.len > 0:
                              result.add "\n" & $files.len & " OpenSpec/backlog/changelog files changed since `" & base & "`.\n"
                            result.add "\nThe full report (proposal, spec diffs, tasks, file diffs) is in this run's `specview` artifact.\n"
                          
                          # ---------------------------------------------------------------------------
                          # Main
                          # ---------------------------------------------------------------------------
                          
                          proc renderSpecs(root: string, changes: seq[Change], files: seq[string]): string =
                            ## Every main spec in full; specs touched by an active change, or changed since
                            ## --base, are marked.
                            var names: seq[string]
                            for kind, dir in walkDir(root / "openspec" / "specs"):
                              if kind == pcDir and fileExists(dir / "spec.md"): names.add dir.lastPathPart
                            names.sort
                            var pending = initTable[string, seq[string]]()
                            for c in changes:
                              if not c.archived:
                                for cap in c.caps: pending.mgetOrPut(cap.name, @[]).add c.name
                            result.add "<h2 id=\"specs\">Specs</h2><p class=\"hint\">The current specs in " &
                              "openspec/specs, as archived changes left them. Changes still open are not applied here.</p>"
                            result.add "<ul class=\"speclist\">"
                            for n in names:
                              result.add "<li><a href=\"#spec-" & esc(n) & "\"><code>" & esc(n) & "</code></a>" &
                                (if n in pending: " <span class=\"pill touched\">open change</span>" else: "") & "</li>"
                            result.add "</ul>"
                            for n in names:
                              let path = "openspec/specs/" & n & "/spec.md"
                              let doc = parseSpec(readFile(root / path))
                              var nreq = 0
                              for sec in doc.sections: nreq += sec.reqs.len
                              result.add "<details class=\"spec\" id=\"spec-" & esc(n) & "\"><summary><code>" & esc(n) &
                                "</code><span class=\"meta\">" & $nreq & " requirements" &
                                (if path in files: " · changed in this diff" else: "") &
                                (if n in pending: " · open change: " & pending[n].mapIt(esc(it)).join(", ") else: "") &
                                "</span></summary>"
                              if doc.purpose.len > 0: result.add "<p><em>Purpose:</em> " & inline(doc.purpose) & "</p>"
                              for sec in doc.sections:
                                for r in sec.reqs: result.add renderReq("CURRENT", r, doc)
                              result.add "</details>\n"
                          
                          type Report* = object
                            ## Everything specview reads: the changes, newest work first, and with a base the
                            ## files changed since it.
                            root*, base*, head*: string
                            changes: seq[Change]
                            files: seq[string]
                          
                          proc loadReport*(root: string, base = ""): Report =
                            result.root = root.absolutePath
                            result.base = base
                            let root = result.root
                            if not dirExists(root / "openspec"): quit "no openspec/ directory in " & root
                            let backlog = backlogEntries(readOr(root / "BACKLOG.md"))
                            for kind, dir in walkDir(root / "openspec" / "changes"):
                              if kind == pcDir and dir.lastPathPart != "archive":
                                result.changes.add loadChange(root, dir, false, backlog)
                            if dirExists(root / "openspec" / "changes" / "archive"):
                              for kind, dir in walkDir(root / "openspec" / "changes" / "archive"):
                                if kind == pcDir: result.changes.add loadChange(root, dir, true, backlog)
                            if base.len > 0:
                              result.files = changedFiles(root, base)
                              for c in result.changes.mitems:
                                c.touched = result.files.anyIt(it.startsWith(c.dir & "/"))
                            result.changes.sort(proc (a, b: Change): int =
                              result = cmp(a.archived, b.archived)
                              if result == 0: result = cmp(b.touched, a.touched)
                              if result == 0: result = cmp(a.name, b.name))
                            result.head = git(root, "log", "-1", "--format=%h %s")[0].strip
                          
                          proc renderNav*(r: Report): string =
                            ## Section links and the "Show archived changes" checkbox (needs `toggleJs`).
                            let base = r.base
                            "<nav class=\"nav\"><a href=\"#overview\">Changes</a><a href=\"#specs\">Specs</a>" &
                              (if base.len > 0: "<a href=\"#raw-diff\">Diff</a>" else: "") &
                              "<label><input type=\"checkbox\" id=\"show-archived\"> " &
                              (if base.len > 0: "Show older archived changes (" else: "Show archived changes (") &
                              $r.changes.countIt(it.archived and not it.touched) & ")</label></nav>" &
                              (if base.len > 0: "<p class=\"hint\">Compared with " & esc(base) &
                                ": changes this branch added, edited or archived are always shown; archived " &
                                "changes it did not touch are hidden.</p>" else: "")
                          
                          proc renderReport*(r: Report): string =
                            ## The changes overview, every change, every spec and, with a base, the file diffs.
                            let active = r.changes.filterIt(not it.archived)
                            result.add "<h2 id=\"overview\">Changes</h2><table class=\"overview\"><tr><th>Change</th><th>Stage</th><th>Tasks</th><th>Specs</th></tr>"
                            for c in r.changes:
                              let (done, total) = c.taskCounts
                              result.add "<tr" & (if c.archived and not c.touched: " class=\"archived\"" else: "") &
                                "><td><a href=\"#" & esc(c.name) & "\">" & esc(c.name) & "</a>" &
                                (if c.touched: " <span class=\"pill touched\">changed</span>" else: "") & "</td><td>" & c.stage &
                                "</td><td>" & $done & "/" & $total & "</td><td>" &
                                c.caps.mapIt("<code>" & esc(it.name) & "</code> " & it.countsLabel).join("<br>") & "</td></tr>"
                            result.add "</table>"
                            if active.len == 0: result.add "<p class=\"unchanged\">No active changes.</p>"
                            for c in r.changes: result.add renderChange(c, r.root)
                            result.add renderSpecs(r.root, r.changes, r.files)
                            if r.base.len > 0: result.add renderRawDiff(r.root, r.base, r.files)
                          
                          proc main() =
                            var root = getCurrentDir()
                            var base, outPath, mdPath = ""
                            outPath = "specview.html"
                            for kind, key, val in getopt():
                              case kind
                              of cmdLongOption, cmdShortOption:
                                case key
                                of "base": base = val
                                of "out": outPath = val
                                of "md": mdPath = val
                                of "root": root = val
                                of "help", "h":
                                  echo "usage: specview [--root:DIR] [--base:GIT_REF] [--out:FILE.html] [--md:FILE.md]"; quit 0
                                else: quit "unknown option --" & key
                              else: discard
                            let r = loadReport(root, base)
                            var html = "<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">" &
                              "<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><title>OpenSpec review</title>" &
                              "<link rel=\"stylesheet\" href=\"https://fonts.googleapis.com/css2?family=Familjen+Grotesk:wght@500;700&family=Literata:ital,opsz,wght@0,7..72,400;0,7..72,600;1,7..72,400&family=JetBrains+Mono:wght@400;600&display=swap\">" &
                              "<style>" & css & "</style></head><body>"
                            html.add "<header class=\"mast\"><span class=\"eyebrow\">" & esc(r.root.lastPathPart) &
                              " · OpenSpec review</span><h1>Where the changes stand</h1><div class=\"meta\">" & esc(r.head) &
                              (if base.len > 0: " · compared with " & esc(base) else: "") & " · generated " &
                              now().format("yyyy-MM-dd HH:mm") & "</div>" & renderNav(r) & "</header><main>"
                            html.add renderReport(r)
                            html.add "</main><footer>Generated by tools/specview.nim</footer>" & toggleJs & "</body></html>\n"
                            writeFile(outPath, html)
                            echo "wrote ", outPath
                            if mdPath.len > 0:
                              let f = open(mdPath, fmAppend)   # $GITHUB_STEP_SUMMARY is appended to
                              f.write renderMarkdown(r.changes, base, r.files)
                              f.close
                              echo "wrote ", mdPath
                          
                          when isMainModule:
                            main()

                          tools/specview.nim