Skip to the page

Guides · Models & ML

Datasets & ML training

Build a fine-tuning dataset from your product’s rows. An access rule holds each workspace’s consent to training.

In the schema
ext::files::File

What you’ll build#

You will build a fine-tuning dataset from rows your product already holds and record every training run across four guarantees.

Consent is a rule
No service key reads a row from a workspace that has not opted in to training.
The export is small
One full read, then only each night’s changes, written as Parquet shards.
Each run names the inputs
Each run links to the shards it read, and every shard record stores a SHA-256 digest of its bytes.
An opt-out is honored
Before each run, the same rule filters older shard IDs so newly opted-out workspaces are dropped.

Napalm holds the data, the consent rule, the Parquet files and the run provenance. Training runs on your own GPU infrastructure.

Before you start#

A service key
Your pipeline’s credential, from napalm keys create. Set the branch’s service globals to { "default::role": "service" } in the console or with POST /projects/{id}/endpoint, so the schema can tell a key from a person.
File storage
Shards and checkpoints are files. A file is a record with bytes in object storage.
Passthrough for keys
The export reads GET /changes, which a project set to --passthrough none refuses. Leave passthrough at all or keys.
Your own GPUs
Napalm does not train models. An action starts your trainer and passes signed links to the shards.

Each workspace records whether its data may train a model, and the access policy on PreferencePair enforces that answer directly. No query, export script or GET /changes page lets a service key read rows from an opted-out workspace, while workspace members continue reading their pairs through user sessions.

Schema-enforced training consent into Parquet shards

Access policies on PreferencePair gate both pairsAfter batch reads and GET /changes tails, streaming only consented workspaces into Zstandard-compressed DatasetShard files.

dbschema/default.gel
using extension auth;using extension files;using extension napalm;using future simple_scoping; module default {  global caller := global ext::auth::ClientTokenIdentity;  global role: str;   scalar type RunStatus extending enum<Queued, Training, Completed, Failed>;   type Workspace {    required name: str;    required owner: ext::auth::Identity;    required allows_training: bool {      default := false;    };     access policy owner_has_full_access      allow all      using (.owner ?= global caller);    access policy service_reads_consenting      allow select      using (global role ?= 'service' and .allows_training);  }   type PreferencePair {    required workspace: Workspace {      readonly := true;      on target delete delete source;    };    required prompt: str;    required chosen: str;    required rejected: str;     notify pair_recorded after insert, update, delete;     access policy owner_has_full_access      allow all      using (.workspace.owner ?= global caller);    access policy service_reads_consenting      allow select      using (global role ?= 'service' and .workspace.allows_training);  }   type DatasetShard extending ext::files::File {    required version: str;    required number: int64;    required row_count: int64;    required sha256: str;    reach: str;     constraint exclusive on ((.version, .number));     constraint expression on (std::contains([ext::files::Format.Parquet], .file_format)) {      errmessage := 'a Parquet file is required';    };     access policy service_has_full_access      allow all      using (global role ?= 'service');  }   type TrainingRun {    required base_model: str;    required version: str;    required status: RunStatus {      default := RunStatus.Queued;    };    multi shards: DatasetShard;    metrics: json;     access policy service_has_full_access      allow all      using (global role ?= 'service');  }   type Checkpoint extending ext::files::File {    required run: TrainingRun {      on target delete delete source;    };    required step: int64;    validation_loss: float64;     access policy service_has_full_access      allow all      using (global role ?= 'service');  }}

A filter in an export script can be forgotten, whereas a schema access policy governs every read by every pipeline.

Export the existing rows#

The initial export pages through every PreferencePair the service key may see in id order and writes one Parquet shard per page. The query needs no consent filter because the schema policy supplies it automatically.

dbschema/queries/pairsAfter.edgeql
select PreferencePair { id, prompt, chosen, rejected }filter .id > <uuid>$afterorder by .idlimit <int64>$limit
pipelines/export_pairs.py
# pipelines/export_pairs.pyimport hashlibimport io import httpximport pyarrow as paimport pyarrow.parquet as pq FIELDS = ("prompt", "chosen", "rejected")COLUMNS = pa.schema([(name, pa.string()) for name in ("id", "op", *FIELDS)])SHARD_ROWS = 50_000  # small enough that a shard goes up in one request  def write_shard(napalm: httpx.Client, version: str, number: int, rows: list[dict], reach: str | None) -> None:    """One Parquet shard and its record."""    buffer = io.BytesIO()    pq.write_table(pa.Table.from_pylist(rows, schema=COLUMNS), buffer, compression="zstd")    data = buffer.getvalue()    registered = napalm.post("/query/registerShard", json={"variables": {        "name": f"{version}-{number:05}.parquet",        "size": len(data),        "version": version,        "number": number,        "row_count": len(rows),        "sha256": hashlib.sha256(data).hexdigest(),        "reach": reach,    }}).raise_for_status().json()    plan = registered["data"][0]["file_upload"]    httpx.request(plan["method"], plan["url"], headers=plan["headers"], content=data).raise_for_status()    napalm.post("/uploads/complete", json={"token": plan["token"]}).raise_for_status()  def export_all(napalm: httpx.Client, version: str) -> int:    """Every pair the key may read, a page at a time by id. Returns the next shard's number."""    after, number = "00000000-0000-0000-0000-000000000000", 0    while True:        asked = {"variables": {"after": after, "limit": SHARD_ROWS}}        page = napalm.post("/query/pairsAfter", json=asked).raise_for_status().json()["data"]        if not page:            return number        write_shard(napalm, version, number, [{**row, "op": "insert"} for row in page], reach=None)        after, number = page[-1]["id"], number + 1

Each shard here holds at most 50,000 rows so it uploads in a single request. Larger files receive a multipart upload plan instead. File uploads documents the calls.

Then export the changes#

After the initial snapshot, the change log streams only commits since the previous run in commit order. Each changed row is re-evaluated under the service key’s access rules when served, so a workspace that has opted out is excluded immediately.

pipelines/export_pairs.py
# pipelines/export_pairs.py, continueddef export_changes(    napalm: httpx.Client, version: str, number: int, after: str | None = None, since: str | None = None) -> tuple[int, str | None]:    """What committed after `after`, or since a time on the first run. Returns the next number and where to resume."""    rows: list[dict] = []    reach = after    params = {"types": "PreferencePair", "limit": 1000, **({"after": after} if after else {"since": since})}    while True:        page = napalm.get("/changes", params=params).raise_for_status().json()        for item in page["items"]:            if "gap" in item:                raise RuntimeError("The change log has a gap: start a new version with export_all.")            for row in item["rows"]:                kept = {} if row["op"] == "delete" else {name: row["fields"][name] for name in FIELDS}                rows.append({"id": row["id"], "op": row["op"], **kept})        reach = page.get("next") or reach        if rows and (len(rows) >= SHARD_ROWS or page["is_caught_up"]):            write_shard(napalm, version, number, rows, reach)            rows, number = [], number + 1        if page["is_caught_up"]:            return number, reach        params = {"types": "PreferencePair", "limit": 1000, "after": reach}
An edit
Arrives as the row again with op update. The shard keeps the row, and the loader lets the newest row for an id win.
A delete
Arrives as the id alone. The shard keeps the id as a row with op delete, which removes the id at load.
A gap
The log could not replay a stretch. Start a new version with a full read, then follow the log from there.
pipelines/nightly.py
# pipelines/nightly.pyimport osfrom datetime import datetime, timedelta, timezone import httpx from export_pairs import export_all, export_changes headers = {"Authorization": f"Bearer {os.environ['NAPALM_KEY']}"}with httpx.Client(base_url="https://notes.napalmdata.com", headers=headers, timeout=60) as napalm:    # The first night: note the time, read everything, then follow the log from just before that time.    started = (datetime.now(timezone.utc) - timedelta(minutes=5)).isoformat()    number = export_all(napalm, "v1")    number, resume = export_changes(napalm, "v1", number, since=started)    # Every night after: number, resume = export_changes(napalm, "v1", number, after=resume)

The first tail starts a few minutes before the full read began, so no write during the full read is missed. Rows read twice are merged at load. Run the pipeline on your own schedule, or have a webhook on pair_recorded start the pipeline when new pairs arrive.

Keep each shard as a file#

Each DatasetShard pairs a Parquet file in object storage with a typed database row recording its dataset version, sequence number, row count, sha256 digest and, for incremental shards, its GET /changes bookmark (reach).

Verified DatasetShard record

Each DatasetShard extends ext::files::File, recording version, sequence number, row count, sha256 digest and reach bookmark while verifying Parquet magic bytes.

Immutable Parquet object storage

Direct-to-bucket uploads write Zstandard-compressed Parquet shards once into object storage and retain bytes across active backup windows.

dbschema/queries/registerShard.edgeql
select (insert DatasetShard {  file_name := <str>$name,  file_size := <int64>$size,  version := <str>$version,  number := <int64>$number,  row_count := <int64>$row_count,  sha256 := <str>$sha256,  reach := <optional str>$reach,}) { id, file_upload }
Checked from the bytes
Napalm reads the stored file’s first bytes when the upload completes. A file that is not Parquet fails the constraint and never becomes Ready.
Never rewritten
A Ready file’s bytes do not change. A run that names a shard names the exact training bytes, and the hash proves the match later.
Kept with backups
A deleted shard’s bytes stay until your oldest restorable backup expires. See how files are cleaned up.

Start a run and keep a record#

Queueing a training run commits the TrainingRun record and its launch job atomically, dispatches to your GPU trainer through an action handler and links every returned checkpoint back to the exact input shards.

Atomic run and job commit

startTrainingRun inserts the TrainingRun record and its ext::napalm::Job inside one SQL statement so neither commits without the other.

Idempotent trainer launch

The launchTraining handler starts your external GPU run keyed by call.job.id and marks the run Training via call.db().

Registered checkpoint crystal

Completed checkpoints register with step, validation_loss and linked TrainingRun provenance tracing back to every input DatasetShard.

  1. Insert the run and queue the start in one statement

    The run and the starting job commit together. If the statement fails, there is no run and nothing is queued.

    dbschema/queries/startTrainingRun.edgeql
    with  run := (insert TrainingRun {    base_model := <str>$base_model,    version := <str>$version,    shards := (      select DatasetShard      filter .version = <str>$version and <str>.file_status = 'Ready'    ),  }),  job := (insert ext::napalm::Job {    query := 'launchTraining',    variables := <json>(run := <str>run.id),  }),select run { id };
  2. Let an action start your trainer

    launchTraining is an action, a deployed query with a handler at your own address. The query finds the run only while the run is still Queued, and a query that finds nothing does not call the handler.

    dbschema/queries/launchTraining.edgeql
    select TrainingRun { id, base_model, version }filter .id = <uuid>$run and .status = RunStatus.Queued
    Attach the handler
    napalm actions add notes launchTraining https://ml.example.com/actions/launchTraining

    A job attempt has 120 seconds, so the handler starts the work and answers without waiting for the training to finish. call.db() acts as the caller that queued the job, which here is the service key.

    app/actions/[action]/route.ts
    // app/actions/[action]/route.tsimport { handleCalls } from 'napalm-client'import { trainer } from '@/lib/trainer' // your GPU platform's client type Run = { id: string; base_model: string; version: string } export const POST = handleCalls(  {    async launchTraining(call) {      const [run] = call.rows as Run[]       // A job tried again carries the same id, so the trainer starts once.      await trainer.start({ run: run.id, baseModel: run.base_model, idempotencyKey: call.job?.id ?? run.id })       const napalm = await call.db()      const marked = await napalm.fetch('https://notes.napalmdata.com/query/markRunTraining', {        method: 'POST',        headers: { 'Content-Type': 'application/json' },        body: JSON.stringify({ variables: { run: run.id } }),      })      if (!marked.ok) throw new Error(`The run wasn't marked: ${marked.status}`)       return { started: true }    },  },  {    address: 'https://notes.napalmdata.com',    handlers: 'https://ml.example.com/actions',    secret: process.env.NAPALM_ACTION_SECRET,  },)
    dbschema/queries/markRunTraining.edgeql
    update TrainingRunfilter .id = <uuid>$run and .status = RunStatus.Queuedset { status := RunStatus.Training }
  3. Send checkpoints back

    A Checkpoint is a file too. Insert each checkpoint with run, step and validation_loss, and upload the weights in parts. Set the run’s status and metrics when the run ends. Every checkpoint links back to the run, and the run links to every shard it read.

Load a run’s rows#

The trainer asks for the run’s shards with the service key. Each file_url is a direct object storage link that works for 6 hours. On a longer run, ask again for fresh links.

dbschema/queries/runShards.edgeql
select TrainingRun {  shards: { number, file_url, sha256 } order by .number,}filter .id = <uuid>$run
trainers/load_rows.py
# trainers/load_rows.pyimport hashlibimport io import httpximport pyarrow.parquet as pq  def rows_of(napalm: httpx.Client, run: str) -> list[dict]:    """A run's rows: its shards in order, the last word on each id kept, deleted ones dropped."""    latest: dict[str, dict] = {}    found = napalm.post("/query/runShards", json={"variables": {"run": run}}).raise_for_status().json()    for shard in found["data"][0]["shards"]:        data = httpx.get(shard["file_url"], timeout=300).raise_for_status().content        if hashlib.sha256(data).hexdigest() != shard["sha256"]:            raise RuntimeError("A shard's bytes don't match its record.")        for row in pq.read_table(io.BytesIO(data)).to_pylist():            if row["op"] == "delete":                latest.pop(row["id"], None)            else:                latest[row["id"]] = row    return list(latest.values())  def split_of(row_id: str) -> str:    """Train, validation or holdout, from the id alone: a row never moves between them."""    bucket = int(hashlib.sha256(row_id.encode()).hexdigest()[:8], 16) % 100    return "train" if bucket < 90 else "validation" if bucket < 95 else "holdout"
Edits and deletes
Shards are read in order. The newest row for an id replaces older rows, and a delete removes the id.
Train and holdout
Each row’s ID determines its split, so a row never moves from holdout into training between runs.
A long version
When a version has gathered many shards, write the merged rows as a new version and follow the log from there.

To serve the model you trained, see Model serving.

Honor an opt-out before each run#

When a workspace opts out, its pairs disappear from every live query and GET /changes read from that commit onward. Earlier Parquet shards still hold those rows on disk because Ready files are immutable, and no pair row itself mutated to emit a delete event.

Re-verify every candidate ID against your live policy before training by passing the loaded IDs through stillReadable and keeping only the IDs returned.

dbschema/queries/stillReadable.edgeql
select PreferencePair { id }filter .id in array_unpack(<array<uuid>>$ids)

The query has no consent filter. The rule applies to this read as to every read by a service key. To remove the rows for good, write the version again from a full read and delete the old shards.

Check the consent rule#

Your terminal
# 1. The key reads only pairs from workspaces that said yes.napalm keys reach notes --new # 2. A shard is Ready, with its hash and row count.napalm query notes "select DatasetShard { version, number, row_count, sha256, file_status }" # 3. Turn a workspace's consent off in your app, then count again: its pairs are gone from the key's reach.napalm keys reach notes --new

The first count shows fewer PreferencePair rows than the table holds, because the workspaces that have not opted in are missing. After the third step, the count drops again. A count of zero means the branch’s service globals are not set. A count of the whole table means some rule lets every key read.

Type a word or two to search every docs page.