Skip to content

The platform for continuously improving AI agents.

19.8 KB
Raw Blame
from datetime import datetime

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

from modal_shared.decisions import DECISION_OBJECTIVES
from modal_shared.stacks import WORKER_MEMORY_MIB
from overbae.core.errors import InputValidationError
from overbae.modal.gpu_selector import select_gpu
from overbae.modal.model_registry import get_model_config_any_backend
from overbae.models import DeployedModel, InferenceRequest
from overbae.services import (
    deployment,
    experiment_training,
    inference_requests,
    provider_pricing,
    research,
    research_evidence,
    research_science,
    research_team,
    serving_lease,
)
from overbae.services.serving_context import job_serving_plan


def deployments(assignment):
    """Deployments whose serving lease this assignment holds and so advances and stops."""
    return DeployedModel.objects.filter(serving_runtime__lease__assignment=str(assignment.pk))


def observed(assignment):
    """Deployments the assignment's investigation uses: the standard deployment of each
    checkpoint its campaigns trained, and any leased anywhere in it. The lead reads what its
    flow runs deployed, and a later run uses what an earlier one left serving."""
    investigation = research_evidence.investigation(assignment)
    return DeployedModel.objects.filter(
        Q(serving_runtime__lease__assignment__in=[str(identifier) for identifier in investigation])
        | Q(serving_runtime__lease__isnull=True)
        & (
            Q(finetuning_job__trial__campaign__in=experiment_training.campaigns(investigation))
            | Q(
                finetuning_job__trial__campaign__in=research_evidence.campaigns(
                    assignment, observe=True
                )
            )
        )
    )


def requests(model):
    lease = serving_lease.policy(model)
    if lease is None:
        return InferenceRequest.objects.filter(deployment=model, payload__source="research")
    return InferenceRequest.objects.filter(
        deployment=model, payload__serving_allocation=lease["allocation"]
    )


def state(item):
    # A ready deployment whose lease has closed serves nothing more.
    return "closed" if serving_lease.closed(item) and item.status == "ready" else item.status


def describe(assignment):
    result = []
    for item in observed(assignment):
        closed = serving_lease.closed(item)
        lease = serving_lease.policy(item)
        result.append(
            {
                "deployment": str(item.pk),
                "generation": str(item.deployment_generation),
                "job": str(item.finetuning_job_id),
                "state": state(item),
                "model_id": item.model_id,
                "error": item.error_message,
                "progress": deployment.deployment_progress(item),
                "lease": {
                    key: value
                    for key, value in lease.items()
                    if key not in {"rate_card", "staged_base"}
                }
                if lease
                else None,
                "inference_admission": "Closed: it takes no further request. deploy starts it again under a new lease."
                if closed
                else "Reuse this ready open deployment for every example; extra infer calls reserve their own allowance automatically. Stop only after all planned requests finish."
                if lease
                else "Standard deployment of this checkpoint. Reuse it for every example.",
                "archive_dispatching": item.serving_runtime.get("archive_dispatching", False),
                "requests": [
                    research_evidence.project_report(assignment, inference_requests.describe(r))
                    for r in requests(item)
                ],
            }
        )
    return result


def inference_ceiling(gpu, card):
    rates = card["rates"]
    gpu_second = provider_pricing.gpu_rate(card, gpu)
    if gpu_second is None or gpu not in WORKER_MEMORY_MIB:
        raise InputValidationError("Serving hardware pricing is unavailable")
    return (
        (serving_lease.STARTUP_SECONDS + 600 + 30)
        * (
            gpu_second
            + (
                8 * rates["cpu_hour_cost"]
                + WORKER_MEMORY_MIB[gpu] / 1024 * rates["mem_gib_hour_cost"]
            )
            / 3600
        )
        / 0.8
    )


def quote(job):
    native = (job.hyperparameters or {}).get("objective") in DECISION_OBJECTIVES
    if not native and not deployment.serves_as_adapter(job):
        raise InputValidationError(
            "Research serving requires a verified decision or supported LoRA checkpoint"
        )
    if native:
        gpu = job.effective_configuration.get("gpu_type")
        if job.effective_configuration.get("gpu_count") != 1:
            raise InputValidationError("Decision serving requires a recorded single-GPU runtime")
    else:
        cfg = get_model_config_any_backend(job.base_model) or {}
        length = job_serving_plan(job)["max_model_len"]
        gpu, _ = select_gpu({**cfg, "fp8_supported": False}, length)
    card = provider_pricing.current_rates()
    rates = card["rates"]
    cpu_hour, memory_hour = rates["cpu_hour_cost"], rates["mem_gib_hour_cost"]
    # with_options bounds execution; the deployed startup bounds remain in force.
    gpu_bound = 2 * inference_ceiling(gpu, card)
    cpu_bound = 4 * (14400 + 600 + 30) * (2 * cpu_hour + 8 * memory_hour) / 3600
    return {
        "ceiling_usd": gpu_bound + cpu_bound / 0.8,
        "rate_card": card,
        "gpu": gpu,
        "basis": "One publication attempt, archive, verification and one inference; full startup/execution/idle reservations, 20 percent margin",
    }


def invoke(action, request):
    agent, assignment = action.agent, action.agent.assignment
    if agent.parent_id:
        raise InputValidationError("Only the research owner may deploy or invoke a model")
    if request.operation == "inspect":
        return describe(assignment)
    if assignment.specification["constraints"].get("no_serving") and request.operation != "stop":
        raise InputValidationError("This assignment forbids serving work")
    if request.operation == "deploy":
        campaign = (
            research_evidence.experiment_campaigns(assignment)
            .select_related("selected")
            .filter(pk=request.campaign)
            .first()
        )
        if campaign is None or campaign.state != "completed" or not campaign.selected_id:
            raise InputValidationError("Deploy a completed campaign's kept run")
        job = campaign.selected
        current = DeployedModel.objects.filter(finetuning_job=job).first()
        bounded = bool({"execution_seconds", "ttl_seconds"} & action.arguments.keys())
        lease = serving_lease.policy(current) if current else None
        if not bounded and not lease:
            with transaction.atomic():
                research_team.admit_mutation(agent)
                if current is None:
                    current = deployment.ensure_training_deployment(str(job.pk))
                elif current.status in ("failed", "deleted"):
                    current = deployment.retry_deployment(current.pk)
            if current is None:
                raise InputValidationError("The selected checkpoint is unavailable for deployment")
            return describe(assignment)
        with transaction.atomic():
            research_team.admit_mutation(agent)
            current = DeployedModel.objects.select_for_update().filter(finetuning_job=job).first()
            lease = serving_lease.policy(current) if current else None
            if bounded and current and not lease and current.status not in ("failed", "deleted"):
                raise InputValidationError(
                    "This checkpoint already has a persistent deployment. It cannot accept "
                    "serving time limits; reuse it without limits or select another checkpoint."
                )
            if (
                current
                and lease
                and serving(current)
                and any(
                    field in action.arguments
                    and lease.get(field, float("inf")) > getattr(request, field)
                    for field in ("execution_seconds", "ttl_seconds")
                )
            ):
                raise InputValidationError(
                    "The open serving allocation exceeds the requested time limits. "
                    "Stop it and wait for settlement before admitting a new allocation."
                )
            if current and lease and lease.get("assignment") != str(assignment.pk):
                if not observed(assignment).filter(pk=current.pk).exists():
                    raise InputValidationError(
                        "This checkpoint already has a deployment with separate authority"
                    )
                current.serving_runtime["lease"]["assignment"] = str(assignment.pk)
                current.save(update_fields=["serving_runtime"])
            if current and serving(current):
                return describe(assignment)
            if current and model_pending(current):
                raise InputValidationError(
                    "This checkpoint's earlier deployment is still stopping. Deploy it again "
                    "once that has stopped."
                )
        cost = quote(job)
        base = (
            None
            if (job.hyperparameters or {}).get("objective") in DECISION_OBJECTIVES
            else serving_lease.staged_base(job, deployment.modal_environment())
        )
        remaining = research.allowance(assignment)["remaining_seconds"]
        if remaining < 180:
            raise InputValidationError(
                "At least three minutes must remain for deployment and verification"
            )
        with transaction.atomic():
            allocation = research.claim(
                agent,
                f"serving:{action.pk}",
                "serving_allocation",
                {"campaign": str(campaign.pk), **cost},
                cost["ceiling_usd"],
            )
            if allocation.state == "denied":
                raise InputValidationError(allocation.result["error"])
            research_team.admit_mutation(agent)
            lease = {
                "assignment": str(assignment.pk),
                "allocation": str(allocation.pk),
                "environment": deployment.modal_environment(),
                "execution_seconds": min(request.execution_seconds, remaining),
                **serving_lease.admitted(request.ttl_seconds, timezone.now(), assignment.deadline),
                "max_requests": request.max_requests,
                "staged_base": base,
                **cost,
            }
            if current is None:
                model = deployment.ensure_training_deployment(str(job.pk), lease=lease)
                if model is None:
                    raise InputValidationError(
                        "The selected checkpoint is unavailable for deployment"
                    )
                if (serving_lease.policy(model) or {}).get("allocation") != str(allocation.pk):
                    raise InputValidationError(
                        "The checkpoint acquired another deployment before this allocation was admitted"
                    )
            else:
                research.event(
                    assignment,
                    "serving_retried",
                    {
                        "deployment": str(current.pk),
                        "generation": str(current.deployment_generation),
                        "previous_runtime": current.serving_runtime,
                        "allocation": str(allocation.pk),
                    },
                    agent,
                )
                model = deployment.retry_deployment(
                    current.pk, lease=lease, expected_generation=current.deployment_generation
                )
            research.complete(allocation, {"deployment": str(model.pk)})
        return describe(assignment)
    model = observed(assignment).filter(pk=request.deployment).first()
    if model is None:
        raise InputValidationError("Select a deployment owned by this assignment")
    if request.operation == "infer":
        if model.inference_contract == "decision" and (request.messages or request.example):
            raise InputValidationError(
                "Decision inference requires input-only decisions, not chat messages"
            )
        if model.inference_contract != "decision" and request.decisions:
            raise InputValidationError("Chat inference requires messages, not decisions")
        if request.example:
            # Acceptance reads this serving service; resolve the frozen input at admission.
            from overbae.services.research_acceptance import example_input

            source, source_receipt = example_input(assignment, request.example)
            if any(
                message.get("role") not in {"system", "developer"} for message in request.messages
            ):
                raise InputValidationError(
                    "For a frozen example supply only system instructions; its exact source input is appended by the platform"
                )
            messages = [*request.messages, {"role": "user", "content": source}]
        else:
            messages = request.messages
        key = f"research:{action.pk}"
        payload = (
            {"decisions": request.decisions}
            if model.inference_contract == "decision"
            else {
                "messages": messages,
                "max_tokens": request.max_tokens,
                "temperature": 0,
                "chat_template_kwargs": {"enable_thinking": request.enable_thinking},
                **({"research_source": source_receipt} if request.example else {}),
            }
        )
        with transaction.atomic():
            research_science.experiment_for(assignment, lock=True)
            research_team.current_turn(agent)
            model = DeployedModel.objects.select_for_update().get(pk=model.pk)
            prior = inference_requests.recover_existing(model, key, payload)
            if prior:
                return inference_requests.describe(prior)
            research_team.admit_mutation(agent)
            serving_lease.require_open(model)
            allocation = None
            if (
                serving_lease.policy(model)
                and requests(model).exclude(error_code="serving_prerequisite_failed").count()
                >= model.serving_runtime["lease"]["max_requests"]
            ):
                card = provider_pricing.current_rates()
                allocation = research.claim(
                    agent,
                    f"inference:{action.pk}",
                    "inference_allocation",
                    {"deployment": str(model.pk), "rate_card": card},
                    inference_ceiling(model.gpu_type, card),
                )
                if allocation.state == "denied":
                    raise InputValidationError(allocation.result["error"])
                model.serving_runtime["lease"]["max_requests"] += 1
                model.save(update_fields=["serving_runtime"])
            inference = inference_requests.submit(
                model, assignment.created_by, key, payload, source="research"
            )
            if allocation:
                research.complete(allocation, {"inference": str(inference.pk)})
            return inference_requests.describe(inference)
    if request.operation == "stop":
        stop(model, actor=agent)
    return describe(assignment)


def stop(model, *, actor=None):
    now = timezone.now()
    with transaction.atomic():
        if actor is not None:
            research_team.current_turn(actor)
        fresh = DeployedModel.objects.select_for_update().get(pk=model.pk)
        if fresh.deployment_generation != model.deployment_generation or any(
            (serving_lease.policy(fresh) or {}).get(key)
            != (serving_lease.policy(model) or {}).get(key)
            for key in ("assignment", "allocation")
        ):
            return
        model = fresh
        leased = serving_lease.policy(model) is not None
        if leased:
            # A lease is closed once: stopping it again keeps when that was.
            model.serving_runtime["lease"].setdefault("closed_at", now.isoformat())
            model.save(update_fields=["serving_runtime"])
    # A standard deployment keeps serving; stopping ends only this research's requests.
    if leased and model.status in deployment.ACTIVE_STATUSES:
        DeployedModel.objects.filter(
            pk=model.pk, deployment_generation=model.deployment_generation
        ).update(deployment_deadline=now, deployment_next_poll_at=now)
    for request in requests(model).filter(state__in=inference_requests.ACTIVE):
        if (
            request.remote_id
            and deployment.cancel_operation(request.remote_id)
            or request.state == "queued"
        ):
            InferenceRequest.objects.filter(pk=request.pk).update(
                state="failed",
                error_code="cancelled",
                completed_at=now,
                claim=None,
                claim_until=None,
            )
    archive = model.serving_runtime.get("archive_call_id")
    if archive and deployment.cancel_operation(archive):
        mark_archive_terminal(model)


@transaction.atomic
def mark_archive_terminal(model):
    fresh = DeployedModel.objects.select_for_update().get(pk=model.pk)
    if fresh.deployment_generation == model.deployment_generation:
        fresh.serving_runtime["archive_terminal"] = True
        fresh.save(update_fields=["serving_runtime"])


def reconcile(assignment, *, cancelling=False):
    for model in deployments(assignment):
        expired = (
            datetime.fromisoformat(model.serving_runtime["lease"]["deadline"]) <= timezone.now()
        )
        try:
            serving_lease.require_open(model)
        except InputValidationError:
            expired = True
        if cancelling or expired:
            stop(model)
        deployment.advance_deployment(model.pk)
        for request in requests(model).filter(state__in=inference_requests.ACTIVE):
            inference_requests.advance(request.pk)
        model.refresh_from_db()
        archive = model.serving_runtime.get("archive_call_id")
        if archive and not model.serving_runtime.get("archive_terminal"):
            state, _ = deployment.poll_operation(archive)
            if state in {"complete", "failed"}:
                mark_archive_terminal(model)


def serving(model):
    """Starting, or ready, under a lease that is still open."""
    return model.status in {*deployment.ACTIVE_STATUSES, "ready"} and not serving_lease.closed(
        model
    )


def released(model):
    """Whether a stop has finished: a lease is closed with nothing left running, and a
    standard deployment has no research request in flight."""
    if serving_lease.policy(model) is None:
        return not requests(model).filter(state__in=inference_requests.ACTIVE).exists()
    return serving_lease.closed(model) and not model_pending(model)


def settle(model):
    """End what a closed lease left running and report whether any of it remains. A
    deployment starts again only once its provider work has stopped."""
    if serving(model):
        return False
    if model_pending(model):
        stop(model)
        deployment.advance_deployment(model.pk)
        model.refresh_from_db()
    return model_pending(model)


def model_pending(m):
    return bool(
        m.status in deployment.ACTIVE_STATUSES
        or m.deployment_cancel_pending
        or m.serving_runtime.get("archive_dispatching", False)
        or (
            m.serving_runtime.get("archive_call_id")
            and not m.serving_runtime.get("archive_terminal")
        )
        or requests(m).filter(state__in=inference_requests.ACTIVE).exists()
    )


def pending(assignment):
    return any(model_pending(m) for m in deployments(assignment))