Skip to content

The platform for continuously improving AI agents.

6.7 KB
Raw Blame
"""A transform spec written out as a retained pipeline package.

The package is a fixed program and a plan for it. The same spec over the same source columns
gives the same bytes, so saving it twice keeps one package.
"""

import hashlib
import io
import json
import zipfile
from pathlib import Path

from django.db.models import F

from overbae.core.errors import DatasetError
from overbae.models import DatasetPipelineRun
from overbae.services.datasets import (
    column_profile,
    pipeline_packages,
    rows,
    store,
    transform_program,
    transform_spec,
)

PROGRAM = Path(transform_program.__file__).read_text()
ENTRYPOINT = "transform.py"


def select(spec, read):
    """One query over the source: the label as stored, each input and each group key."""
    quote = store.quote_identifier
    columns = [
        quote(store.SOURCE_ROW),
        f"CAST({quote(spec.target.column)} AS VARCHAR) AS {quote(transform_program.TARGET)}",
        *(f"({item.sql}) AS {quote(item.name)}" for item in (*spec.inputs, *spec.group_keys)),
    ]
    where = f" WHERE ({spec.filter})" if spec.filter else ""
    return f"SELECT {', '.join(columns)} FROM source{where} ORDER BY {quote(store.SOURCE_ROW)}"


def restricted_error():
    return DatasetError(
        "Held-out sources require an identical previously verified preparation. "
        "Develop new recipes on readable training or development data.",
        code="sealed_preparation",
    )


def compile_package(spec, cell, *, profile=None):
    columns = transform_spec.source_columns(cell)
    read = transform_spec.lineage(spec, columns, profile)
    used = {spec.target.column, *(name for names in read.values() for name in names)}
    plan = {
        "spec": spec.model_dump(mode="json"),
        "columns": {column["name"]: column["type"] for column in columns if column["name"] in used},
        "select": select(spec, read),
        "reads": read,
    }
    manifest = {
        "version": 1,
        "runtime": pipeline_packages.runtime_id(),
        "steps": [
            {
                "name": "Prepare",
                "entrypoint": ENTRYPOINT,
                "input_schema": dict.fromkeys(sorted(used), "any"),
                "output_schema": {
                    store.SOURCE_ROW: "integer",
                    "decision": "object",
                    **{item.name: "any" for item in spec.group_keys},
                },
                "consumer": spec.consumer,
            }
        ],
    }
    stream = io.BytesIO()
    with zipfile.ZipFile(stream, "w", zipfile.ZIP_DEFLATED) as archive:
        for name, content in (
            ("manifest.json", json.dumps(manifest, sort_keys=True)),
            ("plan.json", json.dumps(plan, sort_keys=True, ensure_ascii=False, indent=1)),
            (ENTRYPOINT, PROGRAM),
        ):
            # A fixed timestamp: the archive's bytes depend on its contents alone.
            archive.writestr(zipfile.ZipInfo(name), content)
    return stream.getvalue(), read


def publication_invocation(run):
    return (
        run.mode == run.specification.get("mode") == "publish"
        and run.specification.get("parameters") == {}
        and run.specification.get("preview_rows") == 100
        and not run.specification.get("execution")
    )


def require_verified(cell, package, *, run=None):
    # Workbench invokes the compiler's preparation checks during publication.
    from overbae.services.datasets.workbench import execution_definition

    identity = hashlib.sha256(package).hexdigest()
    candidates = (
        DatasetPipelineRun.objects.filter(
            dataset__project_id=cell.dataset.project_id,
            source__dataset__project_id=cell.dataset.project_id,
            pipeline__project_id=cell.dataset.project_id,
            pipeline__package__project_id=cell.dataset.project_id,
            pipeline__package__sha256=identity,
            source_fingerprint=cell.fingerprint,
            source__fingerprint=F("source_fingerprint"),
            source__state="ok",
            output__dataset_id=F("dataset_id"),
            output__state="ok",
            state="completed",
            mode="publish",
        )
        .select_related("pipeline__package", "source__dataset", "output__dataset")
        .order_by("-created_at")
    )
    if run is not None:
        candidates = candidates.filter(pk=run.pk)
    for run in candidates[:100]:
        steps = run.result.get("steps", [])
        if (
            not publication_invocation(run)
            or run.result.get("definition") != execution_definition(run.pipeline)
            or not isinstance(steps, list)
            or len(steps) != 1
            or not isinstance(steps[0], dict)
        ):
            continue
        step = steps[0]
        checks = step.get("preparation") or {}
        if (
            not isinstance(checks, dict)
            or step.get("state") != "completed"
            or step.get("input_fingerprint") != run.source_fingerprint
            or step.get("inputs")
            != [
                {
                    "step": "source",
                    "cell": str(run.source_id),
                    "fingerprint": run.source_fingerprint,
                    "rows": run.source.rows,
                }
            ]
            or step.get("output_cell") != str(run.output_id)
            or not run.output.fingerprint
            or step.get("output_fingerprint") != run.output.fingerprint
            or checks.get("failed") != []
            or checks.get("rows") != run.output.rows
        ):
            continue
        try:
            pipeline_packages.files(run.pipeline.package)
            rows.verify(run.output)
        except (DatasetError, OSError, ValueError, rows.RowStoreError):
            continue
        return
    raise restricted_error()


def publication_sources(run, sources):
    sources = set(sources)
    if str(run.source_id) not in sources or not run.pipeline_id or not run.pipeline.package_id:
        return sources
    try:
        files = pipeline_packages.files(run.pipeline.package)
        spec = transform_spec.TransformSpec.model_validate(json.loads(files["plan.json"])["spec"])
        package, _ = compile_package(spec, run.source)
        if hashlib.sha256(package).hexdigest() != run.pipeline.package.sha256:
            return sources
        require_verified(run.source, package, run=run)
    except (KeyError, TypeError, ValueError, DatasetError, OSError, rows.RowStoreError):
        return sources
    # This exact checked publication carries its own row source through partition lineage.
    # Code reads, future execution and unrelated authoring context retain their full sources.
    return sources - {str(run.source_id)}


def build(spec, cell):
    return compile_package(spec, cell, profile=column_profile.of(cell))