Skip to content

The platform for continuously improving AI agents.

16.2 KB
Raw Blame
import hashlib
import io
import json
import zipfile
from copy import deepcopy

from django.core.files.base import ContentFile
from django.db import transaction

from overbae.core.errors import InputValidationError
from overbae.models import (
    DatasetPipeline,
    DatasetPipelineRun,
    ExperimentExecution,
    ResearchAssignment,
    ResearchExperiment,
)
from overbae.services import (
    context_graph,
    execution_mandates,
    experiment_reuse,
    research_context_authorship,
    research_experiments,
    research_team,
)
from overbae.services.datasets import pipeline_graph, pipeline_packages, workbench
from overbae.services.experiment_compiler import substitute
from overbae.services.research_tools import source_cell, sources_permitted


def locate(document, path):
    parts = path.split("/")
    if len(parts) > 6:
        raise InputValidationError("Source nesting exceeds the experiment limit")
    for part in parts[:-1]:
        group = next((item for item in document["nodes"] if item["id"] == part), None)
        if group is None or group["kind"] != "map":
            raise InputValidationError("The variant recipe is unavailable in this revision")
        document = group["config"].get("recipe")
        if document is None:
            raise InputValidationError(
                "Copy the pinned recipe into this experiment before editing its source"
            )
    selected = next((item for item in document["nodes"] if item["id"] == parts[-1]), None)
    if selected is None:
        raise InputValidationError("The node is unavailable in this revision")
    return document, selected


def definition(experiment, revision, node):
    saved = experiment.revisions.filter(number=revision).first()
    if saved is None:
        raise InputValidationError("The experiment revision is unavailable")
    document = deepcopy(saved.document)
    local, selected = locate(document, node)
    return document, local, selected


def recipe_for(experiment, node):
    operation = node.get("operation") or {}
    envelope = operation.get("arguments", {})
    if operation.get("tool") != "platform" or envelope.get("name") != "run_dataset_pipeline":
        return None
    recipe = (
        DatasetPipeline.objects.filter(
            project=experiment.project, pk=envelope.get("arguments", {}).get("pipeline")
        )
        .select_related("package")
        .first()
    )
    if recipe is None or not recipe.package_id:
        raise InputValidationError(
            "The retained preparation package is unavailable in this project"
        )
    return recipe


def inspect(experiment, *, revision, node, run=None, assignment=None):
    document, local, selected = definition(experiment, revision, node)
    if run is not None:
        run = ExperimentExecution.objects.filter(
            pk=run, revision__experiment=experiment, revision__number=revision
        ).first()
        if run is None:
            raise InputValidationError("The run is unavailable in this experiment revision")
        document = run.document
        local, selected = locate(document, node)
    recipe = recipe_for(experiment, selected)
    if recipe:
        files = pipeline_packages.files(recipe.package)
        files.pop("manifest.json", None)
        manifest = recipe.package.manifest
        kind, reason = "preparation", ""
    elif selected["kind"] == "transform" and not selected.get("operation"):
        contract = pipeline_packages.authoring_contract()
        files, manifest = {"transform.py": contract["starter_script"]}, contract["manifest"]
        kind, reason = "preparation", ""
    else:
        files, manifest, kind = {}, {}, "unsupported"
        reason = (
            "This step is configured through its operation settings, not retained Python source."
        )
    source = {
        "experiment": str(experiment.pk),
        "revision": revision,
        "node": node,
        "owner": selected["id"],
        "kind": kind,
        "editable": kind != "unsupported" and revision == experiment.version and run is None,
        "reason": reason,
        "files": files,
        "manifest": manifest,
        "fingerprint": context_graph.fingerprint({"files": files, "manifest": manifest}),
        "pipeline": str(recipe.pk) if recipe else None,
        "package": str(recipe.package_id) if recipe else None,
        "steps": pipeline_graph.describe(manifest["steps"])["nodes"]
        if kind == "preparation"
        else [],
    }
    if assignment is not None:
        source = research_context_authorship.project_packets(
            assignment, source, lambda cells: sources_permitted(assignment, cells)
        )
    return source


def package_bytes(files, manifest):
    if not isinstance(files, dict) or "manifest.json" in files:
        raise InputValidationError("Supply source files and a separate manifest")
    if (
        len(files) >= 100
        or any(not isinstance(value, str) for value in files.values())
        or sum(len(value.encode()) for value in files.values()) > pipeline_packages.MAX_BYTES
    ):
        raise InputValidationError(
            "Preparation source must contain fewer than 100 text files and at most 10 MiB"
        )
    target = io.BytesIO()
    with zipfile.ZipFile(target, "w", compression=zipfile.ZIP_DEFLATED) as archive:
        for path, content in sorted(
            {**files, "manifest.json": json.dumps(manifest, sort_keys=True)}.items()
        ):
            if not isinstance(content, str):
                raise InputValidationError("Source files must contain text")
            archive.writestr(zipfile.ZipInfo(path), content)
    return target.getvalue()


@transaction.atomic
def save(experiment, user, *, expected_version, node, files, manifest, request_key, agent=None):
    experiment = (
        ResearchExperiment.objects.select_for_update(of=("self",))
        .select_related("project")
        .get(pk=experiment.pk)
    )
    if agent is not None:
        research_team.current_turn(agent)
    if not request_key.strip() or len(request_key) > 100:
        raise InputValidationError("Supply a request key of 1–100 characters")
    revision_key = f"source:{context_graph.fingerprint(request_key)}"
    existing = experiment.revisions.filter(request_key=revision_key).first()
    if existing is None and experiment.version != expected_version:
        raise InputValidationError(
            f"The experiment changed: expected revision {expected_version}, current revision {experiment.version}. Your source has not been overwritten."
        )
    document, local, selected = definition(experiment, expected_version, node)
    if selected["kind"] == "transform":
        previous = recipe_for(experiment, selected)
        if selected.get("operation") and previous is None:
            raise InputValidationError(
                "Only a retained Python preparation step supports source editing"
            )
        author = (
            research_context_authorship.action_for(experiment.project, request_key)
            if agent is not None
            else None
        )
        package = pipeline_packages.save(
            experiment.project,
            user,
            ContentFile(package_bytes(files, manifest)),
            actor=agent,
            author=author,
            source_cells=pipeline_packages.authored_sources(previous.package)
            if previous
            else set(),
        )
        recipe = workbench.save_pipeline(
            experiment.project,
            user,
            name=selected["title"],
            request_key=f"experiment:{experiment.pk}:{context_graph.fingerprint(request_key)[:32]}",
            package=package.pk,
            derived_from=previous.pk if previous else None,
        )
        arguments = (selected.get("operation") or {}).get("arguments", {}).get("arguments", {})
        selected["operation"] = {
            "tool": "platform",
            "arguments": {
                "name": "run_dataset_pipeline",
                "arguments": {**arguments, "pipeline": str(recipe.pk)},
            },
        }
    else:
        raise InputValidationError("This node does not support source editing")
    revision = research_experiments.revise(
        experiment,
        expected_version=expected_version,
        document=document,
        request_key=revision_key,
        note=f"Edit source for {node}",
        agent=agent,
    )
    experiment.refresh_from_db()
    return inspect(experiment, revision=revision.number, node=node)


def closure(manifest, step):
    graph = pipeline_graph.describe(manifest["steps"])
    nodes = {item["id"]: item for item in graph["nodes"]}
    if step not in nodes:
        raise InputValidationError("Select a retained preparation step")
    needed = set()

    def include(identity):
        if identity == "source" or identity in needed:
            return
        needed.add(identity)
        for parent in nodes[identity]["inputs"]:
            include(parent)

    include(step)
    steps = []
    for item in graph["nodes"]:
        if item["id"] in needed:
            retained = deepcopy(manifest["steps"][item["step"]])
            retained.pop("input", None)
            steps.append({**retained, "id": item["id"], "inputs": item["inputs"]})
    return {**manifest, "steps": steps}


def input_cell(experiment, document, node, reuse_run, *, assignment=None):
    edges = [
        edge for edge in document["edges"] if edge["target"] == node and edge["input"] == "data"
    ]
    if len(edges) != 1:
        raise InputValidationError("Connect one exact dataset input before previewing")
    edge = edges[0]
    parent = next(item for item in document["nodes"] if item["id"] == edge["source"])
    if parent["kind"] == "data":
        binding = parent["config"]
    else:
        previous = experiment_reuse.candidates(experiment.project, document, reuse_run, [])
        receipt = previous.get(parent["id"])
        binding = receipt.outputs.get(edge["output"], {}) if receipt else {}
    if not binding.get("cell"):
        raise InputValidationError(
            "Execute the upstream preparation or select a compatible retained run first"
        )
    if assignment is None:
        root = f"cell:{binding['cell']}"
        assignment = ResearchAssignment(
            project=experiment.project,
            specification={"context_roots": [root]},
            execution_mandate=execution_mandates.admission(
                roots=[root], authority="observe", families=["read"]
            ),
        )
    elif assignment.project_id != experiment.project_id:
        raise InputValidationError("The preview assignment belongs to another project")
    cell = source_cell(assignment, binding["cell"])
    if cell.fingerprint != binding.get("fingerprint"):
        raise InputValidationError("The input fingerprint changed; inspect the current source")
    return cell


@transaction.atomic
def preview(
    experiment,
    user,
    *,
    revision,
    node,
    step,
    request_key,
    parameters=None,
    preview_rows=100,
    reuse_run=None,
    assignment=None,
    agent=None,
):
    if not request_key.strip() or len(request_key) > 100:
        raise InputValidationError("Supply a request key of 1–100 characters")
    experiment = (
        ResearchExperiment.objects.select_for_update(of=("self",))
        .select_related("project")
        .get(pk=experiment.pk)
    )
    if agent is not None:
        research_team.current_turn(agent)
    document, local, selected = definition(experiment, revision, node)
    recipe = recipe_for(experiment, selected)
    if recipe is None:
        raise InputValidationError("Save a retained preparation package before previewing")
    if local is not document:
        raise InputValidationError(
            "Preview shared preparation on the outer canvas before running variants"
        )
    if assignment is not None:
        research_context_authorship.require_pipeline(assignment, recipe.pk)
    manifest = closure(recipe.package.manifest, step)
    files = pipeline_packages.files(recipe.package)
    files.pop("manifest.json", None)
    content = package_bytes(files, manifest)
    parameters = (
        parameters
        if parameters is not None
        else substitute(
            selected["operation"]["arguments"]["arguments"].get("parameters", {}),
            {
                name: item["default"]
                for name, item in document.get("parameters", {}).items()
                if "default" in item
            },
        )
    )
    key = context_graph.fingerprint({"experiment": str(experiment.pk), "request_key": request_key})
    previous = (
        DatasetPipelineRun.objects.select_related("pipeline__package")
        .filter(dataset__project=experiment.project, request_key=f"preview:{key}")
        .first()
    )
    if previous:
        context = previous.specification.get("context", {})
        if (
            any(
                context.get(name) != value
                for name, value in {
                    "experiment": str(experiment.pk),
                    "revision": revision,
                    "node": node,
                    "step": step,
                }.items()
            )
            or context.get("reuse_run") != (str(reuse_run) if reuse_run else None)
            or previous.specification.get("parameters") != parameters
            or previous.specification.get("preview_rows") != preview_rows
            or previous.pipeline.package.sha256 != hashlib.sha256(content).hexdigest()
        ):
            raise InputValidationError("This preview key identifies different work")
        return workbench.run_record(previous)
    if experiment.scientific_lock:
        raise InputValidationError("Final qualification has frozen this experiment's preparation")
    if assignment:
        execution_mandates.require(assignment, "prepare")
    cell = input_cell(experiment, document, node, reuse_run, assignment=assignment)
    package = pipeline_packages.save(
        experiment.project,
        user,
        ContentFile(content),
        actor=agent,
        author=research_context_authorship.action_for(experiment.project, request_key)
        if agent is not None
        else None,
        source_cells=pipeline_packages.authored_sources(recipe.package),
    )
    bounded = workbench.save_pipeline(
        experiment.project,
        user,
        name=f"{selected['title']} · {step}",
        request_key=f"preview:{key}",
        package=package.pk,
        derived_from=recipe.pk,
    )
    run = workbench.submit(
        cell.dataset,
        user,
        source_cell=cell.pk,
        source_fingerprint=cell.fingerprint,
        request_key=f"preview:{key}",
        pipeline=bounded.pk,
        mode="preview",
        preview_rows=preview_rows,
        parameters=parameters,
        context={
            "experiment": str(experiment.pk),
            "revision": revision,
            "node": node,
            "step": step,
            "reuse_run": str(reuse_run) if reuse_run else None,
            **({"assignment": str(assignment.pk)} if assignment else {}),
        },
    )
    return workbench.run_record(run)


def previews(experiment, *, node):
    runs = (
        DatasetPipelineRun.objects.filter(
            dataset__project=experiment.project,
            mode="preview",
            request_key__startswith="preview:",
            specification__context__experiment=str(experiment.pk),
            specification__context__node=node,
        )
        .select_related("pipeline__package", "dataset__project", "source")
        .order_by("-created_at")[:20]
    )
    return [workbench.run_record(run) | {"context": run.specification["context"]} for run in runs]


def page(source, filename=None, offset=0, limit=8000):
    source = dict(source)
    if source.get("access") == "sealed_data":
        return source
    files = source.pop("files")
    source["inventory"] = [
        {"path": path, "characters": len(text), "sha256": hashlib.sha256(text.encode()).hexdigest()}
        for path, text in sorted(files.items())
    ]
    if filename is not None:
        if filename not in files:
            raise InputValidationError("The file is unavailable in this source revision")
        text = files[filename]
        source["file"] = {
            "path": filename,
            "content": text[offset : offset + limit],
            "offset": offset,
            "total": len(text),
            "next_offset": offset + limit if offset + limit < len(text) else None,
        }
    return source