Skip to content

The platform for continuously improving AI agents.

14.8 KB
Raw Blame
import hashlib
import json
from dataclasses import dataclass

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

from overbae.core.errors import DatasetError, InputValidationError
from overbae.models import (
    Cell,
    DataPartitionMember,
    Dataset,
    DatasetPreparation,
    Project,
    WorkshopAction,
    WorkshopTask,
)
from overbae.services import execution_mandates
from overbae.services.datasets import partition_plans, preparation_workflow, use

TERMINAL = frozenset({"completed", "cancelled", "failed"})


def completion_outputs(task, outputs):
    selected = {str(value) for value in outputs}
    if not selected or len(selected) != len(outputs):
        raise DatasetError("Completion requires distinct published output cells.")
    cells = dict(
        Cell.objects.filter(pk__in=selected, dataset__project_id=task.project_id, state="ok")
        .exclude(fingerprint="")
        .values_list("pk", "dataset_id")
    )
    primary = {
        str(pk)
        for pk in preparation_workflow.output_cells(
            task.dataset, task.preparation_id, selected
        ).values_list("pk", flat=True)
    }
    related = {
        str(value)
        for value in DataPartitionMember.objects.filter(
            cell_id__in=selected - primary,
            plan__source_cell_id__in=primary,
            plan__project_id=task.project_id,
            plan__state="completed",
        ).values_list("cell_id", flat=True)
    }
    if not primary or len(cells) != len(selected) or selected != primary | related:
        raise DatasetError(
            "Include published cells from the task dataset. Additional outputs must be completed "
            "partition members of those cells in the same project."
        )
    return sorted(primary)


def digest(value):
    return hashlib.sha256(
        json.dumps(value, sort_keys=True, separators=(",", ":")).encode()
    ).hexdigest()


def authorise(task, *, continuation=False):
    task.refresh_from_db(
        fields=["state", "desired_state", "parent_assignment", "execution_mandate", "result"]
    )
    if not Project.objects.filter(
        pk=task.project_id,
        is_active=True,
        memberships__user_id=task.created_by_id,
        memberships__user__is_active=True,
    ).exists():
        raise DatasetError("Task authority has been revoked.", code="permission_denied")
    if (
        task.preparation_id
        and DatasetPreparation.objects.filter(pk=task.preparation_id, state="cancelled").exists()
    ):
        raise DatasetError("The dataset preparation has ended.", code="dataset_busy")
    if task.desired_state != "running" or task.state in TERMINAL:
        raise DatasetError("The Workshop task is not running.", code="dataset_busy")
    if task.result.get("settlement"):
        raise DatasetError("The Workshop is settling its provider work.", code="dataset_busy")
    if task.parent_assignment_id:
        try:
            authorize = (
                execution_mandates.require_continuation
                if continuation
                else execution_mandates.require
            )
            authorize(task.parent_assignment, "read")
        except InputValidationError as exc:
            raise DatasetError(
                "Parent execution authority has ended.", code="permission_denied"
            ) from exc


def mutation(task, *, continuation=False):
    authorise(task, continuation=continuation)
    mandate = execution_mandates.normalize(task.execution_mandate)
    if mandate["authority"] != "act" or "prepare" not in mandate["families"]:
        raise DatasetError("Preparation is outside the task mandate.", code="permission_denied")
    if task.parent_assignment_id:
        authorize = (
            execution_mandates.require_continuation if continuation else execution_mandates.require
        )
        authorize(task.parent_assignment, "prepare")


def source(task, cell, *, platform_reads=False, continuation=False):
    authorise(task, continuation=continuation)
    if cell.dataset.project_id != task.project_id:
        raise DatasetError("Source not found in this project.", code="permission_denied")
    execution_mandates.require_cell(
        task.execution_mandate, cell, project=task.project, assignment=task.parent_assignment
    )
    if not platform_reads:
        partition_plans.refuse_sealed([cell])
    if task.parent_assignment_id:
        from overbae.services import research_tools  # Research delegates through this lifecycle.

        research_tools.source_cell(task.parent_assignment, cell.pk, platform_reads=platform_reads)
    return cell


@transaction.atomic
def retain_source(task, identifier):
    Project.objects.select_for_update().get(pk=task.project_id)
    current = WorkshopTask.objects.select_for_update().get(pk=task.pk)
    cell = (
        Cell.objects.select_related("dataset")
        .filter(pk=identifier, dataset__project_id=current.project_id)
        .first()
    )
    if cell is None:
        raise DatasetError("Source not found in this project.", code="permission_denied")
    source(current, cell)
    use.freeze(cell)
    retained = next(
        (item for item in current.context_sources if item["cell"] == str(cell.pk)), None
    )
    if retained is not None:
        if retained["fingerprint"] != cell.fingerprint:
            raise DatasetError("The selected source fingerprint changed.")
    else:
        current.context_sources.append(
            {
                "dataset": str(cell.dataset_id),
                "name": cell.dataset.name,
                "cell": str(cell.pk),
                "fingerprint": cell.fingerprint,
                "rows": cell.rows,
                "columns": cell.columns,
                "source_spec": cell.dataset.source_spec,
            }
        )
        current.save(update_fields=["context_sources"])
    task.context_sources = current.context_sources
    return cell


@dataclass(frozen=True)
class NativeGrant:
    project: object
    user: object
    write: bool = True
    client_name: str = "Overmind Workshop"
    execution_mandate: dict | None = None
    parent_assignment: object | None = None

    def has_permission(self, permission):
        if self.execution_mandate is not None:
            mandate = execution_mandates.normalize(self.execution_mandate)
            return (
                permission == "read"
                and "read" in mandate["families"]
                or (
                    permission == "write"
                    and self.write
                    and mandate["authority"] == "act"
                    and "prepare" in mandate["families"]
                )
            )
        return permission == "read" or (permission == "write" and self.write)


def context(task):
    authorise(task)
    return NativeGrant(
        task.project,
        task.created_by,
        execution_mandate=task.execution_mandate,
        parent_assignment=task.parent_assignment,
    )


@transaction.atomic
def start(grant, payload, *, record_objective=True):
    Project.objects.select_for_update().get(pk=grant.project.pk)
    dataset = Dataset.objects.filter(pk=payload.dataset, project=grant.project).first()
    if dataset is None:
        raise DatasetError("Dataset not found.", code="dataset_not_found")
    request = payload.model_dump(mode="json", exclude={"request_key"})
    if not request["context_datasets"]:
        request.pop("context_datasets")
    fingerprint = digest(request)
    existing = WorkshopTask.objects.filter(
        project=grant.project, request_key=payload.request_key
    ).first()
    if existing:
        if existing.fingerprint != fingerprint:
            raise DatasetError(
                "Request key conflicts with an existing task.", code="request_key_conflict"
            )
        if getattr(grant, "parent_assignment", None) != existing.parent_assignment:
            raise DatasetError("The task belongs to another parent.", code="request_key_conflict")
        supplied = getattr(grant, "execution_mandate", None)
        if (
            supplied is not None
            and execution_mandates.identity(supplied) != existing.mandate_fingerprint
        ):
            raise DatasetError("The task mandate differs.", code="request_key_conflict")
        return existing
    if not grant.has_permission("write"):
        raise DatasetError("Write permission is required.", code="permission_denied")
    parent = getattr(grant, "parent_assignment", None)
    mandate = getattr(grant, "execution_mandate", None) or execution_mandates.admission(
        roots=[f"dataset:{value}" for value in [payload.dataset, *payload.context_datasets]],
        families=["read", "author", "prepare"],
    )
    if parent:
        if parent.project_id != grant.project.pk or parent.created_by_id != grant.user.pk:
            raise DatasetError(
                "Parent authority does not match the task.", code="permission_denied"
            )
        execution_mandates.require(parent, "prepare")
        mandate = execution_mandates.intersect(
            parent.execution_mandate, mandate, parent_assignment=parent
        )
    if (
        len(set(payload.context_datasets)) != len(payload.context_datasets)
        or payload.dataset in payload.context_datasets
    ):
        raise DatasetError("Select distinct context datasets, separate from the working dataset.")
    selected = {
        value.pk: value
        for value in Dataset.objects.select_for_update()
        .filter(pk__in=payload.context_datasets, project=grant.project)
        .prefetch_related("cells")
    }
    if len(selected) != len(payload.context_datasets):
        raise DatasetError("Context dataset not found in this project.", code="dataset_not_found")
    context_sources = []
    for identifier in payload.context_datasets:
        reference = selected[identifier]
        cell = reference.active_cell
        if cell is None or cell.state != "ok" or not cell.fingerprint:
            raise DatasetError("Context datasets must have a readable published version.")
        use.freeze(cell)
        execution_mandates.require_cell(mandate, cell, project=grant.project, assignment=parent)
        context_sources.append(
            {
                "dataset": str(reference.pk),
                "name": reference.name,
                "cell": str(cell.pk),
                "fingerprint": cell.fingerprint,
                "rows": cell.rows,
                "columns": cell.columns,
                "source_spec": reference.source_spec,
            }
        )
    task = WorkshopTask.objects.create(
        project=grant.project,
        dataset=dataset,
        created_by=grant.user,
        objective=payload.objective,
        context_sources=context_sources,
        request_key=payload.request_key,
        fingerprint=fingerprint,
        max_steps=payload.max_steps,
        parent_assignment=parent,
        execution_mandate=mandate,
        mandate_fingerprint=execution_mandates.identity(mandate),
    )
    task.preparation = preparation_workflow.start(dataset, context(task), f"native:{task.pk}")
    task.save(update_fields=["preparation"])
    if record_objective:
        # Imported here because conversation.send starts a task through this service.
        from overbae.services.workshop_agent.conversation import emit

        emit(
            task,
            "objective",
            {"id": "objective", "role": "user", "text": task.objective, "status": "completed"},
        )
    return task


def get(task_id):
    return WorkshopTask.objects.select_related(
        "project", "dataset", "created_by", "preparation"
    ).get(pk=task_id)


@transaction.atomic
def control(project, task_id, command):
    Project.objects.select_for_update().get(pk=project.pk)
    task = WorkshopTask.objects.select_for_update().get(pk=task_id, project=project)
    if command not in {"pause", "resume", "cancel"}:
        raise DatasetError("Unknown task command.", code="dataset_invalid")
    if task.state in TERMINAL:
        return task
    if task.desired_state == "cancelled" and command != "cancel":
        raise DatasetError("Wait for cancellation to finish.", code="dataset_busy")
    task.desired_state = {"pause": "paused", "resume": "running", "cancel": "cancelled"}[command]
    if command == "resume":
        if task.result.get("settlement"):
            raise DatasetError("Wait for provider settlement before resuming.", code="dataset_busy")
        task.result = {}
    # The task's loop may have ended: the worker starts a run for a task not dispatched, and a
    # loop still running reads the command itself.
    task.dispatched_at = None
    task.dispatch_generation += 1
    task.save(
        update_fields=[
            "desired_state",
            "result",
            "dispatched_at",
            "dispatch_generation",
            "updated_at",
        ]
    )
    return task


@transaction.atomic
def claim(task_id, sequence, name, arguments):
    task = (
        WorkshopTask.objects.select_for_update()
        .select_related("project", "created_by")
        .get(pk=task_id)
    )
    authorise(task)
    fingerprint = digest({"name": name, "arguments": arguments})
    existing = WorkshopAction.objects.filter(task=task, sequence=sequence).first()
    if existing:
        if existing.fingerprint != fingerprint:
            raise DatasetError("Action sequence conflicts.", code="request_key_conflict")
        return existing, False
    if task.max_steps and sequence >= task.max_steps:
        raise DatasetError("The task action limit was reached.", code="dataset_invalid")
    task.step = sequence
    task.state = "running"
    task.save(update_fields=["step", "state", "updated_at"])
    return WorkshopAction.objects.create(
        task=task, sequence=sequence, name=name, arguments=arguments, fingerprint=fingerprint
    ), True


def record_action(action_id, state, result):
    WorkshopAction.objects.filter(pk=action_id).update(
        state=state, result=result, updated_at=timezone.now()
    )


@transaction.atomic
def count(action_id, field):
    """Add one to a counter an action keeps on its receipt while it is in flight."""
    action = WorkshopAction.objects.select_for_update().get(pk=action_id)
    action.receipt = {**action.receipt, field: action.receipt.get(field, 0) + 1}
    action.save(update_fields=["receipt", "updated_at"])
    return action.receipt[field]


def describe(task):
    usage_known = all(
        receipt.get("usage_known") is True
        for receipt in task.actions.filter(
            name="reason", state__in=["completed", "unknown"]
        ).values_list("receipt", flat=True)
    )
    return {
        "id": str(task.pk),
        "dataset": str(task.dataset_id),
        "objective": task.objective,
        "context_sources": task.context_sources,
        "state": task.state,
        "desired_state": task.desired_state,
        "step": task.step,
        "used_tokens": task.used_tokens if usage_known else None,
        "result": task.result,
        "updated_at": task.updated_at.isoformat(),
    }