Skip to content

Python API

Most projects only need the decorator and the helpers below. The Project class in pipeloom.api runs the same stages as the command line from Python, for notebooks, tests and tools. Both are part of the stable surface.

Authoring

Mark a function as a pipeloom model, as @model or @model(...). Returns the same function with a ModelSpec in __pipeloom_model__.

Source code in src/pipeloom/authoring.py
def model(fn: F | None = None, /, **kwargs: Any) -> F | Callable[[F], F]:
    """Mark a function as a pipeloom model, as `@model` or `@model(...)`. Returns the same
    function with a `ModelSpec` in `__pipeloom_model__`."""
    spec = ModelSpec(MappingProxyType({k: v for k, v in kwargs.items() if v is not None}))

    def mark(f: F) -> F:
        if hasattr(f, MARKER):
            raise TypeError(f"@model is applied twice to {getattr(f, '__qualname__', f)!r}")
        setattr(f, MARKER, spec)
        return f

    return mark if fn is None else mark(fn)

What a Python model receives as ctx.

Source code in src/pipeloom/runtime/context.py
@dataclass(frozen=True, slots=True)
class ModelContext:
    """What a Python model receives as `ctx`."""

    run_id: str
    invocation_id: str
    unit_id: str
    unique_id: str
    model: str
    attempt: int
    target: TargetRef | None
    materialized: str
    vars: Mapping[str, JsonValue]
    full_refresh: bool
    engine: EngineSession
    frame_api: Literal["native", "narwhals"]
    started_at: datetime
    is_incremental: bool = False
    watermark: Any = None
    lower_bound: Any = None
    """The last three are used from 0.3. Fields after them are wiring, not part of the API."""
    emit_log: Callable[[str, str, Mapping[str, JsonValue]], None] | None = field(
        default=None, repr=False, compare=False
    )
    _run_sql: Callable[[str, str | None, Mapping[str, Any] | None], Any] | None = field(
        default=None, repr=False, compare=False
    )
    """Private: set by the runner; backs `sql`."""
    interval: tuple[datetime, datetime] | None = None
    """Since 1.3: the UTC window `[start, end)` an interval model is running, else None. The
    incremental input is already filtered to it (ADR-0054)."""

    def sql(
        self, query: str, *, dialect: str | None = None, inputs: Mapping[str, Any] | None = None
    ) -> Any:
        """Run `query` over the model's inputs, named by alias as read (after the incremental
        filter). `inputs` adds or replaces frames by name. `dialect` (else the model's
        `sql_dialect`) is translated to the engine's when it differs. Returns the native frame,
        or a Narwhals frame under `frame_api: narwhals`."""
        if self._run_sql is None:
            raise RuntimeError("ctx.sql works only while pipeloom runs the model")
        return self._run_sql(query, dialect, inputs)

    def log(
        self,
        message: str,
        *,
        level: Literal["debug", "info", "warning"] = "info",
        **fields: JsonValue,
    ) -> None:
        """Emit a `model.log` event."""
        if self.emit_log is not None:
            self.emit_log(message, level, fields)

interval = None class-attribute instance-attribute

Since 1.3: the UTC window [start, end) an interval model is running, else None. The incremental input is already filtered to it (ADR-0054).

lower_bound = None class-attribute instance-attribute

The last three are used from 0.3. Fields after them are wiring, not part of the API.

log(message, *, level='info', **fields)

Emit a model.log event.

Source code in src/pipeloom/runtime/context.py
def log(
    self,
    message: str,
    *,
    level: Literal["debug", "info", "warning"] = "info",
    **fields: JsonValue,
) -> None:
    """Emit a `model.log` event."""
    if self.emit_log is not None:
        self.emit_log(message, level, fields)

sql(query, *, dialect=None, inputs=None)

Run query over the model's inputs, named by alias as read (after the incremental filter). inputs adds or replaces frames by name. dialect (else the model's sql_dialect) is translated to the engine's when it differs. Returns the native frame, or a Narwhals frame under frame_api: narwhals.

Source code in src/pipeloom/runtime/context.py
def sql(
    self, query: str, *, dialect: str | None = None, inputs: Mapping[str, Any] | None = None
) -> Any:
    """Run `query` over the model's inputs, named by alias as read (after the incremental
    filter). `inputs` adds or replaces frames by name. `dialect` (else the model's
    `sql_dialect`) is translated to the engine's when it differs. Returns the native frame,
    or a Narwhals frame under `frame_api: narwhals`."""
    if self._run_sql is None:
        raise RuntimeError("ctx.sql works only while pipeloom runs the model")
    return self._run_sql(query, dialect, inputs)

Running from Python

A project on disk. Each step runs once and is remembered.

Source code in src/pipeloom/api.py
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
class Project:
    """A project on disk. Each step runs once and is remembered."""

    def __init__(
        self,
        options: ProjectOptions,
        *,
        registry: PluginRegistry | None = None,
        clock: Clock | None = None,
        identity: IdentityProvider | None = None,
        invocation_id: str | None = None,
        redactor: Redactor | None = None,
    ) -> None:
        self.options = options
        self.redactor = redactor or Redactor()
        """Holds every secret the run resolves; pass the same one to the event bus."""
        self._secrets: SecretResolver | None = None
        self._registry = registry
        self._registry_problems: tuple[Diagnostic, ...] = ()
        self.clock: Clock = clock or SystemClock()
        self._identity = identity or LocalIdentity(options.env)
        self._loaded: Outcome[LoadedProject] | None = None
        self._bound: Outcome[BoundProject] | None = None
        self._resolved: Outcome[ProjectGraph] | None = None
        self.discovery: Discovery | None = None
        """The project's model discovery, kept so `docs serve` can refresh it."""
        self._validated: Outcome[ProjectGraph] | None = None
        self._plans: dict[tuple[Selection, str | None], Outcome[Plan]] = {}
        self.invocation_id = invocation_id or uuid.uuid4().hex

    @property
    def identity(self) -> Identity:
        return self._identity.identity()

    @property
    def registry(self) -> PluginRegistry:
        """Discovered on first use from the options' `--plugin` specs and the environment."""
        if self._registry is None:
            report = Report()
            self._registry = PluginRegistry.discover(
                cli_plugins=self.options.plugins, env=self.options.env, report=report
            )
            self._registry_problems = report.sorted()
        return self._registry

    @property
    def secrets(self) -> SecretResolver:
        """Resolves `${secret:...}` references for plugins built to execute. One per project, so
        each provider is built once per invocation."""
        if self._secrets is None:
            self._secrets = SecretResolver(self.registry, self.redactor)
        return self._secrets

    def with_vars(self, vars_: Mapping[str, Any]) -> Project:
        """This project with other vars, which are read at load; self when they are the same.
        It keeps the registry, clock, identity, invocation id and redactor."""
        if dict(vars_) == dict(self.options.vars):
            return self
        other = Project(
            replace(self.options, vars=vars_),
            registry=self.registry,
            clock=self.clock,
            identity=self._identity,
            invocation_id=self.invocation_id,
            redactor=self.redactor,
        )
        other._registry_problems = self._registry_problems
        return other

    def load(self) -> Outcome[LoadedProject]:
        """Read and check pipeloom.yml and properties files (layers L0 and L1)."""
        if self._loaded is None:
            report = Report()
            value = load_project(self.options, report)
            self._loaded = Outcome(value, report.sorted())
        return self._loaded

    def bind(self) -> Outcome[BoundProject]:
        """Load, then pick the target and bind its plugins."""
        if self._bound is None:
            loaded = self.load()
            if loaded.value is None:
                self._bound = Outcome(None, loaded.diagnostics)
            else:
                registry = self.registry
                report = Report()
                report.extend(loaded.diagnostics)
                report.extend(self._registry_problems)
                value = bind_project(loaded.value, self.options, registry, report)
                self._bound = Outcome(value, report.sorted())
        return self._bound

    def resolve(self) -> Outcome[ProjectGraph]:
        """Bind, apply defaults, check references (L2) and build the graph (L3)."""
        if self._resolved is None:
            bound = self.bind()
            if bound.value is None:
                self._resolved = Outcome(None, bound.diagnostics)
            else:
                report = Report()
                report.extend(bound.diagnostics)
                loaded = bound.value.loaded
                if self.discovery is None:
                    self.discovery = Discovery(
                        loaded.project_dir,
                        loaded.config.model_paths,
                        loaded.config.model_packages,
                        loaded.config.python_paths,
                    )
                found = python_models(self.discovery.discover(), loaded.vars, report)
                project = resolve_project(bound.value, found.models, found.broken)
                check_references(project, report, models_incomplete=found.incomplete)
                graph = None if report.has_errors else build_graph(project, report)
                value = None if graph is None else ProjectGraph(project, graph)
                self._resolved = Outcome(value, report.sorted())
        return self._resolved

    def validate(self) -> Outcome[ProjectGraph]:
        """Resolve, then run the plan checks (L4 to L6). None when any layer found an error."""
        if self._validated is None:
            self._validated = validate_project(self.resolve())
        return self._validated

    def compile(
        self,
        selection: Selection | None = None,
        boundary: Literal["process", "task"] | None = None,
    ) -> Outcome[Plan]:
        """Validate, then build the plan. Units always cover the whole project; the selection
        only marks which models are selected. `boundary` defaults to the target's."""
        sel = selection or Selection()
        key = (sel, boundary)
        if key not in self._plans:
            validated = self.validate()
            if validated.value is None:
                self._plans[key] = Outcome(None, validated.diagnostics)
            else:
                report = Report()
                report.extend(validated.diagnostics)
                plan = compile_plan(
                    validated.value,
                    selection=sel,
                    boundary=boundary,
                    registry=self.registry,
                    identity=self.identity,
                    clock=self.clock,
                    invocation_id=self.invocation_id,
                    report=report,
                )
                self._plans[key] = Outcome(plan, report.sorted())
        return self._plans[key]

    def run(
        self,
        opts: RunOptions | None = None,
        bus: EventBus | None = None,
        control: RunControl | None = None,
    ) -> RunOutcome:
        """Validate, plan and run the selected units. Events go to `bus`; without one they are dropped.

        `control.request_stop()` stops the run gracefully from any thread; `hard=True` skips the
        grace period. The outcome is then `cancelled` with exit code 130."""
        opts = opts or RunOptions()
        if control is not None:
            opts = replace(opts, control=control)
        own = bus is None
        events = bus or EventBus(
            [], clock=self.clock, invocation_id=self.invocation_id, redactor=self.redactor
        )
        try:
            return execute_run(self, opts, events)
        finally:
            if own:
                events.close()

    def retry(
        self,
        parent_run_id: str,
        opts: RunOptions | None = None,
        bus: EventBus | None = None,
        control: RunControl | None = None,
        *,
        full_refresh: bool | None = None,
    ) -> RunOutcome:
        """Run again what run `parent_run_id` did not finish: its failed, skipped and cancelled
        units. The new run has its own id and records the parent as `parent_run_id`; it inherits
        the parent's vars (under this project's own), full_refresh (`full_refresh` wins), state
        and defer, and compiles the project fresh. A parent that cannot be retried is PLX113; one
        with nothing to retry gives a succeeded outcome with no run results."""
        project = self.with_vars(inherited_vars(self, parent_run_id))
        resolved, found = retry_options(project, parent_run_id, opts or RunOptions(), full_refresh)
        own = bus is None
        events = bus or EventBus(
            [], clock=self.clock, invocation_id=self.invocation_id, redactor=self.redactor
        )
        try:
            if resolved is None:
                return _early(events, found) if found else RunOutcome("succeeded", 0, None, ())
            if control is not None:
                resolved = replace(resolved, control=control)
            return execute_run(project, resolved, events)
        finally:
            if own:
                events.close()

    def build(
        self,
        opts: RunOptions | None = None,
        bus: EventBus | None = None,
        control: RunControl | None = None,
    ) -> RunOutcome:
        """Run the unit tests of the selected models, then, when every case passed, `run` them
        with data tests on (ADR-0045). A failed case stops the build with exit 1 before a run id
        exists and before any write."""
        opts = opts or RunOptions()
        tested = self.test(opts.selection)
        own = bus is None
        events = bus or EventBus(
            [], clock=self.clock, invocation_id=self.invocation_id, redactor=self.redactor
        )
        try:
            if tested.exit_code:
                outcome = _early(events, tested.diagnostics)
                for payload in tested.events:
                    events.emit(payload)
                return replace(outcome, exit_code=tested.exit_code, extra_errors=tested.failed)
            for payload in tested.events:
                events.emit(payload)
            return self.run(replace(opts, data_tests=True), events, control)
        finally:
            if own:
                events.close()

    def test(self, selection: Selection | None = None) -> TestRunOutcome:
        """Run the unit tests of the selected models (ADR-0045). It writes nothing: no run id, no
        lock, no artifacts. The outcome holds one event payload per case and a summary."""
        compiled = self.compile(selection)
        diags = list(compiled.diagnostics)
        plan, bound = compiled.value, self.bind().value
        if plan is None or bound is None:
            usage = any(d.code in USAGE_CODES for d in diags)
            return TestRunOutcome(2 if usage else 1, (), tuple(diags))
        validated = self.validate().value
        assert validated is not None
        project = validated.project
        order = {uid: i for i, uid in enumerate(plan.nodes)}
        chosen = set(plan.selection.selected)
        cases = sorted(
            (c for c in project.unit_tests if model_id(plan.metadata.project, c.model) in chosen),
            key=lambda c: order[model_id(plan.metadata.project, c.model)],
        )
        events: list[EventPayload] = []
        failed = 0
        if cases:
            engine_plugin, catalog_plugin = (
                bound.plugins.get("engines"),
                bound.plugins.get("catalogs"),
            )
            if engine_plugin is None or catalog_plugin is None:
                missing = _missing(bound, "engine" if engine_plugin is None else "catalog")
                return TestRunOutcome(1, (), (*diags, missing))
            try:
                engine: Engine = engine_plugin.create(self.secrets)
                catalog: Catalog = catalog_plugin.create(self.secrets)
            except SecretError as err:
                return TestRunOutcome(1, (), (*diags, secret_diagnostic(err)))
            project_dir = bound.loaded.project_dir.resolve()
            rt = RuntimeContext(
                run_id=self.invocation_id,
                invocation_id=self.invocation_id,
                project=plan.metadata.project,
                target=plan.metadata.target,
                project_dir=project_dir,
                clock=self.clock,
                identity=self.identity,
                vars=plan.metadata.vars,
            )
            with (
                engine.session(rt, catalog=catalog) as session,
                ModuleLoader(project_dir, plan.metadata.python_paths) as loader,
            ):
                for case in cases:
                    node = plan.nodes[model_id(plan.metadata.project, case.model)]
                    upstream = {
                        alias: plan.nodes[uid].columns if uid in plan.nodes else None
                        for alias, uid in node.inputs.items()
                    }
                    result = run_unit_test(
                        session,
                        node,
                        case.config,
                        load=loader.load,
                        rt=rt,
                        upstream=upstream,
                        sql_dialect=engine.capabilities.sql_dialect,
                    )
                    if result.passed:
                        events.append(UnitTestPassed(model=case.model, unit_test=case.name))
                        continue
                    failed += 1
                    where = project.locate(case.file, f"{case.pointer}/name")
                    events.append(
                        UnitTestFailed(
                            model=case.model,
                            unit_test=case.name,
                            code=result.code or "PLX115",
                            message=result.message,
                            location=where.to_json(),
                            missing=result.missing,
                            unexpected=result.unexpected,
                        )
                    )
        events.append(UnitTestsCompleted(passed=len(cases) - failed, failed=failed))
        return TestRunOutcome(1 if failed else 0, tuple(events), tuple(diags), failed)

    def diff(
        self,
        model: str,
        state: Path,
        *,
        key: tuple[str, ...] = (),
        samples: bool = False,
    ) -> DiffOutcome:
        """Compare `model`'s relation in the `state` reference (the source) with its relation on
        this target (ADR-0053). It writes nothing. `key` wins over the model's
        `write.unique_key`. Exit code 0 no differences, 1 differences or a failure, 2 usage."""
        compiled = self.compile()
        diags = list(compiled.diagnostics)
        plan, bound = compiled.value, self.bind().value
        if plan is None or bound is None:
            usage = any(d.code in USAGE_CODES for d in diags)
            return DiffOutcome(2 if usage else 1, None, tuple(diags))
        project_dir = bound.loaded.project_dir.resolve()
        report = Report()
        reference = load_reference(project_dir / state, plan.metadata.project, report, project_dir)
        if reference is None:
            return DiffOutcome(1, None, (*diags, *report.sorted()))

        def refuse(why: str) -> DiffOutcome:
            found = Report().add(
                "PLX130",
                f"cannot diff model '{model}': {why}",
                hint="name a persisted model, give it write.unique_key or pass --key, and point "
                "--state at a reference of the same catalog kind that built it",
                context={"model": model},
            )
            return DiffOutcome(2, None, (*diags, found))

        node = plan.nodes.get(model_id(plan.metadata.project, model))
        theirs = None if node is None else reference.plan.nodes.get(node.unique_id)
        here = plan.metadata.plugins.get("catalogs")
        there = reference.plan.metadata.plugins.get("catalogs")
        keys = key or tuple((node.config.write.unique_key or []) if node else [])
        if node is None:
            return refuse("the project has no such model")
        if node.relation is None or node.materialized == "intermediate":
            return refuse(f"it is {node.materialized}, so it has no relation")
        if theirs is None or theirs.relation is None or theirs.materialized == "intermediate":
            return refuse("the reference has no relation for it")
        if here is None or there is None or here.kind != there.kind:
            return refuse("the reference was compiled for another catalog kind")
        if not keys:
            return refuse("it has no write.unique_key and no --key was given")
        engine_plugin, catalog_plugin = bound.plugins.get("engines"), bound.plugins.get("catalogs")
        if engine_plugin is None or catalog_plugin is None:
            missing = _missing(bound, "engine" if engine_plugin is None else "catalog")
            return DiffOutcome(1, None, (*diags, missing))
        try:
            engine: Engine = engine_plugin.create(self.secrets)
            catalog: Catalog = catalog_plugin.create(self.secrets)
        except SecretError as err:
            return DiffOutcome(1, None, (*diags, secret_diagnostic(err)))
        rt = RuntimeContext(
            run_id=self.invocation_id,
            invocation_id=self.invocation_id,
            project=plan.metadata.project,
            target=plan.metadata.target,
            project_dir=project_dir,
            clock=self.clock,
            identity=self.identity,
            vars=plan.metadata.vars,
        )
        sensitive = {c.name for c in node.columns or () if c.sensitive}
        try:
            with engine.session(rt, catalog=catalog) as session:
                read = session.reader("table").read
                doc = compare(
                    session,
                    read(ReadSpec("table", table=theirs.relation)),
                    read(ReadSpec("table", table=node.relation)),
                    model=model,
                    names=(theirs.relation.relation_name, node.relation.relation_name),
                    key=keys,
                    sensitive=sensitive,
                    samples=samples,
                )
        except Exception as exc:  # noqa: BLE001 - engine code may raise anything on a read
            # Engine messages can quote cell values, so only the exception type is shown.
            why = (
                str(exc)
                if isinstance(exc, DiffError)
                else f"{type(exc).__name__} while reading or comparing the relations"
            )
            found = Report().add(
                "PLX131",
                f"cannot diff model '{model}': {why}",
                hint="build the model on both sides first; the engine's frames must be supported "
                "by narwhals",
                context={"model": model},
            )
            return DiffOutcome(1, None, (*diags, found))
        return DiffOutcome(1 if doc.differences else 0, doc, tuple(diags))

    def finalize(self, opts: FinalizeOptions, bus: EventBus | None = None) -> RunOutcome:
        """Close a run an orchestrator drove unit by unit: merge the unit results, record the run
        and emit `run.completed`. Repeating the call rewrites the same results."""
        own = bus is None
        events = bus or EventBus(
            [], clock=self.clock, invocation_id=self.invocation_id, redactor=self.redactor
        )
        try:
            return finalize_run(self, opts, events)
        finally:
            if own:
                events.close()

discovery = None instance-attribute

The project's model discovery, kept so docs serve can refresh it.

redactor = redactor or Redactor() instance-attribute

Holds every secret the run resolves; pass the same one to the event bus.

registry property

Discovered on first use from the options' --plugin specs and the environment.

secrets property

Resolves ${secret:...} references for plugins built to execute. One per project, so each provider is built once per invocation.

bind()

Load, then pick the target and bind its plugins.

Source code in src/pipeloom/api.py
def bind(self) -> Outcome[BoundProject]:
    """Load, then pick the target and bind its plugins."""
    if self._bound is None:
        loaded = self.load()
        if loaded.value is None:
            self._bound = Outcome(None, loaded.diagnostics)
        else:
            registry = self.registry
            report = Report()
            report.extend(loaded.diagnostics)
            report.extend(self._registry_problems)
            value = bind_project(loaded.value, self.options, registry, report)
            self._bound = Outcome(value, report.sorted())
    return self._bound

build(opts=None, bus=None, control=None)

Run the unit tests of the selected models, then, when every case passed, run them with data tests on (ADR-0045). A failed case stops the build with exit 1 before a run id exists and before any write.

Source code in src/pipeloom/api.py
def build(
    self,
    opts: RunOptions | None = None,
    bus: EventBus | None = None,
    control: RunControl | None = None,
) -> RunOutcome:
    """Run the unit tests of the selected models, then, when every case passed, `run` them
    with data tests on (ADR-0045). A failed case stops the build with exit 1 before a run id
    exists and before any write."""
    opts = opts or RunOptions()
    tested = self.test(opts.selection)
    own = bus is None
    events = bus or EventBus(
        [], clock=self.clock, invocation_id=self.invocation_id, redactor=self.redactor
    )
    try:
        if tested.exit_code:
            outcome = _early(events, tested.diagnostics)
            for payload in tested.events:
                events.emit(payload)
            return replace(outcome, exit_code=tested.exit_code, extra_errors=tested.failed)
        for payload in tested.events:
            events.emit(payload)
        return self.run(replace(opts, data_tests=True), events, control)
    finally:
        if own:
            events.close()

compile(selection=None, boundary=None)

Validate, then build the plan. Units always cover the whole project; the selection only marks which models are selected. boundary defaults to the target's.

Source code in src/pipeloom/api.py
def compile(
    self,
    selection: Selection | None = None,
    boundary: Literal["process", "task"] | None = None,
) -> Outcome[Plan]:
    """Validate, then build the plan. Units always cover the whole project; the selection
    only marks which models are selected. `boundary` defaults to the target's."""
    sel = selection or Selection()
    key = (sel, boundary)
    if key not in self._plans:
        validated = self.validate()
        if validated.value is None:
            self._plans[key] = Outcome(None, validated.diagnostics)
        else:
            report = Report()
            report.extend(validated.diagnostics)
            plan = compile_plan(
                validated.value,
                selection=sel,
                boundary=boundary,
                registry=self.registry,
                identity=self.identity,
                clock=self.clock,
                invocation_id=self.invocation_id,
                report=report,
            )
            self._plans[key] = Outcome(plan, report.sorted())
    return self._plans[key]

diff(model, state, *, key=(), samples=False)

Compare model's relation in the state reference (the source) with its relation on this target (ADR-0053). It writes nothing. key wins over the model's write.unique_key. Exit code 0 no differences, 1 differences or a failure, 2 usage.

Source code in src/pipeloom/api.py
def diff(
    self,
    model: str,
    state: Path,
    *,
    key: tuple[str, ...] = (),
    samples: bool = False,
) -> DiffOutcome:
    """Compare `model`'s relation in the `state` reference (the source) with its relation on
    this target (ADR-0053). It writes nothing. `key` wins over the model's
    `write.unique_key`. Exit code 0 no differences, 1 differences or a failure, 2 usage."""
    compiled = self.compile()
    diags = list(compiled.diagnostics)
    plan, bound = compiled.value, self.bind().value
    if plan is None or bound is None:
        usage = any(d.code in USAGE_CODES for d in diags)
        return DiffOutcome(2 if usage else 1, None, tuple(diags))
    project_dir = bound.loaded.project_dir.resolve()
    report = Report()
    reference = load_reference(project_dir / state, plan.metadata.project, report, project_dir)
    if reference is None:
        return DiffOutcome(1, None, (*diags, *report.sorted()))

    def refuse(why: str) -> DiffOutcome:
        found = Report().add(
            "PLX130",
            f"cannot diff model '{model}': {why}",
            hint="name a persisted model, give it write.unique_key or pass --key, and point "
            "--state at a reference of the same catalog kind that built it",
            context={"model": model},
        )
        return DiffOutcome(2, None, (*diags, found))

    node = plan.nodes.get(model_id(plan.metadata.project, model))
    theirs = None if node is None else reference.plan.nodes.get(node.unique_id)
    here = plan.metadata.plugins.get("catalogs")
    there = reference.plan.metadata.plugins.get("catalogs")
    keys = key or tuple((node.config.write.unique_key or []) if node else [])
    if node is None:
        return refuse("the project has no such model")
    if node.relation is None or node.materialized == "intermediate":
        return refuse(f"it is {node.materialized}, so it has no relation")
    if theirs is None or theirs.relation is None or theirs.materialized == "intermediate":
        return refuse("the reference has no relation for it")
    if here is None or there is None or here.kind != there.kind:
        return refuse("the reference was compiled for another catalog kind")
    if not keys:
        return refuse("it has no write.unique_key and no --key was given")
    engine_plugin, catalog_plugin = bound.plugins.get("engines"), bound.plugins.get("catalogs")
    if engine_plugin is None or catalog_plugin is None:
        missing = _missing(bound, "engine" if engine_plugin is None else "catalog")
        return DiffOutcome(1, None, (*diags, missing))
    try:
        engine: Engine = engine_plugin.create(self.secrets)
        catalog: Catalog = catalog_plugin.create(self.secrets)
    except SecretError as err:
        return DiffOutcome(1, None, (*diags, secret_diagnostic(err)))
    rt = RuntimeContext(
        run_id=self.invocation_id,
        invocation_id=self.invocation_id,
        project=plan.metadata.project,
        target=plan.metadata.target,
        project_dir=project_dir,
        clock=self.clock,
        identity=self.identity,
        vars=plan.metadata.vars,
    )
    sensitive = {c.name for c in node.columns or () if c.sensitive}
    try:
        with engine.session(rt, catalog=catalog) as session:
            read = session.reader("table").read
            doc = compare(
                session,
                read(ReadSpec("table", table=theirs.relation)),
                read(ReadSpec("table", table=node.relation)),
                model=model,
                names=(theirs.relation.relation_name, node.relation.relation_name),
                key=keys,
                sensitive=sensitive,
                samples=samples,
            )
    except Exception as exc:  # noqa: BLE001 - engine code may raise anything on a read
        # Engine messages can quote cell values, so only the exception type is shown.
        why = (
            str(exc)
            if isinstance(exc, DiffError)
            else f"{type(exc).__name__} while reading or comparing the relations"
        )
        found = Report().add(
            "PLX131",
            f"cannot diff model '{model}': {why}",
            hint="build the model on both sides first; the engine's frames must be supported "
            "by narwhals",
            context={"model": model},
        )
        return DiffOutcome(1, None, (*diags, found))
    return DiffOutcome(1 if doc.differences else 0, doc, tuple(diags))

finalize(opts, bus=None)

Close a run an orchestrator drove unit by unit: merge the unit results, record the run and emit run.completed. Repeating the call rewrites the same results.

Source code in src/pipeloom/api.py
def finalize(self, opts: FinalizeOptions, bus: EventBus | None = None) -> RunOutcome:
    """Close a run an orchestrator drove unit by unit: merge the unit results, record the run
    and emit `run.completed`. Repeating the call rewrites the same results."""
    own = bus is None
    events = bus or EventBus(
        [], clock=self.clock, invocation_id=self.invocation_id, redactor=self.redactor
    )
    try:
        return finalize_run(self, opts, events)
    finally:
        if own:
            events.close()

load()

Read and check pipeloom.yml and properties files (layers L0 and L1).

Source code in src/pipeloom/api.py
def load(self) -> Outcome[LoadedProject]:
    """Read and check pipeloom.yml and properties files (layers L0 and L1)."""
    if self._loaded is None:
        report = Report()
        value = load_project(self.options, report)
        self._loaded = Outcome(value, report.sorted())
    return self._loaded

resolve()

Bind, apply defaults, check references (L2) and build the graph (L3).

Source code in src/pipeloom/api.py
def resolve(self) -> Outcome[ProjectGraph]:
    """Bind, apply defaults, check references (L2) and build the graph (L3)."""
    if self._resolved is None:
        bound = self.bind()
        if bound.value is None:
            self._resolved = Outcome(None, bound.diagnostics)
        else:
            report = Report()
            report.extend(bound.diagnostics)
            loaded = bound.value.loaded
            if self.discovery is None:
                self.discovery = Discovery(
                    loaded.project_dir,
                    loaded.config.model_paths,
                    loaded.config.model_packages,
                    loaded.config.python_paths,
                )
            found = python_models(self.discovery.discover(), loaded.vars, report)
            project = resolve_project(bound.value, found.models, found.broken)
            check_references(project, report, models_incomplete=found.incomplete)
            graph = None if report.has_errors else build_graph(project, report)
            value = None if graph is None else ProjectGraph(project, graph)
            self._resolved = Outcome(value, report.sorted())
    return self._resolved

retry(parent_run_id, opts=None, bus=None, control=None, *, full_refresh=None)

Run again what run parent_run_id did not finish: its failed, skipped and cancelled units. The new run has its own id and records the parent as parent_run_id; it inherits the parent's vars (under this project's own), full_refresh (full_refresh wins), state and defer, and compiles the project fresh. A parent that cannot be retried is PLX113; one with nothing to retry gives a succeeded outcome with no run results.

Source code in src/pipeloom/api.py
def retry(
    self,
    parent_run_id: str,
    opts: RunOptions | None = None,
    bus: EventBus | None = None,
    control: RunControl | None = None,
    *,
    full_refresh: bool | None = None,
) -> RunOutcome:
    """Run again what run `parent_run_id` did not finish: its failed, skipped and cancelled
    units. The new run has its own id and records the parent as `parent_run_id`; it inherits
    the parent's vars (under this project's own), full_refresh (`full_refresh` wins), state
    and defer, and compiles the project fresh. A parent that cannot be retried is PLX113; one
    with nothing to retry gives a succeeded outcome with no run results."""
    project = self.with_vars(inherited_vars(self, parent_run_id))
    resolved, found = retry_options(project, parent_run_id, opts or RunOptions(), full_refresh)
    own = bus is None
    events = bus or EventBus(
        [], clock=self.clock, invocation_id=self.invocation_id, redactor=self.redactor
    )
    try:
        if resolved is None:
            return _early(events, found) if found else RunOutcome("succeeded", 0, None, ())
        if control is not None:
            resolved = replace(resolved, control=control)
        return execute_run(project, resolved, events)
    finally:
        if own:
            events.close()

run(opts=None, bus=None, control=None)

Validate, plan and run the selected units. Events go to bus; without one they are dropped.

control.request_stop() stops the run gracefully from any thread; hard=True skips the grace period. The outcome is then cancelled with exit code 130.

Source code in src/pipeloom/api.py
def run(
    self,
    opts: RunOptions | None = None,
    bus: EventBus | None = None,
    control: RunControl | None = None,
) -> RunOutcome:
    """Validate, plan and run the selected units. Events go to `bus`; without one they are dropped.

    `control.request_stop()` stops the run gracefully from any thread; `hard=True` skips the
    grace period. The outcome is then `cancelled` with exit code 130."""
    opts = opts or RunOptions()
    if control is not None:
        opts = replace(opts, control=control)
    own = bus is None
    events = bus or EventBus(
        [], clock=self.clock, invocation_id=self.invocation_id, redactor=self.redactor
    )
    try:
        return execute_run(self, opts, events)
    finally:
        if own:
            events.close()

test(selection=None)

Run the unit tests of the selected models (ADR-0045). It writes nothing: no run id, no lock, no artifacts. The outcome holds one event payload per case and a summary.

Source code in src/pipeloom/api.py
def test(self, selection: Selection | None = None) -> TestRunOutcome:
    """Run the unit tests of the selected models (ADR-0045). It writes nothing: no run id, no
    lock, no artifacts. The outcome holds one event payload per case and a summary."""
    compiled = self.compile(selection)
    diags = list(compiled.diagnostics)
    plan, bound = compiled.value, self.bind().value
    if plan is None or bound is None:
        usage = any(d.code in USAGE_CODES for d in diags)
        return TestRunOutcome(2 if usage else 1, (), tuple(diags))
    validated = self.validate().value
    assert validated is not None
    project = validated.project
    order = {uid: i for i, uid in enumerate(plan.nodes)}
    chosen = set(plan.selection.selected)
    cases = sorted(
        (c for c in project.unit_tests if model_id(plan.metadata.project, c.model) in chosen),
        key=lambda c: order[model_id(plan.metadata.project, c.model)],
    )
    events: list[EventPayload] = []
    failed = 0
    if cases:
        engine_plugin, catalog_plugin = (
            bound.plugins.get("engines"),
            bound.plugins.get("catalogs"),
        )
        if engine_plugin is None or catalog_plugin is None:
            missing = _missing(bound, "engine" if engine_plugin is None else "catalog")
            return TestRunOutcome(1, (), (*diags, missing))
        try:
            engine: Engine = engine_plugin.create(self.secrets)
            catalog: Catalog = catalog_plugin.create(self.secrets)
        except SecretError as err:
            return TestRunOutcome(1, (), (*diags, secret_diagnostic(err)))
        project_dir = bound.loaded.project_dir.resolve()
        rt = RuntimeContext(
            run_id=self.invocation_id,
            invocation_id=self.invocation_id,
            project=plan.metadata.project,
            target=plan.metadata.target,
            project_dir=project_dir,
            clock=self.clock,
            identity=self.identity,
            vars=plan.metadata.vars,
        )
        with (
            engine.session(rt, catalog=catalog) as session,
            ModuleLoader(project_dir, plan.metadata.python_paths) as loader,
        ):
            for case in cases:
                node = plan.nodes[model_id(plan.metadata.project, case.model)]
                upstream = {
                    alias: plan.nodes[uid].columns if uid in plan.nodes else None
                    for alias, uid in node.inputs.items()
                }
                result = run_unit_test(
                    session,
                    node,
                    case.config,
                    load=loader.load,
                    rt=rt,
                    upstream=upstream,
                    sql_dialect=engine.capabilities.sql_dialect,
                )
                if result.passed:
                    events.append(UnitTestPassed(model=case.model, unit_test=case.name))
                    continue
                failed += 1
                where = project.locate(case.file, f"{case.pointer}/name")
                events.append(
                    UnitTestFailed(
                        model=case.model,
                        unit_test=case.name,
                        code=result.code or "PLX115",
                        message=result.message,
                        location=where.to_json(),
                        missing=result.missing,
                        unexpected=result.unexpected,
                    )
                )
    events.append(UnitTestsCompleted(passed=len(cases) - failed, failed=failed))
    return TestRunOutcome(1 if failed else 0, tuple(events), tuple(diags), failed)

validate()

Resolve, then run the plan checks (L4 to L6). None when any layer found an error.

Source code in src/pipeloom/api.py
def validate(self) -> Outcome[ProjectGraph]:
    """Resolve, then run the plan checks (L4 to L6). None when any layer found an error."""
    if self._validated is None:
        self._validated = validate_project(self.resolve())
    return self._validated

with_vars(vars_)

This project with other vars, which are read at load; self when they are the same. It keeps the registry, clock, identity, invocation id and redactor.

Source code in src/pipeloom/api.py
def with_vars(self, vars_: Mapping[str, Any]) -> Project:
    """This project with other vars, which are read at load; self when they are the same.
    It keeps the registry, clock, identity, invocation id and redactor."""
    if dict(vars_) == dict(self.options.vars):
        return self
    other = Project(
        replace(self.options, vars=vars_),
        registry=self.registry,
        clock=self.clock,
        identity=self._identity,
        invocation_id=self.invocation_id,
        redactor=self.redactor,
    )
    other._registry_problems = self._registry_problems
    return other