Guides · Models & ML
Datasets & ML training
Export Parquet training datasets straight from your application tables while schema policies enforce per-workspace training consent.
- 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.
- Schema-enforced consent
- Service keys read rows only from workspaces that have opted in to model training.
- Incremental Parquet exports
- Run one initial snapshot followed by nightly change-log deltas stored as compressed Parquet shards.
- Verifiable run inputs
- Every training run links to its input shards, and each shard record stores a SHA-256 digest of its bytes.
- Pre-run opt-out filtering
- Re-checking candidate row IDs before training drops workspaces that opted out after earlier shards were written.
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
- Issue a pipeline key with
napalm keys createand set your branch’s service globals to{ "default::role": "service" }in the console or viaPOST /so policies distinguish service keys from user sessions.projects/ {id}/ endpoint - File storage
- Dataset shards and model checkpoints use file records backed by object storage.
- Endpoint passthrough
- Incremental exports read
GET /changes, which requires endpoint passthroughallorkeysrather thannone. - External GPU compute
- Training runs on your own GPU platform. An action triggers your trainer and supplies signed download URLs for input shards.
Enforce training consent in the schema#
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.
Consent-gated Parquet exports
Schema policies exclude opted-out workspaces from snapshots and incremental change streams.
Declare the consent flag on Workspace, gate service-key reads on PreferencePair and track exported DatasetShard, TrainingRun and Checkpoint records in one schema:
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 initial snapshot#
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:
select PreferencePair { id, prompt, chosen, rejected }filter .id > <uuid>$afterorder by .idlimit <int64>$limitexport_all calls pairsAfter in a cursor loop, compresses each 50,000-row batch into Zstandard Parquet and completes the upload:
# 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 # fits inside a single-part upload def write_shard(napalm: httpx.Client, version: str, number: int, rows: list[dict], reach: str | None) -> None: """Upload one Zstandard Parquet shard and register its DatasetShard row.""" 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: """Page through permitted pairs in ID order and return the next shard index.""" 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 + 1Each 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.
Stream incremental 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, continueddef export_changes( napalm: httpx.Client, version: str, number: int, after: str | None = None, since: str | None = None) -> tuple[int, str | None]: """Export changes committed after a cursor or timestamp and return the updated cursor.""" 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("Change log gap detected: start a fresh dataset 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}Each incremental page encodes updates, deletes and retention boundaries in a uniform format:
- Updates
- Committed edits appear with
opset toupdate. Shards append the updated row, and the loader keeps the latest entry per ID. - Deletes
- Committed deletes appear with
opset todeleteand the row ID alone, instructing the loader to evict earlier versions of that ID. - Retention gaps
- If the pipeline stays offline past the change-log retention window,
GET /changesreturns agapmarker so you can start a fresh dataset version from a full snapshot.
Combine the initial snapshot and incremental tail in your nightly runner:
# 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: # Night 1: capture a timestamp slightly before the full snapshot, then tail incremental commits. started = (datetime.now(timezone.utc) - timedelta(minutes=5)).isoformat() number = export_all(napalm, "v1") number, resume = export_changes(napalm, "v1", number, since=started) # Subsequent nights: number, resume = export_changes(napalm, "v1", number, after=resume)The initial change-log tail starts five minutes before the snapshot began so concurrent writes are never missed, and duplicate entries collapse by ID at load time. Trigger the export on a cron schedule or from a webhook listening to pair_recorded.
Store Parquet shards as file records#
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).
Typed shard metadata
Database rows record shard order, row counts and content digests.
Direct object storage
Parquet bytes upload straight to object storage through presigned plans.
Insert each DatasetShard row with its expected byte size to receive a presigned file_upload plan:
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 }Extending ext::files::File enforces three storage guarantees on every shard:
- Validated file headers
- On upload completion, Napalm inspects the stored file header so non-Parquet uploads fail validation and never transition to
Ready. - Immutable bytes
- Once
Ready, a file’s bytes never change. Linking a training run to a shard pins the exact bytes, verified at load time viasha256. - Backup-aligned retention
- Deleted shard bytes remain in storage until your oldest restorable backup ages out. See File cleanup.
Launch runs and record provenance#
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.
Commit the run and launch job together
Inserting the
TrainingRunand its job in one EdgeQL statement ensures neither record exists without the other: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 };Dispatch to your GPU cluster from an action
launchTrainingpairs a gatekeeper query with your HTTPS handler. The query matches only while the run status isQueued, skipping the handler if the run already started:dbschema/queries/launchTraining.edgeql select TrainingRun { id, base_model, version }filter .id = <uuid>$run and .status = RunStatus.QueuedAttach the HTTPS handler URL to
launchTraining:Attach the handlernapalm actions add notes launchTraining https://ml.example.com/ actions/ launchTraining Each job attempt runs for up to 120 seconds, so the handler triggers your external trainer and returns immediately without waiting for training to complete. Calling
call.db()authenticates as the service key that queued the job: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[] // Retried job attempts reuse call.job.id so your trainer deduplicates starts. 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(`Failed to mark run Training: ${marked.status}`) return { started: true } }, }, { address: 'https://notes.napalmdata.com', handlers: 'https://ml.example.com/actions', secret: process.env.NAPALM_ACTION_SECRET, },)markRunTrainingtransitions the run fromQueuedtoTrainingonce your external job starts:dbschema/queries/markRunTraining.edgeql update TrainingRunfilter .id = <uuid>$run and .status = RunStatus.Queuedset { status := RunStatus.Training }Upload checkpoints and final metrics
Each
Checkpointextendsext::files::File. Insert checkpoint rows withrun,stepandvalidation_loss, upload weights via multipart upload and update the run’sstatusandmetricson completion.
Load and deduplicate run shards#
Your trainer queries runShards with the service key to fetch ordered shards and signed file_url download links. Each link stays valid for 6 hours, and longer runs can re-query runShards for fresh URLs:
select TrainingRun { shards: { number, file_url, sha256 } order by .number,}filter .id = <uuid>$runDownload each shard in sequence, verify its sha256 digest and collapse multiple entries for the same row ID:
# trainers/load_rows.pyimport hashlibimport io import httpximport pyarrow.parquet as pq def rows_of(napalm: httpx.Client, run: str) -> list[dict]: """Replay a run's shards in sequence, keeping the latest state per ID and dropping deletes.""" 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("Shard SHA-256 digest mismatch.") 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: """Assign each row deterministically to train, validation or holdout from its UUID.""" bucket = int(hashlib.sha256(row_id.encode()).hexdigest()[:8], 16) % 100 return "train" if bucket < 90 else "validation" if bucket < 95 else "holdout"Replaying shards in order keeps dataset reconstruction deterministic across runs:
- Ordered replay
- Reading shards in sequence replaces older entries with newer updates for the same ID and removes deleted IDs.
- Deterministic splits
- Hashing each row’s UUID keeps train, validation and holdout assignments stable across runs so holdout examples never leak into training.
- Shard compaction
- Once a dataset version accumulates many incremental shards, write the compacted table as a new baseline version and tail changes forward.
To serve the model you trained, see Model serving.
Filter new opt-outs before training#
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.
select PreferencePair { id }filter .id in array_unpack(<array<uuid>>$ids)stillReadable needs no explicit consent filter because the schema policy on PreferencePair filters service-key reads automatically. To purge opted-out rows from object storage as well, export a fresh dataset version and delete the older shards.
Check the consent rule#
# 1. Verify that a new service key reaches only pairs from consented workspaces.napalm keys reach notes --new # 2. Inspect DatasetShard records to confirm Ready status, SHA-256 digest and row count.napalm query notes "select DatasetShard { version, number, row_count, sha256, file_status }" # 3. Opt a workspace out in your app and confirm that its pairs drop from the key's reach.napalm keys reach notes --newThe initial reach count returns fewer PreferencePair rows than total table rows whenever opted-out workspaces exist, and step 3 reduces that count further. A count of zero indicates missing branch service globals, whereas matching the full table indicates an overly permissive policy.