Files and pipelines
Task: accept private documents from your app’s members, process them without any code but a compute run ever reading them, and run the same multi-step job (one step per document, then one that joins the results) on hundreds of files at a time.
Three pieces, each built on the one before:
- Sealed files: a member sends a file as the byte body of a call, the app keeps a
BlobRefto it, and only a compute run can read its bytes. - Compute runs: a method marked
#[app::compute]runs on a job node over files and writes new files. How to write, build, start and test one is in Compute actions; this guide uses it. - Pipelines: a YAML file shipped in the release names compute steps and how they connect; the node runs it as compute runs, without a call per step.
The example is a word counter.
The Rust code builds for both components, and the pipeline passes
calimero_pipeline::compile and check against the app’s compute methods.
What does not work now
Section titled “What does not work now”Pipelines are being moved into an app, and the routes that took a file into a pipeline are gone. These do not work:
- Starting a run over files.
A start that names a file the app does not hold answers
410 INPUT_EXPIRED. A start that binds no file to an input that needs one answers400 BAD_INPUTS. - A package that is only pipelines and compute methods. It has no app component to hold files.
- Downloading or verifying a run’s outputs.
meroctl cloud compute pipeline downloadis gone, andreceipt --verifychecks the receipt’s signature only.
Writing, checking and shipping a pipeline in a release works. The sections below describe what a run does with the files it is given.
A file reaches an app as the byte body of a call, or a compute run writes it.
It leaves only through an export, or a streamed or public view under bytes egress.
App code reads the bytes in a call, view or timer once the release declares bytes.egress and the owner turned it on (EGRESS_OFF before), 1 MiB a read and 64 MiB a run, or in a compute run (files::open).
Keep a member’s file
Section titled “Keep a member’s file”The member sends the file as the byte body of a call to a method marked
#[app::accepts_body], which reads its ref with files::body()
(Client::call_with_body in Rust; Blobs).
use calimero_sdk::blob::BlobRef;use calimero_sdk::compute::{self, ComputeOutcome, ComputeStatus, RunId};use calimero_sdk::files;use calimero_sdk::prelude::*;
#[app::state(version = 1)]pub struct DocIndex { /// The documents submitted, by file id: a reference in state keeps the file. docs: UnorderedMap<String, BlobRef>, /// The count files runs made, by file id. counts: UnorderedMap<String, BlobRef>,}
#[app::error]pub enum Error { NoSuchFile, NotYourFile,}
/// A document as `doc` describes it (D20: the size as a decimal string).#[derive(serde::Serialize)]pub struct DocOut { pub size: String,}
/// `countWords`'s arguments.#[derive(serde::Serialize)]#[serde(rename_all = "camelCase")]struct CountArgs { min_len: u32,}
#[app::logic]impl DocIndex { #[app::init] pub fn init() -> app::Result<Self> { Ok(Self::load()) }
/// Keep the file the call carried, and count its words in a compute run. #[app::accepts_body] pub fn submit(&mut self) -> app::Result<RunId> { let _me = guards::require_member()?; let Some(file) = files::body() else { app::bail!(Error::NoBody); }; self.docs.insert(&file.id(), &file)?; compute::start("countWords", &CountArgs { min_len: 1 }, &[file]) }
/// A kept document's size; its bytes stay sealed. #[app::view] pub fn doc(&self, file: BlobRef) -> app::Result<Option<DocOut>> { if self.docs.get(&file.id())?.is_none() { return Ok(None); } Ok(files::info(&file).map(|info| DocOut { size: info.size.to_string(), })) }
// countWords, join and onCounted: below.}files::info(&file)isSome(FileInfo { size, sha256 })for a file the app holds, elseNone. It works in every kind of run but a migration.- A reference in state is what keeps a file.
A file nothing refers to is forgotten an hour later
(
BLOB_IDLE_MS), and so is one whose lastBlobRefthe app removes. There is no delete call: drop the reference. files::openworks in a compute run always, and in a call, a view and a timer only while egress is declared and on, else it fails withEGRESS_OFF. A read is at most 1 MiB and a run reads at most 64 MiB outside a compute run, else the read answers theFileserrorread too largeorrun read too much.app::stream(&[StreamPart { file, range }])answers a view with byte ranges of files the app holds, which the node sends to the caller as a stream (Byte streams of views).
A call, timer or init may also write a file with files::create() (a
std::io::Write; finish() answers the BlobRef), at most 64 MiB per run.
Process it in a compute run
Section titled “Process it in a compute run”use std::io::{BufRead, BufReader, Write};
/// Writes one line per input, `<file id> <words>`, counting words of at least `min_len` /// characters. Runs on a job node. #[app::compute(fuel = 50_000_000_000, memory_mib = 128, wall_secs = 120, result = "on_counted")] pub fn count_words(min_len: u32) -> app::Result<u64> { let mut out = files::create()?; let mut total = 0u64; let inputs = compute::inputs(); for (i, input) in inputs.iter().enumerate() { let mut words = 0u64; for line in BufReader::new(files::open(input)?).lines() { let line = line?; let long = line .split_whitespace() .filter(|w| w.chars().count() >= min_len as usize); words += long.count() as u64; } compute::progress((100 * (i + 1) / inputs.len()) as u8, "counting"); writeln!(out, "{} {words}", input.id())?; total += words; } out.finish()?; Ok(total) }
/// Joins every input into one file, in the order given. #[app::compute(fuel = 50_000_000_000, memory_mib = 128, wall_secs = 120, result = "on_counted")] pub fn join() -> app::Result<u32> { let mut out = files::create()?; let inputs = compute::inputs(); for input in &inputs { std::io::copy(&mut files::open(input)?, &mut out)?; } out.finish()?; Ok(inputs.len() as u32) }
/// The node runs this when a run the app started ends; it keeps the outputs. #[app::compute_result] pub fn on_counted(&mut self, outcome: ComputeOutcome) -> app::Result<()> { if outcome.status == ComputeStatus::Done { for output in &outcome.outputs { self.counts.insert(&output.id.id(), &output.id)?; } } Ok(()) }submit starts countWords over one file, and on_counted stores the output’s
BlobRef, which is what keeps it.
The rules (caps, determinism, result methods, the
meroctl app build --compute-out build and the meroctl local compute run test runner) are in
Compute actions.
In a compute run, files are bounded by MAX_FILE_BYTES (2 GiB each) and 2 GiB
written in all, 16 open at once, and 1,000 new files.
Ship a pipeline
Section titled “Ship a pipeline”Starting one run per file from a call works for a few files. For hundreds, with a step that waits for all of them, ship a pipeline: the leader decides each step from the run’s record and starts its compute runs in waves, and a client starts the whole thing with one request.
pipelines/wordcount.yaml:
apiVersion: compute.calimero.network/v1kind: Pipelinename: wordcountparams: min-len: { type: number, default: 1, min: 1, max: 64 }inputs: docs: { kind: files, maxItems: 500 }steps: count: method: countWords forEach: inputs.docs maxItems: 500 batch: 10 maxParallel: 8 allowFailures: 5% args: { minLen: params.min-len } limits: { wallSecs: 60 } total: method: join collect: count.outputsoutputs: [total.outputs]| Field | Meaning |
|---|---|
apiVersion, kind, name |
Required: compute.calimero.network/v1, Pipeline, and a name of 1 to 64 characters of [a-z0-9-] starting with a letter (the same rule for every step, input and param name; inputs, params and item are reserved). |
module |
The module steps run in when they name none: self (the release’s own compute component, the default) or another installed package, com.acme.pdf[@0.1.0], pinned at install. |
params |
Typed values a run passes: type (number, string, boolean), default, min, max, enum, secret. A step reads one as params.<name>. |
inputs |
What a run binds: kind: files (with maxItems), artifact or table (one file each), and an optional default. |
steps.<name>.method |
A compute method of the step’s module, by its ABI name (countWords). |
args |
The method’s arguments, a JSON object whose values may be params.x, <step>.result or, in a fan-out, item. A method that takes none gets none. |
inputs (step) |
Files the run gets: inputs.x, <step>.outputs, and item in a fan-out. |
needs |
Steps that must succeed first; a reference to a step adds it. |
forEach |
One item per file of inputs.x or <step>.outputs, or per value of <step>.results; needs maxItems. batch groups items into one run, maxParallel bounds the runs active at once, allowFailures (a count or a percentage) lets the step succeed with some items failed. |
collect |
<fan-out step>.outputs: one run over all of that step’s outputs, in item order. |
limits |
fuel, memoryMib, wallSecs: only lower than the method’s caps. |
pool |
Run this step’s runs on that pool’s job nodes. |
cache |
false turns the step cache off for this step (default on). |
outputs, failFast |
The run’s outputs: the <step>.outputs whose files the run hands out, and only those (none when outputs is absent or empty). A run’s view shows the result and results of those steps only, so a pipeline that returns values names the step that returns them. failFast: true cancels the other steps at the first failed one. |
when, runIf, uses, loops, variables, sources, sinks, publish,
notify and an input’s accept, maxFileSize, format and schema are
refused with NOT_IN_V1, never ignored.
A source is at most 64 KiB, with at most 64 steps, 64 inputs, 64 params and
10,000 items per fan-out (crates/pipeline/src/compile.rs).
A run takes at most 1,024 files, so an install, or a check against a release,
refuses an input’s maxItems above that (BAD_MAX_ITEMS).
Secret params
Section titled “Secret params”secret: true on a param, such as the salt behind a pseudonym, keeps its value out of everything a reader of the run sees.
The job still gets the value.
The run view, its events and its receipt show { "hmacSha256": "<hex>" } in its place, and secretParams names the params shown that way.
params: salt: { type: string, secret: true }The hash is an HMAC-SHA256 of the app, the run, the param’s name and its value under a key derived from the cluster’s key, which never leaves the cluster’s nodes.
A plain or salted hash would let anyone holding the receipt test guesses offline; this one cannot be computed without the cluster’s key, and it differs from run to run, so two runs with the same value do not match.
For the same reason a run with secret params keys its step args under the cluster’s key before they go into a step cache key.
Nobody can check a guess against the hash, the run’s owner included: keep the value where you keep the run’s other secrets.
A secret param takes no default or enum (BAD_PARAM): the pipeline’s source is public, so either would give the value away.
A pipeline without a secret param, and every receipt already issued, are unchanged.
Check it before you pack
Section titled “Check it before you pack”meroctl cloud compute pipeline validate pipelines/wordcount.yaml # structure onlymeroctl cloud compute pipeline validate pipelines/wordcount.yaml --package com.example.docs --version 1.0.0POST /pipelines/validate lists every problem with its path and stable
code (BAD_NAME, BAD_REF, CYCLE, NOT_IN_V1, MISSING_MODULE, …) and
writes nothing; against an installed release it also checks the methods and
caps the release would give it, and answers worstCaseFuel (and
worstCaseCost when the operator has set prices).
Pack it into the release
Section titled “Pack it into the release”meroctl app build apps/doc-index --out app.wasm --compute-out compute.wasmmeroctl app pack --wasm app.wasm --compute compute.wasm \ --pipeline pipelines/wordcount.yaml \ --package com.example.docs --app-version 1.0.0 --key my-signing-key.json \ --out dist/com.example.docs-1.0.0.mpkThe manifest lists the file under pipelines (at most 16 per package, each at
most 64 KiB), signed with the rest.
At install the node compiles each one and checks it against the release’s
compute methods, the modules it names and the cluster’s pools.
Any problem refuses the release with 400 BAD_PIPELINE and details: [{ file, path, code, message }] for every error (NO_COMPUTE for a release without a
compute component, DUPLICATE_NAME for two pipelines of one name); a
multi-service package declaring pipelines is 422 PIPELINES_NEED_ONE_SERVICE.
A release with pipelines installs only once every node runs this release
(409 CLUSTER_NOT_UPGRADED).
meroctl package pipelines com.example.docs prints what a version registered:
each pipeline’s hash, worst-case fuel, pinned modules and canonical JSON.
Run it
Section titled “Run it”meroctl cloud compute pipeline estimate docs wordcount --input docs=<id1>,<id2>,<id3>meroctl cloud compute pipeline run docs wordcount --input docs=<id1>,<id2>,<id3> \ --param min-len=4 --max-fuel 50000000000 --max-wall-ms 600000 --waitmeroctl cloud compute pipeline watch docs <run> # snapshot, run and step events, then endmeroctl cloud compute pipeline receipt docs <run> --verify # the signature onlyFrom mero-js the routes are generated methods of client.apps:
const estimate = await client.apps.pipelinesEstimateRun({ app, name: 'wordcount', counts: { docs: 120 } });const { run } = await client.apps.pipelinesStart({ app, name: 'wordcount', inputs: { docs: ids }, params: { 'min-len': 4 }, maxUsage: { fuel: '50000000000', wallMs: '600000' },});const state = await client.apps.pipelinesGet({ app, run }); // each step's status, runs and reasonIn Python, client.apps.pipelines_start(app=..., name="wordcount", inputs={...})
and pipelines_estimate_run, and in Rust Client::start_pipeline_run,
estimate_pipeline, pipeline_run_events, pipeline_receipt and
verify_receipt.
What happens to the run:
- It pins the release’s pipeline by hash and its compute component at start, so upgrading the app does not change a run already going, and a retry keeps the original release.
- Each step’s work is ordinary compute runs with ids
<run>.<step>.<index>, under the app’s owner, payer and file keys. They have no result method: the step keeps each run’s result (at most 64 KiB) and outputs. Only the files of the steps the pipeline’soutputsnames leave the app. The run’s inputs and every other step’s outputs are held: they are not listed, exported or published, by the run’s starter, the app’s owner or any member, and only the steps read them. A run started before the cluster version that bringsfinalOutputsOnlykeeps the files it made as before. Inputs are held for at least 24 hours after the run ends so a retry can use them, the outputs named in the pipeline’soutputsfor the days the app’s managers set (1 to 90, 7 by default;meroctl cloud compute pipeline settings; a pipeline withoutoutputshands out none), and the other steps’ outputs only while the step cache keeps them (7 days). Have a call keep the outputs you need. - A step run whose method, arguments and input contents match an earlier
successful run in the app is answered from the step cache, at no cost.
meroctl cloud compute pipeline retry docs <run> --limit count.fuel=80000000000starts a new run where only the failed items run again. maxUsage { fuel, wallMs }is a budget for all the run’s jobs together: each job starts with the fuel and wall time left of it (wallMsis the total of the jobs’ own wall time, not the clock’s), so the run stops at the budget, and the step that finds it spent fails withBUDGET_EXHAUSTED. Starts by an API key or another app must give it.- A start or retry with an
idempotencyKeyis the same run each time it is sent by the same caller: a repeat answers the first one’s{ run }, ended or not, while the app keeps the run (its last 64 finished). Once the run is dropped the key is free, and a start with it is a new run. The same key with a different body is refused with409 IDEMPOTENCY_KEY_REUSED. The clients send a fresh key on every start and retry, which covers their own retries; a CI job that may start the same run again passes its own,--idempotency-key "$CI_PIPELINE_ID"in meroctl.
The step and run rules (fan-out waves, allowFailures, failFast, pools,
cache lifetime, cost) are in Pipeline runs;
receipts, events and exports are also covered in
Compute actions.
Start a run from a backend
Section titled “Start a run from a backend”Give the backend a pipeline key, which starts, reads and cancels runs of the pipelines it names and nothing else:
meroctl account api-key create --label ingest --instance docs --pipelines wordcount \ --dev-passkey ./dev-passkey.jsonEvery start and retry with a key takes a maxUsage, a budget the caller chooses and the node does not bound.
The key may also name methods: ["__blob"], the only method it may name; it then exports only the files its pipelines’ runs took in or made.
meroctl resolves no alias for a pipeline key, so name the instance by its id.
Start a run from another app
Section titled “Start a run from another app”Another app of the same organization can run your pipelines, so its backend needs no API key of a person’s.
-
The calling app names the pipeline package as an
attachreference (Build on other apps):[package.metadata.calimero.uses]jobs = { package = "com.example.docs", range = "^1", mode = "attach" } -
Whoever manages both instances links them, with their passkey:
PUT /apps/{your-app}/links/jobs { "app": "<the pipeline app's id>" }. -
The app starts, reads and cancels runs from an
async fnmethod:
use std::collections::BTreeMap;
use calimero_sdk::pipeline;use calimero_sdk::prelude::*;
#[app::state(version = 1)]pub struct Intake { /// The run started for each file. runs: UnorderedMap<String, String>,}
#[app::logic]impl Intake { #[app::init] pub fn init() -> app::Result<Self> { Ok(Self::load()) }
/// Counts the words of `file`, a file the pipeline app holds. pub async fn count(&mut self, file: String) -> app::Result<String> { let Some(jobs) = env::linked("jobs") else { return Err(AppError::new("NotLinked")); }; let start = pipeline::Start { inputs: BTreeMap::from([("docs".to_owned(), vec![file.clone()])]), max_usage: Some(pipeline::Usage { fuel: 50_000_000_000, wall_ms: 600_000, }), ..Default::default() }; let started = pipeline::start(&jobs, "wordcount", &start).await?; self.runs.insert(&file, &started.run)?; Ok(started.run) }
/// The state of `run`: `running`, `succeeded`, `failed` and so on. #[app::view] pub async fn state(&self, run: String) -> app::Result<String> { let jobs = env::linked("jobs").unwrap_or_default(); let seen = pipeline::get(&jobs, &run).await?; Ok(seen["state"].as_str().unwrap_or_default().to_owned()) }}pipeline::cancel(&jobs, &run) stops one.
These calls are not typed by the pipeline: no client is generated from a pipeline’s inputs and params, so a misspelled name is refused at run time.
- The files are the pipeline app’s own, named by id. An app cannot pass a file of its own to a pipeline.
- The app reads and cancels only the runs it started, and sees their results.
- Every start gives a
max_usage: without one it is refusedMAX_USAGE_REQUIRED. - Your code decides which of the app’s users may start, read or cancel a run: check the caller before each call. Each run is paid by the pipeline app’s payer.
- A re-run of the calling method answers the run it already started. Set
idempotency_keyto make separate calls share one run. - Nothing tells the app that a run ended: read it again, from a timer or when a user asks.
The rules are in Runs an app starts.
In the test harness, mock_app plays the pipeline app: it is called with the method pipeline.start, pipeline.get or pipeline.cancel.
Errors
Section titled “Errors”| Status, code | When |
|---|---|
400 BAD_PIPELINE |
at install: a pipeline does not compile or check; details lists every error |
404 NO_SUCH_PIPELINE |
the app’s release registers no pipeline of that name |
400 BAD_INPUTS |
an input that is not the pipeline’s, unbound, past its maxItems, more than 1,024 files in all, or not a file id |
410 INPUT_EXPIRED |
an input (or, on a retry, an original input) is not a file the app holds |
400 BAD_PARAMS |
a param of the wrong type, outside min/max/enum, or undeclared |
400 BAD_MAX_USAGE |
maxUsage without both fuel and wallMs, or one that is not a whole number above zero (a decimal string) |
400 MAX_USAGE_REQUIRED |
a start or retry by an API key or an app without maxUsage |
409 FEATURE_NOT_ACTIVE |
maxUsage given before every node runs the release that carries it |
409 IDEMPOTENCY_KEY_REUSED |
an idempotencyKey that already started a run with another pipeline, inputs, params, limits or usage budget |
400 BAD_IDEMPOTENCY_KEY |
an idempotencyKey that is empty or longer than 256 bytes |
429 TOO_MANY_PIPELINE_RUNS |
8 runs already going in this app |
403 FORBIDDEN |
the caller is not the app’s owner or a member of its organization (start, cancel, retry, receipt), even where an anyone grant admits others; or a calling app is not linked to the pipeline app |
409 FEATURE_NOT_ACTIVE |
a calling app’s start (pipelineAppCaller), or making a pipeline key (pipelineKeyScope), before every node runs a release that has it |
409 STILL_RUNNING, 400 LIMIT_EXCEEDS_CAP, 400 BAD_LIMITS |
a retry of a running run, or with limits above the method’s caps or for a step the pipeline lacks |
409 RUN_NOT_ENDED |
a receipt asked for before the run ended |
A step that cannot be built fails with its own code in the run’s record
(TOO_MANY_ITEMS, TOO_MANY_INPUTS, RUN_TOO_LARGE, COST_CAP,
RESULTS_TOO_LARGE, …): Pipeline runs.