Skip to content

The platform for continuously improving AI agents.

7.8 KB
Raw Blame
from collections import Counter

from pydantic import ValidationError

from overbae.core.errors import InputValidationError
from overbae.services import (
    context_graph,
    experiment_interfaces,
    experiment_partitions,
    experiment_preflight,
    experiment_reuse,
    experiment_scopes,
)
from overbae.services.experiment_compiler import compile_document
from overbae.services.experiment_settings import CONTROL_SETTINGS


def definition(experiment, revision, parameters):
    # The experiment document service also calls admission.
    from overbae.services import research_experiments

    version = experiment.revisions.filter(number=revision).first()
    if version is None:
        raise InputValidationError("Select a saved experiment revision")
    try:
        document, bindings = compile_document(version.document, parameters or {})
        document = research_experiments.validate_document(experiment.project, document)
        document = experiment_scopes.pin(
            experiment.project, document, ((str(experiment.pk), revision),)
        )
        experiment_interfaces.validate(document, executable=True)
        document = experiment_partitions.pin(experiment.project, document)
        experiment_preflight.expansion(document)
    except ValidationError as exc:
        details = "; ".join(
            f"{'.'.join(map(str, item['loc']))}: {item['msg']}"
            for item in exc.errors(include_input=False, include_url=False)[:6]
        )
        raise InputValidationError(f"Complete the flow configuration: {details}") from exc
    return version, document, bindings


def validate(experiment, document):
    experiment_scopes.validate_static(experiment.project, document)
    experiment_preflight.validate(experiment.project, document)


def prepare(experiment, revision, parameters):
    version, document, bindings = definition(experiment, revision, parameters)
    validate(experiment, document)
    return version, document, bindings


def work(project, document, reused, path=(), prior=None, forced=()):
    entries = []
    for node in document["nodes"]:
        operation = node.get("operation") or {}
        tool, arguments = operation.get("tool"), operation.get("arguments", {})
        action = arguments.get("name") if tool == "platform" else arguments.get("operation")
        previous = reused.get(node["id"])
        resource = (
            "training"
            if tool == "training" and action == "create"
            else "evaluation"
            if tool in {"benchmark", "prediction", "score"} and action == "run"
            else "deployment"
            if tool == "serving" and action == "deploy"
            else "preparation"
            if node["kind"] in {"transform", "split"}
            else "agent"
            if node["kind"] == "research"
            else "execution"
            if operation
            else None
        )
        entries.append(
            {
                "node": node["id"],
                "title": node["title"],
                "kind": node["kind"],
                "path": list(path),
                "disposition": "reuse"
                if previous
                else "execute"
                if resource
                else "reference"
                if node["kind"] in {"data", "model", "suite"}
                else "coordinate",
                "resource": resource,
                "receipt": str(previous.pk) if previous else None,
                "reason": "Unchanged definition, inputs and verified retained output"
                if previous
                else "New execution or changed/unavailable evidence"
                if resource
                else "",
                "limit_usd": node["config"].get("trial", {}).get("allocation_usd"),
            }
        )
        if node["kind"] in CONTROL_SETTINGS and not previous:
            settings = CONTROL_SETTINGS[node["kind"]].model_validate(node["config"])
            bindings = (
                settings.bindings
                if node["kind"] == "map"
                else [{}] * (settings.max_iterations if node["kind"] == "iterate" else 1)
            )
            for index, binding in enumerate(bindings):
                incoming = [edge for edge in document["edges"] if edge["target"] == node["id"]]
                known = experiment_reuse.scope_candidates(
                    project, document, prior, forced, include_sources=True
                )
                inputs = {
                    edge["input"]: known[edge["source"]].outputs[edge["output"]]
                    for edge in incoming
                    if edge["source"] in known and edge["output"] in known[edge["source"]].outputs
                }
                bound = all(port in inputs for port in settings.inputs.values())
                values = {
                    **settings.parameters,
                    **binding,
                    **(
                        {parameter: inputs[port] for parameter, port in settings.inputs.items()}
                        if bound
                        else {}
                    ),
                }
                child, _ = compile_document(
                    settings.definition,
                    values,
                    deferred=settings.inputs,
                )
                key = settings.keys[index] if node["kind"] == "map" else str(index)
                previous_scope = (
                    experiment_reuse.child_scope(
                        prior, node["id"], key=key if node["kind"] == "map" else "", index=index
                    )
                    if bound and node["id"] not in forced
                    else None
                )
                if previous_scope and previous_scope.parent.inputs != inputs:
                    previous_scope = None
                child_reused = experiment_reuse.scope_candidates(project, child, previous_scope)
                entries.extend(
                    work(project, child, child_reused, (*path, node["id"], key), previous_scope)
                )
    return entries


def resolve(experiment, *, revision, parameters=None, reuse_run=None, rerun_from=None):
    experiment.refresh_from_db(fields=["version"])
    version, document, bindings = prepare(experiment, revision, parameters)
    reused = experiment_reuse.candidates(experiment.project, document, reuse_run, rerun_from or [])
    prior = experiment_reuse.source_scope(experiment.project, reuse_run)
    forced = set(rerun_from or ())
    for _ in document["nodes"]:
        forced.update(edge["target"] for edge in document["edges"] if edge["source"] in forced)
    entries = work(experiment.project, document, reused, prior=prior, forced=forced)
    resources = Counter(item["resource"] for item in entries if item["disposition"] == "execute")
    inputs = [
        {
            "node": node["id"],
            "cell": node["config"].get("cell"),
            "fingerprint": node["config"].get("fingerprint"),
        }
        for node in document["nodes"]
        if node["kind"] == "data"
    ]
    result = {
        "experiment": str(experiment.pk),
        "revision": revision,
        "head_version": experiment.version,
        "definition": version.fingerprint,
        "parameters": bindings,
        "inputs": inputs,
        "entries": entries,
        "node_attempts": experiment_preflight.expansion(document),
        "resources": dict(resources),
        "reuse_run": str(reuse_run) if reuse_run else None,
        "rerun_from": sorted(set(rerun_from or [])),
        "cost_usd": None,
        "cost_note": "Cost estimate unavailable. Allocations are limits, not expected charges.",
        "job_note": "Execution requests; provider calls and validation work may expand within each job. Iterations show their upper bound.",
    }
    return {
        **result,
        "fingerprint": context_graph.fingerprint({**result, "resolved_document": document}),
    }