ADR-0069: ctx.read and ctx.spark: inputs named inside the model body¶
Architecture: Section 4, Configuration and section 5, Core protocols. Amends ADR-0050 points 2, 3, 8, 11 and 13.
Context¶
- Since 0.9 a model's inputs are its parameters, bound by name or through
inputs=(ADR-0050 point 3). A model that reads many tables carries all of them in its signature. Code brought from notebooks or SQL tools names its tables in the body instead:ref()in dbt SQL,spark.table(...)andspark.sql(...)in PySpark. ctx.engine.nativealready exposes the engine's native session (theSparkSessionon Spark). A table read through it is invisible to the plan: no edge in the graph, so no run order, no lineage and nostate:modifiedpropagation. The name must also be the physical one, which differs per target (a Delta path on the filesystem catalog,catalog.schema.tableon Unity Catalog).- The author's earlier prototype gave models a session wrapper. Its
table()resolved model names to physical names, and itssql()passed queries through unchanged. - 1.x constraints: changes are additive (ADR-0016, stability). Nothing is added to
EngineSessionorStateStore; an optional member lives in its own protocol, reached through a core helper (ADR-0016 amendment 1.1). The core never imports a plugin. sqlglot is an optional extra, imported only by the modules the import-linter contract lists (ADR-0050 point 8). An unchanged project keeps its plan hash and 1.0 checksum (ADR-0052). - Dependencies are declared, never traced at run time (architecture section 4). The plan, the unit graph, Airflow assets and OpenLineage all read
node.inputs.
Options¶
- How a read in the body reaches the plan.
- Static: the compiler finds calls with literal arguments in the decorated function and turns them into inputs, as dbt does with
ref(). Chosen. - Runtime only: the body reads any name and the plan never knows. Rejected: no ordering and no lineage, and a read of a model that has not run yet returns stale data.
- An explicit
depends_on=on@modelnext to free-form reads. Rejected: the same dependency is written twice, and the two copies drift. - What
ctx.readmay name. Only inputs already bound (sugar), which leaves the signature as long as before. Or any model or source, creating the input when it is not bound yet. The second is chosen. - A non-literal argument. An error (chosen), or a warning with a runtime fallback (rejected: the fallback is a read outside the plan).
- Where the Spark wrapper lives.
- In the core, duck-typed over
ctx.engine.native. Rejected: the core cannot compute a physical Spark name, because identifier quoting, the default catalog and the Delta path rule live in the Spark plugin's catalogs. - A new
EngineSessionmethod. Not allowed in 1.x. - In
pipeloom-spark, reached through an optional protocol and declared by a capability. Chosen. - How
ctx.spark.sqlrewrites names. - A regular expression. Rejected: it cannot tell a table from a CTE, a column, a string or a comment.
- Bind each name to a DataFrame through
spark.sql(query, **frames), asctx.sqldoes on Spark. Rejected: the query would no longer name physical tables, which is whatctx.sparkusers ask for, and it duplicatesctx.sql. - Parse with sqlglot in the Spark dialect, replace resolved table references with physical names and generate the query again. Chosen.
Decision¶
ctx.read.ModelContext.read(name: str | SourceRef) -> Any.ctx.read("orders")reads a model, or any input by its alias (point 3).ctx.read(source("tpch", "orders"))reads a source table;sourceis the existing helper.- It returns the input as a parameter would receive it: the native frame, or a Narwhals frame under
frame_api: narwhals. - When the input is the model's incremental input, the frame comes after the incremental filter, and for an interval model it is limited to the window (ADR-0054).
-
It coexists with parameters and
inputs=; one model may use all three. -
Static discovery. For each discovered model, the AST resolver walks its function body, nested functions and lambdas included. It records these calls:
ctx.read(<str literal>)andctx.read(source(<str literal>, <str literal>)). Herectxis the function'sctxparameter, andsourceis recognised by the import rules of ADR-0050 point 2.ctx.spark.table(<str literal>)andctx.spark.sql(<str literal>, ...).ctx.sparkmay also be used through a local name assigned exactlyname = ctx.sparkin the same function.
A first argument that is not a literal is PLK607 at the call's line and column. That covers a variable, an f-string, a concatenation, or source() with a non-literal argument. A function without a ctx parameter has no reads.
- Static modules. Reads are parse data, cached with the model. The discovery cache schema becomes 2.
- Dynamic modules and factories. After import, each marked function is matched to its def in the parsed file by __code__.co_name and __code__.co_firstlineno, and that def is scanned. A factory calling ctx.read(var) gets PLK607. It should declare the input in its decorator instead (inputs={"src": ref(upstream)}) and call ctx.read("src"). A function whose def is not in its file (built with exec, or a lambda) has no reads.
- Helpers. A read inside a helper outside the model function is not seen, for example def load(ctx): return ctx.read("x"). At run time it is PLX123.
- Binding and aliases. Reads bind after parameters and
inputs=, in source order, with the rules of ADR-0050 point 3. ctx.read("x"). Ifxis already an alias of the model, the call reads that input. Otherwisexbinds like a bare name: the model namedx(never the model itself), else the one source table namedx, else PLR201. A tablexin several groups is PLR210. The new alias isx.ctx.read(source("g", "t")). If an alias of the model already bindssource.<project>.g.t, the call reads that input. Otherwise the new alias ist. An unknown group or table is PLR201.- Alias collision. If the new alias is taken by another input, or is not a valid alias (
ctxor a Python keyword), it is PLR211 at the call. Example: a parameterordersbound to a model, plusctx.read(source("tpch", "orders")). Fix:inputs={"tpch_orders": source("tpch", "orders")}andctx.read("tpch_orders"). - Duplicates. Reading the same input twice, or reading an input a parameter also binds, is one input with one alias.
ctx.sparknames. A one-part name binds likectx.read("x"). A two-part nameg.tbinds likectx.read(source("g", "t"))when groupgdeclares tablet.-
Incremental.
incremental.inputmay name an alias created by a read. -
Run time.
- The runner reads every input of the node before calling the function, as today.
ctx.readreturns the prepared frame for the alias its argument resolves to: the alias itself for a string, or the alias bound to that source id. Repeated reads return the same frame. - An argument that is not an input of the node is PLX123.
- Aliases bound only by reads are never passed as arguments, even when the function takes
**kwargs(point 9 says how the runner knows). - In view mode,
ctx.readreturns the placeholder a parameter gets; any use other than naming the alias inctx.sqlis PLX120. - In an inlined ephemeral model,
ctx.readreads that model's own inputs. pipeloom testgives rows to read aliases like any input (givenkeyed by alias, PLR208 when rows are missing).-
Outside pipeloom, as in a plain pytest,
ctx.readraisesRuntimeError, asctx.sqldoes. -
ctx.sql.ctx.sqlsees every input by alias, read aliases included, and PLK603 counts them as declared. Table names inctx.sqlqueries stay aliases and create no inputs. Onlyctx.spark.sqlcreates inputs. -
ctx.spark. On an engine with a Spark session,ctx.sparkis a thin wrapper around the session. table(name)returns the inputnameresolves to. It reads through the same path as the runner's input reads: the catalog plugin, plus--deferand the reference relation (ADR-0042). The incremental filter is not applied. A name that resolves to nothing goes toSparkSession.tableunchanged.sql(query, *args, **kwargs)parsesquerywith sqlglot in the Spark dialect, replaces every table reference that resolves to an input with its physical name, and passes the new text and all other arguments toSparkSession.sql.- A query with nothing to replace is passed byte for byte.
- A replaced table without an alias gets its written name as alias, for example
delta.`/w/orders` AS orders, so column references qualified by the table name still resolve. - Parameter markers (
:name,?) and{name}DataFrame format fields are kept. A format field is never a table name.
- Every other attribute (
read,createDataFrame,conf,catalog, ...) is the session's own. - Name resolution is the same at compile time and at run time.
- A one-part name equal to an alias of the model, a model or a source table resolves as in point 3.
- A two-part name
g.tresolves to a source table when groupgdeclares tablet. - Every other name passes through untouched and declares nothing. That covers three-part names, two-part names that are not a declared source (
samples.tpch.orders,my_schema.orders), and one-part names that match nothing. - Comparison is case-insensitive, as Spark compares identifiers by default. Quoted and unquoted identifiers compare equal.
- What counts as a name. Only table references in a query. A reference that resolves to a CTE in scope is not one:
with orders as (...) select * from ordersreads no model. Table-valued functions, subquery aliases and format fields are not names. Statements that are not queries (SET,CACHE, DDL, DML) pass through untouched and declare nothing. - Physical name. The mapping
create_viewalready uses on Spark: the catalog identifier of a table (three-part on Unity Catalog),delta.`path``` orparquet.path` for a path, and the Delta path of anintermediate` model.- An input without such a name cannot appear in
ctx.spark.sql(PLC516), thoughctx.spark.tablereads it. That means an ephemeral model, or a csv, json or ndjson source. - Reader options of a path source do not apply in SQL, as for views.
- An input without such a name cannot appear in
- Incremental filter.
ctx.sparknever applies it. A model reading its incremental input throughctx.sparkfilters it itself withctx.lower_boundorctx.interval. - Names the plan missed. At run time, a name that resolves to a model or source of the project that is not an input of this model is PLX123, never a pass-through. A missed read therefore never falls back to another table with the same name.
- Views and unit tests. In view mode
ctx.sparkraises, reported as PLX120. Inpipeloom test,ctx.spark.tablereturns the input's given rows, andctx.spark.sqlnaming an input raises, reported as PLX115. -
Frame API.
ctx.sparkreturns native Spark objects whateverframe_apisays. -
Where
ctx.sparklives. - Core.
EngineCapabilitiesgainsspark_session: bool = False.pipeloom.engine.protocolsgains the optional protocolSupportsSparkHandle, withspark_handle(resolve, read) -> Any. The core helperspark_handle(session, resolve, read)returns None when the session lacks the member.resolve(name)returns the input'sReadSpec, returns None to pass the name through, or raises for PLX123.read(name)returns the input relation, unfiltered, through the runner's read path.- This is plugin API (1, 2). Plugins built for (1, 0) or (1, 1) keep loading and have no
ctx.spark.
- pipeloom-spark. A small
SparkHandleclass inpipeloom_spark.handleimplements the protocol, and the spec setsspark_session=True. The physical-name mapping moves out ofcreate_viewinto one function that both use. Databricks runs on the Spark engine and gets Unity names throughUnityCatalog. - Validation. A model whose function uses
ctx.spark, on a target whose engine lacksspark_session, is PLC515. At run time,ctx.sparkthere raisesAttributeErrornaming the engine, reported as PLX101. -
sqlglot. The table finder and the rewrite live in one core module,
pipeloom.engine.sqlnames. It imports sqlglot lazily and gets an import-linter ignore entry, aspipeloom.runtime.sqlhas. Resolve uses the finder at compile time and the handle uses the rewrite at run time, so both see the same names.pipeloom-sparkdepends onpipeloom[sqlglot]; the core keeps sqlglot optional.- When sqlglot is missing at compile time, a
ctx.spark.sqlmodel gets PLC515 on a target without Spark, else PLK607. A literal sqlglot cannot parse is also PLK607.
-
ModelContext. - It gains the method
readand the propertyspark. Two private wiring fields,_readand_spark, back them; they come afterinterval, with defaults,compare=Falseandrepr=False, as_run_sqlbackssql. - A new method, a new property and defaulted trailing fields on an exported class are additive under the stability policy, like
intervalin 1.3. SourceRefis annotated through aTYPE_CHECKINGimport, becausepipeloom.authoringimports the context.-
EngineSessionandStateStoredo not change. -
Manifest, hashes and lineage.
- Read inputs are ordinary
node.inputsentries. The graph, units,parent_map, the unit graph, Airflow assets, OpenLineage inputs (unit_inputs, ADR-0055), docs lineage and selectors all see them unchanged. - New optional node field
reads. It lists the sorted aliases that are bound only by reads and not passed as arguments. It is absent when empty and hashed when present, likecolumns. The schema stayspipeloom.manifest/1. - Unaffected projects. A project using neither
ctx.readnorctx.sparkkeeps its manifest bytes, plan hash, 1.0 checksum and split checksums. -
Effect on
plan --diff.- Turning a parameter into a
ctx.readof the same name is a code change only. - Adding or changing a read changes
inputs, which is breaking (ADR-0052) and reaches descendants throughupstream. plan --diffrecords onlyctx.sqlliterals, so any edit to actx.spark.sqlquery is breaking, which is the safe side.module_treealready normalizes every literal.sql(...)argument, so layout edits stay out ofcode.
- Turning a parameter into a
-
Portable models. Under
frame_api: narwhals,ctx.readreturns Narwhals frames, and the portable rules and PLX122 apply exactly as for parameters. A model usingctx.sparkis not portable. -
Diagnostics.
Code Layer, severity Title Status PLR211 L2 E Read alias unavailable: taken by another input, or not a valid alias new PLK607 L6 E Read cannot be resolved at compile time: non-literal argument, unparseable ctx.spark.sqlliteral, or sqlglot missingnew PLC515 L5 E ctx.sparkon an engine without a Spark sessionnew PLC516 L5 E ctx.spark.sqlnames an input with no Spark SQL name (ephemeral model, csv, json or ndjson source)new PLX123 Runtime E ctx.readorctx.sparknames a model or source that is not an input of the modelnew PLR201, PLR210 L2 E Also emitted for ctx.readandctx.sparknamesextended, same meaning PLK603 L6 W Counts read aliases as declared reused PLX101, PLX115, PLX120 Runtime E ctx.sparkon another engine, in a unit test, in a viewreused -
Docs.
- Architecture sections 4 and 5. The principle becomes: dependencies are declared in the decorator, the signature or literal reads in the body, and never traced at run time.
- A new guide,
docs/guide/reading-inputs.md. - The Spark plugin page, the stability page (plugin API 1.2), and the CHANGELOG under Added.
Provenance: designed from the pipeloom code base, the author's earlier prototype (its session wrapper), and the public documentation of dbt ref(), PySpark SparkSession and sqlglot. No code was copied from other projects.
Example. polars:
from pipeloom import ModelContext, model, source
@model(materialized="incremental", incremental={"input": "orders", "column": "o_orderdate"})
def orders_enriched(ctx: ModelContext):
orders = ctx.read(source("tpch", "orders")) # alias "orders", filtered
customer = ctx.read("customer") # the model customer
return orders.join(customer, left_on="o_custkey", right_on="c_custkey")
Spark: lineitem_revenue and orders_enriched become inputs, and tpch.nation is a source. On Unity Catalog each is replaced with its three-part name.
@model
def revenue_by_nation(ctx):
return ctx.spark.sql("""
select n.n_name as nation, sum(l.net_revenue) as revenue
from lineitem_revenue l
join orders_enriched o on l.order_key = o.order_key
join tpch.nation n on o.nation = n.n_name
group by n.n_name
""")
Consequences¶
- Models with many inputs keep short signatures. PySpark code from notebooks moves into
ctx.sparkalmost unchanged, and its table names work on every target. - Factories declare their inputs in the decorator and read them by alias.
- An f-string in
ctx.spark.sqlis rejected. Use parameter markers withargs=or DataFrame filters instead. - There are three ways to read an input. The docs recommend parameters for a few inputs,
ctx.readfor many, andctx.sparkfor PySpark code. ctx.spark.sqlnames create inputs andctx.sqlnames do not. Revisit if users ask.- Compiling parses every
ctx.spark.sqlliteral with sqlglot. Measure it against the 1.2 budget of 1,000 models. - ADR-0050 gets an amendment for points 2, 3, 8, 11 and 13.
Risks:
- A valid Spark query that sqlglot cannot parse fails compile with PLK607. The fallback is
ctx.sqlorctx.readwith DataFrame code. Pin the sqlglot range inpipeloom-spark. - Generating the query again changes its layout in Spark error messages, and may differ on dialect edge cases. Tests run the TPC-H queries and the conformance kit through the rewrite.
- A session temp view named like a model is rewritten to the model. A two-part name equal to a declared source wins over a real schema of that name. The docs say both.
- Case-insensitive matching is wrong for a session with
spark.sql.caseSensitive=true.
Amendment (decision 134, before release): splice, do not regenerate¶
Point 6 changes in four details, after review:
sqlkeeps the query text. sqlglot only finds the table references and their positions. Each resolved name is replaced in the original text, and the rest stays byte for byte: layout, comments, optimizer hints,VERSION AS OFandTIMESTAMP AS OF,TABLESAMPLE,PIVOT, options,QUALIFYand${var}substitutions. A reference without an alias getsAS <written name>after its temporal clause and sample, where Spark expects the alias. The risk "generating the query again changes its layout" no longer applies.- Hints. A table named inside an optimizer hint (
/*+ BROADCAST(customer) */) is not a name: it is not rewritten and declares nothing. - CTE scope. Inside CTE
iof a WITH clause only CTEs0..i-1are in scope, sowith orders as (select * from orders)reads the inputorders. In the query body every CTE is in scope. - Unit tests. In
pipeloom test,ctx.sparknames resolve as the compiler resolved them (case-insensitive,group.tableincluded) and reach the given rows; a name that is not an input fails the case with PLX115 instead of reaching the session.
pipeloom-spark pins sqlglot below its next major, as the risk note asks.
Status¶
Accepted
Date¶
2026-11-29