# RFC 0002: Pipes as query-language functions

- **State:** proposed
- **Author(s):** OpenFlange specification lead (founder direction)
- **Created:** 2026-12-03
- **Affected specifications:** `openflange.org/pipe/v0.1` (`cardinality`,
  `deterministic`, function-like pipes), `openflange.org/lock/v0.1` (pinning
  of extensions). No change to the pipeline, CLI, HTTP or registry
  specifications.
- **Feature maturity requested:** proposed (the two manifest fields are
  `experimental` in the Pipe specification; the host contract in this RFC is
  `proposed`)
- **Supersedes / superseded by:** none

## Summary

Query languages that have no extension mechanism of their own can use
OpenFlange pipes as that mechanism instead of growing a private
user-defined-function system. This RFC defines a generic **host contract**:
what a query-language host must do to call pipes safely, reproducibly and
without taking a dependency on any particular OpenFlange implementation. It
defines two forms of extension — the scalar function and the more general
table function (which covers sources and row-stream stages) — both
`proposed`.

The motivating host is TugQL (<https://tugql.org>, Go implementation in
`github.com/dal-go/dalgo/tugql`). Founder direction: TugQL has no extension
points, so pipes become its extension mechanism rather than TugQL defining
its own UDFs.

**Scope boundary.** This RFC specifies obligations of a *host* in
OpenFlange terms. It does not specify TugQL grammar. Any change to TugQL's
grammar, to DALgo, or to OpenVaultDB is a separate proposal subject to those
projects' own approval processes and is **not part of OpenFlange v0.1**. All
query syntax shown here is illustrative.

## Motivation

A query author regularly needs a value transformation the query language
does not have: mask an e-mail address, normalise a phone number, classify a
string. The usual answers are a language-specific UDF system (a second,
incompatible packaging, versioning and security story) or post-processing
outside the query (which loses the declarative description of the result).

OpenFlange already has what a UDF system needs: a contract with typed
ports and parameters, a manifest, version ranges, an integrity-pinning
lockfile, declarative permissions and portable tests. What it lacked was a
way for a pipe to say "I behave like a function". The Pipe specification
now has that:

- `cardinality: one-to-one` — exactly one output item per input item, in
  order, enforced by the runner at run time;
- `deterministic: true` — the same input and parameters always give the
  same output, and the pipe performs no I/O (a declaration; not verifiable
  in general).

A pipe with exactly one input, exactly one output, `scope: record`,
`cardinality: one-to-one` and `deterministic: true` is **function-like**.

## Proposal

A **host** is a query language, engine or library that evaluates queries
and wants to call pipes. An **extension** is a pipe made available to a
query under an alias.

### (a) Extension points

Two forms. Both are `proposed`.

1. **Scalar function.** A function-like pipe applied to one value inside a
   projection. Illustrative: `pipe::mask-email(c.Email) as Email`. The host
   feeds the column value as one item and takes the single resulting item as
   the value of the expression.
2. **Table function.** Any pipe whose inputs are record streams, used as a
   *source* (a derived table) in `from`. Each input is fed by a subquery and
   one output is read as rows. Illustrative (founder's sketch):

   ```
   from pipe:r-stats(
      from Customers
      where ...
      select c.id, c.email
   ) ...
   ```

   The arity of the pipe gives the familiar special cases: a **source pipe**
   (zero inputs) is the zero-argument table function — a pipe used as a
   table; a one-input, one-output records pipe applied to a query result (a
   "row-stream stage") is the one-argument case; multi-input pipes (joins,
   lookups) take several subqueries.

The table form is the more general of the two and probably the more
valuable: it admits window- and dataset-scope pipes (statistics, models),
multi-port pipes and sources, none of which fit a scalar call. The scalar
form is the cheaper one to implement and to secure.

A host MUST refuse to use as a scalar function any pipe that is not
function-like. In particular a pipe such as the reference `mask-email`,
which can route an item to a `rejected` output instead of producing a
result, is not one-to-one and cannot be called as a scalar function as it
stands; a function-like variant has to define a result for every input. (As
a table function it is fine: see the output-selection rule below.)

### (b) Declaration and pinning

Extensions MUST be declared up front, by alias, with a pipe reference and a
version range, in a part of the query that can be read without evaluating
it. Illustrative, mirroring TugQL's existing `databases (` block:

```
pipes (
  mask-email = "openflange/mask-email-fn@^0.1"
)
```

Every declared extension MUST be pinned in an `openflange.lock.yaml`
(Lockfile specification) by integrity. A host:

- MUST NOT evaluate a query that uses an extension which is not declared;
- MUST NOT resolve an extension from ambient state (a search path, an
  installed-package directory, the network) at evaluation time;
- MUST verify the pinned integrity before first use and fail with a
  diagnostic equivalent to `E_LOCK` when it is missing or differs.

A query therefore never runs an unpinned or ambient pipe, and the set of
code a query can execute is visible in its header.

### (c) Evaluation model (scalar form)

Pipes are opaque to the engine. Extension evaluation happens **after the
engine has returned rows**; a host MUST NOT push a pipe call down into a
storage engine, and MUST NOT assume algebraic properties (for example
monotonicity or injectivity) of a pipe.

Consequently a construct whose correct evaluation would need the piped
value *before* rows are returned — filtering, joining, grouping or ordering
on it — cannot be delegated to the engine. A host MUST refuse such a
construct, with a diagnostic naming it, unless the host itself defines and
documents client-side semantics for it. Silently fetching all rows and
filtering client-side is not permitted by this RFC.

### (d) Value mapping (scalar form)

- A column value is passed as one JSON item on the pipe's input, which is
  consumed as a `values` stream; the result item is taken from the output.
- Numbers MUST be mapped losslessly in both directions (integers beyond
  2^53 and decimals keep their exact value); a host type that cannot be
  represented exactly as a JSON value MUST be refused rather than rounded.
- SQL-style `NULL` maps to JSON `null` and is passed to the pipe; the host
  MUST NOT short-circuit nulls unless the pipe's input schema excludes
  `null`, in which case the host MUST either yield `NULL` without calling
  the pipe or fail — and MUST document which.
- Pipe parameters are bound from literals or from query parameters only.
  They MUST NOT be bound from column values: parameters are immutable for a
  node execution, and per-row parameters would defeat that.
- The declared output schema of the pipe gives the static type of the
  expression. A pipe with an untyped output yields a dynamically typed
  value; a host with static typing MAY refuse it.
- If the declared input schema is demonstrably incompatible with the
  argument's type, the host MUST reject the query before execution.

### (d2) Table-function contract

**Arguments.**

- Each input port is fed by exactly one subquery. A single-input pipe takes
  one positional subquery; a multi-input pipe takes named arguments, one per
  port (illustrative: `left = (...)`, `right = (...)`). A required input
  without an argument is refused; an optional input MAY be omitted and is
  then disconnected.
- Parameters are named scalar arguments bound from literals or query
  parameters only.
- Subqueries are **uncorrelated**: they cannot refer to rows of the
  enclosing query. There are no lateral semantics in phase 1.

**Output selection.**

- A pipe with a single output yields that output.
- A multi-output pipe requires the port to be named at the call site
  (illustrative: `.rejected`, or `output rejected`).
- Every output that is *not* selected MUST be optional; it is then
  disconnected, and the pipe's documented behaviour for a disconnected
  optional output applies. If an unselected output is required, the host
  MUST refuse the query. There is no silent discard.

**Schema.** The declared schema of the selected output port defines the
columns and types of the derived table. An untyped output cannot be
resolved statically, so a host MUST require either a typed port — a JSON
Schema object schema with `properties` — or an explicit column declaration
at the call site, and MUST otherwise refuse the query. Rows that do not
match the declared or stated columns fail the query; they are not coerced.

**Evaluation.**

1. The engine runs each subquery; push-down applies *inside* the subquery
   exactly as it would without the pipe.
2. The resulting rows are streamed into the pipe's inputs as records.
3. The pipe's selected output stream is treated like a table from another
   database. Everything composed on top of it — `where`, `join`,
   `group by`, `order by`, `limit` — is evaluated by the host's
   engine-independent executor, as for cross-database (federated) queries,
   and is **never pushed down** past the pipe.

A host without such an executor MUST restrict what may follow a pipe source
(for example to projection only) and MUST refuse anything else, rather than
approximate it.

**Streaming and bounds.**

- `record`-scope pipes stream: rows flow with bounded memory and
  backpressure.
- `window`- and `dataset`-scope pipes (for example an R statistical
  summary) materialise their input. A host MUST apply row and byte limits
  to what it feeds such a pipe and, on reaching a limit, MUST either fail
  the query explicitly or report the truncation with the result. It MUST
  NOT truncate silently.
- Cancellation and fail-fast follow the Pipeline specification: cancelling
  the query cancels the run; a pipe failure fails the query; rows already
  delivered are not rolled back.
- Row order is guaranteed only as far as the pipe declares it. A host MUST
  NOT assume that an output preserves the order of the subquery unless the
  pipe is `one-to-one` or documents it.

**Authorization and lineage.** Unless a pipe declares finer lineage (an
open question), every field of a pipe's output is derived from **all**
fields of **all** its inputs. A host with field-level authorization MUST
authorize the subqueries' fields for the caller *before* invoking the pipe,
and MUST treat the output accordingly.

**Security.** The rules of (f) apply unchanged. Table functions more often
need `subprocess` or `network` (R, Python, HTTP services); a
security-sensitive host such as a vault refuses those. Only pipes that are
granted, allowlisted and integrity-pinned run, and never by default.

### (d3) Worked examples (illustrative syntax)

All syntax below is illustrative; aliases come from the `pipes (` header
block of (b).

A dataset-scope summary over a filtered subquery, returning one row. With
values 10, 20 and 30 the result row is `count = 3, mean = 20, median = 20,
sd = 10` (the `r-summary` fixture of the Pipe specification):

```
pipes ( stats = "openflange/r-summary@^0.1" )

from stats::(
   from Orders o
   where o.customerId = @customer
   select o.total as value
)
select count, mean, median, sd
```

A window pipe over an ordered subquery (ordering is the subquery's job;
the pipe sees rows in the order the engine returns them). The call states
the columns because a `windows` output has no column schema:

```
pipes ( window = "std:window@0.1" )

from window::(
   from Readings r order by r.at select r.at, r.value
)(size = 10, step = 1) columns (window object, items array)
```

A multi-output pipe, selecting a non-default output. `valid` is a required
output of `validate-email`, so selecting only `rejected` is **refused**
unless the query also consumes `valid` or the pipe marks it optional — the
host must not discard it silently:

```
pipes ( check = "openflange/validate-email@^0.1" )

from check::(from Customers c select c.id, c.email).rejected
select record, reason          -- refused as written: `valid` is required
```

With a pipe (or a wrapper composite) that declares `valid` as
`required: false`, the same query is accepted and returns one row per
rejected record. This is deliberate: the contract, not the query, decides
what may go unread.

A zero-input source pipe used as a table:

```
pipes ( rates = "acme/exchange-rates@^1" )

from rates::() r
where r.currency = 'EUR'       -- evaluated by the host, not pushed down
select r.currency, r.rate
```

### (d4) Surface syntax options (illustrative, owned by the host language)

The table-function form needs *a* spelling; which one is the host
language's decision. Two are sketched here. Neither is a third extension
point.

**Call form.** `alias::( subquery )` with named arguments and an output
suffix, as in the examples above. TugQL already uses `alias::path` for
database-qualified sources and a `databases (` header block, so a declared
alias from a `pipes (` block — `stats::(...)`, or a fixed `pipe::r-stats(...)`
— would be consistent with the existing language.

**Pipe operator (sugar).** `source | pipe` is exactly the single-input
table function applied to that source. Chains read left to right, which
mirrors Unix pipes and the OpenFlange name:

```
from Customers | lowercase-emails | mask-emails
```

Parameters are a call suffix (`| window(size = 10)`); a non-default output
is a port suffix (`| check.rejected`).

**Placement rule (RECOMMENDED).** The bar follows a **complete, closed
query**, or a bare source name. It never appears between the clauses of an
open query. Concretely, a bar may follow:

- the closing parenthesis of a CTE body or of a subquery — the CTE name
  then binds to the output of the *whole chain*:

  ```
  with Stat as (
    from Customers as c
    ...
  ) | some-transform-pipe | some-stats-pipe
  ```

- the last clause of the top-level query — the query result flows through
  the chain;
- a bare source name: `from Customers | p`. The whole collection flows
  through the pipe and every later clause applies to the pipe's output,
  evaluated by the host's engine-independent executor. Nothing after the
  bar is pushed down, so a host SHOULD warn about, or refuse, streaming an
  unfiltered collection through a pipe this way.

With this rule there is no question of which clauses run before or after
the pipe: **everything inside the parentheses runs first and is pushed
down as usual; everything outside sees the pipe's output.** A host that
adopts the operator MUST define its placement unambiguously, and SHOULD
adopt this rule. The CTE form is the primary idiom because the filter
visibly happens before the pipe; it also fits TugQL's existing formatting
rule that block closers sit on their own aligned line.

Limits of the operator: a single input per bar (multi-input pipes need the
named-argument call form); parameters as a call suffix and `.port` for a
non-default output, as above; uncorrelated; and the same pinning, schema,
bounds, authorization and security rules as the table form, of which it is
only a spelling.

Lexical notes for TugQL specifically (as reported by the founder from
`github.com/dal-go/dalgo/tugql/tugql_lex.go`; not re-verified by this
RFC's author): `||` is already a token and a single `|` is currently
unused. Hyphenated pipe ids (`r-stats`, `mask-email`) collide with the
minus operator and need an alias from the header block, or quoting.

The grammar decision belongs to the TugQL project.

### (e) Resolver and runner injection

The query-language library MUST NOT depend on an OpenFlange implementation.
Instead the host application injects two capabilities:

- a **resolver** — maps a declared reference plus lockfile to a verified
  pipe;
- a **runner** — evaluates a function-like pipe over values.

A host with no resolver or runner injected MUST fail closed: a query that
declares extensions is rejected with a clear diagnostic stating that pipe
extensions are not available in this host. It MUST NOT ignore the
declaration or substitute an identity function.

### (f) Security

Calling a pipe from a query executes third-party code inside the query
path. In security-sensitive hosts — for example a user-data vault such as
OpenVaultDB — the following profile applies:

- extension support is **off by default** and enabled explicitly;
- only **in-process** implementations (`builtin`, Starlark `expression` or
  `script`, composites of those) with **no declared or implied
  permissions** are accepted; `executable` and `http` implementations are
  refused;
- extensions are **allowlisted** by the host operator and
  **integrity-pinned**; the query's own declaration cannot widen the
  allowlist;
- `deterministic: true` is a claim by the author. It is credible only for
  implementations that cannot perform I/O, which is why the profile above
  restricts implementations.

General hosts SHOULD adopt the same profile unless they implement the full
permission model (enforce or refuse) of the Pipe specification.

**Future work (not this RFC).** Function-like pipes create an opportunity
for capability grants of the form "field X is readable only through pipe
P@version" (for example: the e-mail column only through a masking pipe).
That belongs in an RFC of the project that owns the authorization model.

### (g) Portability

A query that uses an extension runs only where that pipe can run. This is
explicit, because the extension is declared in the query header. An
implementation of the query language without an OpenFlange runtime cannot
evaluate such a query and MUST say so rather than produce a different
result.

## Compatibility

`cardinality` and `deterministic` are optional manifest fields with
defaults (`any`, `false`); existing manifests are unaffected. A runner that
predates them rejects manifests that use them as unknown top-level keys
(`E_MANIFEST`), which is the safe failure. No `requires` feature is needed:
the fields constrain the pipe, not the runner's stream model.

## Security considerations

See (f). Additionally: evaluation cost is controlled by the pipe author,
so hosts SHOULD bound per-call execution (steps or time) and fail the query
on excess; error messages from pipes can contain row data and MUST be
treated as sensitive in logs.

## Conformance

Phase 1 fixtures (not yet written): a function-like manifest
(`conformance/manifests/valid/function-like` exists), a run fixture showing
that a script declaring `cardinality: one-to-one` fails with `E_RUNTIME`
when it emits zero or two items for one input, and host-side fixtures owned
by the host project.

## Alternatives considered

- **A TugQL-native UDF system.** Rejected by founder direction: a second
  packaging, versioning and permission model.
- **Allowing any single-input single-output pipe as a function.** Rejected:
  without `one-to-one` the expression has no defined value for some rows.
- **Push-down of known pipes.** Rejected for now: it requires engines to
  understand pipe semantics and breaks opacity.

## Non-goals

Defining TugQL grammar; changing DALgo or OpenVaultDB; push-down or query
optimisation across pipe calls; SQL-style aggregate or analytical window
functions implemented by scalar pipes; per-row parameters.

## Open questions

- **Errors:** fail the whole query on the first failing row (consistent
  with fail-fast runs), or allow a per-row error value?
- **Batching:** may a host send many values through one node execution
  (yes in principle — it is a stream), and what batch sizes are sensible?
- **Caching** of results of `deterministic` pipes within and across
  queries, and its interaction with integrity pinning.
- **Lineage and authorization** of derived fields: is `mask(email)` still
  "email" for access control?
- **Ordering** of a trailing pipe relative to `ORDER BY` and `LIMIT`:
  before or after, and who decides.
- **Finer lineage:** should a manifest be able to declare which output
  fields derive from which input fields?
- **Correlated (lateral) table functions**, deferred from phase 1.
- **Multiple outputs in one query** (consuming both `valid` and
  `rejected` from a single execution).
- Whether `deterministic` should imply a machine-checkable "no permissions,
  in-process" constraint in the manifest schema.

## Deferred

Lateral/correlated table functions; consuming several outputs of one
execution; capability grants bound to pipes.

## Decision

Pending.
