# RFC 0004: Parallel instances and declared order sensitivity

- **State:** draft — under consideration by the founder; **not implemented**
  by any runner
- **Author(s):** OpenFlange maintainers
- **Created:** 2026-12-03
- **Affected specifications:** `openflange.org/pipe/v0.1` (new 5.8, 6),
  `openflange.org/pipeline/v0.1` (3.2, new 3.9, 6.5, 8.1, new 8.12, 10,
  11), `openflange.org/cli/v0.1` (9.1, 5)
- **Feature maturity requested:** proposed (feature identifier `parallel`)
- **Supersedes / superseded by:** none

## Summary

A pipe may declare that **several instances of it can run side by side**
on disjoint parts of its input: `concurrency: {safe: true, maxInstances:
N}`. The default is "not safe". An input port may declare that the pipe
**depends on the order of its items**: `inputs.<port>.ordered: true`. Order
matters for windows, running totals, `limit` and "first wins"
de-duplication. A pipeline node then asks for `parallel: N` instances
(`N ≤ maxInstances`) and chooses `order: preserve` (the default) or
`order: any`. With `preserve`, the runner reassembles the output in input
order through a bounded reorder buffer. With `any`, it emits output as it
completes. Validation refuses any path on which an `order: any` stream
reaches an `ordered: true` port.

## Motivation

Batch mode (RFC 0003) removes the per-record cost of a call. It does not
help when **one call is slow and the work is independent**: a language-model
request that takes two seconds, an enrichment API with per-request latency,
a CPU-bound R or Python step that uses one core of an eight-core machine.
The batch benchmark (`openflange-go/benchmarks/batch`) shows that a pipe
whose call costs a fixed 5 ms is capped at 200 calls per second, whatever
the batch size. Running several calls at once is the remaining lever.

Today a pipe author can parallelise only inside the program, with a private
thread pool. The runner then knows nothing about it. Backpressure,
cancellation, memory bounds and the order of the output become the
program's problem, and every author solves them again, usually by holding
the whole input in memory.

The runner cannot simply parallelise every pipe:

- Many pipes keep state across items. Examples: `std:window`, a running
  total, `std:limit`, de-duplication, an R script that reads the whole input
  (`scope: dataset`). Two instances of these would each see half of the
  stream and produce wrong results.
- Some pipes are stateless but **order-sensitive downstream**: their output
  is correct item by item, but a later window or `limit` relies on the
  items arriving in order.

So the declaration has to come from the people who know: the pipe author
says whether instances may run side by side, and which inputs depend on
order. The consumer, who knows the machine and the budget, chooses how
many instances to run and whether output order matters for this pipeline.

## Proposal

### Pipe: `concurrency`

```yaml
concurrency:
  safe: true            # default false
  maxInstances: 8       # integer ≥ 1; default 1
```

| Key | Type | Meaning |
|---|---|---|
| `safe` | boolean, default `false` | Instances of the pipe MAY run concurrently, each on a disjoint part of the input, and the union of their outputs is a correct output of the pipe for the whole input. |
| `maxInstances` | integer ≥ 1, default `1` | The largest number of instances the author vouches for. Examples: a rate limit, a licence, memory per instance. `maxInstances > 1` requires `safe: true` (`E_MANIFEST`). |

`safe: true` is a promise by the author:

1. **No cross-item state.** The output for an item (or, in batch mode, for
   a slice) depends only on that item or slice and the parameters. It does
   not depend on other items, on how the input is partitioned, or on what
   other instances do.
2. **No shared mutable resources** that make instances interfere, for
   example a fixed output file name or a local database without locking.
   Resources that are designed for concurrent use, such as an HTTP API, are
   fine.
3. **Scope.** `safe: true` is valid only with `scope: record` (the default)
   or `scope: window` (each window frame is one item, 8.1; frames are never
   split). With `scope: dataset` it is `E_MANIFEST`.

`concurrency` is invalid on `pipeline` implementations (`E_MANIFEST`). A
composite pipe is not parallelised as a whole; its nodes are, individually.
On `builtin` implementations it is the runner's own declaration: a standard
pipe such as `std:map` MAY declare `safe: true`.

### Pipe: `inputs.<port>.ordered`

```yaml
inputs:
  records:
    ordered: true       # default false
```

`ordered: true` states that the pipe's output depends on the **order** of
the items on this port, not only on the items themselves. It is
descriptive: it constrains what may feed the port (below), not how the
pipe runs. It is independent of `concurrency`. A pipe whose input is
`ordered` is normally not `safe`, but the two are separate statements.

Standard pipes that would declare `ordered: true`: `std:window`,
`std:window-processing-time`, `std:limit`, `std:skip`, `std:distinct` (the
first occurrence wins), `std:merge` with `mode: concat`. Ports of
`scope: dataset` pipes are **not** implicitly ordered: an R summary over a
whole dataset typically is not. The author declares it when it is.

### Pipeline node: `parallel` and `order`

```yaml
nodes:
  enrich:
    pipe: ./pipes/enrich          # concurrency: {safe: true, maxInstances: 8}
    inputs:
      records: {from: clean.outputs.out}
    parallel: 4                   # run 4 instances
    order: preserve               # default
```

| Key | Type | Meaning |
|---|---|---|
| `parallel` | integer ≥ 1, default `1` | Number of instances. MUST be ≤ the pipe's `maxInstances`; `parallel > 1` on a pipe that is not `safe` is `E_PARAM`. |
| `order` | `preserve` \| `any`, default `preserve` | Whether each output stream of the node keeps the input order. Meaningless and ignored with `parallel: 1`. |

Rules:

1. **Tighten only, as for batch.** `openflange run --parallel
   [node=]N` and `--order [node=]any|preserve` (CLI 9.1) set or lower
   `parallel` for a run. They never raise it above `maxInstances`.
2. **`order: preserve` needs attributable output.** To reassemble output in
   input order, the runner must know which input unit each output item
   answers. It knows this when the pipe declares `cardinality: one-to-one`,
   when it runs in batch mode (one answer per slice, CLI 5.1/5.2), or when
   it is a Starlark pipe (one call per item). For any other pipe,
   `order: preserve` with `parallel > 1` is `E_UNSUPPORTED`: the consumer
   chooses `order: any` or `parallel: 1`.
3. **Single input.** In this proposal `parallel > 1` is allowed only for
   pipes with exactly one *enabled* input. Inputs that every instance would
   need in full (lookup tables, side inputs) are an open question.

### Ordered streams and validation

Every stream in a plan is **ordered** (its items are in the order its
producer emitted them, 8.1 as today) or **unordered**:

- The outputs of a node with `parallel > 1` and `order: any` are
  unordered.
- The outputs of any node that has an unordered input are unordered, unless
  the pipe declares that it **establishes** order. A sorting pipe is the
  obvious case (std v0.1 has none); the mechanism is an open question.
- Pipeline inputs are ordered. Outputs of `std:merge` are ordered per input
  as today (8.1); `interleave` is not "unordered" in this sense, because
  each input's order is kept.

A runner MUST refuse, before anything runs, a plan in which an
**unordered stream reaches an `ordered: true` port**. The error is
`E_SCHEMA` (alternative: a new `E_ORDER`, open question). It names the
port, the node that made the stream unordered, and the path between them:

```
E_SCHEMA: input "in" of node "first-100" (std:limit) needs its items in order,
  but node "enrich" runs 4 instances with order: any
  path: enrich → clean2 → first-100
  hint: set `order: preserve` on node "enrich", or remove the order-sensitive step
```

`validate --plan` shows, for each edge, whether its stream is ordered. It
also shows each node's `parallel` and `order` (plan schema, 6.5).

### Execution

**Units.** The runner hands work to instances in **units**: one item, or
one slice when the pipe runs in batch mode. Units are numbered in input
order. A unit is processed by exactly one instance. Which instance gets
which unit is the runner's choice (round robin, least busy). It carries no
meaning: a `safe` pipe gives the same multiset of output whatever the
assignment.

**Instances.** An instance is whatever one execution of the implementation
is:

- a process, for executables and subprocess scripts;
- a session, for `http` pipes;
- an interpreter thread, for Starlark.

Each instance receives the same parameters, grants and configuration
document. The CLI configuration gains `instance: {index, count}` (CLI 5),
for logging only. A pipe MUST NOT change its output based on it.

**`order: preserve`.** The runner emits a unit's output only after the
output of every earlier unit. Units completed out of turn wait in a
**reorder buffer**, which is bounded:

- at most `parallel` units in flight, plus at most `R` completed units
  waiting (default `R = 2 × parallel`; a runner MAY make it configurable;
  it MUST be finite);
- when the buffer is full, no new unit is dispatched until the oldest unit
  completes (head-of-line blocking). Backpressure then reaches the
  producer as in 8.2.

With `order: preserve`, the output of a `safe` pipe at `parallel: N` is
**identical**, item for item and in order, to its output at `parallel: 1`.
Conformance fixtures can test exactly that.

**`order: any`.** Output is emitted as units complete. Per instance, the
order of its own units is kept; across instances it is unspecified. The
multiset of output items equals that of `parallel: 1`.

**Memory bound.** A parallel node holds at most `parallel` units in flight,
`R` completed units, and the unit being accumulated or read. In batch mode
that is at most `(parallel + R + 1) × maxItems` items. This replaces the
2 × `maxItems` of 8.11 for such nodes. The bound MUST be stated in
`validate --plan`.

**Batch mode with several batches in flight.** Batch mode and `parallel`
compose: the slicer of 8.11 fills one accumulating slice, and every ready
slice goes to an idle instance. Up to `parallel` slices are in flight at
once, instead of one. `maxWaitMs` still applies to the accumulating slice
only. With file delivery, each in-flight slice has its own input and output
file, so the on-disk bound grows the same way. Batch statistics in the run
report (10) are per node, summed over instances, with an added
`maxInFlight`. The one-to-one check of 8.11 applies per slice, as today.

**Failure and cancellation.** If an instance fails on a unit, the node
fails (8.7) and the other instances are cancelled (8.8). With `preserve`,
output of units after the failed one that is still in the reorder buffer is
**discarded**, never emitted, so the emitted output is always a prefix of
the `parallel: 1` output. With `any`, output already emitted stays (8.7).
No unit is retried in this proposal.

**Usage and counters.** Usage counters (CLI 5.3) of all instances are
summed. Port counters count items, never units, as before.

### Run report

`nodes.<id>` gains `parallel: {instances, order, maxInFlight,
reorderHighWater}` (experimental).

### Schema changes

- `pipe`: `concurrency` object; `ordered` boolean on input ports.
- `pipeline`: `parallel` and `order` on nodes.
- `plan`: `parallel`, `order` per node; `ordered` per edge; memory bound.
- `run-report`: `nodes.<id>.parallel`.
- `cli-config`: `instance`.

## Compatibility

All new keys are optional, and their defaults (`safe: false`,
`ordered: false`, `parallel: 1`, `order: preserve`) give today's
behaviour exactly. A pipe that declares `concurrency` or `ordered` must list
the feature `parallel` in `requires` only if it cannot work without it. As
written it can, because a runner that ignores the declaration runs one
instance, which is always correct. A **pipeline** that sets
`parallel > 1` on a runner without the feature gets `E_UNSUPPORTED`. A
runner could run it serially instead; whether that is allowed is an open
question.

Declaring `ordered: true` on existing standard pipes adds validation errors
only to pipelines that use `order: any`, which do not exist yet.

## Security considerations

- **Resource multiplication.** `parallel: N` multiplies CPU, memory,
  processes, open files and outbound requests by N. The pipe's
  `maxInstances` caps what a consumer can ask for. A runner SHOULD also
  have a global cap (for example `--max-instances` or a default of the CPU
  count) and MUST report `E_RESOURCE` rather than exceed it silently.
- **Rate limits and cost.** A pipe that calls a paid API at `parallel: 8`
  spends eight times as fast. `maxInstances` is where the author encodes
  a provider's limit. `--parallel` on the command line can only lower it.
- **No new data flows.** Instances receive the same grants. Permissions are
  checked once per node, not per instance. Secrets go to every instance,
  as they would to one.
- **Isolation between instances** is not provided. A `safe` pipe that
  writes to a shared location without locking is a bug in the pipe, not a
  runner error. The runner cannot detect it.

## Conformance

Fixtures that would demonstrate the behaviour:

- `manifests/invalid/concurrency-*`: `maxInstances > 1` without `safe`;
  `safe` with `scope: dataset`; `concurrency` on a `pipeline`
  implementation.
- `pipelines/invalid/parallel-*`: `parallel` above `maxInstances`
  (`E_PARAM`); `parallel > 1` on an unsafe pipe (`E_PARAM`); `order: any`
  into `std:limit`, directly and through an order-transparent node
  (`E_SCHEMA`); `order: preserve` on a pipe whose output is not
  attributable (`E_UNSUPPORTED`).
- `runs/parallel/`: a Starlark pipe that sleeps a pseudo-random time per
  item, run at `parallel: 4, order: preserve`. Its output must equal the
  serial output byte for byte. With `order: any`, the test asserts the
  multiset only (`ordered: false` in the test expectations, which exists
  today).
- A batch-mode variant that asserts `maxInFlight ≤ parallel` from the run
  report.

## Alternatives considered

- **Do nothing; parallelise inside the program.** That works today, but it
  hides concurrency from the runner. The runner then cannot bound memory,
  apply backpressure, cancel cleanly or keep output order. It also does
  not help pipes their authors did not write for concurrency.
- **The runner decides automatically** for every `cardinality: one-to-one`,
  `deterministic` pipe. One-to-one and deterministic do not imply safe. A
  pipe can be both and still use a local cache file, a connection with
  session state, or a rate-limited key. The author has to say it.
- **Parallelism declared only on the pipe** (`parallel: 4` in the
  manifest). The author does not know the machine, the budget or whether
  the consumer needs order. The split is author: *may*, consumer: *how
  many* and *in which order*. It mirrors batch mode's author: *largest*,
  consumer: *tighten*.
- **Order as a property of streams only, with no `ordered` on ports.**
  Every pipe would then have to be treated as order-sensitive, and
  `order: any` would be refused almost everywhere. The alternative is to
  accept it everywhere and silently break windows and limits.
- **Partitioned parallelism (`partitionBy`)**: route items with the same
  key to the same instance, which would make stateful per-key pipes
  parallel. It is valuable, and it is how `std:window` with `partitionBy`
  could scale. It needs a key expression, skew handling and per-partition
  order. It is deferred.

## Open questions

1. **Error code.** Is an unordered stream into an `ordered` port
   `E_SCHEMA`, or should it be a new `E_ORDER`? The former reuses "this
   edge is incompatible", the latter is clearer in tooling.
2. **Order-establishing pipes.** How does a sorting pipe say
   that its output is ordered whatever its input order? One option is
   `orders: true` on an output port. Another is to treat every
   `scope: dataset` pipe as order-establishing, which is wrong for a
   pass-through.
3. **Side inputs.** May a `safe` pipe with a second input run in parallel if
   that input is broadcast in full to every instance (a lookup table)? That
   needs a declaration, for example `inputs.lookup.broadcast: true`, and
   multiplies the memory for that input by `parallel`.
4. **Fallback.** May a runner without the feature run `parallel: N` as 1
   (always correct), or must it refuse? Refusing is honest about
   performance; running is more portable.
5. **Default reorder capacity `R`.** Is `2 × parallel` right for slow,
   variable calls (LLM requests), where one slow unit stalls everything
   behind it? Should `R` be a node setting?
6. **`order` per output port.** A pipe with a `valid` and a `rejected`
   output might want `rejected` in any order and `valid` preserved. Is the
   node-level setting enough?
7. **`maxInstances` default when `safe: true`.** Is 1 (useless until raised)
   too conservative? Is "unbounded" too generous, given cost? A middle
   ground is "the runner's global cap".
8. **Retry.** With independent units, retrying a failed unit (an API
   timeout) becomes possible. Should the spec say anything now, or leave it
   to a later RFC?
9. **Determinism of `order: any` in tests.** Should `openflange test` run
   `order: any` nodes with a shuffled completion order, to catch pipelines
   that depend on the order by accident?

## Deferred

- Partitioned (keyed) parallelism, see the alternatives.
- Distributed execution: instances on other machines.
- Automatic choice of `parallel` from measured throughput.
- Parallel composite pipes (a whole sub-pipeline per instance).

## Decision

Not decided. This draft records a design the founder is considering. No
runner implements it, and nothing in the v0.1 specifications changes until
it is accepted.
