Skip to content

The platform for continuously improving AI agents.

3.7 KB
Raw Blame
import json

from overbae.services import experiment_execution

UPSTREAM = "Not run: an upstream stage did not complete"
REFUSED = {"ValidationError", "InputValidationError", "ToolArgumentsError"}
# Whether running the stage again unchanged can succeed. A class that is absent is unknown.
RETRYABLE = {
    "upstream_failed": True,
    "stopped": True,
    "code_error": False,
    "output_contract": False,
    "invalid_configuration": False,
    "admission_denied": False,
    # An uncertain provider outcome is reconciled from its saved identity, never resubmitted.
    "outcome_unknown": False,
}


def raised(result):
    """The last exception a workspace program raised, from its retained output."""
    for line in reversed(str(result.get("output") or "").splitlines()):
        try:
            entry = json.loads(line)
        except ValueError:
            continue
        if isinstance(entry, dict) and entry.get("type") == "error":
            content = entry.get("content") or {}
            name, value = content.get("ename"), content.get("evalue")
            if name:
                return f"{name}: {value}" if value else str(name)
    return None


def workspace_error(action):
    if action.tool != "workspace":
        return None
    result = experiment_execution.execution_result(action)
    if result.get("timed_out"):
        return f"The program did not finish within {action.arguments.get('timeout')} seconds"
    if result.get("exit_code") not in {None, 0}:
        return raised(result) or result.get("error") or f"Exit code {result['exit_code']}"
    if result.get("reason"):
        return str(result["reason"]).replace("_", " ")
    return None


def failure(node, state, error):
    action = node.action if node.action_id else None
    result = action.result if action and isinstance(action.result, dict) else {}
    if error == UPSTREAM:
        return "upstream_failed"
    if state == "cancelled":
        return "stopped"
    if error.startswith("Operation did not register required outputs") or (
        error.startswith("Output ") and "incompatible format" in error
    ):
        return "output_contract"
    if action is None:
        return "not_admitted"
    if action.state == "unknown":
        return "outcome_unknown"
    if action.state == "denied":
        return "admission_denied"
    if action.state == "failed" and result.get("type") in REFUSED:
        return "invalid_configuration"
    if action.tool == "workspace":
        observed = experiment_execution.execution_result(action)
        if observed.get("timed_out"):
            return "timeout"
        if observed.get("exit_code") not in {None, 0}:
            return "code_error"
        if observed.get("state") == "unknown":
            return "sandbox_lost"
    return "operation_failed"


def build(node, state, error):
    """What a finished stage records beside its state: how it ran and, when it did not
    complete, the class of its failure. The message stays in ``error``."""
    action = node.action if node.action_id else None
    report = {
        "tool": action.tool if action else None,
        "action": str(action.pk) if action else None,
        "duration_seconds": round((node.completed_at - node.started_at).total_seconds(), 3)
        if node.started_at and node.completed_at
        else None,
    }
    if state in {"failed", "cancelled"}:
        code = failure(node, state, error)
        report["failure"] = {"code": code, "retryable": RETRYABLE.get(code)}
        if action and action.tool == "workspace":
            observed = experiment_execution.execution_result(action)
            report["failure"] |= {
                key: observed[key] for key in ("exit_code", "timed_out") if key in observed
            }
    return report