# RFC 0003: Declared batch mode

- **State:** accepted — accepted for experimental implementation (founder decisions of 2026-12-03)
- **Author(s):** OpenFlange maintainers
- **Created:** 2026-12-03
- **Affected specifications:** `openflange.org/pipe/v0.1` (5.7, 9.5), `openflange.org/pipeline/v0.1` (3.8, 6.5, 8.11), `openflange.org/cli/v0.1` (5.1, 5.2), `openflange.org/test/v0.1` (3.4), `openflange.org/std/v0.1` (5.4)
- **Feature maturity requested:** experimental (feature identifier `batch`)
- **Supersedes / superseded by:** none

## Summary

A pipe may declare in its manifest that its implementation wants its input
in **batches**: `batch: {maxItems, maxWaitMs, delivery}`. The runner then
collects items and hands the implementation up to `maxItems` at a time,
never holding an item back for longer than `maxWaitMs`. Batch mode is for
implementations that live **outside the runner** — subprocesses in R,
Python, Node or any other language, and scripts. Batch boundaries carry no
meaning: a conformant pipe gives the same output however its input is cut.

## Motivation

A per-record pipe that is a subprocess pays for every record: a line to
parse and print, a round trip through two kernel pipes, and whatever the
language charges for a scalar call. Three kinds of pipe suffer from that:

- **Vectorised languages.** R and NumPy-style Python are fast on vectors
  and slow on scalars. `toupper(x)` on a thousand strings costs about what
  it costs on one.
- **External calls.** A request to a language model, an embedding service,
  an enrichment API or a database (bulk insert) has a cost *per call* that
  dwarfs the cost per record in it.
- **File-in/file-out tools.** DuckDB, pandas scripts and many command-line
  programs want a file, not a stream of lines.

Without a declaration each such pipe has to reinvent buffering inside the
program, with its own flush timer, and the runner — which is where
backpressure, cancellation and latency are decided — knows nothing about it.

**Honest numbers** (reference Go runner, one 8-vCPU virtual machine,
2026-12-03, single runs, ±30 %; `docs/performance.md` of
`openflange-go` has the tables and the method):

| Pipe | Without batch mode | Batch mode |
|---|---:|---:|
| R: row-wise tidy of records (`fromJSON`/`toJSON`) | 720 records/s | 21,900 (`lines`, 1000 per batch) – 36,500 records/s on a longer run |
| Python: add a field per record (standard library) | 64,000 – 118,000 records/s | 96,000 – 155,000 (`lines`, 100 – 500 per batch) |
| A pipe whose call costs 5 ms regardless of size | 160 records/s (1 per call) | 1,640 (10 per call), 141,000 (1000 per call) |
| DuckDB row-wise SQL, one process per batch file | — | 880 (100 per batch) … 237,000 records/s (50,000 per batch) |
| Starlark `mask-email` | 55,000 records/s | 68,000 – 73,000 (`process_batch`, 16 – 256 per call) |

So: **large gains** for vectorised R and for anything priced per call;
**moderate** for Python doing per-record work; **small** for Starlark,
which runs in-process already; **none** for native Go, which is why
builtins cannot declare it. And a caution: `maxItems: 1` is *slower* than
no batch mode for a subprocess (6,600 – 9,400 against 64,000 – 118,000
records/s in the Python case), because batch delivery is request/answer.

These were single runs of different pipes. A systematic comparison — one
transformation in R, Python, Node.js, DuckDB and Starlark at batch sizes
from 1 to 100,000, both delivery modes, every output verified — is
`benchmarks/batch/` in `openflange-go`, with its results, charts and a
section on choosing `maxItems` and `maxWaitMs`.

## Proposal

### The declaration

```yaml
batch:
  maxItems: 100        # REQUIRED, integer >= 1: the largest batch
  maxWaitMs: 1000      # optional, integer >= 0, default 0
  delivery: lines      # optional: lines (default) | file — executables only
```

`batch` is valid only on a pipe with **exactly one input port**, of kind
`records`, `values` or `windows`, not variadic, whose implementation type
is **`executable`** or **`script`** (Starlark, R, Python, Node). Everything
else is `E_MANIFEST`:

- `builtin` — native Go (or any in-runner) code already receives its input
  in the runner's own units and controls its own reads; a declaration adds
  nothing. A Go host that wants size-or-wait grouping calls the batching
  utility directly (`stream.NewSlicer` in the reference implementation),
  with no manifest involved.
- `expression` — per item by construction.
- `pipeline` — a composite has no implementation to hand batches to.
- `http` — out of scope, see Deferred.

Starlark is included although it gains little, because it is the
network-free, dependency-free runtime every runner has: it lets the
conformance fixtures demonstrate the invariants portably.

Without `batch` nothing changes for any pipe.

### The delivery rule: two slots

Per node the runner keeps **one batch in flight** (delivered, being
processed) and **one batch accumulating**. It reads the node's input into
the accumulating batch all the time — *accumulation never waits for the
pipe*. The accumulating batch is **ready** when the first of these holds:

1. it holds `maxItems` items;
2. `maxWaitMs` has elapsed since its first item arrived (the clock starts
   at that item, also when it arrives while the previous batch is in
   flight);
3. the input has ended (the remainder; never an empty batch).

A batch is delivered when it is ready and nothing is in flight. If it
became ready while the pipe was busy it is delivered the moment the pipe
finishes, and until then it keeps growing up to `maxItems` — under load,
batches fill toward the maximum by themselves (adaptive batching). When
the accumulating batch is full and the pipe is still busy, the runner
stops reading: ordinary backpressure. With `maxWaitMs: 0` a non-empty
batch is always ready: the runner never waits and never delays a lone
record.

```text
maxItems: 4, maxWaitMs: 100. Items a…l arrive; the pipe needs a while per slice.

time ─────────────────────────────────────────────────────────────────────►
arrivals      a b c d   e f      g h i        j             k l  <EOF>
in flight            [a b c d]·········  [e f g h]·····  [i j]·····  [k l]··
                     ▲                   ▲               ▲           ▲
                     full, pipe idle:    pipe finished;  pipe        end of
                     delivered at once   e–h was full:   finished;   input:
                                         delivered       i arrived   remainder
                                         at once         >100 ms
                                                         ago: at once
accumulating           e f g h                i j            k l
                       (full while the pipe is busy: the runner stops
                        reading; i waits upstream until e–h is delivered)
```

There is **no minimum batch size** in v0.1, and **one batch in flight**
per node.

### Invariants (normative)

- **Batch boundaries are not semantic.** The same output items in the same
  order for every way of cutting the input. Grouping that means something
  is a window (`std:window`).
- **Order is preserved**; nothing is dropped or duplicated.
- **Bounded memory:** at most 2 × `maxItems` items per node (one in
  flight, one accumulating); with file delivery at most three batch files.
  A full accumulating batch blocks the producer.
- **Cancellation and failure** release both slots, stop the wait timer and
  remove batch files.
- **Counters count items**, never batches.
- **`cardinality: one-to-one` composes:** every batch must yield exactly
  as many outputs as it has inputs, in order (`E_RUNTIME` otherwise).

### Consumers may only tighten

A pipeline node (and a portable test) may carry
`batch: {maxItems, maxWaitMs}` with values less than or equal to the
declared ones; a larger value is `E_PARAM`, as is `batch` on a pipe that
does not declare batch mode. `delivery` cannot be changed by a consumer.
The execution plan shows the effective settings per node.

An invoker is a consumer too. The reference CLI takes
`--batch [<node>=]<maxItems>[,<maxWaitMs>]` on `run` and `validate`
(CLI specification, section 9.1) and `--batch <maxItems>[,<maxWaitMs>]`
on `test`; the value is applied after the node's own settings and may
only tighten them (`E_PARAM` otherwise). That is how one finds a good
`maxItems` for a pipe without editing its manifest.

### What the run report says

For every node that ran in batch mode the run report carries `batch`
(Pipeline specification, section 10): the number of slices, the largest
and the mean slice, how many slices were closed because they were full,
because `maxWaitMs` expired or because the input ended, and the largest
number of items the node held at once. A pipe whose slices are mostly
closed by the wait is limited by its producer, not by `maxItems`; one
whose mean slice is far below `maxItems` at the end of a short run simply
had little input.

### Usage counters

A batch-mode executable that pays per call — the reason many of them
exist — reports what the calls cost through the usage endpoint of the CLI
protocol (CLI specification, section 5.3; `implementation.usage: true`
for a pipe without additional ports) in either delivery mode. The
acknowledgement of a batch file may carry `"usage"` as well.

### Window frames

On an input of kind `windows` (proposed) one window frame is one item of a
slice in both delivery modes; `maxItems` counts frames.

### Delivery by implementation

**Starlark script** — `def process_batch(items, params)`: called once per
batch with a list. `process_batch` is the default entry point when `batch`
is declared (`entrypoint` overrides it). A returned list (or tuple) goes to
the sole required output, element by element; `emit` works as usual.

**Executable, `delivery: lines`** (the default; also for `script` in R,
Python, Node) — on standard input the runner writes **one JSON array per
line**, 1 to `maxItems` items each, flushed when the batch is delivered.
The program answers **each input line with exactly one output line, a JSON
array** of that batch's output items (possibly `[]`), which the runner
flattens exactly one level — so `[[1,2,3]]` is the one item `[1,2,3]`. The
answer line is the acknowledgement: the next line is written only after
it. With `cardinality: one-to-one` the answer has the same length as the
line it answers. `OPENFLANGE_CONFIG` carries
`"batch": {"maxItems": n, "maxWaitMs": n, "delivery": "lines"}`.

A program written this way is still an ordinary Unix filter; without a
runner you feed it array lines yourself:

```r
library(jsonlite); con <- file("stdin", open = "r")
while (length(line <- readLines(con, n = 1)) > 0)
  cat(toJSON(toupper(fromJSON(line))), "\n", sep = "")   # one vectorised call per batch
```

```sh
printf '%s\n' '["a","b"]' '["c"]' | Rscript --vanilla upper.R
# ["A","B"]
# ["C"]
```

**Executable, `delivery: file`** — every batch is a **plain NDJSON file**
(one item per line, not an array) in a directory the runner creates for the
node (under `TMPDIR`, mode 0700, files 0600, random name). The runner
writes the file of the accumulating batch while the previous batch is
processed, deletes a batch's files once its output is consumed, and removes
the directory when the node ends — completed, failed or cancelled. Using
that directory needs no `filesystem` permission. The path reaches the
program in one of two ways, chosen by how `command` is written:

- **(A) One process per batch.** If `command` contains `{batch.input}`
  (and optionally `{batch.output}`), the runner starts it once per batch
  with the absolute paths substituted — plain text substitution inside
  argv elements, no shell; `{{` is a literal `{`. With `{batch.output}` the
  program writes NDJSON there and must not write to standard output
  (`E_PROTOCOL`); without it, standard output is the batch's NDJSON.
  Exit 0 = batch done. This wraps a file-in/file-out tool with no protocol
  code:

  ```yaml
  batch: {maxItems: 50000, maxWaitMs: 1000, delivery: file}
  implementation:
    type: executable
    command: [duckdb, -c, "copy (select id, qty * unitCents as netCents from read_json('{batch.input}')) to '{batch.output}' (format json)"]
  ```

  A process start is paid per batch, so this suits large batches. And the
  query must be **row-wise**: `select customer, sum(total) … group by all`
  in this position would return one partial total per batch — wrong,
  because boundaries are not semantic. A true aggregate is a
  `scope: dataset` pipe.

- **(B) A long-running process.** Without placeholders the process starts
  once. Per batch the runner writes one line
  `{"input": "<path>", "output": "<path>", "items": n}` to standard input;
  the program reads the input file, writes NDJSON to the output path and
  acknowledges with one line `{"ok": true}` (optionally `"usage": {…}`)
  on standard output. Then the runner reads the output file, deletes both
  files and sends the next line.

Output files are validated as NDJSON (`E_FORMAT`), size-bounded
(`E_RESOURCE`), and with `one-to-one` must hold as many items as the input
file. `OPENFLANGE_CONFIG.batch` carries `"delivery": "file"` and `"dir"`.

### Errors

| Situation | Code |
|---|---|
| `batch` malformed; on a pipe with ≠ 1 input, a non-item or variadic input; on `builtin`, `expression`, `pipeline`, `http`; `delivery: file` on Starlark; a placeholder that is unknown, used without `delivery: file`, or `{batch.output}` without `{batch.input}` | `E_MANIFEST` |
| A node, a test or the command line loosens the settings, or sets `batch` for a pipe that does not declare it | `E_PARAM` |
| The runner cannot batch this implementation type; with `delivery: file`, the temporary directory is missing, not writable or has an unsafe path | `E_UNSUPPORTED` |
| An output line that is not a JSON array; an invalid batch output file | `E_FORMAT` |
| A line that is not an acknowledgement (file delivery); standard output written although `{batch.output}` is used | `E_PROTOCOL` |
| A missing or extra answer; a one-to-one count mismatch; a missing output file; `{"ok": false}`; a non-zero exit | `E_RUNTIME` |
| A batch output larger than the runner's limit | `E_RESOURCE` |

### Schema changes

`pipe-v0.1`: `batch` (`maxItems`, `maxWaitMs`, `delivery`) and
`batchOverride`; `pipeline-v0.1`: node `batch`; `plan-v0.1`: node `batch`;
`test-v0.1`: test `batch`; `cli-config-v0.1`: top-level `batch`
(`maxItems`, `maxWaitMs`, `delivery`, `dir`); `run-report-v0.1`: node
`batch` (slice statistics); `pipe-v0.1`: `implementation.usage` on
`executable` and `script`.

## Compatibility

Purely additive. A manifest without `batch` behaves exactly as before, and
so does every existing executable. The `batch` key itself is the demand: a
pipe need not list `batch` in `requires` (it may). A runner that does not
implement batch mode for an implementation type rejects the pipe with
`E_UNSUPPORTED` at validation time; it must never run a batch pipe
unbatched, because the program expects a different framing. One existing
shape becomes invalid: a `command` that literally contains
`{batch.<something>}`.

## Security considerations

- Memory per node is bounded by 2 × `maxItems` and latency by `maxWaitMs`;
  both have schema bounds and can only be tightened by consumers.
- Batch files hold record data. They are private to the user (0700/0600),
  removed however the node ends, and never named in reports or errors.
- The implicit access to the batch directory is not a sandbox and not a
  permission: a subprocess can read whatever its user can, which is why
  `subprocess` must be granted as for every executable.
- Placeholders are replaced by runner-generated paths only (no whitespace,
  quotes or metacharacters). Record data and parameters never enter an
  argument vector, and there is no shell.
- Batch mode grants nothing: a pipe that sends batches to a remote service
  still declares `network` and `remoteData`.

## Conformance

`conformance/manifests/{valid,invalid}/batch-*`,
`conformance/pipelines/{valid,invalid}/batch-*` and `conformance/runs/batch/`
(Starlark pipes run under several pinned batch sizes with identical
expectations; one-to-one violation; wrong return type; node settings in a
pipeline). The subprocess framings and the timing of the two-slot rule
cannot be shown portably — there is no interpreter every platform has, and
no portable clock — and are covered by implementation tests (reference
runner: injected clock and a deliberately slow pipe; `sh`, `awk`,
`python3` and a Go helper process; R and DuckDB examples).

## Alternatives considered

- **Do nothing; let each program buffer.** Every program reinvents a flush
  timer, and latency and backpressure become invisible to the runner.
- **`std:batch` in front of the pipe.** That is a *data* transformation:
  arrays become the items, visible downstream, of an exact size with no
  time limit, and the pipe's contract changes. Batch mode leaves the
  streams between nodes untouched.
- **A minimum size.** Deferred: with a wait limit it is redundant in most
  cases and it complicates the end-of-input and timeout rules.
- **Reusing windows.** Windows are semantic and must not be split or
  joined by a runner; batches are the opposite.
- **Letting the consumer switch batch mode on.** A program written per
  record cannot read array lines; only the author knows.
- **Pipelined delivery to subprocesses** (write the next line before the
  answer). Faster for tiny batches, but the operating system's pipe buffer
  becomes an unbounded-looking queue, "in flight" stops being well defined
  and one-to-one cannot be checked per batch.

## Open questions

- ~~Whether `usage` in the file-delivery acknowledgement should be
  available to `lines` delivery too.~~ Resolved: the usage endpoint of the
  CLI protocol (CLI specification, section 5.3, experimental) serves both
  delivery modes and pipes without batch mode.
- Whether a runner should warn when the effective `maxItems` is so small
  that batch mode is slower than per-record streaming.

## Deferred

- **Batching over the HTTP Pipe Protocol.** Out of scope for v0.1: a
  manifest with `implementation.type: http` and `batch` is invalid. An HTTP
  pipe already receives a continuous stream and can group it itself; a
  change to the wire format of the protocol is not justified yet.
- **Batch mode for `builtin` implementations** — nothing to gain (above).
- **A minimum batch size** (`minItems`).
- **Several batches in flight** (parallel workers, "parallelism: N"): needs
  ordered reassembly of outputs and a wider memory bound.
- **Batch files in CSV, Arrow or Parquet.** v0.1 has NDJSON only.
- **Batch mode for pipes with several inputs**, parameter bindings in node
  `batch` settings, and settings addressed to nodes inside a composite.
- **Function-like pipes and TugQL:** a host that calls a batch-mode,
  one-to-one pipe as a scalar function (RFC 0002) could collect the calls
  of one query step into batches. How a host does that — and what a query
  language may assume about it — is future work; today the reference
  runner delivers each scalar call as a batch of one, without waiting.

## Decision

Accepted for experimental implementation on 2026-12-03 by the founder, in
five steps taken the same day: declared batch mode with the size-or-wait
rule; no batch mode for HTTP pipes; batch mode for subprocess and script
implementations only, with the array framing normative; file delivery in
two forms; and the two-slot accumulation model. Implemented in the
reference Go runner (branch `batch-mode`).
