Skip to content

The platform for continuously improving AI agents.

10.9 KB
Raw Blame
from copy import deepcopy

from django.utils import timezone

from overbae.core.errors import InputValidationError
from overbae.models import (
    Cell,
    DatasetPipelineRun,
    ExperimentAsset,
    ExperimentExecution,
    NativeEvaluationPlan,
    PredictionEvaluation,
    PredictionSet,
    ResearchArtifact,
)
from overbae.services import context_graph, experiment_execution, research, research_evidence
from overbae.services.datasets import workbench
from overbae.services.experiment_interfaces import operation_key


def reusable_operation(node):
    if node["kind"] in {"data", "model", "suite", "compare", "join", "condition"}:
        return True
    if operation_key(node) in {("prediction", "run"), ("score", "run")}:
        return True
    if node["kind"] in {"subflow", "map", "iterate"}:
        return all(reusable_operation(child) for child in node["config"]["_definition"]["nodes"])
    operation = node.get("operation") or {}
    return (
        node["kind"] == "train"
        and operation.get("tool") == "training"
        # A check or an export of an exact dataset version writes the same receipt again.
        or node["kind"] in {"transform", "split", "check_data", "export_data"}
        and operation.get("tool") == "platform"
        or node["kind"] == "evaluate"
        and (
            operation.get("tool") == "benchmark"
            and operation.get("arguments", {}).get("phase", "development") == "development"
            or operation.get("tool") == "training"
            and operation.get("arguments", {}).get("operation") == "inspect"
        )
    )


def measured(binding):
    if binding.get("kind") != "scores":
        return False
    if binding.get("coverage", {}).get("complete") is False:
        return False
    if binding.get("report"):
        return (
            binding.get("phase") == "development"
            and binding["report"].get("completion", {}).get("status") == "complete"
        )
    if binding.get("selected"):
        return measured(binding["selected"]["input"])
    reports = binding.get("reports")
    return bool(reports) and all(measured(report.get("input", report)) for report in reports)


def retained(project, binding):
    if binding.get("kind") == "variants":
        return bool(binding.get("variants")) and all(
            variant["state"] == "completed"
            and all(retained(project, output) for output in variant["outputs"].values())
            for variant in binding["variants"]
        )
    if binding.get("artifact"):
        return ResearchArtifact.objects.filter(
            assignment__project=project, pk=binding["artifact"], sha256=binding.get("fingerprint")
        ).exists()
    if binding.get("asset"):
        return ExperimentAsset.objects.filter(
            project=project, pk=binding["asset"], fingerprint=binding.get("fingerprint")
        ).exists()
    if binding.get("prediction_set"):
        return PredictionSet.objects.filter(
            project=project,
            pk=binding["prediction_set"],
            state="completed",
            fingerprint=binding.get("fingerprint"),
        ).exists()
    if binding.get("evaluation"):
        if PredictionEvaluation.objects.filter(
            run__project=project,
            run_id=binding["evaluation"],
            run__status="completed",
            fingerprint=binding.get("fingerprint"),
        ).exists():
            return True
        native = NativeEvaluationPlan.objects.filter(
            project=project, pk=binding["evaluation"], state="completed"
        ).first()
        return bool(
            native
            and measured(binding)
            and binding.get("data") == str(native.final_cell_id)
            and native.config.get("purpose") == "development"
            and binding.get("fingerprint")
            == context_graph.fingerprint({"config": native.config, "results": native.results})
        )
    if binding.get("kind") == "model":
        return not binding.get("job") or research_evidence.verified_model(project, binding)
    if binding.get("kind") == "data":
        return Cell.objects.filter(
            dataset__project=project,
            pk=binding.get("cell"),
            fingerprint=binding.get("fingerprint"),
            state="ok",
        ).exists()
    return measured(binding)


def retained_implementation(project, node, previous):
    visited = set()
    while previous.reused_from_id:
        if previous.pk in visited or previous.identity != previous.reused_from.identity:
            return False
        visited.add(previous.pk)
        previous = previous.reused_from
    if node["kind"] in {"subflow", "map", "iterate"}:
        scopes = list(previous.scopes.prefetch_related("nodes"))
        if not scopes or any(scope.state != "completed" for scope in scopes):
            return False
        for scope in scopes:
            latest = {
                item.node: item for item in sorted(scope.nodes.all(), key=lambda item: item.attempt)
            }
            for child in scope.document["nodes"]:
                receipt = latest.get(child["id"])
                if receipt is None or receipt.state not in {"completed", "skipped"}:
                    return False
                if receipt.state == "completed" and not retained_implementation(
                    project, child, receipt
                ):
                    return False
        return True
    if operation_key(node) != ("platform", "run_dataset_pipeline"):
        return True
    arguments = node["operation"]["arguments"]["arguments"]
    if not arguments.get("pipeline") or previous.action_id is None:
        return False
    recipe = workbench.resolve_pipeline(
        project, arguments["pipeline"], parameters=arguments.get("parameters", {})
    )
    receipt = DatasetPipelineRun.objects.filter(
        dataset__project=project,
        request_key=f"research:{previous.action_id}",
        pipeline=recipe,
        state="completed",
    ).first()
    return receipt is not None and receipt.result.get(
        "definition"
    ) == workbench.execution_definition(recipe)


def source_scope(project, identifier):
    if not identifier:
        return None
    # A stopped or expired run keeps the stages it completed; those are as reusable as a
    # finished run's.
    source = ExperimentExecution.objects.filter(
        pk=identifier, assignment__project=project, assignment__state__in=research.TERMINAL
    ).first()
    if source is None or source.engine_version != 1:
        raise InputValidationError("Select a settled compatible flow run in this project")
    if (
        source.lease
        or experiment_execution.has_unconfirmed_work(source.assignment)
        or source.nodes.filter(action__state__in=["unknown", "running", "pending"]).exists()
    ):
        raise InputValidationError("Settle provider acknowledgements before reusing this run")
    return source.scopes.get(parent__isnull=True)


def candidates(project, document, identifier, rerun_from):
    nodes = {node["id"] for node in document["nodes"]}
    if set(rerun_from) - nodes:
        raise InputValidationError("Select existing nodes to rerun")
    if not identifier and rerun_from:
        raise InputValidationError("Select a previous run when reusing upstream results")
    return scope_candidates(project, document, source_scope(project, identifier), rerun_from)


def scope_candidates(project, document, scope, rerun_from=(), *, include_sources=False):
    # The document service imports execution, so identity is resolved after loading.
    from overbae.services.research_experiments import node_identity

    if scope is None:
        return {}
    nodes = {node["id"]: node for node in document["nodes"]}
    prior = {item.node: item for item in scope.nodes.order_by("attempt")}
    parents = {
        key: [edge["source"] for edge in document["edges"] if edge["target"] == key]
        for key in nodes
    }
    stable = {}

    def unchanged(key):
        if key not in stable:
            previous = prior.get(key)
            stable[key] = bool(
                key not in rerun_from
                and previous
                and previous.state == "completed"
                and previous.identity == node_identity(document, key)
                and reusable_operation(nodes[key])
                and retained_implementation(project, nodes[key], previous)
                and all(retained(project, value) for value in previous.outputs.values())
                and all(unchanged(parent) for parent in parents[key])
            )
        return stable[key]

    return {
        key: prior[key]
        for key in nodes
        if unchanged(key)
        # A dataset stage is admitted again as the source stands now: rows of it may have
        # been held out since the earlier run read it.
        and (include_sources or nodes[key]["kind"] != "data")
        and prior[key].outputs
        and all(retained(project, value) for value in prior[key].outputs.values())
    }


def child_scope(scope, node, *, key="", index=0):
    if scope is None:
        return None
    receipt = scope.nodes.filter(node=node).order_by("-attempt").first()
    seen = set()
    while receipt and receipt.reused_from_id:
        if receipt.pk in seen:
            return None
        seen.add(receipt.pk)
        receipt = receipt.reused_from
    if receipt is None:
        return None
    return receipt.scopes.filter(**({"variant_key": key} if key else {"index": index})).first()


def nested_candidates(scope):
    task = scope.execution.assignment.specification.get("task", {})
    prior = source_scope(scope.execution.assignment.project, task.get("reuse_run"))
    if prior is None or scope.parent_id is None:
        return {}
    trail, current = [], scope
    while current.parent_id:
        trail.append(current)
        current = current.parent.scope
    forced = set(task.get("rerun_from", []))
    for _ in current.document["nodes"]:
        forced.update(
            edge["target"] for edge in current.document["edges"] if edge["source"] in forced
        )
    if trail[-1].parent.node in forced:
        return {}
    for child in reversed(trail):
        prior = child_scope(prior, child.parent.node, key=child.variant_key, index=child.index)
        if prior is None:
            return {}
        # Stable keys identify candidates; current bindings must also match their exact inputs.
        if prior.parent.inputs != child.parent.inputs:
            return {}
    return scope_candidates(scope.execution.assignment.project, scope.document, prior)


def apply(scope, candidates):
    for node in scope.nodes.filter(node__in=candidates):
        previous = candidates[node.node]
        node.reused_from = previous
        node.inputs = deepcopy(previous.inputs)
        node.outputs = deepcopy(previous.outputs)
        node.state = "completed"
        node.started_at = node.completed_at = timezone.now()
        node.save(
            update_fields=[
                "reused_from",
                "inputs",
                "outputs",
                "state",
                "started_at",
                "completed_at",
            ]
        )