Skip to content

The platform for continuously improving AI agents.

13.3 KB
Raw Blame
from copy import deepcopy

from django.db import transaction
from django.utils.dateparse import parse_datetime
from pydantic import ValidationError

from overbae.core.errors import InputValidationError
from overbae.models import (
    DataPartitionPlan,
    ExperimentNodeExecution,
    ExperimentScope,
    ResearchExperimentRevision,
)
from overbae.services import (
    context_graph,
    experiment_partitions,
    experiment_preflight,
    experiment_reuse,
)
from overbae.services.experiment_catalog import resolved
from overbae.services.experiment_compiler import bind_parameters, compile_document
from overbae.services.experiment_contract import Document
from overbae.services.experiment_settings import CONTROL_SETTINGS, lookup, matches


def pin(project, document, trail=()):
    document = deepcopy(document)
    for node in document["nodes"]:
        if node["kind"] not in CONTROL_SETTINGS:
            continue
        settings = CONTROL_SETTINGS[node["kind"]].model_validate(node["config"])
        inline = node["kind"] == "map" and settings.recipe is not None
        reference = (
            ("inline", str(node["id"])) if inline else (str(settings.experiment), settings.revision)
        )
        if (not inline and reference in trail) or len(trail) >= 5:
            raise InputValidationError(
                "Subflow references must be acyclic and at most five levels deep"
            )
        if inline:
            source = Document.model_validate(settings.recipe).model_dump(mode="json")
        else:
            version = (
                ResearchExperimentRevision.objects.filter(
                    experiment_id=settings.experiment,
                    experiment__project=project,
                    number=settings.revision,
                )
                .select_related("experiment")
                .first()
            )
            if version is None:
                raise InputValidationError("Select an existing flow revision in this project")
            frozen = version.experiment.scientific_lock
            frozen_at = parse_datetime(str(frozen.get("at", ""))) if frozen else None
            if frozen and (frozen_at is None or version.created_at >= frozen_at):
                raise InputValidationError(
                    "A reporting revision created after final qualification cannot be an adaptive subflow"
                )
            source = version.document
        child = pin(project, source, (*trail, reference))
        unknown = (settings.inputs.keys() | settings.parameters.keys()) - child.get(
            "parameters", {}
        ).keys()
        if unknown or set(settings.inputs.values()) - resolved(node).inputs.keys():
            raise InputValidationError("Bind declared child parameters to the subflow input ports")
        connected = {edge["input"] for edge in document["edges"] if edge["target"] == node["id"]}
        if node["config"].get("model"):
            connected.add("model")
        if set(settings.inputs.values()) - connected:
            raise InputValidationError("Connect every mapped subflow input")
        child_nodes = {item["id"]: item for item in child["nodes"]}
        for port, name in settings.outputs.items():
            output = child.get("outputs", {}).get(name)
            if output is None or resolved(node).outputs.get(port) != resolved(
                child_nodes[output["node"]]
            ).outputs.get(output["port"]):
                raise InputValidationError(
                    "Subflow outputs must match the pinned child output types"
                )
        node["config"] = {**node["config"], "_definition": child}
        if node["kind"] == "map":
            node["config"]["keys"] = settings.keys
    return document


def validate_static(project, document):
    # Project validation calls scope pinning through the root admission service.
    from overbae.services.research_experiments import validate_document

    for node in document["nodes"]:
        if node["kind"] not in CONTROL_SETTINGS:
            continue
        settings = CONTROL_SETTINGS[node["kind"]].model_validate(node["config"])
        definition = Document.model_validate(settings.definition)
        bindings = settings.bindings if node["kind"] == "map" else [{}]
        for binding in bindings:
            values = {**settings.parameters, **binding}
            bind_parameters(definition.parameters, values, deferred=settings.inputs)
            child, _ = compile_document(settings.definition, values, deferred=settings.inputs)
            child = validate_document(project, child)
            if not settings.inputs:
                child = experiment_partitions.pin(project, child)
            experiment_preflight.validate(project, child)
            validate_static(project, child)


def data_roots(document):
    for node in document["nodes"]:
        if (
            node["kind"] == "data"
            and isinstance(node["config"].get("cell"), str)
            and not node["config"].get("_metadata_only")
        ):
            yield f"cell:{node['config']['cell']}"
        if node["kind"] == "split" and node["config"].get("_cached_partition"):
            plan = DataPartitionPlan.objects.get(pk=node["config"]["_cached_partition"])
            yield from (
                f"cell:{identifier}"
                for identifier in plan.members.exclude(role="final").values_list(
                    "cell_id", flat=True
                )
            )
        if node["kind"] in CONTROL_SETTINGS:
            yield from data_roots(node["config"]["_definition"])


def platform_sources(document):
    """Sources a sealed partition was cut from: the platform prepares them, no agent reads them."""
    for node in document["nodes"]:
        if node["kind"] == "data" and node["config"].get("_metadata_only"):
            yield node["config"]["cell"]
        if node["kind"] in CONTROL_SETTINGS:
            yield from platform_sources(node["config"]["_definition"])


@transaction.atomic
def create(execution, document, parameters, *, parent=None, index=0, variant_key=""):
    # Identity calculation excludes presentation-only edits, like root flow execution.
    from overbae.services.research_experiments import node_identity

    scope, created = ExperimentScope.objects.get_or_create(
        execution=execution,
        parent=parent,
        index=index,
        defaults={"document": document, "parameters": parameters, "variant_key": variant_key},
    )
    if created:
        ExperimentNodeExecution.objects.bulk_create(
            [
                ExperimentNodeExecution(
                    execution=execution,
                    scope=scope,
                    node=node["id"],
                    identity=node_identity(document, node["id"]),
                )
                for node in document["nodes"]
            ]
        )
    return scope


def outputs(scope, nodes):
    bindings = {}
    for name, reference in scope.document.get("outputs", {}).items():
        result = nodes[reference["node"]].outputs.get(reference["port"])
        if result is None and (
            nodes[reference["node"]].state == "skipped"
            or reference["port"] == "model"
            and nodes[reference["node"]].outputs.get("scores", {}).get("outcome")
            in {"tie", "no_qualifier", "insufficient_evidence"}
        ):
            continue
        if result is None:
            raise InputValidationError(f"The declared output {name} is unavailable")
        bindings[name] = result
    return bindings


def advance(parent, node):
    # Nested execution uses the same project validation and authority as the root.
    from overbae.services.research_experiments import validate_document

    settings = CONTROL_SETTINGS[node["kind"]].model_validate(node["config"])
    children = list(parent.scopes.order_by("index"))
    if parent.error:
        return {
            "state": "waiting" if any(child.state == "running" for child in children) else "failed",
            "error": parent.error,
            "outputs": {},
        }
    failed = next((child for child in children if child.state == "failed"), None)
    if failed and node["kind"] != "map":
        if any(child.state == "running" for child in children):
            return {"state": "waiting", "outputs": {}}
        return {"state": "failed", "error": failed.error, "outputs": {}}
    settled = children and all(
        child.state in {"completed", "failed", "cancelled"} for child in children
    )
    parameters = {
        **settings.parameters,
        **{parameter: parent.inputs[port] for parameter, port in settings.inputs.items()},
    }
    if node["kind"] == "iterate" and settled:
        latest = children[-1]
        if matches(latest.outputs, settings.until):
            return {
                "state": "completed",
                "outputs": {port: latest.outputs[name] for port, name in settings.outputs.items()},
            }
        if len(children) >= settings.max_iterations:
            return {
                "state": "failed",
                "error": "Iteration limit reached without meeting the declared stop criterion",
                "outputs": {},
            }
        parameters.update(
            {
                parameter: lookup(latest.outputs, path)
                for parameter, path in settings.feedback.items()
            }
        )
    elif settled and (node["kind"] != "map" or len(children) == len(settings.bindings)):
        if node["kind"] == "map":
            variants = [
                {
                    "key": child.variant_key or settings.keys[child.index],
                    "label": settings.labels.get(
                        settings.keys[child.index], settings.keys[child.index]
                    ),
                    "scope": str(child.pk),
                    "state": child.state,
                    "parameters": child.parameters,
                    "outputs": child.outputs,
                    "error": child.error,
                }
                for child in children
            ]
            result = {"kind": "variants", "variants": variants}
            outputs = {"variants": {**result, "fingerprint": context_graph.fingerprint(result)}}
            if "scores" in settings.outputs:
                reports = [
                    child.outputs[settings.outputs["scores"]]
                    for child in children
                    if settings.outputs["scores"] in child.outputs
                ]
                score_result = {
                    "kind": "scores",
                    "reports": reports,
                    "coverage": {
                        "complete": all(child.state == "completed" for child in children),
                        "expected": len(children),
                        "completed": len(reports),
                    },
                    "variants": variants,
                }
                outputs["scores"] = {
                    **score_result,
                    "fingerprint": context_graph.fingerprint(score_result),
                }
            return {"state": "completed", "outputs": outputs}
        return {
            "state": "completed",
            "outputs": {port: children[0].outputs[name] for port, name in settings.outputs.items()},
        }
    active = sum(child.state == "running" for child in children)
    count = (
        min(settings.concurrency - active, len(settings.bindings) - len(children))
        if node["kind"] == "map"
        else int(not children or (node["kind"] == "iterate" and settled))
    )
    admitted = []
    for index in range(len(children), len(children) + count):
        values = {**parameters, **(settings.bindings[index] if node["kind"] == "map" else {})}
        try:
            document, values = compile_document(settings.definition, values)
            document = validate_document(parent.execution.assignment.project, document)
            document = experiment_partitions.pin(parent.execution.assignment.project, document)
            experiment_preflight.validate(parent.execution.assignment.project, document)
            admitted.append((index, document, values))
        except (InputValidationError, ValidationError, ValueError) as exc:
            if node["kind"] == "map":
                rejected = create(
                    parent.execution,
                    settings.definition,
                    values,
                    parent=parent,
                    index=index,
                    variant_key=settings.keys[index],
                )
                rejected.state, rejected.error = "failed", str(exc)
                rejected.save(update_fields=["state", "error"])
                rejected.nodes.update(
                    state="cancelled", error="Not admitted: candidate inputs are invalid"
                )
                continue
            parent.error = str(exc)
            parent.save(update_fields=["error"])
            return {
                "state": "waiting"
                if any(child.state == "running" for child in children)
                else "failed",
                "error": str(exc),
                "outputs": {},
            }
    for index, document, values in admitted:
        child = create(
            parent.execution,
            document,
            values,
            parent=parent,
            index=index,
            variant_key=settings.keys[index] if node["kind"] == "map" else "",
        )
        experiment_reuse.apply(child, experiment_reuse.nested_candidates(child))
    return {"state": "waiting", "outputs": {}}