151 lines
6.0 KiB
Python
151 lines
6.0 KiB
Python
"""Sources over stored results: reuse any node's outputs as seeds for new work.
|
|
|
|
- `store.query`: select items from this (or another project's) store by graph, node,
|
|
port, run, kind, provenance, labels, an expression and lineage.
|
|
- `graph.import`: the virtual source behind cross-graph edges (`alias:node.port`
|
|
inputs; see `pipewright.imports`). Not usually written by hand.
|
|
|
|
Both emit the stored items unchanged (same ids), so downstream results computed for
|
|
them before are memoized: re-running only processes items that are new upstream.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from pathlib import Path
|
|
from typing import Literal
|
|
|
|
from pydantic import BaseModel, ConfigDict, Field
|
|
|
|
from ..errors import ConfigError
|
|
from ..registry import register_node
|
|
from ..store import Store
|
|
from .base import ANY, NodeType, Port
|
|
from .builtin import _check_exprs
|
|
|
|
|
|
class P(BaseModel):
|
|
model_config = ConfigDict(extra="forbid")
|
|
|
|
|
|
def _open_other(ctx, store: str | None) -> Store | None:
|
|
"""None for this project's store; else a Store on `store` (a store dir, a project
|
|
file, or a directory containing pipewright.yaml)."""
|
|
if not store:
|
|
return None
|
|
path = ctx.resolve_path(store)
|
|
if path.is_file() or (path / "pipewright.yaml").exists():
|
|
from ..project import Project
|
|
|
|
proj = Project.load(path if path.is_file() else path / "pipewright.yaml")
|
|
path = proj.store_dir
|
|
if path.resolve() == Path(ctx.store.root).resolve():
|
|
return None
|
|
if not (path / "index.sqlite").exists():
|
|
raise ConfigError(f"no pipewright store at {path}")
|
|
return Store(path)
|
|
|
|
|
|
def query_and_copy(ctx, store: str | None, **q) -> list:
|
|
other = _open_other(ctx, store)
|
|
src = other or ctx.store
|
|
try:
|
|
items = src.query(exclude_run=ctx.run_id, **q)
|
|
if other is not None:
|
|
ctx.store.copy_from(other, [i.id for i in items]) # local lineage + blobs
|
|
return items
|
|
finally:
|
|
if other is not None:
|
|
other.close()
|
|
|
|
|
|
class StoreQueryParams(P):
|
|
graph: str | None = Field(None, description="graph name whose runs to read (default: this graph)")
|
|
node: str | None = Field(None, description="node whose outputs to select (default: every item those runs "
|
|
"stored)")
|
|
port: str | None = Field(None, description="output port (default: all ports of the node)")
|
|
run: str = Field("latest", description="latest | previous | all | <run id or prefix>; the current run is "
|
|
"never read")
|
|
store: str | None = Field(None, description="another project's store dir or project file (default: this one); "
|
|
"selected items are copied here with their lineage")
|
|
kind: str | None = Field(None, description="keep only items of this kind; also the declared output kind")
|
|
provenance: Literal["real", "derived", "synthetic"] | None = None
|
|
labels: dict[str, object] = Field(default_factory=dict, description="label equality filters")
|
|
where: str | None = Field(None, description="expression over each item, e.g. labels.pass_rate >= 0.75")
|
|
derived_from: str | None = Field(None, description="keep only descendants of this item (id, prefix or key)")
|
|
limit: int | None = Field(None, ge=1)
|
|
|
|
|
|
@register_node
|
|
class StoreQuery(NodeType):
|
|
"""Select earlier results as seeds for new work: items that flowed out of a node
|
|
(and port) in a previous run of this or another graph (or another project's store),
|
|
filtered by labels, provenance, an expression and lineage. Examples: validated tasks
|
|
whose pass rate is at least 0.75; items routed to `too_easy` in run X; failures
|
|
audited in the previous run, fed back to a generator (re-entrant loop without a
|
|
live cycle). Items keep their ids, so downstream work on them stays memoized."""
|
|
|
|
name = "store.query"
|
|
kind = "source"
|
|
Params = StoreQueryParams
|
|
outputs = {"out": Port(kind=ANY)}
|
|
cacheable = False
|
|
example = {"graph": "coding-tasks", "node": "bucket", "port": "too_easy", "run": "latest",
|
|
"where": "labels.pass_rate >= 0.75", "kind": "task_result"}
|
|
|
|
@classmethod
|
|
def output_ports(cls, params):
|
|
return {"out": Port(kind=(params.kind if params and params.kind else ANY))}
|
|
|
|
@classmethod
|
|
def validate_params(cls, params) -> list[str]:
|
|
return _check_exprs([params.where]) if params.where else []
|
|
|
|
async def generate(self, ctx):
|
|
p = self.params
|
|
items = query_and_copy(ctx, p.store, graph=p.graph or ctx.engine.spec.name, node=p.node, port=p.port,
|
|
run=p.run, kind=p.kind, provenance=p.provenance, labels=p.labels or None,
|
|
where=p.where, derived_from=p.derived_from, limit=p.limit)
|
|
for it in items:
|
|
yield it
|
|
|
|
|
|
class GraphImportParams(P):
|
|
graph: str
|
|
node: str
|
|
ports: dict[str, str] = Field(description="port -> item kind")
|
|
run: str = "latest"
|
|
store: str | None = None
|
|
where: str | None = None
|
|
alias: str = ""
|
|
source: str = ""
|
|
|
|
|
|
@register_node
|
|
class GraphImport(NodeType):
|
|
"""Outputs of another graph's node (a cross-graph edge). Generated from a graph's
|
|
`imports:` for every `alias:node.port` input; one output port per referenced port."""
|
|
|
|
name = "graph.import"
|
|
kind = "source"
|
|
Params = GraphImportParams
|
|
outputs = {"out": Port(kind=ANY)}
|
|
cacheable = False
|
|
example = {"graph": "build", "node": "bucket", "ports": {"too_easy": "task_result"}}
|
|
|
|
@classmethod
|
|
def output_ports(cls, params):
|
|
if params is None:
|
|
return dict(cls.outputs)
|
|
return {p: Port(kind=k) for p, k in params.ports.items()}
|
|
|
|
@classmethod
|
|
def validate_params(cls, params) -> list[str]:
|
|
return _check_exprs([params.where]) if params.where else []
|
|
|
|
async def generate(self, ctx):
|
|
p = self.params
|
|
for port in sorted(p.ports):
|
|
for it in query_and_copy(ctx, p.store, graph=p.graph, node=p.node, port=port, run=p.run,
|
|
where=p.where):
|
|
yield port, it
|