Skip to content

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(...) and spark.sql(...) in PySpark.
  • ctx.engine.native already exposes the engine's native session (the SparkSession on Spark). A table read through it is invisible to the plan: no edge in the graph, so no run order, no lineage and no state:modified propagation. The name must also be the physical one, which differs per target (a Delta path on the filesystem catalog, catalog.schema.table on Unity Catalog).
  • The author's earlier prototype gave models a session wrapper. Its table() resolved model names to physical names, and its sql() passed queries through unchanged.
  • 1.x constraints: changes are additive (ADR-0016, stability). Nothing is added to EngineSession or StateStore; 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 @model next to free-form reads. Rejected: the same dependency is written twice, and the two copies drift.
  • What ctx.read may 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 EngineSession method. Not allowed in 1.x.
  • In pipeloom-spark, reached through an optional protocol and declared by a capability. Chosen.
  • How ctx.spark.sql rewrites 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), as ctx.sql does on Spark. Rejected: the query would no longer name physical tables, which is what ctx.spark users ask for, and it duplicates ctx.sql.
  • Parse with sqlglot in the Spark dialect, replace resolved table references with physical names and generate the query again. Chosen.

Decision

  1. ctx.read. ModelContext.read(name: str | SourceRef) -> Any.
  2. ctx.read("orders") reads a model, or any input by its alias (point 3). ctx.read(source("tpch", "orders")) reads a source table; source is the existing helper.
  3. It returns the input as a parameter would receive it: the native frame, or a Narwhals frame under frame_api: narwhals.
  4. 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).
  5. It coexists with parameters and inputs=; one model may use all three.

  6. Static discovery. For each discovered model, the AST resolver walks its function body, nested functions and lambdas included. It records these calls:

  7. ctx.read(<str literal>) and ctx.read(source(<str literal>, <str literal>)). Here ctx is the function's ctx parameter, and source is recognised by the import rules of ADR-0050 point 2.
  8. ctx.spark.table(<str literal>) and ctx.spark.sql(<str literal>, ...). ctx.spark may also be used through a local name assigned exactly name = ctx.spark in 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.

  1. Binding and aliases. Reads bind after parameters and inputs=, in source order, with the rules of ADR-0050 point 3.
  2. ctx.read("x"). If x is already an alias of the model, the call reads that input. Otherwise x binds like a bare name: the model named x (never the model itself), else the one source table named x, else PLR201. A table x in several groups is PLR210. The new alias is x.
  3. ctx.read(source("g", "t")). If an alias of the model already binds source.<project>.g.t, the call reads that input. Otherwise the new alias is t. An unknown group or table is PLR201.
  4. Alias collision. If the new alias is taken by another input, or is not a valid alias (ctx or a Python keyword), it is PLR211 at the call. Example: a parameter orders bound to a model, plus ctx.read(source("tpch", "orders")). Fix: inputs={"tpch_orders": source("tpch", "orders")} and ctx.read("tpch_orders").
  5. Duplicates. Reading the same input twice, or reading an input a parameter also binds, is one input with one alias.
  6. ctx.spark names. A one-part name binds like ctx.read("x"). A two-part name g.t binds like ctx.read(source("g", "t")) when group g declares table t.
  7. Incremental. incremental.input may name an alias created by a read.

  8. Run time.

  9. The runner reads every input of the node before calling the function, as today. ctx.read returns 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.
  10. An argument that is not an input of the node is PLX123.
  11. Aliases bound only by reads are never passed as arguments, even when the function takes **kwargs (point 9 says how the runner knows).
  12. In view mode, ctx.read returns the placeholder a parameter gets; any use other than naming the alias in ctx.sql is PLX120.
  13. In an inlined ephemeral model, ctx.read reads that model's own inputs.
  14. pipeloom test gives rows to read aliases like any input (given keyed by alias, PLR208 when rows are missing).
  15. Outside pipeloom, as in a plain pytest, ctx.read raises RuntimeError, as ctx.sql does.

  16. ctx.sql. ctx.sql sees every input by alias, read aliases included, and PLK603 counts them as declared. Table names in ctx.sql queries stay aliases and create no inputs. Only ctx.spark.sql creates inputs.

  17. ctx.spark. On an engine with a Spark session, ctx.spark is a thin wrapper around the session.

  18. table(name) returns the input name resolves to. It reads through the same path as the runner's input reads: the catalog plugin, plus --defer and the reference relation (ADR-0042). The incremental filter is not applied. A name that resolves to nothing goes to SparkSession.table unchanged.
  19. sql(query, *args, **kwargs) parses query with 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 to SparkSession.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.
  20. Every other attribute (read, createDataFrame, conf, catalog, ...) is the session's own.
  21. 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.t resolves to a source table when group g declares table t.
    • 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.
  22. 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 orders reads 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.
  23. Physical name. The mapping create_view already 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), though ctx.spark.table reads 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.
  24. Incremental filter. ctx.spark never applies it. A model reading its incremental input through ctx.spark filters it itself with ctx.lower_bound or ctx.interval.
  25. 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.
  26. Views and unit tests. In view mode ctx.spark raises, reported as PLX120. In pipeloom test, ctx.spark.table returns the input's given rows, and ctx.spark.sql naming an input raises, reported as PLX115.
  27. Frame API. ctx.spark returns native Spark objects whatever frame_api says.

  28. Where ctx.spark lives.

  29. Core.
    • EngineCapabilities gains spark_session: bool = False.
    • pipeloom.engine.protocols gains the optional protocol SupportsSparkHandle, with spark_handle(resolve, read) -> Any. The core helper spark_handle(session, resolve, read) returns None when the session lacks the member.
    • resolve(name) returns the input's ReadSpec, 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.
  30. pipeloom-spark. A small SparkHandle class in pipeloom_spark.handle implements the protocol, and the spec sets spark_session=True. The physical-name mapping moves out of create_view into one function that both use. Databricks runs on the Spark engine and gets Unity names through UnityCatalog.
  31. Validation. A model whose function uses ctx.spark, on a target whose engine lacks spark_session, is PLC515. At run time, ctx.spark there raises AttributeError naming the engine, reported as PLX101.
  32. 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, as pipeloom.runtime.sql has. Resolve uses the finder at compile time and the handle uses the rewrite at run time, so both see the same names.

    • pipeloom-spark depends on pipeloom[sqlglot]; the core keeps sqlglot optional.
    • When sqlglot is missing at compile time, a ctx.spark.sql model gets PLC515 on a target without Spark, else PLK607. A literal sqlglot cannot parse is also PLK607.
  33. ModelContext.

  34. It gains the method read and the property spark. Two private wiring fields, _read and _spark, back them; they come after interval, with defaults, compare=False and repr=False, as _run_sql backs sql.
  35. A new method, a new property and defaulted trailing fields on an exported class are additive under the stability policy, like interval in 1.3.
  36. SourceRef is annotated through a TYPE_CHECKING import, because pipeloom.authoring imports the context.
  37. EngineSession and StateStore do not change.

  38. Manifest, hashes and lineage.

  39. Read inputs are ordinary node.inputs entries. The graph, units, parent_map, the unit graph, Airflow assets, OpenLineage inputs (unit_inputs, ADR-0055), docs lineage and selectors all see them unchanged.
  40. 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, like columns. The schema stays pipeloom.manifest/1.
  41. Unaffected projects. A project using neither ctx.read nor ctx.spark keeps its manifest bytes, plan hash, 1.0 checksum and split checksums.
  42. Effect on plan --diff.

    • Turning a parameter into a ctx.read of the same name is a code change only.
    • Adding or changing a read changes inputs, which is breaking (ADR-0052) and reaches descendants through upstream.
    • plan --diff records only ctx.sql literals, so any edit to a ctx.spark.sql query is breaking, which is the safe side. module_tree already normalizes every literal .sql(...) argument, so layout edits stay out of code.
  43. Portable models. Under frame_api: narwhals, ctx.read returns Narwhals frames, and the portable rules and PLX122 apply exactly as for parameters. A model using ctx.spark is not portable.

  44. 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.sql literal, or sqlglot missing new
    PLC515 L5 E ctx.spark on an engine without a Spark session new
    PLC516 L5 E ctx.spark.sql names an input with no Spark SQL name (ephemeral model, csv, json or ndjson source) new
    PLX123 Runtime E ctx.read or ctx.spark names a model or source that is not an input of the model new
    PLR201, PLR210 L2 E Also emitted for ctx.read and ctx.spark names extended, same meaning
    PLK603 L6 W Counts read aliases as declared reused
    PLX101, PLX115, PLX120 Runtime E ctx.spark on another engine, in a unit test, in a view reused
  45. 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.spark almost 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.sql is rejected. Use parameter markers with args= or DataFrame filters instead.
  • There are three ways to read an input. The docs recommend parameters for a few inputs, ctx.read for many, and ctx.spark for PySpark code.
  • ctx.spark.sql names create inputs and ctx.sql names do not. Revisit if users ask.
  • Compiling parses every ctx.spark.sql literal 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.sql or ctx.read with DataFrame code. Pin the sqlglot range in pipeloom-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:

  • sql keeps 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 OF and TIMESTAMP AS OF, TABLESAMPLE, PIVOT, options, QUALIFY and ${var} substitutions. A reference without an alias gets AS <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 i of a WITH clause only CTEs 0..i-1 are in scope, so with orders as (select * from orders) reads the input orders. In the query body every CTE is in scope.
  • Unit tests. In pipeloom test, ctx.spark names resolve as the compiler resolved them (case-insensitive, group.table included) 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