Skip to content

The platform for continuously improving AI agents.

8.1 KB
Raw Blame
from django.db.models import BooleanField, CharField, Exists, F, Func, OuterRef, Q, Value
from django.db.models.fields.json import KT, KeyTextTransform, KeyTransform
from django.db.models.functions import Cast, Concat
from django.db.models.lookups import StartsWith

from overbae.models import (
    DataPartitionPlan,
    DatasetPipelineRun,
    DecisionProviderRequest,
    DeployedModel,
    InferenceRequest,
    NativeEvaluationPlan,
    PredictionEvaluation,
    PredictionSet,
    ResearchAction,
    ResearchAgent,
    WorkshopTask,
)
from overbae.services.research_contract import WORKSPACE_RUNS


def action_owners(assignments, project_field="project_id"):
    return (
        ResearchAction.objects.filter(
            agent__assignment_id__in=assignments,
            agent__assignment__project_id=OuterRef(project_field),
        )
        .alias(owner_key=Concat(Value("research:"), Cast("pk", CharField())))
        .filter(owner_key=OuterRef("request_key"))
    )


def owned_tasks(assignments):
    parents = assignments.filter(
        pk=OuterRef("parent_assignment_id"), project_id=OuterRef("project_id")
    )
    actions = action_owners(assignments).filter(tool="workshop", arguments__operation="prepare")
    return WorkshopTask.objects.filter(Exists(parents) | Exists(actions))


def owned_data(assignments, *, workshop_assignments=None):
    if workshop_assignments is None:
        workshop_assignments = assignments

    def key_ownership(project_field):
        tasks = owned_tasks(workshop_assignments).filter(
            StartsWith(
                OuterRef("request_key"),
                Concat(Value("workshop:"), Cast("pk", CharField()), Value(":")),
            ),
            project_id=OuterRef(project_field),
        )
        return Exists(action_owners(assignments, project_field)) | Exists(tasks)

    context_owners = (
        assignments.filter(project_id=OuterRef("dataset__project_id"))
        .alias(owner_text=Cast("pk", CharField()))
        .filter(owner_text=OuterRef("context_owner"))
    )
    pipelines = DatasetPipelineRun.objects.alias(
        context_owner=KT("specification__context__assignment")
    ).filter(key_ownership("dataset__project_id") | Exists(context_owners))
    partitions = DataPartitionPlan.objects.filter(key_ownership("project_id"))
    return pipelines, partitions


def json_owned(records, assignments, path, project_field="project_id"):
    owners = (
        assignments.filter(project_id=OuterRef(project_field))
        .alias(owner_text=Cast("pk", CharField()))
        .filter(owner_text=OuterRef("owner_reference"))
    )
    return records.alias(owner_reference=KT(path)).filter(Exists(owners))


def pending_calls(plans):
    # NativeEvaluationPlan.calls has dynamic stage keys and UUID-string leases.
    calls = Func(
        F("calls"),
        Value(
            '$.* ? ((exists(@.lease) && @.lease != null && @.lease != "")'
            ' || @.state == "submitting" || @.state == "running"'
            ' || @.state == "submission_unknown")'
        ),
        function="jsonb_path_exists",
        output_field=BooleanField(),
    )
    requests = DecisionProviderRequest.objects.filter(
        plan_id=OuterRef("pk"), state__in=["submitting", "running", "submission_unknown"]
    )
    return plans.alias(pending_stage=calls).filter(Q(pending_stage=True) | Exists(requests))


def unsettled_scripts(records, field="receipt"):
    return records.alias(
        script_submitted=KT(f"{field}__submission_started_at"),
        script_rejected=KT(f"{field}__submission_rejected"),
        script_exit=KT(f"{field}__exit_code"),
    ).filter(
        Q(script_submitted__isnull=False) & ~Q(script_submitted=""),
        Q(script_rejected__isnull=True) | ~Q(script_rejected="true"),
        script_exit__isnull=True,
    )


def unconfirmed_unknown(records, field="receipt"):
    return records.alias(
        script_exit=KT(f"{field}__exit_code"), script_rejected=KT(f"{field}__submission_rejected")
    ).filter(
        Q(state="unknown", script_exit__isnull=True),
        Q(script_rejected__isnull=True) | ~Q(script_rejected="true"),
    )


def pending_pipelines(records):
    unresolved = Func(
        F("result"),
        Value(
            "$.steps[*] ? (exists(@.submission_started_at) && @.submission_started_at != null"
            ' && @.submission_started_at != "" && (!exists(@.submission_rejected) || @.submission_rejected != true)'
            " && (!exists(@.exit_code) || @.exit_code == null))"
        ),
        function="jsonb_path_exists",
        output_field=BooleanField(),
    )
    return records.alias(unsettled_script=unresolved).filter(
        Q(state__in=["queued", "running"])
        | Q(unsettled_script=True)
        | (~Q(container_id="") & (Q(result__steps__isnull=True) | Q(result__steps=[])))
    )


def pending(assignments):
    # Native admission imports these receipt owners.
    from overbae.services import (
        deployment,
        experiment_execution,
        experiment_training,
        inference_requests,
        research_qualification,
        research_workshop,
    )
    from overbae.services.workshop_agent import sandbox

    if research_qualification.pending_actions(assignments).exists():
        return True
    if experiment_training.pending(assignments):
        return True
    tasks = owned_tasks(assignments)
    if (
        tasks.exclude(state__in=research_workshop.SETTLED).exists()
        or sandbox.pending(tasks).exists()
    ):
        return True
    if experiment_execution.pending_work(assignments):
        return True
    if (
        PredictionSet.objects.filter(
            assignment_id__in=assignments, state__in=["pending", "running"]
        ).exists()
        or PredictionEvaluation.objects.filter(
            assignment_id__in=assignments, run__status__in=["pending", "running"]
        ).exists()
    ):
        return True
    pipelines, partitions = owned_data(assignments)
    if (
        pending_pipelines(pipelines).exists()
        or partitions.filter(state__in=["queued", "running"]).exists()
    ):
        return True
    plans = json_owned(
        NativeEvaluationPlan.objects.all(), assignments, "config__research__assignment"
    )
    if plans.exclude(state__in=["completed", "failed", "paused", "cancelled"]).exists():
        return True
    if pending_calls(plans).exists():
        return True
    models = json_owned(
        DeployedModel.objects.all(), assignments, "serving_runtime__lease__assignment"
    )
    models = models.alias(
        archive_id=KT("serving_runtime__archive_call_id"),
        archive_terminal=KT("serving_runtime__archive_terminal"),
    )
    if models.filter(
        Q(status__in=deployment.ACTIVE_STATUSES)
        | Q(deployment_cancel_pending=True)
        | Q(serving_runtime__archive_dispatching=True)
        | (
            Q(archive_id__isnull=False)
            & ~Q(archive_id="")
            & (Q(archive_terminal__isnull=True) | ~Q(archive_terminal="true"))
        )
    ).exists():
        return True
    requests = InferenceRequest.objects.filter(state__in=inference_requests.ACTIVE)
    if requests.filter(Exists(action_owners(assignments))).exists():
        return True
    if (
        requests.filter(deployment__in=models)
        .alias(
            allocation=KT("payload__serving_allocation"),
            lease_allocation=KeyTextTransform(
                "allocation", KeyTransform("lease", F("deployment__serving_runtime"))
            ),
        )
        .filter(allocation=F("lease_allocation"))
        .exists()
    ):
        return True
    if (
        ResearchAction.objects.filter(
            agent__assignment_id__in=assignments,
            tool="workspace",
            arguments__operation__in=WORKSPACE_RUNS,
        )
        .exclude(agent__workspace__has_key="stopped_at")
        .filter(
            Q(state__in=["pending", "running", "unknown"])
            | Q(result__state__in=["accepted", "running"])
        )
        .exists()
    ):
        return True
    return (
        ResearchAgent.objects.filter(assignment_id__in=assignments)
        .filter(Q(workspace__creation_started=True) | Q(workspace__has_key="sandbox"))
        .exclude(workspace__has_key="stopped_at")
        .exists()
    )