Skip to content

The platform for continuously improving AI agents.

14.9 KB
Raw Blame
import json
from copy import deepcopy

from django.db import transaction

from overbae.core.errors import DatasetError, InputValidationError
from overbae.models import Cell, ResearchAssignment
from overbae.services import research_effects, research_team
from overbae.services.datasets import preparation, preparation_workflow, use
from overbae.services.workshop_agent import lifecycle, sandbox
from overbae.services.workshop_agent.contracts import StartTask

ROLES = ("train", "development", "calibration", "final")
# A blocked task waits on its requester, so it too has settled for whoever delegated it.
SETTLED = {"completed", "failed", "cancelled", "blocked"}


def owned(assignment):
    return research_effects.owned_tasks(ResearchAssignment.objects.filter(pk=assignment.pk))


def pinned_source(task):
    receipt = task.actions.get(sequence=0).receipt
    # The task's first run replaces the admission receipt with that of the version it pinned.
    return receipt.get("source_cell") or receipt.get("input", {}).get("cell")


def publications(task):
    """What the task published, newest first. A preview publishes nothing."""
    return [
        result
        for result in task.actions.filter(name="publish_workshop", state="completed")
        .order_by("-sequence")
        .values_list("result", flat=True)
        if result.get("cell")
    ]


def training_format(cell):
    """The trainer that reads a version's rows, or ``None`` when none does."""
    report = (cell.intent_report or {}).get("train") or {}
    if not report.get("ok"):
        return None
    return "decision" if report.get("format") == "decision" else "conversation"


def trainable(cell, held):
    """Whether a train stage reads this version as it stands: campaign admission's checks,
    against each partition's final rows the same task holds out."""
    try:
        use.check(cell.dataset, "train", cell=cell, verify=False)
        for final in held:
            use.check_held_out(cell, final)
    except DatasetError:
        return False
    return True


def publication(task):
    """The publication a flow builds on: the newest whose partition a trainer can read, else
    the newest. A task may publish evaluation data beside its training data."""
    verified = publications(task)
    for result in verified:
        members = {
            member["role"]: member["cell"]["id"]
            for member in (result.get("partition") or {}).get("members", [])
        }
        train = Cell.objects.filter(pk=members.get("train")).first()
        if train is not None and training_format(train):
            return result
    return verified[0] if verified else None


def held_out(results):
    """The final members of the partitions these publications cut."""
    return list(
        Cell.objects.select_related("dataset").filter(
            pk__in=[
                member["cell"]["id"]
                for result in results
                for member in (result.get("partition") or {}).get("members", [])
                if member["role"] == "final"
            ]
        )
    )


def published(result, held=()):
    prepared = Cell.objects.select_related("dataset").filter(pk=result["cell"]).first()
    if prepared is None:
        return None
    partition = result.get("partition") or {}
    members = sorted(
        partition.get("members", []),
        key=lambda member: ROLES.index(member["role"]) if member["role"] in ROLES else len(ROLES),
    )
    report = partition.get("report", {})
    readable = {
        str(cell.pk): cell
        for cell in Cell.objects.filter(pk__in=[member["cell"]["id"] for member in members])
    }
    return {
        "prepared": {
            "dataset": {"id": str(prepared.dataset_id), "name": prepared.dataset.name},
            "version": prepared.position,
            "title": prepared.title,
            "rows": result["rows"],
            "training_format": training_format(prepared),
            "cell": str(prepared.pk),
            "access": "readable",
            "trainable": trainable(prepared, held),
        },
        "partition": {
            "id": partition["id"],
            "name": partition["name"],
            "recipe": partition["recipe"],
            **{
                key: report[key]
                for key in ("counts", "groups", "overlap", "duplicates_removed", "source_rows")
                if key in report
            },
        }
        if members
        else None,
        "outputs": [
            {
                "role": member["role"],
                "rows": member["cell"]["rows"],
                **{
                    "cell": member["cell"]["id"],
                    "dataset": member["cell"]["dataset_id"],
                    "access": "readable",
                    "training_format": training_format(readable[member["cell"]["id"]])
                    if member["cell"]["id"] in readable
                    else None,
                },
            }
            for member in members
        ],
        "pipeline": result.get("pipeline"),
    }


def unanswered(task):
    """Whether the task stopped because its model provider did not answer its last request."""
    last = task.actions.filter(name="reason").order_by("-sequence").first()
    return (
        task.state == "blocked"
        and last is not None
        and (last.state == "unknown" or last.result.get("status", 200) >= 429)
    )


def describe(task):
    result = publication(task)
    verified = publications(task)
    held = held_out(verified)
    return {
        "task": str(task.pk),
        "state": task.state,
        "activity": task.result.get("activity"),
        # The task's own reason is the provider's exception text, which names no next step.
        "summary": "The Workshop's model provider stopped answering before anything was "
        "published. Calling prepare again starts the preparation afresh."
        if unanswered(task)
        else task.result.get("reason"),
        "published": published(result, held) if result else None,
        # More than one: each is listed, so data the summary names can be found by its cell.
        **(
            {"publications": [record for item in verified if (record := published(item, held))]}
            if len(verified) > 1
            else {}
        ),
    }


def unstarted(reason):
    """The record of a delegation the Workshop was never given."""
    return {
        "task": None,
        "state": "blocked",
        "activity": None,
        "summary": reason,
        "published": None,
    }


def observations(assignment):
    return [describe(task) for task in owned(assignment).order_by("created_at", "pk")]


def pending(assignment):
    tasks = owned(assignment)
    return tasks.exclude(state__in=SETTLED).exists() or sandbox.pending(tasks).exists()


def pending_effects(owners):
    return sandbox.pending(
        research_effects.owned_tasks(ResearchAssignment.objects.filter(pk__in=owners))
    ).exists()


def settled(assignment):
    """The most recent task that completed with a verified publication, with that
    publication, or ``(None, None)``."""
    for task in owned(assignment).filter(state="completed").order_by("-created_at", "-pk"):
        result = publication(task)
        if result:
            return task, result
    return None, None


def published_cells(assignment):
    identifiers = {
        identifier
        for task in owned(assignment).filter(state="completed")
        if (result := publication(task))
        for identifier in result.get("outputs", [])
    }
    return set(
        Cell.objects.filter(pk__in=identifiers, dataset__project=assignment.project).values_list(
            "pk", flat=True
        )
    )


def cancel(assignment):
    for task in owned(assignment):
        if task.state not in lifecycle.TERMINAL:
            lifecycle.control(assignment.project, task.pk, "cancel")
        sandbox.stop(task)


def supersede(assignment, dataset):
    """End this assignment's earlier delegations on a dataset that have not ended.

    A dataset holds one open preparation, and a task that stopped without publishing keeps
    its own open: the delegation that replaces it could not start.
    """
    for task in (
        owned(assignment)
        .filter(dataset_id=dataset)
        .exclude(state__in=lifecycle.TERMINAL)
        .select_related("dataset", "preparation")
    ):
        lifecycle.control(assignment.project, task.pk, "cancel")
        if task.preparation.state in {"preparing", "paused"}:
            preparation_workflow.update(task.dataset, task.preparation_id, "cancelled", [])


def record(agent):
    """Put data the Workshop published for this assignment on its experiment's flow.

    The dataset input moves to its prepared version, and a partition adds the stage that
    yields its members: a later run reuses that retained partition instead of cutting a new
    one. Applies once per publication, and only while nothing consumes the input yet.
    """
    # The document service dispatches native tools, which delegate here.
    from overbae.services import research_experiments

    assignment = agent.assignment
    if not assignment.experiment_revision_id or hasattr(assignment, "execution"):
        return None
    task, result = settled(assignment)
    if task is None:
        return None
    experiment = assignment.experiment_revision.experiment
    key = f"workshop:{task.pk}"
    saved = experiment.revisions.filter(request_key=key).first()
    if saved:
        return saved
    revision = research_experiments.current_revision(assignment)
    document = deepcopy(revision.document)
    source = next(
        (
            node
            for node in document["nodes"]
            if node["kind"] == "data" and node["config"].get("dataset") == str(task.dataset_id)
        ),
        None,
    )
    if source is None or any(edge["source"] == source["id"] for edge in document["edges"]):
        return None
    source["config"] = {"cell": result["cell"]}
    partition = result.get("partition")
    if partition:
        taken = {node["id"] for node in document["nodes"]}
        identifier = next(f"split_{i}" for i in range(len(taken) + 1) if f"split_{i}" not in taken)
        roles = {member["role"] for member in partition["members"]}
        document["nodes"].append(
            {
                "id": identifier,
                "kind": "split",
                "title": "Partition",
                "position": {
                    "x": source["position"]["x"] + 340,
                    "y": source["position"]["y"],
                },
                "config": {},
                "operation": {
                    "tool": "platform",
                    "arguments": {
                        "name": "create_data_partition",
                        "arguments": {"name": partition["name"], "recipe": partition["recipe"]},
                    },
                },
                "notes": "",
            }
        )
        document["edges"].append(
            {"source": source["id"], "output": "data", "target": identifier, "input": "data"}
        )
        document["outputs"] = document.get("outputs", {}) | {
            f"{role}_data": {"node": identifier, "port": role}
            for role in ("train", "development", "final")
            if role in roles
        }
    return research_experiments.revise(
        experiment,
        expected_version=revision.number,
        document=document,
        request_key=key,
        note="Data prepared by the Workshop",
        agent=agent,
    )


@transaction.atomic
def invoke(action, request):
    # Source admission owns the research holdout boundary; delegation cannot bypass it.
    from overbae.services import research_tools

    assignment = ResearchAssignment.objects.select_for_update().get(pk=action.agent.assignment_id)
    if assignment.state != "running":
        raise InputValidationError("This assignment no longer has execution authority")
    if request.operation == "inspect":
        tasks = owned(assignment)
        task = (
            tasks.filter(pk=request.task).first()
            if request.task
            else tasks.order_by("-created_at", "-pk").first()
        )
        if task is None:
            raise InputValidationError("Select a Workshop task owned by this assignment")
        return describe(task)
    research_team.current_turn(action.agent)
    if action.agent.parent_id:
        raise InputValidationError("Only the active research lead may delegate data preparation")
    if assignment.result.get("selection_locked"):
        return unstarted(
            "Final qualification has locked this investigation's model selection. Data for "
            "another model is prepared in a new experiment."
        )
    existing = owned(assignment).filter(request_key=f"research:{action.pk}").first()
    if existing:
        if pinned_source(existing) != str(request.source_cell):
            raise InputValidationError("The retained Workshop source differs from this request")
        return describe(existing)
    research_team.admit_mutation(action.agent)
    source = research_tools.source_cell(assignment, request.source_cell)
    use.freeze(source)
    context = {
        "objective": assignment.specification.get("objective"),
        "request": assignment.specification.get("task", {}),
        "constraints": assignment.specification.get("constraints", {}),
        "acceptance": assignment.specification.get("acceptance", {}),
        "source_cell": str(source.pk),
        "source_fingerprint": source.fingerprint,
        "downstream_context": request.downstream_context,
    }
    objective = request.objective + "\n\nDownstream request context:\n" + json.dumps(context)
    lineage = preparation.describe(source.dataset, cell=source, include_siblings=False)
    workspace = (
        owned(assignment)
        .filter(dataset_id__in={node["dataset"] for node in lineage["nodes"]})
        .order_by("created_at", "pk")
        .values_list("dataset_id", flat=True)
        .first()
        or source.dataset_id
    )
    payload = StartTask(
        dataset=workspace,
        objective=objective,
        request_key=f"research:{action.pk}",
    )
    supersede(assignment, workspace)
    try:
        task = lifecycle.start(
            lifecycle.NativeGrant(
                assignment.project,
                assignment.created_by,
                execution_mandate=assignment.execution_mandate,
                parent_assignment=assignment,
            ),
            payload,
        )
    except DatasetError as refused:
        if refused.code != "preparation_active":
            raise
        return unstarted(
            "This dataset is being prepared in another session. The Workshop can take it "
            "once that preparation ends."
        )
    bootstrap, created = lifecycle.claim(task.pk, 0, "prepare_workshop_environment", {})
    if created:
        bootstrap.receipt = {"source_cell": str(source.pk)}
        bootstrap.save(update_fields=["receipt"])
    elif bootstrap.receipt.get("source_cell") != str(source.pk):
        raise InputValidationError("The retained Workshop source differs from this request")
    return describe(task)