Skip to content

The platform for continuously improving AI agents.

8.4 KB
Raw Blame
import json
import tempfile
from pathlib import Path

from django.db import transaction
from django.utils import timezone

from overbae.core.errors import InputValidationError
from overbae.models import ResearchAction, ResearchAgent, ResearchAssignment
from overbae.services import (
    context_graph,
    execution_mandates,
    experiment_assets,
    research,
    research_context_authorship,
    research_evidence,
)
from overbae.services.isolated_execution import execute_jsonl
from overbae.services.research_contract import Artifact


def execute(component, inputs, parameters, *, receipt, progress, assignment, source_asset=None):
    manifest = component.definition
    if set(inputs) != set(manifest["inputs"]):
        raise InputValidationError("Connect every declared component input exactly once")
    for name, value in inputs.items():
        experiment_assets.check_schema(manifest["inputs"][name]["schema"], value, validate=True)
    experiment_assets.check_schema(manifest["parameters"], parameters, validate=True)
    for name, value in inputs.items():
        if (
            len(json.dumps({"port": name, "value": value}, allow_nan=False).encode())
            > 4 * 1024 * 1024
        ):
            raise InputValidationError(
                "Each component port is limited to 4 MiB; use Workshop packages for streamed datasets"
            )
    outputs = {}
    with tempfile.TemporaryDirectory(prefix="experiment-component-") as directory:
        research_context_authorship.require_asset(assignment, source_asset or component)
        for record in execute_jsonl(
            manifest=manifest,
            records=[{"port": name, "value": value} for name, value in inputs.items()],
            directory=Path(directory),
            entrypoint=manifest["entrypoint"],
            files=manifest["files"],
            parameters=parameters,
            receipt=receipt,
            progress=progress,
        ):
            if set(record) != {"port", "value"}:
                raise InputValidationError(
                    "Component output lines must contain only port and value"
                )
            port = record["port"]
            if not isinstance(port, str) or port not in manifest["outputs"] or port in outputs:
                raise InputValidationError(
                    "Component outputs must identify declared ports exactly once"
                )
            experiment_assets.check_schema(
                manifest["outputs"][port]["schema"], record["value"], validate=True
            )
            outputs[port] = record["value"]
    if set(outputs) != set(manifest["outputs"]):
        raise InputValidationError("The component did not produce all declared outputs")
    if not progress():
        raise InputValidationError("Component execution no longer has publication authority")
    return outputs


def values(action, bindings):
    from overbae.services.datasets import rows
    from overbae.services.research_tools import (
        source_cell,  # Native tools dispatch component execution.
    )

    result = {}
    for port, binding in bindings.items():
        if not isinstance(binding, dict):
            raise InputValidationError("Component inputs require retained bindings")
        if binding.get("artifact"):
            artifact = research.accessible_artifact(action.agent.assignment, binding["artifact"])
            if artifact.sha256 != binding.get("fingerprint"):
                raise InputValidationError("The retained artifact fingerprint changed")
            result[port] = json.loads(research.artifact_bytes(artifact, limit=4 * 1024 * 1024))
        elif binding.get("cell"):
            cell = source_cell(action.agent.assignment, binding["cell"])
            if cell.fingerprint != binding.get("fingerprint"):
                raise InputValidationError("The connected data fingerprint changed")
            rows.verify(cell)
            result[port] = [
                {
                    **row.extra,
                    "index": row.index,
                    "input": row.input,
                    "expected_output": row.expected_output,
                }
                for row in rows.iter_rows(cell)
            ]
        else:
            raise InputValidationError(
                "Components consume retained JSON artifacts or registered development data"
            )
    return result


def invoke(action, request):
    if request.operation == "validate":
        inputs = values(action, request.inputs)
        for value in inputs.values():
            experiment_assets.check_schema(request.schema_, value, validate=True)
        return {
            "state": "completed",
            "valid": True,
            "outputs": request.inputs,
            "fingerprint": context_graph.fingerprint(
                {"inputs": request.inputs, "schema": request.schema_}
            ),
        }
    from overbae.services import component_execution  # The worker uses this execution contract.

    return component_execution.describe(component_execution.create(action, request))


@transaction.atomic
def publish(action, component, request, outputs, receipt, *, execution=None):
    assignment = ResearchAssignment.objects.select_for_update().get(pk=action.agent.assignment_id)
    agent = ResearchAgent.objects.select_for_update().get(pk=action.agent_id)
    action = ResearchAction.objects.select_for_update().get(pk=action.pk)
    if (
        execution is None
        and assignment.state != "running"
        or assignment.deadline <= timezone.now()
        or agent.state in research.TERMINAL
        and not (
            execution is not None and research.continues_admitted_work(assignment, agent=agent)
        )
        or action.state
        not in ({"pending", "running", "completed"} if execution else {"pending", "running"})
        or not research.authorized(assignment)
    ):
        raise InputValidationError("Component execution no longer has publication authority")
    if execution is not None:
        execution = type(execution).objects.select_for_update().get(pk=execution.pk)
        if (
            execution.state != "running"
            or execution.expires_at <= timezone.now()
            or execution.action_id != action.pk
            or execution.component_id != component.pk
            or execution.request != request.model_dump(mode="json", by_alias=True)
        ):
            raise InputValidationError("Component execution no longer has publication authority")
        execution_mandates.require_continuation(assignment, "prepare")
    else:
        execution_mandates.require(assignment, "prepare")
    source_cells = research_evidence.input_sources(assignment.project, request.inputs)
    source_cells |= research_context_authorship.asset_use_sources(component)
    bindings = {}
    for port, value in outputs.items():
        retained = research.claim(
            action.agent,
            f"component-output:{action.pk}:{port}",
            "artifact",
            {"component": str(component.pk), "port": port},
            effect=execution,
        )
        if retained.state == "denied":
            raise InputValidationError("Component output publication was denied")
        artifact = research.retain(
            retained,
            Artifact(
                kind="report",
                title=port,
                path=f"{port}.json",
                metadata={
                    "component": str(component.pk),
                    "component_fingerprint": component.fingerprint,
                    "producer_action": str(action.pk),
                    "inputs_fingerprint": context_graph.fingerprint(
                        action.experiment_inputs or request.inputs
                    ),
                },
            ),
            json.dumps(value, allow_nan=False).encode(),
            source_cells=source_cells,
        )
        research.complete(retained, research.artifact_record(artifact), cost=0)
        bindings[port] = {
            "kind": component.definition["outputs"][port]["type"],
            "artifact": str(artifact.pk),
            "path": f"{port}.json",
            "fingerprint": artifact.sha256,
        }
    if execution is not None:
        execution.state, execution.outputs, execution.receipt = "completed", bindings, receipt
        execution.completed_at = timezone.now()
        execution.save(update_fields=["state", "outputs", "receipt", "completed_at"])
    return {
        "state": "completed",
        "component": str(component.pk),
        "receipt": receipt,
        "outputs": bindings,
    }