# packmem 0.3.4 documentation Every page of https://hamedmp.github.io/packmem/docs/ as Markdown. # Overview packmem keeps a collection of records (a Python list of dicts, a JavaScript array of objects) as packed columns. Your code still indexes it, loops over it, appends to it and updates it, and filters and aggregates run on the packed data without unpacking it. It is a Rust library with packages for Python, Node and WebAssembly. ```python rows = [json.loads(line) for line in open("events.jsonl")] # before rows = packmem.load_jsonl("events.jsonl") # after ``` On 336,776 flight records (nycflights13, 104 MB of JSON lines), the Python list of dicts takes 712 MB and the packmem table 20 MB, measured on an Apple M4 Pro ([benchmarks/results](https://github.com/HamedMP/packmem/tree/main/benchmarks/results)). Every number on this site comes from a results file in the repository. ## What you get - **A container, not a dataframe.** `len`, indexing, slicing, iteration, `append`, `update`, `sort`, `insert`, `pop`: the operations of a list. Rows come back as plain dicts or objects. - **Queries on the packed data.** `count`, `sum`, `group_count` / `groupCount` and `where` with equality, ranges, prefixes and substrings. - **JSON written from the columns.** API responses are produced without building an object per record. - **Sharing.** Python tables can be saved and memory-mapped (`save` and `open`) or shared with worker processes (`share`); Node tables can be shared with worker threads. - **Bytes you can send.** `to_bytes` / `toBytes` write the packed table; a browser running `packmem/wasm` opens them without parsing JSON. `packmem/http` and `packmem/react` wire that into servers and React components. ## When to use it - A server or worker holds a large collection of records in memory: an API's dataset, a cache, training annotations read by data-loader workers. Memory is the main gain. - Many processes or threads read the same records. - A browser receives a large table and shows a window of it: it can open packed bytes and build objects only for the rows on screen. ## When not to use it - **Small collections.** packmem breaks even with a Python list at about 300 records; the large ratios start around 100,000. - **Small HTTP responses.** After Brotli, packmem bytes are larger than JSON for tables of a few dozen rows, and for text-heavy data such as chat logs. Keep JSON for those; `packmem/http` sends JSON to any client that does not ask for bytes. - **Touching every field of every row.** Plain iteration rebuilds a dict or object per record and is slower than looping over the original list (about 5 times in Python). Lazy rows (`rows.lazy()`) and column queries close most of that gap. - **Analytics on columns.** For joins and heavy numeric work, use a dataframe or a database. packmem replaces the list of records, not polars or DuckDB. - **Sorting or inserting in the middle often.** Those rebuild the table, so each costs time proportional to its size. The [README](https://github.com/HamedMP/packmem#where-it-loses) lists every case where packmem loses, with the measurements. ## How it works Each field becomes a column. A sampling selector picks a lightweight encoding per chunk of 16,384 rows (frame of reference, dictionaries, run-length, FSST for strings, and others), and filters run on the encoded form. New rows go to an uncompressed tail that is packed when it fills. Lists of records inside a record, such as the turns of a conversation, are stored as their own columns. ## Next - [Install](/docs/install/) for your language. - [Quickstart](/docs/quickstart/): load, query and serve records. - [For coding agents](/docs/agents/): a brief and a skill file to give your agent. # Install The current release is 0.3.4. Install the same version on every side that exchanges packed bytes (see [Byte format](/docs/format/)). ## Python ```sh pip install packmem ``` Python 3.10 or later. Wheels for Linux (x86-64 and arm64, glibc and musl), macOS and Windows. `to_arrow`, `from_arrow`, `read_parquet` and `to_parquet` need `pyarrow` installed. ## Node, Bun and Deno ```sh npm install packmem ``` Node 20 or later. The package ships prebuilt native addons for Linux x86-64 and arm64 (glibc 2.17 or later, and musl), macOS on Apple silicon and Intel, and Windows x64. On other platforms, build from source with Rust (`npm run build` in the package). - Bun: `bun add packmem`. - Deno: `import { from } from "npm:packmem"`, run with `--allow-ffi` (or `-A`). The package is an ES module. CommonJS code can `require` it on Node 22.12 or later. ## Browsers and edge runtimes The same npm package includes `packmem/wasm`, the library compiled to WebAssembly, for runtimes that cannot load a native addon: browsers, Cloudflare Workers, Deno without FFI. See [Browsers and edge](/docs/browser/). | Import | What it is | | --- | --- | | `packmem` | The native addon for Node, Bun and Deno | | `packmem/wasm` | The same API on WebAssembly (no file paths or Node streams) | | `packmem/wasm/packmem.wasm` | The WebAssembly binary, for bundlers and Workers | | `packmem/http` | Send and fetch tables over HTTP; no Node imports | | `packmem/react` | `useTable` and `useRows` for React components | ## Rust ```sh cargo add packmem --no-default-features ``` The default `baselines` feature only exists for the repository's benchmarks and pulls in C dependencies. ## From a checkout ```sh # Python wheel cd python && pip install maturin && maturin build --release -o dist && pip install dist/*.whl # Node addon and WebAssembly build cd node && npm run build && npm run build:wasm ``` # Quickstart Each section loads records, queries them on the packed data, and writes JSON or bytes. Pick your language. ## Python ```sh pip install packmem ``` ```python import packmem rows = packmem.load_jsonl("events.jsonl") # or load_json, read_csv, Table(iterable_of_dicts) len(rows); rows[0]; rows[-5:] # still a sequence of dicts rows.append({"status": 200, "bytes": 512}) rows.update(3, status=500) rows.count(status=404) # runs on the packed data rows.sum("bytes", agent__contains="curl") rows.group_count("country", path__prefix="/api/") rows.where(status=404).rows(limit=10) # a page of matching dicts rows.to_json() # one JSON array, written from the columns rows.save("events.pkm") # reopen with packmem.open, memory-mapped ``` More in [Python](/docs/python/). ## Node ```sh npm install packmem ``` ```js import { loadJsonl } from "packmem"; const rows = loadJsonl("events.jsonl"); // or loadJson, loadCsv, parse(text), new Table(records) rows.length; rows.at(0); rows.slice(0, 10); // plain objects rows.push({ status: 200, bytes: 512 }); rows.update(3, { status: 500 }); rows.count({ status: 404 }); rows.sum("bytes", { agent: { contains: "curl" } }); rows.groupCount("country", { path: { prefix: "/api/" } }); rows.where({ status: 404 }).rows({ limit: 10 }); rows.jsonBuffer(); // JSON array bytes, written from the columns ``` More in [Node](/docs/node/). ## A server and a browser The server answers with packed bytes when the client asks for them, and JSON otherwise. The browser opens the bytes with WebAssembly and builds objects only for the rows it shows. ```js // server (Express); in a Next.js route handler use respond(request, rows) instead import express from "express"; import { loadJsonl } from "packmem"; import { send } from "packmem/http"; const flights = loadJsonl("flights.jsonl"); const app = express(); app.get("/api/flights", (req, res) => send(req, res, flights.where({ carrier: "UA" }))); app.listen(3000); ``` ```js // browser import { init } from "packmem/wasm"; import { fetchTable } from "packmem/http"; const pm = await init("/packmem.wasm"); // serve node_modules/packmem/wasm-dist/packmem_bg.wasm at this path const table = await fetchTable(pm, "/api/flights"); table.length; table.slice(0, 20); // objects for 20 rows only ``` In React, `useTable` does the loading and fetching, and `useRows` builds objects for a window of rows: ```tsx import { useRows, useTable } from "packmem/react" const { table } = useTable("/api/flights") // the .wasm file is served by Next.js, Vite or webpack const rows = useRows(table, { offset: 0, limit: 20 }) ``` Use the same packmem version in the server and the browser. More in [packmem/http](/docs/http/), [packmem/react](/docs/react/) and the [Next.js guide](/docs/nextjs/). ## Rust ```sh cargo add packmem --no-default-features ``` ```rust use packmem::{Hint, PackedInts, PackedStrs}; let latency = PackedInts::encode(&values, Hint::Balanced); latency.get(42); latency.sum(); latency.count_range(1_000, 5_000); let agents = PackedStrs::encode(&strings, Hint::Balanced); agents.count_where(|s| s.starts_with(b"curl")); ``` More in [Rust](/docs/rust/). # Benchmarks packmem's gain is memory. These measurements put it inside real code: two training scripts, two open-source apps and a demo, plus a direct comparison with Hugging Face `datasets`. Each one names the code it changed, what it compared against, and where packmem is slower or only level. Every number below comes from a results file in the repository, next to its raw output. | | Without packmem | With packmem | | | --- | ---: | ---: | --- | | VLM training data, 8 ranks x 4 workers, node memory | 47.81 GiB | 4.47 GiB | 10.7x less | | Lightdash, 100,000 rows held in the browser | 115.25 MB | 15.52 MB | 7.4x less | | paperless-ngx exporter, 100,000 documents, peak RSS | 1,191 MiB | 580 MiB | 2.05x less, 2.0x slower | | Log viewer, 1,000,000 rows until usable | 3,275 ms | 1,327 ms | about the same bytes over the network | | DataLoader, 4 forkserver workers, vs HF `datasets` (Arrow) | 1,810 MB | 1,144 MB | 37% less; HF faster in batches | The machine for all of these is a shared Linux server (AMD Ryzen 9 7950X3D, 16 cores, 124 GiB RAM) that also runs CI. Memory figures held steady across runs; times are noisier and are marked where the load was high. ## VLM fine-tuning: annotation lists in every rank Training scripts for LLaVA-style vision-language models read the whole annotation file with `json.load` in every rank, and each DataLoader worker inherits that list. Here the training scripts of Qwen3-VL (qwen-vl-finetune) and MiniCPM-V read the LLaVA-1.5 665k annotations (1 GB of JSON) through a patch that loads them with `packmem.load_json` instead. The patch for Qwen3-VL is +29/-12 lines in `data_processor.py`. 8 torchrun ranks with 4 fork workers each. Memory for the whole job (PSS summed over every process), median of 3 runs, packmem 0.3.3: | Model | Samples per rank | List (`json.load`) | packmem | | | --- | ---: | ---: | ---: | --- | | Qwen3-VL | 20,000 | 47.81 GiB | 4.47 GiB | 10.7x less | | Qwen3-VL | 83,163 (full shard, 1 run) | 54.88 GiB | 6.12 GiB | 9.0x less | | MiniCPM-V | 20,000 | 37.82 GiB | 7.25 GiB | 5.2x less | One rank reading a full shuffled epoch through 4 workers, median of 3, packmem 0.3.2: | | List | packmem | | | --- | ---: | ---: | --- | | 4 fork workers | 10.24 GiB | 1.05 GiB | 9.8x less | | 4 spawn workers | 15.32 GiB | 2.68 GiB | 5.7x less | | Main process only, 20,000 samples | 4.02 GiB | 1.04 GiB | 3.9x less | - The batches are bit-identical between the two arms, for all 8 ranks, in every run. - The figures are host RAM for the annotations and the processes around them: no images, no model, no GPU. - In 0.3.2 the Qwen3-VL peak at 20,000 samples was 5.77 GiB, above 0.1.0's 4.86 GiB: its loader parses on up to 4 threads, and glibc kept each thread's freed buffers. 0.3.3 returns them, so the 8 simultaneous loads peak lower. The full-shard and MiniCPM-V peaks come from iteration and barely moved (6.21 to 6.12 and 7.31 to 7.25 GiB). - The 0.3.3 rows were measured on a build of commit 4bf9c3e, which has the same code as the 0.3.3 release; the published wheel gives the same one-process loader peak (441 against 442 MiB). The list arms are the 0.3.2 runs, since list memory does not depend on packmem. Details and raw files: [RESULT-0.3.2.md](https://github.com/HamedMP/packmem/blob/main/benchmarks/ml_swaps/linux-node/RESULT-0.3.2.md). ## Against Hugging Face `datasets` (memory-mapped Arrow) packmem replaces lists of Python records. It is not a replacement for Arrow, and a memory-mapped Arrow table is already far smaller than a list. This compares the two directly: one PyTorch DataLoader of 4 workers serving 20,000 random LLaVA-1.5 records (batch size 8, no images or model), with the data from `datasets` 5.2.0 / pyarrow 26.0.1 and from packmem 0.2.0 saved to a file and opened with `packmem.open()`. Median of 3 runs. | Forkserver workers | Python list | HF `datasets` | packmem | packmem vs HF | | --- | ---: | ---: | ---: | --- | | Memory for the whole job (PSS) | 15,961 MB | 1,810 MB | 1,144 MB | 37% less | | Anonymous memory above an empty DataLoader | +15,099 MB | +243 MB | +5 MB | | | Sent to each worker | 687 MB pickle | 2.2 KB | 134 B | | | First batch | 63.5 s | 1.80 s | 1.02 s | indicative (shared host) | | | HF `datasets` | packmem | | | --- | ---: | ---: | --- | | File on disk (Arrow cache / `.pkm`) | 785 MB | 309 MB | 2.54x smaller | | The same data as zstd Parquet | 164 MB | | Parquet is smaller at rest | | Memory each worker adds by importing the library, over torch | +55 MB | +0.2 MB | anonymous memory | | Memory for the whole job with fork workers | 994 MB | 549 MB | | | Random row to a Python dict, `x[i]` (packmem 0.1.1) | 22.2 us | 6.05 us | 3.7x faster | | Batched reads, 64 rows at a time, per row (packmem 0.1.1) | 2.25 us | 4.96 us | HF 2.2x faster | | One pass in batches of 1,000 (packmem 0.1.1) | 2.0 s | 2.8 s | HF faster | | First build from the JSON | 22.4 s (conversion) | a `load_json` plus 0.2 s `save()` | | - Most of HF's gap here is per-process: every forkserver worker imports `datasets` and pyarrow again (about 55 MB each), and touches 407 MB of the Arrow file against 176 MB of the `.pkm` file for the same rows. - HF's batched and columnar paths are faster than packmem's. packmem is faster on the per-row path, which is what a map-style DataLoader dataset uses. - For storage at rest, zstd Parquet is the smaller format. packmem's file is for opening and querying in place. - packmem took the JSON as it is and round-tripped every record exactly. `datasets` 5.2.0 silently rewrote 158,383 mixed-type `id` values, even with a string type declared for `id`, so the HF arm reads a copy with the ids written as strings first. - Every arm returned the same batches (one digest over all 24 runs), and the full table's per-record digest is equal for HF and packmem. Details and raw files: [RESULT_0.2.0.md](https://github.com/HamedMP/packmem/blob/main/benchmarks/ml_swaps/hf-datasets/pypi-0.2.0/RESULT_0.2.0.md) (memory, file size, import cost) and [RESULT.md](https://github.com/HamedMP/packmem/blob/main/benchmarks/ml_swaps/hf-datasets/RESULT.md) (access speed). ## Lightdash: a large query in the browser [Lightdash](https://github.com/lightdash/lightdash) 3.261.1's client fetches query results as 500-row JSON pages. A 25-line patch to its v2 results endpoint sends the same rows as packmem bytes when the client asks for them, and JSON otherwise. The browser opens them with `fetchTable` from `packmem/wasm`. The fair comparison is JSON at Lightdash's 2,500-row page limit, gzipped by an nginx proxy in front. 100,000 rows, 17 fields each, median of 5 rounds in headless Chromium: | | Until usable | Over the network | Held in the browser | | --- | ---: | ---: | ---: | | JSON, 2,500-row pages, gzipped | 13.73 s | 4.09 MB | 115.25 MB | | packmem, 2,500-row pages | 13.46 s | 3.27 MB | 18.69 MB | | packmem, every row in one response | 11.85 s | 3.25 MB | 15.52 MB | | JSON, 500-row pages (Lightdash's client today) | 20.57 s | 4.93 MB | 115.18 MB | - **Memory** in the browser is 6.2x to 7.4x lower. - **Bytes** are about a fifth fewer than gzipped JSON (1.25x less). - **Time** barely changes at the same page size: about 12 s of the 13.7 s is Lightdash's server reading and formatting rows, which packmem does not touch. One response with every row is 1.16x faster, but it needs Lightdash's page-size limit raised. - Every arm returned the same 100,000 rows (same SHA-256 hash in all 25 runs). Details, the patch and raw files: [RESULT.md](https://github.com/HamedMP/packmem/blob/main/benchmarks/apps/lightdash/RESULT.md). ## paperless-ngx: the document exporter paperless-ngx's `document_exporter` builds its whole manifest as a Python list before writing it. A patched exporter keeps the manifest in a packmem table. 100,000 seeded documents, `--data-only`, peak RSS of the exporter process, median of 5 runs, packmem 0.3.2: | | Peak RSS | Wall time | | --- | ---: | ---: | | List | 1,191 MiB | 196 s | | packmem, `default=` | 660 MiB | 277 s | | packmem, `default=`, `hint="compact"` | 580 MiB | 400 s | - **Memory** is 1.80x to 2.05x lower, and every export is byte-identical to the list version's. - **It is slower:** 1.4x with the default encodings, 2.0x with `hint="compact"`. Times are indicative, since CI raised the load in two of the five rounds. - **At 20,000 documents packmem does worse:** the process peaks 15 to 39 MiB above the list. Importing packmem and building the table cost more than the smaller manifest saves. Details and raw files: [RESULT-0.3.2.md](https://github.com/HamedMP/packmem/blob/main/benchmarks/apps/paperless-ngx/RESULT-0.3.2.md). ## Log viewer: a million rows in a Next.js page [demos/log-viewer](/docs/examples/#log-viewer) serves 1,000,000 generated log records with `packmem/http` and scrolls through them with `useTable` and `useRows`. A switch on the page loads the same rows as JSON with `res.json()`. Served by `next start` over localhost, packmem 0.3.2 from npm, three runs in headless Chromium: | | packmem bytes | JSON | | --- | ---: | ---: | | Over the network | 31.7 MB (gzip inside the payload) | 32.7 MB (gzip by Next.js) | | Not compressed | 49.1 MB | 222.1 MB | | Until usable | 1,327 to 1,471 ms | 3,275 to 3,287 ms | | Held in the page | a 49.2 MB packed table | 1,000,000 objects | - **Over the network** the two are about level, because Next.js gzips the JSON. The gain is time until usable. - **Uncompressed** the bytes are 4.5x smaller than the JSON. - These are one-off runs at a 1-minute load of 3.6 to 4.3, not a benchmark. The heap readings from these headless runs were not consistent, so the page's JS heap is not compared here. Details: [demos/log-viewer/README.md](https://github.com/HamedMP/packmem/blob/main/demos/log-viewer/README.md). ## Smaller measurements - 336,776 flight records: a 712 MB Python list against a 20 MB table, on an Apple M4 Pro ([benchmarks/results](https://github.com/HamedMP/packmem/tree/main/benchmarks/results)). - Bytes over the network against JSON, gzip and other formats: [benchmarks/wire-size/RESULT.md](https://github.com/HamedMP/packmem/blob/main/benchmarks/wire-size/RESULT.md). # Python `packmem.Table` is a mutable sequence of dicts stored as packed columns. It replaces a list of records; most code that reads and writes the list keeps working. ```sh pip install packmem ``` ## Load | Before | After | | --- | --- | | `[json.loads(l) for l in f]` | `packmem.load_jsonl(path_or_lines)` | | `json.load(f)` for a list of records | `packmem.load_json(path_or_file)` (streamed) | | `list(csv.DictReader(f))` | `packmem.read_csv(path)` (`infer=True` for numbers) | | `[dict(zip(names, r)) for r in cursor]` | `packmem.from_cursor(cursor)` (any DB-API cursor) | | `list(queryset.values())` (Django) | `packmem.from_queryset(queryset)` | | `pq.read_table(path).to_pylist()` | `packmem.read_parquet(path, columns=[...])` (needs pyarrow) | | `arrow_table.to_pylist()` | `packmem.from_arrow(table)` (needs pyarrow) | | any iterable of dicts | `packmem.Table(records)` or `packmem.from_records(records)` | `load_jsonl` and `load_json` take `fields=[...]` to keep only those top-level keys. Every loader takes `hint=` (below). `Table`, `from_records`, `from_cursor`, `from_queryset`, `from_arrow` and `read_parquet` take `default=`, called for values JSON has no form for (dates, decimals, UUIDs) as with `json.dumps(default=...)`; `default=str` stores them as text. ## Use it as a list ```python len(rows); rows[0]; rows[-5:]; rows[3] = {...} rows.append({...}); rows.extend(more); rows.insert(0, {...}) rows.pop(); del rows[10:20]; rows.clear(); rows.reverse() rows.sort(key="bytes") # a column name, or a function of a record; reverse=True rows.update(3, status=500) # change fields of one record in place rows.set_column("source", "a.jsonl") # one value for every record, or one value per record rows.take([3, 1, 2]); rows.copy(); rows.shuffle() for r in rows: ... # dicts ``` A returned row is a fresh dict: changing it does not change the table. Use `rows[i] = ...` or `rows.update(i, ...)`. `sort`, `del`, `pop`, `reverse` and `insert` anywhere but the end rebuild the table. ## Query the packed data ```python rows.count(status=404) rows.sum("bytes", agent__contains="curl") rows.group_count("country", path__prefix="/api/") v = rows.where(dep_delay__gt=60, carrier="UA") # a View: matching row numbers len(v); v.sum("distance"); v.group_count("dest"); v.column("dest") v.rows(limit=10, offset=0) # a page of dicts v.indices() # the row numbers ``` Filters: `col=value`, `col__prefix`, `col__contains`, `col__gt`, `col__gte`, `col__lt`, `col__lte`, `col__between=(lo, hi)`. Every condition must hold. ## Loops that read a few fields ```python for r in rows.lazy(): total += r["bytes"] # decodes only the fields you read r["seen"] = True # writes to the table ``` A lazy row is a mapping, not a dict; `r.to_dict()` gives a dict. ## JSON without dicts ```python rows.to_json() # bytes: one JSON array rows.where(carrier="UA").to_json(limit=50, offset=100) for chunk in rows.iter_json(batch=4096): ... # for streaming responses ``` In FastAPI: ```python from fastapi import FastAPI from fastapi.responses import StreamingResponse import packmem app = FastAPI() rows = packmem.load_jsonl("flights.jsonl") @app.get("/flights") def flights(carrier: str, limit: int = 50, offset: int = 0): return StreamingResponse(rows.where(carrier=carrier).iter_json(limit=limit, offset=offset), media_type="application/json") ``` ## Lists of records inside a record A field that holds a list of records, such as the turns of a conversation, is stored as its own columns. Compute per-record figures without a Python loop; the names follow pandas: ```python turns = rows.col("conversations") turns.list.len() # turns per record turns.list.field("value").str.len().list.sum() # characters per record turns.list.field("value").str.split().list.len().list.sum() # words per record rows.col("image").notna() # which records have the key ``` Each returns one value per record as a list, with `.to_numpy()` and `.to_arrow()` when those libraries are installed. ## Save, open and share ```python rows.save("events.pkm") rows = packmem.open("events.pkm") # memory-mapped, read in place, read-only rows = packmem.load_json("annotations.json").share() # worker processes read one shared copy ``` - `open` takes milliseconds whatever the size; pages are read as they are touched and shared by every process that opens the file. `copy()` gives a private, writable table. - `share(dir=None)` writes the table to a file (in `/dev/shm` on Linux) and makes it read-only, so pickling it to a `DataLoader` or `multiprocessing` worker sends only the file's location. `unshare()` makes it writable again. `packmem.cleanup_stale()` removes files left by a crashed process. - `to_bytes()` and `Table.from_bytes(data)` give the same packed form as bytes, for sending or storing. See [Byte format](/docs/format/). ## Arrow and Parquet With pyarrow installed: ```python rows = packmem.read_parquet("events.parquet", columns=["status", "bytes"]) rows = packmem.from_arrow(arrow_table) # a table, a record batch or an iterable of batches rows.to_arrow() # a pyarrow.Table, for polars, pandas or DuckDB rows.to_parquet("events.parquet") ``` These copy the data. Arrow cannot say a key is absent, so absent keys become nulls, and a column holding more than one type raises `TypeError` in `to_arrow()`. ## Hints `hint=` chooses what the encodings favour: `"balanced"` (default), `"memory"`, `"speed"`, or `"compact"`. `"compact"` also compresses long text (documents, conversation turns) with Zstandard in small blocks that share a dictionary trained on the column: smaller for prose, slower to load and to read. A table saved with `"compact"` cannot be opened by the WebAssembly build. ## Inspect ```python rows.columns # column names rows.nbytes # approximate bytes held rows.describe() # (column, encodings, bytes) per column ``` ## Threads Filters, group counts and sums run on several threads once a table has 16 chunks (about 260,000 rows), and `load_jsonl`, `load_json` and `read_csv` on a file of 8 MB or more load on up to four threads. Answers are the same as with one thread. `PACKMEM_THREADS=1` turns this off; `PACKMEM_THREADS=n` sets the number of threads (default: the cores, at most 8). ## Semantics - Values round-trip exactly: ints (including beyond 64 bits), floats (including NaN), bools, None, strings, nested lists and dicts. Tuples come back as lists. - Key order in returned dicts is the order columns were first seen. - `sum` adds ints, floats and bools and skips everything else. - Nested values are written by `to_json()` in a canonical form: the same values, not necessarily the same text as the source. - A table pickles as its packed columns; a shared or opened table pickles as its file's location. The full list is in [python/README.md](https://github.com/HamedMP/packmem/blob/main/python/README.md). # Node `Table` is an array-like collection of records stored as packed columns, for Node 20+, Bun and Deno. Rows come back as plain objects. ```sh npm install packmem ``` ## Load | Before | After | | --- | --- | | `text.split("\n").map(JSON.parse)` | `loadJsonl(path)` or `parse(textOrBytes)` | | `JSON.parse(readFileSync(path))` for an array of records | `loadJson(path)` (streamed) or `parse(bytes)` | | an array or iterable of objects | `new Table(records)` or `from(records)` | | a CSV or TSV file | `loadCsv(path)`, `loadTsv(path)` or `parseCsv(textOrBytes)` | | a Postgres query | `fromPg`, `fromPgCopy`, `fromPgResult`, `fromQuery` (below) | Parsing happens in Rust, straight into columns. Skip `JSON.parse` to get the memory benefit: once V8 has built the objects, the peak memory is spent. Every loader takes `{ hint }`: `"balanced"` (default), `"memory"`, `"speed"`, `"compact"` (zstd on long text, smaller files) or `"archive"` (level 19, long values sharing larger blocks, nested values kept as JSON text: smallest, slower to read a single row). The WebAssembly build has no zstd: it can use both hints, but cannot read a table whose long text Node or Python compressed with them. `{ keepKeyOrder: true }` reads each row back with its keys in the order they were written, instead of the table's column order, so `JSON.stringify(row)` gives back the line that was loaded. It costs a few bits a row while rows share a handful of key orders. Such a table is saved as byte format 6, which Python reads from 0.3.4 and Node and the WebAssembly build from 0.4.0. JavaScript itself always lists integer-like keys (`"1"`, `"42"`) first, whatever the table stored. CSV options: `delimiter`, `header` (default true), `names`, `types` per column (`"infer"`, `"text"`, `"int"`, `"float"`, `"bool"`, `"json"`) and `emptyIsNull`. ## Use it as an array ```js rows.length; rows.at(0); rows.at(-1); rows.slice(10, 20); for (const r of rows) {} // plain objects, built in batches rows.map(fn); rows.filter(fn); rows.reduce(fn, init); rows.forEach(fn); rows.toArray(); rows.push({ ... }); rows.extend(iterable); rows.set(3, { ... }); // replace a record rows.update(3, { status: 500, note: undefined }); // change fields; undefined removes a key rows.splice(10, 2); rows.insert(0, { ... }); rows.pop(); rows.shift(); rows.unshift({ ... }); rows.reverse(); rows.clear(); rows.sort({ key: "dest" }); rows.sort((a, b) => a.delay - b.delay); rows.take([3, 1, 2]); rows.copy(); ``` `rows[i]` does not work; use `rows.at(i)`. A `Table` is iterable and has `length` but is not an `Array`. `sort`, `splice`, `insert`, `pop`, `shift`, `unshift` and `reverse` each rebuild the table once. ## Query the packed data ```js rows.count({ status: 404 }); rows.sum("bytes", { ua: { contains: "curl" } }); rows.groupCount("country", { path: { prefix: "/api/" } }); rows.column("dest", { carrier: "UA" }); const v = rows.where({ carrier: "UA", dep_delay: { gt: 60 } }); // a View v.length; v.ids; v.sum("distance"); v.groupCount("dest"); v.rows({ offset: 0, limit: 50 }); // a page of objects v.rowsJsonBuffer({ offset: 0, limit: 50 }); // the same page as JSON bytes, no objects ``` Filters: `{ col: value }` for equality, or `{ col: { eq, gt, gte, lt, lte, between: [lo, hi], prefix, contains } }`. Every condition must hold. ## Loops that read a few fields ```js for (const r of rows.lazy()) total += r.distance; // reads only the fields the loop touches ``` A lazy row has the column names as properties, `get(name)`, `toObject()` and `index`. Assigning a field writes to the table. ## JSON responses without objects ```js rows.where({ carrier: "UA" }).jsonStream().pipe(res); // Express, Fastify, node:http return new Response(rows.where({ carrier: "UA" }).jsonWebStream(), { headers: { "content-type": "application/json" }, // Next.js route handlers, Hono, Bun, Deno }); rows.jsonBuffer(); // one Buffer for (const chunk of rows.jsonChunks({ batch: 4096 })) {} // Buffers, one batch at a time ``` For flat records the bytes are the same as `JSON.stringify`. To send a table as packed bytes instead, see [packmem/http](/docs/http/). ## Postgres ```js import pg from "pg"; import Cursor from "pg-cursor"; import { fromPg, fromPgCopy, fromPgResult, fromQuery } from "packmem"; import { to as copyTo } from "pg-copy-streams"; const flights = await fromPg(client, "select * from flights where year = $1", [2013], { Cursor }); const all = await fromPgCopy(client, "select * from flights", { copyTo }); // COPY as CSV; no parameters const small = fromPgResult(await client.query({ text: "select * from airports", rowMode: "array" })); const recent = await fromQuery(client, drizzleOrKyselyQuery); // .toSQL(), .compile() or { sql, params } ``` `pg-cursor` and `pg-copy-streams` are optional peer dependencies. `fromPgCopy` is the fastest: no row objects are built in the driver or in JavaScript. ## Worker threads ```js // main thread const rows = loadJsonl("logs.jsonl"); new Worker("./worker.js", { workerData: rows.share() }); // worker.js import { workerData } from "node:worker_threads"; import { Table } from "packmem"; const rows = Table.fromShared(workerData); ``` `share()` makes the table read-only and returns a small handle; workers read the same memory, with no copy. `unshare()` makes it writable again; `copy()` gives a private table. This covers the threads of one process. ## Bytes ```js const bytes = rows.toBytes(); // Uint8Array const back = Table.fromBytes(bytes); // also ArrayBuffer or any ArrayBufferView ``` The same form Python's `to_bytes` writes. See [Byte format](/docs/format/) and [packmem/http](/docs/http/). ## Inspect ```js rows.names; // column names rows.nbytes; // bytes held by the packed columns rows.describe(); // [{ name, encoding, bytes }] rows.compact(); // pack rows still held uncompressed (done automatically) ``` ## Semantics - Values go in and come out as through `JSON.stringify` and `JSON.parse`: `-0` becomes `0`, `undefined` values are dropped, a `Date` becomes a string. - A returned row is a fresh object; mutating it does not change the table. Use `set` or `update`. - `sum` adds numbers and booleans and skips everything else. - The package is an ES module; CommonJS can `require` it on Node 22.12 or later. The full list is in [node/README.md](https://github.com/HamedMP/packmem/blob/main/node/README.md). # Browsers and edge `packmem/wasm` is packmem compiled to WebAssembly from the same Rust source as the native addon. It has the same `Table` and `View` API, without file paths and Node streams, for runtimes that cannot load a native addon. | Where | How it is tested | | --- | --- | | Browsers | Headless Chromium in CI reads tables from Node and Python servers (`node/test/browser.test.js`) | | Cloudflare Workers | The `demos/workers` app under `wrangler dev` | | Deno and Bun | Each release runs the package's smoke test, native and WebAssembly, under both | | Vercel Edge and other runtimes | Not tested yet. They load WebAssembly the same way; report what you find | ## Instantiate ```js import { init, initSync } from "packmem/wasm"; const pm = await init("/packmem.wasm"); // a URL, a Response, bytes or a WebAssembly.Module const pm2 = initSync(compiledModule); // synchronous, from a WebAssembly.Module or bytes ``` `init` and `initSync` return the API: `pm.Table`, `pm.View`, `pm.parse`, `pm.parseCsv`, `pm.from`, and the Postgres helpers. Instantiate once and reuse it; later calls return the same API. The binary is in the package at `packmem/wasm/packmem.wasm` (the file `wasm-dist/packmem_bg.wasm`). In a browser app, serve that file and pass its URL to `init`. See the [Next.js guide](/docs/nextjs/) for one way to do it. ## Cloudflare Workers Workers import `.wasm` files as compiled modules: ```js import wasm from "packmem/wasm/packmem.wasm"; import { initSync } from "packmem/wasm"; const pm = initSync(wasm); const DATA_URL = "https://example.com/events.jsonl"; // JSON lines or a JSON array export default { async fetch(request) { const events = pm.parse(await (await fetch(DATA_URL)).arrayBuffer()); return new Response(events.where({ status: 404 }).jsonWebStream(), { headers: { "content-type": "application/json" }, }); }, }; ``` A Worker has 128 MB of memory. `demos/workers` holds a synthetic web log built in batches; its README has the measurements. ## Open a table sent by a server ```js const pm = await init("/packmem.wasm"); const rows = pm.Table.fromBytes(new Uint8Array(await (await fetch("/api/rows.pkm")).arrayBuffer())); rows.length; rows.slice(0, 50); // objects only for the rows on screen ``` `fetchTable` from [packmem/http](/docs/http/) does the asking and falls back to JSON. The browser's packmem must be the same version as the server's, or newer: see [Byte format](/docs/format/). ## Limits - No `share()`: WebAssembly runs on one thread. - Tables written with Python's `hint="compact"` cannot be read (the WebAssembly build has no Zstandard). - WebAssembly memory grows and never shrinks while the module is alive. # packmem/http `packmem/http` sends tables over HTTP: packed bytes to clients that ask for them, a streamed JSON array to every other client. It has no Node imports, so the same module runs in Node, Next.js route handlers, Cloudflare Workers and browsers. ```js import { respond, send, fetchTable, wantsPackmem, PACKMEM_TYPE } from "packmem/http"; ``` ## How it negotiates A client asks for bytes with `Accept: application/vnd.packmem`. The server sends bytes only when that type has a quality greater than zero and at least as high as `application/json`; otherwise it sends JSON. Every response carries `Vary: Accept`, so caches keep the two forms apart. Clients that know nothing about packmem (curl, a browser address bar, another service) get JSON, unchanged. From 0.3.2, a client that also accepts `application/vnd.packmem; enc=gzip` gets bytes over 1 KB gzipped inside the payload, with that media type. `fetchTable` asks for it and unzips with `DecompressionStream`. This is done in the payload because hosts compress only the types they know: Next.js gzips JSON but not packmem bytes, and drops a route's own `Content-Encoding`. Pass `{ gzip: false }` to `respond` or `send` when a proxy or CDN in front compresses `application/vnd.packmem` already. Clients on 0.3.0 and 0.3.1 do not ask for gzip, so they keep getting plain bytes. ## Server: web Request and Response For Next.js route handlers, Cloudflare Workers, Hono, Bun, Deno, anything with `Request` and `Response`: ```js export function GET(request) { return respond(request, flights.where({ carrier: "UA" })); } ``` `respond(request, rows, init?, options?)` takes a `Table` or a `View`; `init` sets the status and extra headers, `options` is `{ gzip }`. A `View` sends only its rows. ## Server: Node's response object For Express, plain `node:http`, and Fastify's raw reply: ```js app.get("/api/flights", (req, res) => send(req, res, flights.where({ carrier: req.query.carrier }))); ``` `send(req, res, rows, status = 200, options?)` writes the bytes, gzipped or not, or the JSON array in batches. It returns a Promise that resolves when the response has been written (from 0.3.2; before, it returned nothing). ## Client ```js import { init } from "packmem/wasm"; // or: import * as pm from "packmem" in Node import { fetchTable } from "packmem/http"; const pm = await init("/packmem.wasm"); const table = await fetchTable(pm, "/api/flights?carrier=UA"); ``` `fetchTable(pm, input, init?)` sends `Accept: application/vnd.packmem; enc=gzip, application/vnd.packmem;q=0.95, application/json;q=0.9` unless you set an `accept` header, then reads bytes with `pm.Table.fromBytes` or JSON with `pm.parse`, by the response's `content-type`. A response that is not OK throws an `Error` naming the status and URL. Either way you get a `Table`. If the server sends bytes from a newer packmem than `pm` can read, `fetchTable` asks again with `Accept: application/json` and returns the table from the JSON (from 0.3.1). In React, [`useTable`](/docs/react/) wraps `fetchTable` and loads `packmem/wasm` for you. Elsewhere it works as an SWR or TanStack Query fetcher: ```js const { data: table } = useSWR("/api/flights?carrier=UA", (url) => fetchTable(pm, url)); ``` With TanStack Query, set `structuralSharing: false`: a `Table` is not a plain object and must not be deep-compared or copied. ## Versions Bytes carry a format version, and a reader refuses bytes from a newer format. The client's packmem must be the same version as the server's, or newer. Pin the same version on both sides (one `package.json` for a Next.js app does this), and deploy the client no later than the server when you upgrade. See [Byte format](/docs/format/). If the client falls behind anyway, `fetchTable` from 0.3.1 on falls back to JSON: the page keeps working, with a second request and without the gain from bytes. `fetchTable` in 0.3.0 throws the "written by a newer packmem" error instead. ## When to send bytes - Bytes pay off for large tables that the client keeps and scrolls, filters or aggregates: the browser opens them without parsing and builds objects only for the rows it shows. - For a few dozen rows, compressed JSON is smaller. Keep those endpoints on JSON (do not send the `Accept` header, or return JSON from the server). - Text-heavy rows (chat messages, documents) compress about as well as JSON, so the gain there is in parsing and memory, not in download size. Where the bytes go, by table size and dataset, against JSON with and without Brotli: [benchmarks/wire-size/RESULT.md](https://github.com/HamedMP/packmem/blob/main/benchmarks/wire-size/RESULT.md). ## Reference | Export | Signature | | --- | --- | | `PACKMEM_TYPE` | `"application/vnd.packmem"` | | `wantsPackmem` | `(accept: string \| Request \| { headers } \| null \| undefined) => boolean` | | `respond` | `(request: Request, rows: Table \| View, init?: ResponseInit, options?: { gzip?: boolean }) => Response` | | `send` | `(req, res, rows: Table \| View, status?: number, options?: { gzip?: boolean }) => Promise` | | `fetchTable` | `(pm, input: RequestInfo \| URL, init?: RequestInit) => Promise` | # packmem/react Two hooks for React components that show a packmem table: `useTable` fetches it into the browser, and `useRows` builds objects only for the rows on screen, so a list over a million rows holds a few dozen objects at a time. ```js import { useTable, useRows } from "packmem/react"; ``` `useTable` is new in 0.3.2; `useRows` has been there since 0.3.0. React 18 or later is an optional peer dependency. ## useTable ```ts useTable(url: string | URL | null | undefined, options?: { wasm?: WebAssembly.Module | BufferSource | Response | URL | string packmem?: { Table; parse } init?: RequestInit }): { table: Table | null; error: Error | null; loading: boolean; ms: number } ``` Fetches `url` with [`fetchTable`](/docs/http/) (packmem bytes when the server sends them, JSON otherwise) and opens it with `packmem/wasm`, which it instantiates once per page. - When `url` changes it fetches again, keeping the previous table until the new one is ready, and drops a response for a URL that is no longer current. `null` fetches nothing. - `ms` is the time from the request to the table being ready, for the latest table. - The `.wasm` file is found through `new URL(file, import.meta.url)`, which Next.js, Vite and webpack serve without setup. Elsewhere, pass its URL: `useTable(url, { wasm: "/packmem.wasm" })`. - `packmem` passes an API you already have instead (from `init` in `packmem/wasm`); `init` is passed to `fetch` (headers, credentials). - On the server it returns the loading state without fetching, which is what a fetch-in-an-effect hook renders there anyway. ## useRows ```ts useRows(rows: Table | View | null | undefined, range?: { offset?: number; limit?: number }): Row[] ``` Returns rows `offset` to `offset + limit` (defaults 0 and 50) as plain objects. It returns the same array on every render until the range changes or the table changes through packmem's own methods (`push`, `set`, `update`, ...), so it can feed `React.memo` children and effect dependencies. A window past the end stops at the last row; `null` gives an empty array. ## Together ```tsx "use client" import { useState } from "react" import { useRows, useTable } from "packmem/react" const ROW = 28 const SHOWN = 20 export function Logs({ level }: { level: string }) { const { table, error, loading, ms } = useTable(`/api/logs?level=${level}`) const [offset, setOffset] = useState(0) const rows = useRows(table, { offset, limit: SHOWN }) if (error) return

{error.message}

if (!table) return

Loading…

return ( <>

{table.length} lines, ready in {Math.round(ms)} ms{loading && " (updating)"}

setOffset(Math.floor(e.currentTarget.scrollTop / ROW))}>
    {rows.map((r, i) => (
  • {String(r.message)}
  • ))}
) } ``` Pair `useRows` with any virtualizer (TanStack Virtual, react-window) by passing it the visible range. ## Why they work inside Next.js Next.js loads packmem outside its server bundle, because of the native addon. There, `import "react"` finds a second copy of React, and hooks called from it fail. So `useRows` calls no React hooks at all (it keeps its last result per table in a small cache), and `useTable` calls them only in the browser, where packmem is bundled with the app's own React. The [Next.js guide](/docs/nextjs/) puts the server and this page together, and [demos/log-viewer](/docs/examples/#log-viewer) is a full app built on both hooks. # Rust The `packmem` crate is the core the Python, Node and WebAssembly packages are built on: the encodings, the sampling selector, the mutable record table and the operators on packed data. ```sh cargo add packmem --no-default-features ``` | Feature | What it adds | | --- | --- | | `baselines` (default) | LZ4 and Zstandard, only for the repository's comparison benchmark. Turn it off. | | `ztext` | `Hint::Compact`: long text compressed with Zstandard in small blocks. Native builds only (C code). | ## Packed columns ```rust use packmem::{Hint, PackedInts, PackedStrs}; let latency = PackedInts::encode(&values, Hint::Balanced); // values: &[i64] latency.get(42); latency.sum(); latency.count_range(1_000, 5_000); latency.describe(); // the encoding chosen let agents = PackedStrs::encode(&strings, Hint::Balanced); // strings: &[impl AsRef] agents.count_where(|s| s.starts_with(b"curl")); agents.count_eq("curl/8.0"); agents.get_string(7); ``` `Hint` is `Memory`, `Balanced`, `Speed` or `Compact` (as `Memory` without the `ztext` feature). ## The record table `DynTable` is the table behind `packmem.Table` in Python and `Table` in Node: records of any shape, columns created as keys appear, values as `Cell`s. ```rust use packmem::{Cell, DynTable, Hint, Pred}; let mut t = DynTable::new(Hint::Balanced); t.append([("carrier", Cell::Str("UA".into())), ("delay", Cell::Int(12))]); t.append([("carrier", Cell::Str("B6".into())), ("delay", Cell::Int(-3))]); let carrier = t.col_index("carrier").unwrap(); let delay = t.col_index("delay").unwrap(); let ua = t.select(carrier, &Pred::Eq(Cell::Str("UA".into()))); // row ids let total = t.sum(delay, Some(&ua)); // Num::Int or Num::Float let by_carrier = t.group_count(carrier, None); // Vec<(Cell, usize)> t.get(0, delay); // a Cell let bytes = t.to_bytes(); // the byte form let back = DynTable::from_bytes(&bytes)?; ``` `Pred` is `Eq(Cell)`, `Range { lo, hi, lo_incl, hi_incl }`, `Prefix(String)` or `Contains(String)`. `Cell` is `Missing`, `Null`, `Bool`, `Int`, `Float`, `Str` or `Json` (nested values as JSON text). The crate's API is lower level than the Python and Node packages and may change between minor versions. The source of truth is [the crate on docs.rs](https://docs.rs/packmem) and the [source](https://github.com/HamedMP/packmem/tree/main/src). # Next.js A Next.js app holds a table in its server process, answers queries from it in route handlers, and sends a client page the packed bytes to open in the browser. This is how `demos/nextjs` and `demos/log-viewer` in the repository are built, on Next.js 16 with React 19. ```sh npm install packmem ``` ## 1. Keep packmem out of the server bundle packmem loads a native addon, which a bundler cannot include. List it in `serverExternalPackages`: ```ts // next.config.ts import type { NextConfig } from "next" const nextConfig: NextConfig = { serverExternalPackages: ["packmem"], } export default nextConfig ``` Without it, the build fails with an error about the `.node` file not being placeable in a chunk. ## 2. Load the data once per process ```ts // lib/flights.ts import path from "node:path" import { loadJsonl, type Table } from "packmem" const g = globalThis as { __flights?: Table } export function flights(): Table { g.__flights ??= loadJsonl(path.join(process.cwd(), "data/flights.jsonl")) return g.__flights } ``` Keeping it on `globalThis` keeps one table across hot reloads in development. Load from Postgres with `fromPg` or `fromPgCopy` instead (see [Node](/docs/node/#postgres)). ## 3. Route handlers JSON for small answers, and the whole selection as bytes or JSON through [`respond`](/docs/http/): ```ts // app/api/flights/route.ts import { flights } from "@/lib/flights" export const dynamic = "force-dynamic" export function GET(request: Request) { const carrier = new URL(request.url).searchParams.get("carrier") ?? "UA" return Response.json(flights().where({ carrier }).rows({ limit: 50 })) } ``` ```ts // app/api/flights/export/route.ts import { respond } from "packmem/http" import { flights } from "@/lib/flights" export const dynamic = "force-dynamic" export function GET(request: Request) { const carrier = new URL(request.url).searchParams.get("carrier") ?? "UA" return respond(request, flights().where({ carrier })) } ``` `respond` gzips the bytes inside the payload for clients that ask for it (from 0.3.2), because Next.js compresses JSON responses but not `application/vnd.packmem`. ## 4. A client component `useTable` fetches the export and opens it with `packmem/wasm`; `useRows` builds objects for the rows on screen. Next.js serves the `.wasm` file for you. ```tsx // app/browse/browser.tsx "use client" import { useState } from "react" import { useRows, useTable } from "packmem/react" export function Browser({ carrier }: { carrier: string }) { const { table, error } = useTable(`/api/flights/export?carrier=${carrier}`) const [offset, setOffset] = useState(0) const rows = useRows(table, { offset, limit: 20 }) if (error) return

{error.message}

if (!table) return

Loading…

return ( <>

{table.length} flights

) } ``` Render it from a server component page: ``. See [packmem/react](/docs/react/) for a virtualized list. ### Without useTable (0.3.0 and 0.3.1) `useTable` is new in 0.3.2. With an earlier version, or to control loading yourself, serve the `.wasm` file and call `init` and `fetchTable`. Copy the file into `public/` when installing: ```json { "scripts": { "postinstall": "cp node_modules/packmem/wasm-dist/packmem_bg.wasm public/packmem.wasm" } } ``` or serve it from a route handler, as `demos/nextjs` does: ```ts // app/packmem.wasm/route.ts import { readFile } from "node:fs/promises" import path from "node:path" export async function GET() { const wasm = await readFile(path.join(process.cwd(), "node_modules/packmem/wasm-dist/packmem_bg.wasm")) return new Response(new Uint8Array(wasm), { headers: { "content-type": "application/wasm", "cache-control": "public, max-age=3600" }, }) } ``` then, in the client component: ```tsx import { useEffect, useState } from "react" import { fetchTable } from "packmem/http" import { init, type PackmemWasm } from "packmem/wasm" import type { Table } from "packmem" let pm: Promise | undefined function useFlights(carrier: string) { const [table, setTable] = useState
(null) useEffect(() => { let live = true pm ??= init("/packmem.wasm") pm.then((api) => fetchTable(api, `/api/flights/export?carrier=${carrier}`)).then((t) => live && setTable(t)) return () => { live = false } }, [carrier]) return table } ``` ## Versions The server and the browser read and write packed bytes with the packmem installed in the app, so one `package.json` keeps them on the same version. If the browser code is cached or served separately (a CDN, another app), deploy it no later than the server: a reader refuses bytes from a newer format. From 0.3.1, `fetchTable` (and so `useTable`) then falls back to JSON instead of failing. See [Byte format](/docs/format/). ## Deploying The route handlers need the Node.js runtime (the default), not the Edge runtime, because they use the native addon. On Vercel the Linux x86-64 addon in the npm package is the one that loads; this setup has not been tested on Vercel yet. Vercel Functions limit a response that is not streamed to 4.5 MB: JSON and gzipped bytes are streamed, plain bytes are sent as one buffer. Memory is the main gain on the server: the demo's Next.js server holding the flights data settles at a fraction of the memory of an array of objects (figures in [demos/README.md](https://github.com/HamedMP/packmem/blob/main/demos/README.md)). # Byte format `to_bytes()` in Python, `toBytes()` in Node and WebAssembly, `save()` and `share()` in Python and `DynTable::to_bytes` in Rust all write the same form: the packed columns as they are in memory, so reading them back copies or maps them and re-encodes nothing. Any binding reads what any other wrote, subject to the version rule below. ## Versions The bytes start with `PKMT` and a format version. | packmem | Writes | Reads | | --- | --- | --- | | 0.2.0 | `PKM2` (format 2) | format 2 | | 0.3.0 | format 4 | formats 2, 3 and 4 | | 0.3.1 and 0.3.2 | format 5 | formats 2 to 5 | Format 3 was only written by development builds between 0.2.0 and 0.3.0. Format 5 stores no per-row offsets for columns of records that are never absent, which 0.3.0 did. A reader refuses bytes from a newer format with an error that says so: ```text written by a newer packmem (format 5, this build reads up to 4): upgrade packmem to read it ``` Anything else that is not a table fails with "not packed table data, or written by packmem 0.1". ## The rule for servers and clients **A reader must be the same version as the writer, or newer.** Pin the same packmem version on both sides. When the two are deployed separately, upgrade the reader first: the browser bundle, the worker that opens saved files, the service that receives bytes. So far every release reads the formats of the releases before it, so files saved with `save()` keep opening after an upgrade. Over HTTP, [`packmem/http`](/docs/http/) negotiates per request: clients that do not ask for bytes get JSON, and from 0.3.1 `fetchTable` asks again for JSON when the server's bytes are from a newer packmem than the client's. `fetchTable` in 0.3.0 does not, and throws instead. ## What is inside - A header: `PKMT`, the format version, the table's hint, the row count and the column count. - For each column, its name and its chunks of 16,384 rows. Each chunk holds its encoded values (packed integers, dictionaries, FSST-compressed strings, sub-columns for lists of records), null and missing bitmaps, and any patched cells. - Since format 4, single integers in the headers (counts, lengths, chunk metadata) are variable-length (LEB128, signed ones zigzagged). Vectors and floats are at full width and padded to their element size from the start of the bytes, so a memory-mapped file is read in place without copying. The exact layout is defined by the code in [src/wire.rs](https://github.com/HamedMP/packmem/blob/main/src/wire.rs) and [src/dynamic.rs](https://github.com/HamedMP/packmem/blob/main/src/dynamic.rs). It is not a stable interchange format like Arrow or Parquet; for exchange with other tools, use `to_arrow()` and `to_parquet()` in Python, or JSON. ## Limits - Tables written with Python's `hint="compact"` hold Zstandard-compressed text, which the WebAssembly build cannot read. - After compression (gzip, Brotli), the bytes of a table of a few dozen rows, or of text-heavy rows, are about as large as JSON or larger. Send JSON for those. # Sample projects Each demo is in the [repository](https://github.com/HamedMP/packmem/tree/main/demos) and runs from a checkout. The server demos serve the same 336,776 flight records (`data/flights.jsonl`, nycflights13) and switch between a plain array or list (`MODE=baseline`) and a packmem table (`MODE=packmem`, the default), so you can compare the two on your machine. Their measurements are in [demos/README.md](https://github.com/HamedMP/packmem/blob/main/demos/README.md), with the raw results in `demos/bench/results/`. Build the Node addon once before the Node demos (`cd node && npm run build`), and the Python wheel before the FastAPI demo (see [Install](/docs/install/#from-a-checkout)). The flights file comes from `benchmarks/fetch_data.py`, which needs the `nycflights13` Python package: ```sh pip install nycflights13 mkdir -p data && (cd data && python ../benchmarks/fetch_data.py) ``` ## Express `demos/express`: an Express 5 server with filtered pages, group-bys, a summary and a full export. The export answers `Accept: application/vnd.packmem` with packed bytes through `packmem/http`, and JSON otherwise. ```sh cd demos/express && npm install && npm start # port 3001; npm run start:baseline to compare ``` Shows: server memory at rest and under load against an array of objects, and JSON written from the columns. ## Next.js `demos/nextjs`: the same API as route handlers, a dashboard at `/`, and `/browse`, a client page that fetches the export as packed bytes, opens it with `packmem/wasm` and scrolls it with `useRows`. ```sh cd demos/nextjs && npm install && npm run build && npm start # port 3002 ``` Shows: `serverExternalPackages`, `respond` in a route handler, serving the `.wasm` file, and a virtualized list that holds objects only for the rows on screen. The [Next.js guide](/docs/nextjs/) walks through it. ## Log viewer `demos/log-viewer`: a Next.js app that sends 1,000,000 generated log records to the browser and scrolls through them, with `respond` on the server and `useTable` and `useRows` in the page. A switch loads the same rows as JSON with `res.json()`, so the two can be compared on one page: time until usable, the browser's JS heap, and bytes over the network. The records come from a seeded generator, so nothing is downloaded. ```sh cd demos/log-viewer && npm install && npm run build && npm start # packmem from npm; http://localhost:3000, in Chrome ``` Shows: the whole browser path with the two hooks, and where packed bytes pay off and where they do not. Its [README](https://github.com/HamedMP/packmem/blob/main/demos/log-viewer/README.md) has one run's figures and notes on deploying to Vercel. ## FastAPI `demos/fastapi`: the same routes in Python, including the byte export. ```sh cd demos/fastapi uv venv .venv && uv pip install --python .venv/bin/python -r requirements.txt ../../python/dist/packmem-*.whl MODE=packmem .venv/bin/uvicorn app:app --port 3003 ``` Shows: a Python server's memory with a list of dicts against a packmem table, and `iter_json` streaming. All three servers can load from Postgres instead of the file: set `FLIGHTS_PG_URL` (setup in the demos README). ## Cloudflare Workers `demos/workers`: a synthetic web log held in a Worker through `packmem/wasm`, with `/stats` (a filtered group count and sum) and `/export` (matching rows streamed as JSON). `MODE=plain` holds the same rows as objects. ```sh cd demos/workers && npm install npx wrangler dev # http://localhost:8787/stats?country=SE&path=/api node bench.mjs # both modes at 200,000 and 1,000,000 rows ``` Shows: `initSync` with an imported `.wasm` module, and packmem inside a 128 MB isolate. ## Fine-tuning data loader `demos/finetune-loader`: a PyTorch `DataLoader` over LLaVA instruction data with the annotations held four ways: a list of dicts, Hugging Face `datasets`, packmem `share()` and packmem `open()` of a saved table. It measures the parent and every worker. ```sh pip install torch datasets psutil huggingface_hub packmem python run.py --mode list python run.py --mode packmem-open ``` Shows: one changed line in a training loader, and how much memory each worker holds under fork and spawn. # Agent history archive `packmem archive` keeps your Claude Code and Codex transcripts, compressed, after the agents delete them. Claude Code removes transcripts after 30 days by default. The archive keeps a private copy on your machine that you can restore byte for byte, and answers history-wide questions without decompressing any session. ```sh npx packmem archive --dry-run # what would be archived and the expected size; writes nothing npx packmem archive # archive every session unchanged for a day ``` It needs Node 20 or newer. On Node 22.15 and newer it compresses with zstd; on older Node it uses Brotli, which is slower and gives a somewhat larger archive. ## What it reads and writes - **Reads** `~/.claude/projects` (or each `CLAUDE_CONFIG_DIR` entry's `projects`, or `$XDG_CONFIG_HOME/claude/projects`), including subagent transcripts, and `~/.codex/sessions` and `~/.codex/archived_sessions` (or `$CODEX_HOME`). Codex's own `.jsonl.zst` files are already compressed; they are counted and left as they are. - **Writes** only to `~/.packmem/agent-history` (or `--dir`, or `PACKMEM_ARCHIVE_DIR`). Files there are readable only by you (`0600`, directories `0700`). - **Never** deletes, moves or changes an agent's own files. Space is freed when the agent's own cleanup removes the originals; until then the archive is extra. - **Stays local.** Nothing is sent anywhere. ## Safety rules - A session counts as archived only after it has been read back from the archive and matched the sha256 of the original. A session that does not match is reported and not recorded. - Every later read checks the sha256 again, so a damaged archive is reported, not served. - Sessions changed in the last day are left for a later run (`--older-than` changes the window), and a session that changes while it is being read is skipped. A session that grows later is archived again. - It writes only into a folder that is new, empty, or already an archive, and `delete --all` removes only the files the archive wrote there, so pointing `--dir` at the wrong folder cannot clear it. - `restore` never overwrites a file, even one created while it runs. - One run writes at a time (a lock file); an interrupted run leaves nothing that looks valid. - When a session changed and is archived again, text only its earlier version used is removed in the same run. - The archive is a full copy of your transcripts, including anything sensitive in them, such as a token a command printed. It is kept after the agents delete their copies. Delete it when you no longer want it. ## Commands ```sh npx packmem archive status # sessions, original size, archive size npx packmem archive list # archived sessions, newest first npx packmem archive verify # re-check every session against its original's sha256 npx packmem archive restore claude-code/ # write it back where it was, if nothing is there now npx packmem archive restore codex/ --to x.jsonl npx packmem archive stats --by tool # counts across all history, read in place npx packmem archive delete claude-code/ # delete one archived copy and the text only it used npx packmem archive delete --all --yes # delete the whole archive ``` `restore` never overwrites a file. `delete` never touches the agent's own files. Add `--json` to any command for machine-readable output; it carries sizes, ids and counts, never transcript text. ## How it saves space Agent transcripts repeat themselves. Claude Code stores each tool result twice, Codex logs each item twice, and the same file contents, instructions and skill lists come back session after session. The archive stores every string of 256 bytes or more once, across all sessions, in compressed frames grouped by the JSON key it came from, and keeps each session as a small compressed skeleton that points at those strings. A line that is not JSON, or that would not re-serialise to the same bytes, is kept as written. Next to it, a packmem table of one row per record (type, time, tool, model, token counts, size; no text) lets `stats` answer questions about all of your history without decompressing a session. ## Measurements Two measurements. Raw results are in [node/bench/results](https://github.com/HamedMP/packmem/tree/main/node/bench/results) (`agent-history-*.json`). **Synthetic history, reproducible.** 600 sessions (358.3 MB of JSONL) from `node bench/agent-history-data.mjs data 10`, which imitates the repetition measured in real transcripts. Linux, AMD Ryzen 9 7950X3D, Node 24.22, on a shared server whose load average ran from 30 to 9 during the runs, so the times are indicative. | | size on disk | compared with JSONL | | --- | --- | --- | | JSONL as the agents write it | 358.3 MB | 1x | | zstd -19, each file on its own | 69.4 MB | 5.2x smaller | | `packmem archive` | 38.0 MB | 9.4x smaller | | zstd -19, all files as one stream with a 128 MB window | 28.2 MB | 12.7x smaller | The single stream is the smallest, but it cannot take a new session without recompressing everything, and reading one session means decompressing up to it. The archive takes new sessions in later runs and restores any one on its own. Archiving took 103 s and peaked at 444 MB of memory (measured alone); verifying all 600 sessions took 50 s. **One person's own history.** About 450 Claude Code and Codex sessions, about 1 GB of JSONL, on an Apple M4 Pro with macOS and Node 24.18. It ran on that machine because the transcripts are private and were not copied anywhere, so others cannot reproduce it; the file holds rounded sizes only. | | size on disk | compared with JSONL | | --- | --- | --- | | JSONL | about 1.0 GB | 1x | | zstd -19, each file on its own | about 240 MB | 4.0x smaller | | `packmem archive` | about 210 MB | 4.7x smaller | Archiving took 112 s with a peak of about 1.2 GB of memory, which on macOS includes memory the allocator freed but kept; verifying every session took 45 s. Sessions Codex had already compressed were left as they are. How much smaller your archive comes out depends on how much your sessions repeat each other: this history is mostly Codex, whose sessions share less than the synthetic ones do. A later run with the current code, on the same machine and a later state of the same history (about 430 sessions, about 0.9 GB: some sessions had become too recent, others had been removed by the agents' own cleanup), archived it into about 190 MB (4.9x smaller) in 133 s, with a peak of about 0.96 GB. The zstd baseline was not re-run on that set. ## Limits - Only Claude Code and Codex for now. - Sessions in Codex's own `.jsonl.zst` files are not archived. - Archiving is not light on memory: 444 MB for 358 MB of synthetic history on Linux, and about 1 GB for about 0.9 GB of real history on macOS, where the allocator keeps memory it has freed. - Reading a full session needs a restore. A later format will store sessions as packmem tables that can be read in place. # For coding agents Give your coding agent (Claude Code, Cursor, Codex, Copilot and others) what it needs to use packmem correctly: the docs as Markdown, and a skill file with the API and the rules. ## The docs as Markdown - [/llms.txt](/llms.txt): an index of these pages, in the [llms.txt](https://llmstxt.org) format. - [/llms-full.txt](/llms-full.txt): every page as one Markdown file. Paste the URL into your agent's chat, or add it as a docs source. Both are generated from the same files as these pages, so they always match the site. ## The skill file Copy the file below into your project. Claude Code reads it from `.claude/skills/packmem/SKILL.md`; for other agents, add it to `AGENTS.md` or the agent's rules file, or keep it in the repository and point the agent at it. The same file is in the repository at [skills/packmem/SKILL.md](https://github.com/HamedMP/packmem/blob/main/skills/packmem/SKILL.md). ```sh mkdir -p .claude/skills/packmem curl -o .claude/skills/packmem/SKILL.md https://raw.githubusercontent.com/HamedMP/packmem/main/skills/packmem/SKILL.md ``` ````markdown --- name: packmem description: Use packmem to hold large collections of records (Python lists of dicts, JavaScript arrays of objects) in packed columns, query them without unpacking, and send them to browsers as packed bytes. Use when a server, worker or data loader holds many records in memory, when replacing json.load / JSON.parse of a big file, or when a React or Next.js app shows a large table. --- # packmem packmem keeps records as packed columns that code can still index, loop over, update and query, in a fraction of the memory. Python (`pip install packmem`), Node, Bun and Deno (`npm install packmem`), WebAssembly for browsers and Cloudflare Workers (`packmem/wasm`, in the npm package), and Rust (`cargo add packmem --no-default-features`). Docs: https://hamedmp.github.io/packmem/docs/ (all of it as Markdown: https://hamedmp.github.io/packmem/llms-full.txt). ## When to use it - A process holds thousands to millions of records in memory: an API's dataset, a cache, training annotations read by data-loader workers. The gain is memory; queries on the packed data are also fast. - A browser receives a large table and shows a window of it. ## When not to - Fewer than about 300 records: no gain. - HTTP responses of a few dozen rows, or text-heavy rows: after gzip or Brotli, JSON is as small or smaller. Keep JSON there. - Code that touches every field of every row in a hot loop, or that needs joins and numeric analytics: keep the list, or use a dataframe or database. ## Python ```python import packmem rows = packmem.load_jsonl("events.jsonl") # json.loads per line -> load_jsonl rows = packmem.load_json("records.json") # json.load of a list of records -> load_json (streamed) rows = packmem.read_csv("data.csv", infer=True) rows = packmem.from_cursor(cursor) # any DB-API cursor rows = packmem.Table(list_of_dicts) rows[0]; rows[-5:]; len(rows); rows.append({...}); rows.update(3, status=500); rows.sort(key="ts") rows.count(status=404); rows.sum("bytes", ua__contains="curl"); rows.group_count("country") rows.where(delay__gt=60, carrier="UA").rows(limit=50, offset=0) for r in rows.lazy(): total += r["bytes"] # fast loops that read a few fields rows.to_json(); rows.where(carrier="UA").iter_json(limit=50) # JSON bytes without dicts rows.save("t.pkm"); rows = packmem.open("t.pkm") # memory-mapped, read-only rows = packmem.load_json("annotations.json").share() # DataLoader workers share one copy ``` Filters: `col=value`, `col__gt`, `col__gte`, `col__lt`, `col__lte`, `col__between=(lo, hi)`, `col__prefix`, `col__contains`. ## Node ```js import { loadJsonl, loadJson, parse, Table } from "packmem"; const rows = loadJsonl("events.jsonl"); // not readFileSync + JSON.parse: that spends the memory first rows.at(0); rows.slice(0, 10); rows.length; rows.push({ ... }); rows.update(3, { status: 500 }); rows.count({ status: 404 }); rows.sum("bytes", { ua: { contains: "curl" } }); rows.groupCount("country"); rows.where({ carrier: "UA", dep_delay: { gt: 60 } }).rows({ offset: 0, limit: 50 }); rows.where({ carrier: "UA" }).jsonStream().pipe(res); // Express return new Response(rows.where({ carrier: "UA" }).jsonWebStream()); // fetch-style servers ``` `rows[i]` does not work: use `rows.at(i)`. A `Table` is not an `Array`. ## Server to browser ```js // server import { respond, send } from "packmem/http"; export const GET = (request) => respond(request, table.where({ carrier: "UA" })); // Next.js, Workers app.get("/api/rows", (req, res) => send(req, res, table)); // Express // React (0.3.2+): fetches bytes or JSON and opens them with packmem/wasm, loaded once per page import { useTable, useRows } from "packmem/react"; const { table, error, loading, ms } = useTable("/api/rows"); const visible = useRows(table, { offset, limit: 20 }); // objects only for the rows on screen // without React import { init } from "packmem/wasm"; import { fetchTable } from "packmem/http"; const pm = await init("/packmem.wasm"); // serve node_modules/packmem/wasm-dist/packmem_bg.wasm here const t = await fetchTable(pm, "/api/rows"); ``` `respond` and `send` gzip bytes over 1 KB inside the payload for clients that ask (`fetchTable` and `useTable` do); when a proxy in front compresses already, turn it off with `respond(req, rows, {}, { gzip: false })` or `send(req, res, rows, 200, { gzip: false })`. `send` returns a Promise. ## Rules - Next.js: add `serverExternalPackages: ["packmem"]` to `next.config.ts`. Route handlers that use packmem need the Node.js runtime, not Edge. - Use the same packmem version on the server and the client, or a newer one on the client. A reader refuses bytes written by a newer packmem ("written by a newer packmem (format N, this build reads up to M)"); from 0.3.1, `fetchTable` then asks again for JSON, so the page keeps working without the gain from bytes. - `fetchTable` asks for bytes and accepts JSON; servers using `respond` or `send` send JSON to clients that do not ask for bytes. Keep small endpoints on JSON. - With TanStack Query, set `structuralSharing: false` for queries that return a packmem `Table`. - Tables saved with Python's `hint="compact"` cannot be read by `packmem/wasm`. - `sort`, `insert`, and deletes in the middle rebuild the table: batch them. - A returned row is a copy: change the table with `rows[i] = ...` / `update` (Python) or `set` / `update` (Node). ```` ## A prompt to start with ```text Replace the list of dicts loaded in with a packmem table (https://hamedmp.github.io/packmem/llms-full.txt). Keep the behaviour the same: the endpoints must return identical JSON. Use the loader that matches how the data is read today, use the table's queries instead of Python or JavaScript loops where it filters or counts, and measure the process's memory before and after. ``` ## Working on packmem itself The repository has an [AGENTS.md](https://github.com/HamedMP/packmem/blob/main/AGENTS.md) with its layout, build and test commands, and the rules for changing the byte format and publishing numbers.