Skip to content

The platform for continuously improving AI agents.

18.6 KB
Raw Blame
import hashlib
import json
from concurrent.futures import ThreadPoolExecutor, as_completed
from decimal import Decimal

import modal
import numpy as np
from django.db import transaction
from django.db.models import Q
from django.db.models.fields.json import KT
from django.utils import timezone
from sklearn.metrics import average_precision_score, brier_score_loss, log_loss, roc_auc_score

from overbae.core.errors import InputValidationError
from overbae.models import Cell, ResearchAction, ResearchAssignment
from overbae.services import (
    context_graph,
    execution_mandates,
    provider_pricing,
    research,
    research_science,
    research_workspace,
)
from overbae.services.datasets import rows
from overbae.services.research_contract import Artifact


@transaction.atomic
def request(assignment, *, artifact, cell, request_key, positive="1", negative="0"):
    research_science.experiment_for(assignment, lock=True)
    assignment = ResearchAssignment.objects.select_for_update().get(pk=assignment.pk)
    if assignment.state not in {"completed", "unmet"} or not research.authorized(assignment):
        raise InputValidationError("Lock the research outcome before independent qualification")
    if research.allowance(assignment)["remaining_seconds"] < 240:
        raise InputValidationError(
            "The assignment deadline leaves insufficient time for qualification"
        )
    selected = assignment.artifacts.filter(pk=artifact, kind="model").first()
    source = Cell.objects.filter(pk=cell, dataset__project=assignment.project, state="ok").first()
    if (
        selected is None
        or source is None
        or str(cell) not in assignment.specification["sealed_cells"]
        or str(artifact) not in assignment.result.get("artifacts", [])
        or positive == negative
    ):
        raise InputValidationError("Select a retained model and a sealed cell from this assignment")
    if not 1 <= source.rows <= 100000:
        raise InputValidationError("Independent CPU qualification supports up to 100000 records")
    arguments = {
        "artifact": str(selected.pk),
        "artifact_sha256": selected.sha256,
        "cell": str(cell),
        "fingerprint": source.fingerprint,
        "positive": positive,
        "negative": negative,
        "seconds": 180,
    }
    identity = context_graph.fingerprint(arguments)
    owner = assignment.agents.get(parent__isnull=True)
    key = "qualification:" + request_key
    prior = owner.actions.filter(request_key=key).first()
    if prior:
        if prior.fingerprint != identity:
            raise InputValidationError("The qualification key has different inputs")
        return prior
    if not permitted(assignment, seconds=240):
        raise InputValidationError("Qualification is outside the current execution authority")
    research_science.freeze(
        assignment,
        candidates=[{"artifact": str(selected.pk), "fingerprint": selected.sha256}],
        sealed=[{"cell": str(source.pk), "fingerprint": source.fingerprint}],
        protocol={"positive": positive, "negative": negative},
    )
    assignment.refresh_from_db(fields=["result"])
    locked = assignment.result.get("qualification_artifact")
    if locked and locked != str(selected.pk):
        raise InputValidationError("Final qualification has already locked another model artifact")
    card = provider_pricing.current_rates()
    try:
        rates = card["rates"]
        reserve = Decimal(
            str(
                (2 * rates["cpu_hour_cost_sandbox"] + 4 * rates["mem_gib_hour_cost_sandbox"])
                * 180
                / 3600
                / 0.8
                + 0.02
            )
        )
    except (KeyError, TypeError) as exc:
        raise InputValidationError("Qualification pricing is unavailable") from exc
    assignment.result = {
        **assignment.result,
        "selection_locked": assignment.result.get("selection_locked") or timezone.now().isoformat(),
        "qualification_artifact": str(selected.pk),
    }
    assignment.save(update_fields=["result"])
    return ResearchAction.objects.create(
        agent=owner,
        request_key=key,
        tool="qualification",
        fingerprint=identity,
        arguments=arguments,
        reservation_usd=reserve,
        usage={"rate_card": card},
    )


def pending_actions(assignments=None):
    actions = ResearchAction.objects.filter(tool="qualification")
    if assignments is not None:
        actions = actions.filter(agent__assignment_id__in=assignments)
    return actions.alias(
        cleanup_exit=KT("result__sandbox_cleanup_exit_code"),
        creation_started=KT("result__creation_started"),
    ).filter(
        Q(state__in=["pending", "running"])
        | (
            Q(started_at__isnull=False, cleanup_exit__isnull=True)
            & (Q(creation_started__isnull=True) | ~Q(creation_started="false"))
        )
    )


def permitted(assignment, *, seconds=0):
    visited = set()
    while assignment is not None:
        assignment.refresh_from_db()
        if (
            assignment.pk in visited
            or assignment.state not in {"completed", "unmet"}
            and (not visited or not research.continues_admitted_work(assignment))
            or not research.authorized(assignment)
            or research.allowance(assignment)["remaining_seconds"] <= seconds
        ):
            return False
        mandate = execution_mandates.normalize(assignment.execution_mandate)
        if mandate["authority"] != "act" or "qualify" not in mandate["families"]:
            return False
        visited.add(assignment.pk)
        try:
            assignment = execution_mandates.parent_assignment(assignment)
        except InputValidationError:
            return False
    return True


@transaction.atomic
def record_provider(action, **result):
    ResearchAssignment.objects.select_for_update().get(pk=action.agent.assignment_id)
    current = (
        ResearchAction.objects.select_for_update(of=("self",))
        .select_related("agent__assignment")
        .get(pk=action.pk)
    )
    current.result = {**current.result, **result}
    current.save(update_fields=["result"])
    return current


@transaction.atomic
def progress(action, *, submitting=False):
    assignment = ResearchAssignment.objects.select_for_update().get(pk=action.agent.assignment_id)
    current = (
        ResearchAction.objects.select_for_update(of=("self",))
        .select_related("agent__assignment")
        .get(pk=action.pk)
    )
    if (
        current.state != "running"
        or current.result.get("stop_requested_at")
        or not permitted(assignment, seconds=180 if submitting else 0)
    ):
        raise InputValidationError("Qualification no longer has execution authority")
    if submitting:
        current.result = {**current.result, "creation_started": True}
        current.save(update_fields=["result"])
    return current


def cleanup(action):
    action.refresh_from_db()
    if action.result.get("sandbox_cleanup_exit_code") is not None:
        return True
    if action.result.get("creation_started") is False:
        return True
    try:
        if action.result.get("sandbox"):
            sandbox = modal.Sandbox.from_id(action.result["sandbox"])
        elif action.result.get("sandbox_name") and "environment" in action.result:
            sandbox = modal.Sandbox.from_name(
                research_workspace.APP,
                action.result["sandbox_name"],
                environment_name=action.result["environment"],
            )
        else:
            record_provider(
                action, cleanup_error="The original sandbox environment is not retained"
            )
            return False
        action = record_provider(action, sandbox=sandbox.object_id)
        code = sandbox.poll()
        if code is None:
            sandbox.terminate(wait=False)
            code = sandbox.poll()
        if code is None:
            return False
        action = record_provider(action, sandbox_cleanup_exit_code=code)
        with transaction.atomic():
            ResearchAssignment.objects.select_for_update().get(pk=action.agent.assignment_id)
            current = (
                ResearchAction.objects.select_for_update(of=("self",))
                .select_related("agent__assignment")
                .get(pk=action.pk)
            )
            if current.result.get("stop_requested_at") and current.state != "completed":
                research.complete(current, current.result, state="denied")
        return True
    except Exception as exc:
        record_provider(action, cleanup_error=type(exc).__name__)
        return False


def cancel_action(action, *, reason="Qualification owner stopped"):
    with transaction.atomic():
        ResearchAssignment.objects.select_for_update().get(pk=action.agent.assignment_id)
        current = (
            ResearchAction.objects.select_for_update(of=("self",))
            .select_related("agent__assignment")
            .get(pk=action.pk)
        )
        current.result = {
            **current.result,
            "stop_requested_at": current.result.get("stop_requested_at")
            or timezone.now().isoformat(),
        }
        if current.state != "completed":
            current.result["error"] = reason
        if current.state == "pending" or current.result.get("creation_started") is False:
            current.result["creation_started"] = False
            research.complete(current, current.result, state="denied", cost=0)
            return
        research.complete(
            current,
            current.result,
            state="unknown" if current.state != "completed" else "completed",
        )
    cleanup(current)


def cancel(assignment):
    for action in pending_actions([assignment.pk]).select_related("agent__assignment"):
        cancel_action(action)


def execute(action_id):
    owner = ResearchAction.objects.select_related("agent").get(pk=action_id, tool="qualification")
    with transaction.atomic():
        assignment = ResearchAssignment.objects.select_for_update().get(
            pk=owner.agent.assignment_id
        )
        action = (
            ResearchAction.objects.select_for_update(of=("self",))
            .select_related("agent__assignment")
            .get(pk=action_id)
        )
        if action.state != "pending":
            return action
        if not permitted(assignment, seconds=180):
            return research.complete(
                action,
                {
                    "creation_started": False,
                    "error": "Qualification authority or time allowance expired",
                },
                state="denied",
                cost=0,
            )
        action.state = "running"
        action.started_at = timezone.now()
        action.result = {
            "creation_started": False,
            "sandbox_name": f"research-qualification-{action.pk}",
            "environment": research_workspace.environment(),
        }
        action.save(update_fields=["state", "started_at", "result"])
    sandbox = None
    try:
        selected = assignment.artifacts.get(pk=action.arguments["artifact"])
        source = Cell.objects.select_related("dataset").get(pk=action.arguments["cell"])
        rows.verify(source)
        if source.fingerprint != action.arguments["fingerprint"]:
            raise InputValidationError("Sealed input identity changed")
        inputs = []
        targets = []
        identities = []
        for record in rows.iter_rows(source):
            inputs.append(record.input)
            label = str(record.expected_output)
            if label not in {action.arguments["positive"], action.arguments["negative"]}:
                raise InputValidationError(
                    "A recorded target is outside the declared binary label domain"
                )
            targets.append(int(label == action.arguments["positive"]))
            identities.append(record.index)
        if len(set(targets)) != 2:
            raise InputValidationError("Binary qualification needs both recorded classes")
        with selected.file.open("rb") as file:
            bundle = file.read(research_workspace.MAX_FILE + 1)
        if hashlib.sha256(bundle).hexdigest() != action.arguments["artifact_sha256"]:
            raise InputValidationError("Retained predictor identity changed")
        progress(action)
        app = modal.App.lookup(
            research_workspace.APP,
            create_if_missing=True,
            environment_name=action.result["environment"],
        )
        image = research_workspace.image()
        action = progress(action, submitting=True)
        sandbox = modal.Sandbox.create(
            "sleep",
            "180",
            app=app,
            name=action.result["sandbox_name"],
            image=image,
            cpu=(2, 2),
            memory=(4096, 4096),
            timeout=180,
            block_network=True,
            secrets=[],
            include_oidc_identity_token=False,
        )
        action = record_provider(
            action,
            sandbox=sandbox.object_id,
            model_sha256=selected.sha256,
            cell_fingerprint=source.fingerprint,
        )
        progress(action)
        sandbox.filesystem.write_bytes(bundle, "/evaluation/bundle.zip")
        progress(action)
        sandbox.filesystem.write_bytes(json.dumps(inputs).encode(), "/evaluation/inputs.json")
        progress(action)
        process = sandbox.exec(
            "python", "-m", "agent_runtime.predict", "/evaluation", timeout=120, text=False
        )
        streams = {}

        def bounded(stream):
            data = bytearray()
            for chunk in stream:
                data.extend(chunk)
                if len(data) > 16 * 1024 * 1024:
                    sandbox.terminate()
                    raise InputValidationError("Predictor output exceeds the qualification limit")
            return data.decode(errors="replace")

        with ThreadPoolExecutor(max_workers=2) as pool:
            futures = {
                pool.submit(bounded, stream): name
                for name, stream in (("output", process.stdout), ("error", process.stderr))
            }
            for future in as_completed(futures):
                streams[futures[future]] = future.result()
        output, error = streams["output"], streams["error"]
        exit_code = process.wait()
        lines = [line for line in output.splitlines() if line.startswith("OVERMIND_PREDICTIONS=")]
        if exit_code != 0 or len(lines) != 1:
            raise InputValidationError(
                "Predictor failed in independent execution: " + error[-2000:]
            )
        predictions = np.asarray(json.loads(lines[0].split("=", 1)[1]), dtype=float)
        if (
            predictions.shape != (len(inputs),)
            or not np.isfinite(predictions).all()
            or (predictions < 0).any()
            or (predictions > 1).any()
        ):
            raise InputValidationError("Predictor must return one finite probability per input")
        result = {
            **action.result,
            "rows": len(inputs),
            "predictor_exit_code": exit_code,
            "labels": {
                "positive": action.arguments["positive"],
                "negative": action.arguments["negative"],
                "positive_count": sum(targets),
            },
            "predictions_sha256": hashlib.sha256(predictions.tobytes()).hexdigest(),
            "metrics": {
                "roc_auc": float(roc_auc_score(targets, predictions)),
                "pr_auc": float(average_precision_score(targets, predictions)),
                "log_loss": float(log_loss(targets, predictions)),
                "brier": float(brier_score_loss(targets, predictions)),
            },
            "verification": "Independent input-only predictor execution; sealed labels scored outside its sandbox",
            "scope": "Held out from this research assignment; historical source exposure is separate",
        }
        with transaction.atomic():
            action = progress(action)
            retained = research.retain(
                action,
                Artifact(
                    path="sealed-predictions.jsonl",
                    title="Independent sealed predictions",
                    kind="evaluation",
                    metadata={
                        "cell": str(source.pk),
                        "model": str(selected.pk),
                        "access": "final_data",
                    },
                ),
                b"".join(
                    (
                        json.dumps(
                            {"row": row, "target": target, "probability": float(probability)}
                        )
                        + "\n"
                    ).encode()
                    for row, target, probability in zip(
                        identities, targets, predictions, strict=True
                    )
                ),
            )
            result["predictions_artifact"] = str(retained.pk)
            research.complete(action, result)
    except Exception as exc:
        with transaction.atomic():
            ResearchAssignment.objects.select_for_update().get(pk=action.agent.assignment_id)
            current = (
                ResearchAction.objects.select_for_update(of=("self",))
                .select_related("agent__assignment")
                .get(pk=action.pk)
            )
            if current.state != "denied":
                research.complete(
                    current,
                    {
                        **current.result,
                        "error": "Qualification owner stopped"
                        if current.result.get("stop_requested_at")
                        else str(exc)[:3000],
                    },
                    state="unknown"
                    if current.result.get("creation_started") and sandbox is None
                    else "failed",
                )
    finally:
        cleanup(action)
    action.refresh_from_db()
    return action


def reconcile(action):
    action.refresh_from_db()
    if not pending_actions().filter(pk=action.pk).exists():
        return
    allowed = permitted(action.agent.assignment)
    fresh = action.started_at and (timezone.now() - action.started_at).total_seconds() < 240
    if (
        allowed
        and not action.result.get("stop_requested_at")
        and action.state in research.FINISHED_ACTIONS
    ):
        cleanup(action)
        return
    if (
        allowed
        and not action.result.get("stop_requested_at")
        and (action.state == "pending" or action.state == "running" and fresh)
    ):
        return
    cancel_action(
        action,
        reason="Qualification authority expired"
        if not allowed
        else "Qualification worker did not retain a completed observation before its deadline",
    )