The first build of Nanuq compiles Polars from source, which takes about ten minutes.
That's fine for us but not for someone trying the library for the first time. Python
users never see this because PyPI hosts a prebuilt wheel per platform. Nim has no such
registry, so this post looks at how other projects ship a native library without one,
and what Nanuq will do. Nothing here was implemented when it was written; the plan
shipped with Nanuq 0.1, and the comment at the top of src/nanuq/ffi.nim describes how
it works today. It follows How Nanuq works.
The plan in one paragraph. Do what Elixir's Explorer (Polars for Elixir) and r-polars do. A GitHub Actions workflow, run when we push a
lib-v*tag, builds the static library for four Rust targets and attaches the archives to a GitHub Release. The repository commits their SHA-256 sums. At compile time,ffi.nimpicks the archive for the host, downloads it once into a user cache withcurl, checks the sum and links it. If anything is missing, it falls back to the cargo build we have today. It happens at compile time rather than in a nimble hook, because Atlas, nimby and plain git clones never run nimble hooks.
Where Nanuq is today↑ contents
src/nanuq/ffi.nim already does half of this. At compile time it looks for
rust/target/release/libnanuq_ffi.a, runs cargo build through gorgeEx if it's
missing, and accepts -d:nanuqLibDir=… for a library built elsewhere, or
-d:nanuqNoCargo to never run cargo. So the missing piece is a third source between
"already there" and "build it": "download a prebuilt one".
Three facts shape the choice:
- The crate builds both a
staticliband acdylib. The static lib is about 300 MB unstripped. - Nim on Windows uses MinGW gcc by default. A Rust static lib for the
x86_64-pc-windows-msvctarget won't link with MinGW, so the Windows build must bex86_64-pc-windows-gnu. r-polars shipsgnuon Windows for the same reason (R uses Rtools gcc). - Nim has no binary registry. Nimble, Atlas and nimby all install packages as git checkouts.
How Nim packages ship native code↑ contents
| Approach | Real examples | How it works | For Nanuq |
|---|---|---|---|
| Vendor C sources | status-im sqlite3_abi, naylib (raylib), nim-bearssl |
C sources in the repo, compiled by Nim with {.compile.} |
No: Rust needs cargo, and Polars takes minutes |
| Build at compile time | nim-leopard (CMake through gorge), Nanuq today |
The wrapper module runs a build tool when imported | Keep, as the fallback |
Nimble before install hook |
nim-rocksdb, the Nim compiler's own nim.nimble |
Nimble runs NimScript before installing the package | Partial: Atlas, nimby, submodules and nimble develop skip it |
| Download prebuilt, else build | nwaku's build_rln.sh |
Fetch zerokit's Rust librln.a from GitHub Releases by host triple, else cargo build |
Yes: the closest Nim precedent, and it's Rust |
| Fetch from a C package manager | nimterop getHeader with -d:headerConan / -d:headerJBB |
Compile-time download from Conan Center or Julia BinaryBuilder | Shows the pattern is accepted, but nimterop is unmaintained |
| System library | sdl2, openssl, most wrappers | The user installs it with apt or brew | No: nobody packages a Polars C ABI |
Nimble itself downloads prebuilt Nim compilers now, but it has no mechanism for a package's own native files. So whatever we do lives in the package.
How other ecosystems do it↑ contents
The useful models are the ecosystems that, like Nim, have no registry that knows about platforms.
| Ecosystem | Mechanism | Takeaway |
|---|---|---|
| Elixir | rustler_precompiled: at compile time, download the library for the host triple from GitHub Releases. A checksum file in the package pins every archive. EXPLORER_BUILD=1 forces a cargo build, and a pre-release version always builds. Explorer ships 9 targets plus a legacy_cpu variant. |
The best template: same library, same constraint |
| R | r-polars' tools/prep-lib.R downloads from a separate lib-v* tag, checks tools/lib-sums.tsv, else builds with cargo |
Version the Rust lib apart from the package |
| Go | Modules are source only and cgo has no build hooks. wasmtime-go commits prebuilt static libs into the repo on release tags | Fine for 20 MB, not for 300 MB times four targets |
| Deno | Deno.dlopen plus @denosaurs/plug, which downloads a shared library on first use and caches it |
Runtime download only suits dynamic libs |
| Zig | build.zig.zon dependencies are URLs pinned by content hash, fetched lazily into a global cache |
Pin by hash, cache globally |
| Julia | BinaryBuilder cross-compiles everything. JLL packages carry an Artifacts.toml from platform to URL and hash |
Our sums file is a small Artifacts.toml |
Ecosystems with a platform-aware registry still have ideas worth taking:
- Python ships platform wheels. Polars also publishes a build for old x86 CPUs
(
polars-lts-cpu, nowpolars[rtcompat]), so the CPU baseline needs a decision. - Node started with install scripts (prebuild-install, node-pre-gyp) that download from GitHub Releases and fall back to node-gyp. It moved to one npm package per platform (napi-rs, esbuild, nodejs-polars) because install scripts broke behind corporate proxies. So errors must be clear, and a local path must always work.
- Ruby ships platform gems built with rb-sys plus a source gem that runs cargo. polars-ruby is shipped this way.
The plan for Nanuq↑ contents
Compile-time download in ffi.nim
Before the cargo step, ffi.nim tries these sources in order:
-d:nanuqLibDir=…if given (exists today).- The local cargo output in
src/rust/target/release, so contributors are unaffected. - The user cache:
~/.cache/nanuq/<libver>/<triple>/(%LOCALAPPDATA%on Windows,~/Library/Cacheson macOS). It is shared across projects and survives reinstalls. - A download of
libnanuq_ffi-<libver>-<triple>.tar.gzwithcurlandtar, which ship with Windows 10 and later, macOS and mainstream Linux. The SHA-256 is checked withsha256sum,shasum -a 256orcertutil, as r-polars does, since hashing 100 MB in the Nim VM would be too slow. - A cargo build, as today.
Downloading is the default. -d:nanuqLib=source never downloads, and
-d:nanuqLib=prebuilt fails instead of building. Each step prints a hint, so a
compile that goes to the network says so.
Platforms
| Target | Notes |
|---|---|
x86_64-unknown-linux-gnu |
Built against glibc 2.28 (manylinux container or cargo zigbuild), so it runs on older distros |
aarch64-unknown-linux-gnu |
On GitHub's arm runners, same glibc floor |
aarch64-apple-darwin |
With MACOSX_DEPLOYMENT_TARGET=11.0 |
x86_64-pc-windows-gnu |
MinGW, to link with Nim's default C compiler. MSVC if someone asks |
Any other platform builds from source.
CPU variants
Intel and AMD CPUs share a baseline instruction set, and newer ones add vector
instructions (AVX2, FMA) that process several numbers at once. Polars uses them in its
fast paths, but a library built to need them crashes on CPUs that lack them. We do what
Explorer does: each x86_64 target ships a modern build (x86-64-v3, roughly 2013 and
later) and a legacy-cpu baseline build. On Linux, ffi.nim reads /proc/cpuinfo
at compile time and picks the legacy build if a needed flag is missing. Elsewhere the
legacy build is only used with -d:nanuqLegacyCpu, which also forces it on Linux, for
example when the program will run on older machines than the one compiling it. arm64
has a single build.
Static, not dynamic
The static lib makes the user's program self-contained: nothing to find at runtime and no DLL search paths. That's also what nwaku and r-polars ship. The costs are a big download and slower links. A shared library option stays in the backlog. The release can carry both kinds later, since the crate already builds both.
Size needs measuring first: lto = "fat" and codegen-units = 1 should shrink the
archive, and gzip keeps it readable by every tar.
Versions
- The lib is versioned by the crate's
Cargo.toml, apart from the Nim package, and its binaries live under alib-v<libver>tag. Most Nim releases reuse the last lib. Lib releases are tagged by hand. - The sums are committed in
src/nanuq/lib-sums.txtand read withstaticRead. - A
-devlib version never downloads. CI fails if the crate changed while the version still matches a published lib, so new Rust code is never paired with an old binary. - Rust exports
nq_version(), and Nanuq checks it at startup.
Fallback
Every miss falls back to cargo with a hint saying why, for example
"nanuq: no prebuilt library for riscv64gc-unknown-linux-gnu, building with cargo
(about 10 minutes)". A checksum mismatch is the exception: it stops with an error,
because it may mean a release was replaced. Without cargo, the error names both ways
out: install Rust, or download the archive by hand and pass -d:nanuqLibDir.
The release workflow
on: push: tags: ["lib-v*"]
jobs:
build: # matrix over the targets above, plus legacy-cpu for x86_64
- cargo build --release --target $TRIPLE (zigbuild for linux-gnu.2.28)
- tar czf libnanuq_ffi-$VER-$TRIPLE.tar.gz libnanuq_ffi.a
- smoke test: nim c -r -d:nanuqLibDir=. tests/test_basic.nim
release:
- sha256sum *.tar.gz > lib-sums.txt
- create the GitHub Release with the archives and lib-sums.txt
- open a PR that commits src/nanuq/lib-sums.txt
Set aside↑ contents
- Binaries in git (wasmtime-go's way) or Git LFS: 300 MB per target would bloat every clone, and Nimble doesn't handle LFS.
- One nimble package per platform, like npm's per-platform packages: the binaries still need a git home, and the package managers resolve requirements differently.
- A nimble hook only: misses Atlas, nimby, submodules and
nimble develop. - Runtime download: only works for dynamic libs, and a data library that goes online on first run would surprise people.
One more thing turned up while writing the OpenSpec change: nimble install copies only
srcDir, so a top-level rust/ never reaches users. The crate therefore moves to
src/rust/, which also keeps the cargo fallback working in installed packages.
Source files↑ contents
Every source file this page mentions, folded: tap one to read it. A file's name in the text leads here.
ffi.nim: where the library comes from, as it works today 186 lines
## Raw bindings to the `nanuq_ffi` Rust crate (see `src/rust/src/lib.rs`).
##
## This mirrors the C ABI one to one, in the style of an
## `nbindgen <https://github.com/arnetheduck/nbindgen>`_ generated header.
## You normally want the high level API in `nanuq` instead.
##
## Linking: the static library `libnanuq_ffi.a` comes from the first of
##
## 1. `-d:nanuqLibDir=/some/dir`, a library built or downloaded by hand;
## 2. the local cargo output in `src/rust/target/release` (git checkouts);
## 3. the prebuilt library for this platform, downloaded once from the
## GitHub release `lib-v<version>` into a per-user cache and checked
## against the SHA-256 in `lib-sums.txt`;
## 4. `cargo build --release` of the crate shipped with this package.
##
## `-d:nanuqLib=source` never downloads, `-d:nanuqLib=prebuilt` (or
## `-d:nanuqNoCargo`) never runs cargo, and the default `auto` allows both.
## `-d:nanuqLegacyCpu` picks the build for x86_64 CPUs without AVX2/FMA, which
## is otherwise chosen automatically on Linux. `-d:nanuqCacheDir` moves the
## cache, and `-d:nanuqReleaseUrl` downloads from a mirror of the releases
## (the checksums still apply).
import std/[os, strutils]
const
rustDir = currentSourcePath.parentDir.parentDir / "rust"
libFileName = "libnanuq_ffi.a"
nanuqLib {.strdefine.} = "auto"
nanuqLibDir {.strdefine.} = ""
nanuqCacheDir {.strdefine.} = ""
nanuqReleaseUrl {.strdefine.} = "https://github.com/pietroppeter/nanuq/releases/download"
libPolicy = (when defined(nanuqNoCargo): "prebuilt" else: nanuqLib)
when libPolicy notin ["auto", "prebuilt", "source"]:
{.error: "nanuq: -d:nanuqLib must be auto, prebuilt or source, not " & libPolicy.}
proc crateVersion(cargoToml: string): string =
## The `version` of the `[package]` section.
var inPackage = false
for line in cargoToml.splitLines:
let l = line.strip
if l.startsWith("["): inPackage = l == "[package]"
elif inPackage and l.startsWith("version"):
return l.split('=', 1)[1].strip.strip(chars = {'"'})
const nanuqLibVersion* = crateVersion(staticRead(rustDir / "Cargo.toml"))
## Version of the `nanuq_ffi` crate these bindings were compiled for.
proc targetTriple(): string =
when defined(linux) and defined(amd64): "x86_64-unknown-linux-gnu"
elif defined(linux) and defined(arm64): "aarch64-unknown-linux-gnu"
elif defined(macosx) and defined(arm64): "aarch64-apple-darwin"
elif defined(windows) and defined(amd64): "x86_64-pc-windows-gnu"
else: ""
proc lacksModernCpu*(cpuinfo: string): bool =
## True when the first `flags` line of `/proc/cpuinfo` text misses a feature
## of the x86-64-v3 build.
for line in cpuinfo.splitLines:
if line.startsWith("flags"):
let flags = line.split(':', 1)[1].splitWhitespace
for f in ["avx", "avx2", "bmi1", "bmi2", "fma", "f16c", "movbe"]:
if f notin flags: return true
return false
proc hostLacksModernCpu(): bool =
## True when compiling on x86_64 Linux for x86_64 Linux and the CPU lacks a
## feature of the x86-64-v3 build. Elsewhere we can't tell, so false.
when defined(linux) and defined(amd64):
let arch = gorgeEx("uname -m")
let info = gorgeEx("cat /proc/cpuinfo")
arch.exitCode == 0 and arch.output.strip == "x86_64" and info.exitCode == 0 and
lacksModernCpu(info.output)
else:
false
proc archiveName(): string =
## Release asset for this target, or "" when there is none.
let triple = targetTriple()
if triple.len == 0: return ""
result = "libnanuq_ffi-" & nanuqLibVersion & "-" & triple
if triple.startsWith("x86_64") and (defined(nanuqLegacyCpu) or hostLacksModernCpu()):
result.add "-legacy-cpu"
result.add ".tar.gz"
proc expectedSum(archive: string): string =
## SHA-256 of `archive` from lib-sums.txt (sha256sum format), or "".
for line in staticRead(currentSourcePath.parentDir / "lib-sums.txt").splitLines:
let parts = line.splitWhitespace
if parts.len == 2 and parts[1].strip(chars = {'*'}) == archive:
return parts[0].toLowerAscii
proc cacheRoot(): string =
if nanuqCacheDir.len > 0: return nanuqCacheDir
if getEnv("LOCALAPPDATA").len > 0: return getEnv("LOCALAPPDATA") / "nanuq"
if dirExists(getHomeDir() / "Library" / "Caches"):
return getHomeDir() / "Library" / "Caches" / "nanuq"
let xdg = getEnv("XDG_CACHE_HOME")
(if xdg.len > 0: xdg else: getHomeDir() / ".cache") / "nanuq"
proc sha256(file: string): string =
for cmd in ["sha256sum " & quoteShell(file), "shasum -a 256 " & quoteShell(file),
"certutil -hashfile " & quoteShell(file) & " SHA256"]:
let r = gorgeEx(cmd)
if r.exitCode == 0:
for line in r.output.splitLines:
let h = line.strip.split(' ')[0].toLowerAscii
if h.len == 64 and h.allCharsInSet(HexDigits): return h
proc removeTmp(file: string) =
# removeFile needs C at compile time
discard gorgeEx((when defined(windows): "cmd /c del " else: "rm -f ") & quoteShell(file))
proc prebuiltLib(): tuple[lib, why, error: string] =
## Path of the cached or downloaded library, or "" and the reason why not.
## `error` is set when the compile must stop instead of building.
let archive = archiveName()
if archive.len == 0:
return ("", "no prebuilt library for this platform", "")
if nanuqLibVersion.endsWith("-dev"):
return ("", "lib version " & nanuqLibVersion & " is a development version", "")
let sum = expectedSum(archive)
if sum.len == 0:
return ("", "no published " & archive & " in lib-sums.txt", "")
let dir = cacheRoot() / nanuqLibVersion / archive.replace(".tar.gz", "")
if fileExists(dir / ".complete"):
return (dir / libFileName, "", "")
let url = nanuqReleaseUrl & "/lib-v" & nanuqLibVersion & "/" & archive
echo "nanuq: downloading the prebuilt Polars wrapper " & url
# a name of our own, so two compiles at once don't write the same archive
let tmp = dir / ("download-" & CompileDate & "-" & CompileTime.replace(":", "") & ".tar.gz")
let dl = gorgeEx("curl -fsSL --retry 2 --create-dirs -o " & quoteShell(tmp) & " " & url)
if dl.exitCode != 0:
return ("", "download of " & url & " failed: " & dl.output.strip, "")
let actual = sha256(tmp)
if actual != sum:
removeTmp(tmp)
return ("", "", "nanuq: checksum mismatch for " & url & "\n expected " & sum &
"\n actual " & actual & "\nThe download was deleted. If it persists, the " &
"release may have been replaced: please open an issue.")
let ex = gorgeEx("tar -xzf " & quoteShell(tmp) & " -C " & quoteShell(dir))
removeTmp(tmp)
if ex.exitCode != 0 or not fileExists(dir / libFileName):
return ("", "could not unpack " & url & ": " & ex.output.strip, "")
writeFile(dir / ".complete", url)
(dir / libFileName, "", "")
proc findLib(): tuple[lib, error: string] =
if nanuqLibDir.len > 0:
if not fileExists(nanuqLibDir / libFileName):
return ("", "nanuq: -d:nanuqLibDir has no " & libFileName & ": " & nanuqLibDir)
return (nanuqLibDir / libFileName, "")
let local = rustDir / "target" / "release" / libFileName
if fileExists(local): return (local, "")
var why = "-d:nanuqLib=source"
if libPolicy != "source":
let (lib, reason, error) = prebuiltLib()
if error.len > 0: return ("", error)
if lib.len > 0: return (lib, "")
why = reason
if libPolicy == "prebuilt":
return ("", "nanuq: no Polars wrapper library (" & why &
"). Install Rust (https://rustup.rs) and compile with -d:nanuqLib=auto, or " &
"download a release archive and pass -d:nanuqLibDir=<dir>.")
echo "nanuq: building the Polars wrapper with cargo (" & why &
"), this compiles Polars and its dependencies..."
let cargo = gorgeEx("cargo build --release --manifest-path " &
quoteShell(rustDir / "Cargo.toml"))
if cargo.exitCode != 0 or not fileExists(local):
return ("", "nanuq: cargo build failed (" & why & "):\n" & cargo.output &
"\nIs Rust installed? See https://rustup.rs")
(local, "")
const found = findLib()
when found.error.len > 0:
{.error: found.error.}
const libFile = found.lib
{.hint: "nanuq: linking " & libFile.}
{.passL: quoteShell(libFile).}
when defined(linux):
{.passL: "-lpthread -ldl -lm".}
elif defined(macosx):
{.passL: "-framework CoreFoundation -framework IOKit -framework Security -framework SystemConfiguration -lc++".}
elif defined(windows):
{.passL: "-lws2_32 -luserenv -lbcrypt -lntdll -lole32 -loleaut32 -lkernel32 -ladvapi32 -lcrypt32 -lsecur32 -lncrypt".}src/nanuq/ffi.nim
lib-sums.txt: the committed SHA-256 sums 9 lines
# SHA-256 of the prebuilt libnanuq_ffi archives (sha256sum format), generated by
# .github/workflows/release-lib.yml for each lib-v<version> release. An archive is
# downloaded only when listed here.
0ff06ea73f46b2df21e12c9bafe29ac8493ef58d3aca2ada510f4e10a8213911 libnanuq_ffi-0.6.1-aarch64-apple-darwin.tar.gz
a29f09b7347a4bd85177d65a84a9f45f4e0bc35e9be61f32bdb524b2efd77a7d libnanuq_ffi-0.6.1-aarch64-unknown-linux-gnu.tar.gz
e2aeaa81817326125e715893c77577476011515218e26fb312d9e395a48d9a6c libnanuq_ffi-0.6.1-x86_64-pc-windows-gnu-legacy-cpu.tar.gz
c61eb384d4c0d609430f62afcd37f74d9efc22bf423a5ea67d89bfec1624db2c libnanuq_ffi-0.6.1-x86_64-pc-windows-gnu.tar.gz
57fc9e76af3fdf3f0b0121fa2e58b37d17b8fd0da4ca28bfd32645ec116f1ba2 libnanuq_ffi-0.6.1-x86_64-unknown-linux-gnu-legacy-cpu.tar.gz
7624fba20c7edd4d016d409fdac2664cd61ac1336ac9fbbb378b74ded4fdcc63 libnanuq_ffi-0.6.1-x86_64-unknown-linux-gnu.tar.gzsrc/nanuq/lib-sums.txt
release-lib.yml: the workflow that builds the archives 182 lines
name: Release lib
# Builds the prebuilt Polars wrapper (libnanuq_ffi.a) for every supported target,
# smoke-tests each archive on its own platform, and, for a pushed lib-v<version>
# tag, publishes them as a GitHub Release and opens a PR with their SHA-256 sums
# (src/nanuq/lib-sums.txt). Running it by hand (workflow_dispatch) builds and tests
# without publishing, unless "publish" is ticked on main: then the release step
# also creates the lib-v<version> tag on the commit it built. PRs that change this
# workflow build and test without publishing. The smoke tests also check the
# per-platform link flags in src/nanuq/ffi.nim (cloud storage added crypt32 on
# Windows and SystemConfiguration on macOS), so a PR that changes those should
# touch this file or be run by hand.
#
# The archives are built with a pinned nightly Rust and the crate features
# "nightly" (Polars' SIMD and nightly-only code paths) and "jemalloc" (the
# allocator py-polars uses), which bring Nanuq within a few percent of py-polars
# on PDS-H. Windows uses the system allocator, as py-polars does (it uses mimalloc
# there).
on:
push:
tags: ["lib-v*"]
pull_request:
paths: [".github/workflows/release-lib.yml"]
workflow_dispatch:
inputs:
publish:
description: "Publish lib-v<Cargo.toml version> from main (creates the tag)"
type: boolean
default: false
jobs:
version:
runs-on: ubuntu-24.04
outputs:
version: ${{ steps.v.outputs.version }}
steps:
- uses: actions/checkout@v4
- id: v
run: |
version=$(grep -m1 '^version' src/rust/Cargo.toml | cut -d'"' -f2)
echo "version=$version" >> "$GITHUB_OUTPUT"
if [ "${GITHUB_REF_TYPE}" = tag ] && [ "${GITHUB_REF_NAME}" != "lib-v$version" ]; then
echo "::error::tag ${GITHUB_REF_NAME} does not match the crate version $version"
exit 1
fi
if [ "${{ inputs.publish }}" = true ]; then
if [ "${GITHUB_REF}" != refs/heads/main ]; then
echo "::error::publish only from main, not ${GITHUB_REF}"; exit 1
fi
case "$version" in *-dev) echo "::error::$version is a development version"; exit 1;; esac
if git ls-remote --exit-code --tags origin "refs/tags/lib-v$version" > /dev/null; then
echo "::error::lib-v$version already exists. Bump the version in src/rust/Cargo.toml."; exit 1
fi
fi
build:
needs: version
strategy:
fail-fast: false
matrix:
include:
# Linux builds run in manylinux_2_28, so they link on glibc 2.28 and newer
- { target: x86_64-unknown-linux-gnu, variant: "", cpu: x86-64-v3, os: ubuntu-24.04, container: "quay.io/pypa/manylinux_2_28_x86_64", features: "nightly jemalloc" }
- { target: x86_64-unknown-linux-gnu, variant: "-legacy-cpu", cpu: "", os: ubuntu-24.04, container: "quay.io/pypa/manylinux_2_28_x86_64", features: "nightly jemalloc" }
- { target: aarch64-unknown-linux-gnu, variant: "", cpu: "", os: ubuntu-24.04-arm, container: "quay.io/pypa/manylinux_2_28_aarch64", features: "nightly jemalloc" }
- { target: aarch64-apple-darwin, variant: "", cpu: "", os: macos-15, container: "", features: "nightly jemalloc" }
# gnu, so the library links with Nim's default MinGW gcc
- { target: x86_64-pc-windows-gnu, variant: "", cpu: x86-64-v3, os: windows-latest, container: "", features: "nightly" }
- { target: x86_64-pc-windows-gnu, variant: "-legacy-cpu", cpu: "", os: windows-latest, container: "", features: "nightly" }
runs-on: ${{ matrix.os }}
container: ${{ matrix.container }}
env:
ARCHIVE: libnanuq_ffi-${{ needs.version.outputs.version }}-${{ matrix.target }}${{ matrix.variant }}.tar.gz
MACOSX_DEPLOYMENT_TARGET: "11.0"
TOOLCHAIN: nightly-2026-09-01 # pinned, so release builds are reproducible; the toolchain of the Polars tag in src/rust/Cargo.toml (py-2.1.0)
defaults:
run:
shell: bash
steps:
- uses: actions/checkout@v4
- name: Install Rust
run: |
# the GitHub runners have rustup, the manylinux containers don't
if command -v rustup > /dev/null; then
rustup toolchain install "$TOOLCHAIN" --profile minimal --target ${{ matrix.target }}
else
curl -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal \
--default-toolchain "$TOOLCHAIN" --target ${{ matrix.target }}
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
fi
- name: Build
run: |
if [ -n "${{ matrix.cpu }}" ]; then export RUSTFLAGS="-C target-cpu=${{ matrix.cpu }}"; fi
# 64 KiB pages, so the library also runs on aarch64 kernels that use them (as py-polars)
if [ "${{ matrix.target }}" = aarch64-unknown-linux-gnu ]; then
export JEMALLOC_SYS_WITH_LG_PAGE=16
# fat LTO in one codegen unit runs the 16 GB arm runner out of memory
# since 0.6 (cloud storage), so this target uses thin LTO
export CARGO_PROFILE_DIST_LTO=thin CARGO_PROFILE_DIST_CODEGEN_UNITS=16
fi
cargo "+$TOOLCHAIN" build --profile dist --manifest-path src/rust/Cargo.toml \
--target ${{ matrix.target }} --features "${{ matrix.features }}"
tar czf "$ARCHIVE" -C src/rust/target/${{ matrix.target }}/dist libnanuq_ffi.a
ls -l "$ARCHIVE"
- uses: actions/upload-artifact@v4
with:
name: ${{ env.ARCHIVE }}
path: ${{ env.ARCHIVE }}
retention-days: 7
# Each archive is linked and run on a plain runner of its platform, with the
# default Nim toolchain (MinGW on Windows).
smoke-test:
needs: [version, build]
strategy:
fail-fast: false
matrix:
include:
- { target: x86_64-unknown-linux-gnu, variant: "", os: ubuntu-24.04 }
- { target: x86_64-unknown-linux-gnu, variant: "-legacy-cpu", os: ubuntu-24.04 }
- { target: aarch64-unknown-linux-gnu, variant: "", os: ubuntu-24.04-arm }
- { target: aarch64-apple-darwin, variant: "", os: macos-15 }
- { target: x86_64-pc-windows-gnu, variant: "", os: windows-latest }
- { target: x86_64-pc-windows-gnu, variant: "-legacy-cpu", os: windows-latest }
runs-on: ${{ matrix.os }}
env:
ARCHIVE: libnanuq_ffi-${{ needs.version.outputs.version }}-${{ matrix.target }}${{ matrix.variant }}.tar.gz
defaults:
run:
shell: bash
steps:
- uses: actions/checkout@v4
- uses: actions/download-artifact@v4
with:
name: ${{ env.ARCHIVE }}
- uses: jiro4989/setup-nim-action@v2
with:
nim-version: "2.2.4"
repo-token: ${{ secrets.GITHUB_TOKEN }}
- run: mkdir prebuilt && tar xzf "$ARCHIVE" -C prebuilt
- run: nim r -d:nanuqLibDir=prebuilt --hints:off tests/test_basic.nim
- run: nim r -d:nanuqLibDir=prebuilt -d:nanuqNightly --hints:off tests/test_strings.nim
release:
if: github.ref_type == 'tag' || inputs.publish
needs: [version, smoke-test]
runs-on: ubuntu-24.04
permissions:
contents: write
pull-requests: write
env:
VERSION: ${{ needs.version.outputs.version }}
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
steps:
- uses: actions/checkout@v4
- uses: actions/download-artifact@v4
with:
path: dist
merge-multiple: true
- name: Sums
run: |
cd dist && sha256sum libnanuq_ffi-*.tar.gz > lib-sums.txt && cat lib-sums.txt
- name: Publish the release
run: |
# --target creates the tag when the run was started by hand
gh release create "lib-v$VERSION" dist/*.tar.gz dist/lib-sums.txt --target "$GITHUB_SHA" \
--title "Polars wrapper library $VERSION" \
--notes "Prebuilt libnanuq_ffi $VERSION. Nanuq downloads these at compile time; see the README."
- name: Commit the sums in a PR
run: |
head -3 src/nanuq/lib-sums.txt > header.txt
cat header.txt dist/lib-sums.txt > src/nanuq/lib-sums.txt
branch="lib-sums-$VERSION"
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git switch -c "$branch"
git add src/nanuq/lib-sums.txt
git commit -m "lib-sums.txt for lib-v$VERSION"
git push origin "$branch"
gh pr create --base main --head "$branch" \
--title "Prebuilt library sums for lib-v$VERSION" \
--body "Turns on downloads of the lib-v$VERSION archives. Generated by the Release lib workflow.".github/workflows/release-lib.yml
Cargo.toml: the crate and its version 60 lines
[package]
name = "nanuq_ffi"
version = "0.6.1"
edition = "2021"
description = "C ABI over Polars, consumed by the Nanuq Nim library"
license = "MIT"
publish = false
[lib]
crate-type = ["staticlib", "cdylib"]
[dependencies]
# Polars is pinned to the commit py-polars 2.1.0 is built from (git tag py-2.1.0),
# so Nanuq behaves like the Python Polars the book and explainers compare against.
# The crates.io releases lag py-polars by months (0.55.2 matches py 1.43). Bump this
# tag together with the py-polars version used by the book and the explainers.
polars = { git = "https://github.com/pola-rs/polars", tag = "py-2.1.0", default-features = false, features = ["lazy", "csv", "fmt", "dtype-i8", "dtype-i16", "dtype-u8", "dtype-u16", "semi_anti_join", "cross_join", "diagonal_concat", "random", "is_in", "is_between", "abs", "round_series", "rank", "strings", "regex", "string_pad", "string_reverse", "concat_str", "temporal", "dtype-date", "dtype-datetime", "dtype-duration", "dtype-time", "timezones", "offset_by", "range", "month_start", "month_end", "parquet", "ipc", "dtype-categorical", "dtype-array", "dtype-struct", "dtype-extension", "cum_agg", "diff", "pct_change", "rolling_window", "rolling_window_by", "ewma", "ewma_by", "log", "sign", "dtype-decimal", "trigonometry", "propagate_nans", "moment", "mode", "unique_counts", "is_unique", "is_first_distinct", "is_last_distinct", "top_k", "interpolate", "interpolate_by", "replace", "cutqcut", "repeat_by", "pivot", "partition_by", "dynamic_group_by", "asof_join", "product", "search_sorted", "rle", "approx_unique", "arg_where", "dot_product", "peaks", "cov", "to_dummies", "index_of", "list_eval", "list_gather", "list_count", "list_sets", "list_drop_nulls", "list_sample", "list_to_struct", "list_filter", "list_arithmetic", "array_count", "array_to_struct", "extract_groups", "extract_jsonpath", "find_many", "json", "sql", "meta", "row_hash", "cumulative_eval", "iejoin", "serde", "serde-lazy", "binary_encoding", "bitwise", "hist", "string_encoding", "string_to_integer", "dtype-u128", "dtype-i128", "cloud", "aws", "gcp", "azure", "http", "is_close", "merge_sorted", "business", "string_normalize", "reinterpret", "ipc_streaming", "cse"] }
# Only for polars_core::random::set_global_random_seed, which polars does not re-export.
polars-core = { git = "https://github.com/pola-rs/polars", tag = "py-2.1.0", default-features = false }
# Only for FunctionFlags (re-entrant and scalar Nim callbacks), which polars does not re-export.
polars-plan = { git = "https://github.com/pola-rs/polars", tag = "py-2.1.0", default-features = false, features = ["ffi_plugin"] }
# Only to run expression plugins (ffi_plugin), see nq_expr_plugin.
polars-lazy = { git = "https://github.com/pola-rs/polars", tag = "py-2.1.0", default-features = false, features = ["ffi_plugin"] }
either = "1"
tikv-jemallocator = { version = "0.6", optional = true }
serde_json = "1"
polars-utils = { git = "https://github.com/pola-rs/polars", tag = "py-2.1.0", default-features = false, features = ["serde"] }
calamine = { version = "0.37.0", features = ["dates"] }
rust_xlsxwriter = "0.102.0"
polars-arrow = { git = "https://github.com/pola-rs/polars", tag = "py-2.1.0", default-features = false }
chrono = { version = "0.4", default-features = false }
[features]
# Both are off by default, so local builds work on stable Rust everywhere. The
# release archives (release-lib.yml) are built with nightly Rust and both
# features, which closes most of the gap to Python Polars' speed: Polars' nightly
# feature turns on SIMD code paths and more (it is what py-polars ships with), and
# jemalloc is the allocator py-polars uses on Linux and macOS. jemalloc as Rust's
# global allocator is safe here because everything Rust allocates is freed by Rust
# (the nq_*_free functions); Nim never frees Rust memory itself.
nightly = ["polars/nightly"]
jemalloc = ["dep:tikv-jemallocator"]
[profile.release]
opt-level = 3
# Release archives (release-lib.yml): halves the archive (44 → 22 MB gzipped on
# x86_64 Linux) for a slower build (12 instead of 7 minutes), so local builds keep
# the plain release profile.
[profile.dist]
inherits = "release"
lto = "fat"
codegen-units = 1
# Copied from Polars' own workspace at py-2.1.0: a git dependency does not inherit
# them. Keep in sync when moving the tag.
[patch.crates-io]
color-backtrace = { git = "https://github.com/orlp/color-backtrace", rev = "20f5eea183563bb4cfac9a4d65901d4a1002cde2" }
tikv-jemalloc-sys = { git = "https://github.com/pola-rs/jemallocator", rev = "0d683dfb157097e2075d5e0eaf25f71f514a7552" }
hashbrown = { git = "https://github.com/pola-rs/hashbrown", rev = "d76a6f81abd8f388676aff15068236a8d21c7e1a" }src/rust/Cargo.toml