Skip to content

The platform for continuously improving AI agents.

35.7 KB
Raw Blame
import uuid
from datetime import timedelta
from typing import TypedDict

from django.db import connection, transaction
from django.utils import timezone
from langgraph.graph import END, START, StateGraph
from langgraph.types import Command, interrupt
from pydantic import ValidationError
from rest_framework.exceptions import ValidationError as ServiceValidationError

from overbae.core.errors import InputValidationError
from overbae.models import (
    Cell,
    ExperimentExecution,
    ExperimentNodeExecution,
    ProjectMembership,
    ResearchAssignment,
    ResearchExperiment,
)
from overbae.services import (
    context_graph,
    execution_mandates,
    experiment_artifacts,
    experiment_checkpoints,
    experiment_execution,
    experiment_interfaces,
    experiment_operator,
    experiment_partitions,
    experiment_reports,
    experiment_research,
    experiment_reuse,
    experiment_scopes,
    experiment_serving,
    research,
    research_evidence,
    research_science,
    research_telemetry,
)
from overbae.services.datasets.rows import RowStoreError
from overbae.services.experiment_catalog import resolved
from overbae.services.experiment_settings import CONTROL_SETTINGS, compare, matches
from overbae.services.research_contract import ResearchBudget

FINISHED = {"completed", "skipped", "failed", "cancelled"}
FAILED = {"failed", "error", "denied", "cancelled", "stopped", "exhausted", "expired", "superseded"}
# Native outcomes that were ended on request: the stage is cancelled, not failed.
STOPPED = {"cancelled", "stopped"}


class State(TypedDict):
    execution: str
    ready: list[str]
    disposition: str


@transaction.atomic
def start(
    experiment,
    user,
    *,
    revision,
    request_key,
    budget,
    parameters=None,
    instructions="",
    controller=None,
    reuse_run=None,
    rerun_from=None,
    plan_fingerprint=None,
    execution_mandate=None,
    admission=None,
    operator=None,
):
    # Both the native domain dispatcher and the document service call the executor.
    from overbae.services import experiment_plans, research_tools

    experiment = ResearchExperiment.objects.select_for_update().get(pk=experiment.pk)
    if (
        experiment.deleted_at
        or not user
        or not ProjectMembership.objects.filter(
            project_id=experiment.project_id,
            project__is_active=True,
            user=user,
            user__is_active=True,
        ).exists()
    ):
        raise InputValidationError("Experiment authority has been revoked")
    request_input = {
        "revision": revision,
        "parameters": parameters or {},
        "budget": budget,
        "instructions": instructions,
        "reuse_run": str(reuse_run) if reuse_run else None,
        "rerun_from": sorted(set(rerun_from or [])),
        "plan": plan_fingerprint,
        "controller": str(controller.pk) if controller else None,
        "admission": admission,
    }
    supplied_identity = context_graph.fingerprint(request_input)
    parsed_budget = ResearchBudget.model_validate(budget)
    budget = parsed_budget.model_dump(mode="json")
    request_identity = context_graph.fingerprint({**request_input, "budget": budget})
    omitted_defaults_identity = context_graph.fingerprint(
        {
            **request_input,
            "budget": parsed_budget.model_dump(mode="json", exclude_defaults=True),
        }
    )
    existing = ResearchAssignment.objects.filter(
        project=experiment.project, request_key=f"flow:{experiment.pk}:{request_key}"
    ).first()
    if existing:
        if not research.authorized(existing):
            raise InputValidationError("Run authority has been revoked")
        task = existing.specification.get("task", {})
        retained = task.get("admission_request")
        if retained is not None:
            matches = retained in {request_identity, supplied_identity, omitted_defaults_identity}
        else:
            # Historical runs retain their resolved request, without an admission envelope.
            matches = (
                task.get("revision") == revision
                and task.get("parameters", {}) == (parameters or {})
                and task.get("instructions", "") == instructions
                and task.get("reuse_run") == (str(reuse_run) if reuse_run else None)
                and task.get("rerun_from", []) == sorted(set(rerun_from or []))
                and task.get("controller_action") == (str(controller.pk) if controller else None)
            )
        if not matches:
            raise InputValidationError("This request key belongs to a different flow run")
        if (
            execution_mandate is not None
            and execution_mandates.identity(execution_mandate) != existing.mandate_fingerprint
        ):
            raise InputValidationError("This request key has a different execution mandate")
        return existing
    reviewed_request = request_identity if plan_fingerprint else None
    if plan_fingerprint:
        plan = experiment_plans.resolve(
            experiment,
            revision=revision,
            parameters=parameters,
            reuse_run=reuse_run,
            rerun_from=rerun_from,
        )
        if plan["fingerprint"] != plan_fingerprint:
            raise InputValidationError(
                "The run plan changed. Review the current revision, inputs and reusable work before starting."
            )
    version, document, bindings = experiment_plans.definition(experiment, revision, parameters)
    roots = list(dict.fromkeys(experiment_scopes.data_roots(document)))
    platform_sources = sorted(set(experiment_scopes.platform_sources(document)))
    admitted_roots = list(dict.fromkeys([*roots, *(f"cell:{key}" for key in platform_sources)]))
    mandate = (
        execution_mandates.normalize(execution_mandate)
        if execution_mandate
        else execution_mandates.admission(
            roots=admitted_roots,
            sources=execution_mandates.flow_sources(experiment.project, document),
            experiment=experiment.pk,
            explicit={"local_platform_data_only": True},
        )
    )
    if controller:
        mandate = execution_mandates.intersect(
            controller.agent.assignment.execution_mandate,
            mandate,
            parent_assignment=controller.agent.assignment,
        )
    required_sources = execution_mandates.flow_sources(experiment.project, document)
    execution_mandates.intersect(
        mandate, {**mandate, "sources": required_sources}, project=experiment.project
    )
    execution_mandates.require_flow(mandate, document)
    for identifier in platform_sources:
        cell = (
            Cell.objects.select_related("dataset")
            .filter(pk=identifier, dataset__project=experiment.project, state="ok")
            .first()
        )
        if cell is None:
            raise InputValidationError("The retained platform source is unavailable")
        execution_mandates.require_cell(
            mandate,
            cell,
            project=experiment.project,
            assignment=controller.agent.assignment if controller else None,
        )
    scientific_admission = research_science.admit(
        experiment,
        controller=controller,
        admission=admission,
        revision=revision,
        execution_fingerprint=context_graph.fingerprint(
            {"document": document, "parameters": bindings}
        ),
    )
    assignment = research.initialize(
        experiment.project,
        user=user,
        request_key=f"flow:{experiment.pk}:{request_key}",
        objective=experiment.objective,
        task={
            "experiment": str(experiment.pk),
            "revision": revision,
            "parameters": bindings,
            "instructions": instructions,
            "execution": "flow",
            "admission_request": request_identity,
            "scientific_admission": scientific_admission,
            **({"reviewed_request": reviewed_request} if reviewed_request else {}),
            "platform_sources": platform_sources,
            **({"supervision": {"autonomy": operator}} if operator else {}),
            **(
                {"reuse_run": str(reuse_run), "rerun_from": sorted(set(rerun_from or []))}
                if reuse_run
                else {}
            ),
            **(
                {
                    "controller_action": str(controller.pk),
                    "controller_assignment": str(controller.agent.assignment_id),
                }
                if controller
                else {}
            ),
        },
        context_roots=roots,
        constraints={"local_platform_data_only": True},
        # Deterministic completion does not call a model. Adaptive children reserve
        # their own review budget inside their explicit node allowance.
        budget=budget,
        execution_mandate=mandate,
    )
    if hasattr(assignment, "execution"):
        return assignment
    experiment_plans.validate(experiment, document)
    reused = experiment_reuse.candidates(experiment.project, document, reuse_run, rerun_from or [])
    for root in roots:
        research_tools.source_cell(assignment, root.split(":", 1)[1])
    assignment.experiment_revision = version
    assignment.save(update_fields=["experiment_revision"])
    execution = ExperimentExecution.objects.create(
        assignment=assignment,
        revision=version,
        document=document,
        parameters=bindings,
        fingerprint=context_graph.fingerprint({"document": document, "parameters": bindings}),
    )
    scope = experiment_scopes.create(execution, document, bindings)
    experiment_reuse.apply(scope, reused)
    assignment.agents.update(state="idle")
    research.event(
        assignment, "flow_started", {"revision": revision, "fingerprint": execution.fingerprint}
    )
    if operator:
        experiment_operator.attach(assignment)
    return assignment


def latest_nodes(scope):
    return {
        node.node: node
        for node in scope.nodes.select_related(
            "action__agent__assignment", "scope", "execution__assignment__project"
        ).order_by("attempt")
    }


@transaction.atomic
def retry(assignment, *, request_key):
    # The parent dispatcher starts flows through this engine.
    from overbae.services import experiment_dispatch

    research_science.experiment_for(assignment, lock=True)
    execution = (
        ExperimentExecution.objects.select_for_update()
        .select_related("assignment")
        .get(pk=assignment.pk)
    )
    assignment = execution.assignment
    if assignment.events.filter(kind="flow_retry", payload__request_key=request_key).exists():
        return assignment
    research_science.require_adaptive(assignment)
    if assignment.state != "unmet":
        raise InputValidationError("Retry a settled incomplete flow")
    if execution.lease or not research.authorized(assignment):
        raise InputValidationError("The flow is still settling or is no longer authorized")
    allowance = research.allowance(assignment)
    if allowance["remaining_seconds"] < 60:
        raise InputValidationError("This run's execution deadline has expired. Start a new run.")
    scope = execution.scopes.get(parent__isnull=True)
    failed = [
        node for node in latest_nodes(scope).values() if node.state in {"failed", "cancelled"}
    ]
    if not failed:
        raise InputValidationError("No failed operations are eligible for retry")
    if experiment_execution.has_unconfirmed_work(assignment) or any(
        node.action_id and node.action.state in {"running", "unknown", "pending"} for node in failed
    ):
        raise InputValidationError("Reconcile pending provider acknowledgements before retrying")
    experiment_dispatch.reopen_allocation(assignment)
    ExperimentNodeExecution.objects.bulk_create(
        [
            ExperimentNodeExecution(
                execution=execution,
                scope=scope,
                node=node.node,
                identity=node.identity,
                attempt=node.attempt + 1,
            )
            for node in failed
        ]
    )
    scope.state, scope.error, scope.outputs = "running", "", {}
    scope.save(update_fields=["state", "error", "outputs"])
    research.event(
        assignment,
        "flow_retry",
        {
            "request_key": request_key,
            "previous_result": assignment.result,
            "nodes": [node.node for node in failed],
        },
    )
    scientific = {
        key: value
        for key, value in assignment.result.items()
        if key in {"selection_locked", "scientific_lock"}
    }
    assignment.state, assignment.result, assignment.completed_at = "running", scientific, None
    assignment.save(update_fields=["state", "result", "completed_at"])
    assignment.agents.filter(parent__isnull=True).update(state="idle")
    return assignment


def inputs_for(scope, node, receipts):
    inputs = {}
    if isinstance(node.get("config", {}).get("model"), dict):
        inputs.update(
            builtin(scope.execution, {"kind": "model", "config": node["config"]["model"]}, {})
        )
    for edge in sorted(
        scope.document["edges"],
        key=lambda edge: (
            edge["input"],
            edge["output"],
            receipts[edge["source"]].identity,
            context_graph.fingerprint(receipts[edge["source"]].outputs.get(edge["output"])),
        ),
    ):
        if edge["target"] != node["id"]:
            continue
        source = receipts[edge["source"]]
        binding = source.outputs.get(edge["output"])
        if not binding:
            if node["kind"] == "join" and source.state in {"completed", "skipped"}:
                continue
            raise InputValidationError("An upstream output is unavailable")
        if edge["input"] in resolved(node).many:
            inputs.setdefault(edge["input"], []).append(binding)
        else:
            inputs[edge["input"]] = binding
    return inputs


def retain(node, *, state, outputs=None, error=""):
    if state == "completed":
        document = node.scope.document
        definition = next(item for item in document["nodes"] if item["id"] == node.node)
        if definition.get("operation"):
            required = {
                edge["output"] for edge in document["edges"] if edge["source"] == node.node
            } | {
                ref["port"]
                for ref in document.get("outputs", {}).values()
                if ref["node"] == node.node
            }
            contract = experiment_interfaces.interface(definition)
            if contract is not None:
                required.update(
                    port
                    for port in contract["produces"]
                    if experiment_interfaces.output_formats(document, node.node, port)
                )
            missing = sorted(port for port in required if not (outputs or {}).get(port))
            if missing:
                state, outputs = "failed", {}
                error = "Operation did not register required outputs: " + ", ".join(missing)
            else:
                for port, binding in (outputs or {}).items():
                    expected = experiment_interfaces.output_formats(document, node.node, port)
                    supplied = experiment_interfaces.binding_format(binding)
                    if expected is not None and supplied not in expected:
                        state, outputs = "failed", {}
                        error = (
                            f"Output {port} has incompatible format {supplied}; expected {expected}"
                        )
                        break
    node.state, node.error = state, error
    if outputs is not None:
        node.outputs = outputs
    if state in FINISHED:
        node.completed_at = timezone.now()
        node.report = experiment_reports.build(node, state, error)
    node.save(update_fields=["state", "outputs", "error", "report", "completed_at"])
    if state in FINISHED:
        research_telemetry.node_retained(node)
        assignment = node.execution.assignment
        research.event(
            assignment,
            "flow_node",
            {
                "node": node.node,
                "scope": str(node.scope_id),
                "state": state,
                "attempt": node.attempt,
                "receipt": str(node.pk),
                **({"failure": node.report["failure"]["code"]} if "failure" in node.report else {}),
            },
        )
        if state == "failed":
            experiment_operator.notify(assignment)


def workspace_busy(execution):
    return execution.nodes.filter(state="waiting", action__tool="workspace").exists()


def downstream(document, start):
    found, pending = set(), [start]
    while pending:
        current = pending.pop()
        for edge in document["edges"]:
            if edge["source"] == current and edge["target"] not in found:
                found.add(edge["target"])
                pending.append(edge["target"])
    return found


def precedes(document, node):
    """Stages a stage waits for although no edge puts them before it."""
    after = downstream(document, node["id"]) | {node["id"]}
    if node["kind"] == "stop_deployment":
        # Closing a deployment cancels the requests other stages have out on it: everything
        # downstream of the stage that produced it goes first.
        producers = {
            edge["source"]
            for edge in document["edges"]
            if edge["target"] == node["id"] and edge["input"] == "deployment"
        }
        return set().union(*(downstream(document, producer) for producer in producers)) - after
    if node["kind"] == "qualify":
        # Reading sealed data ends selection for the whole investigation, so qualification
        # is refused while any of its training still runs.
        return {other["id"] for other in document["nodes"] if other["kind"] == "train"} - after
    return set()


def inspect_scope(scope):
    receipts = latest_nodes(scope)
    definitions = {node["id"]: node for node in scope.document["nodes"]}
    for receipt in receipts.values():
        if receipt.state in FINISHED:
            continue
        node = definitions[receipt.node]
        if receipt.state == "waiting" and node["kind"] == "research":
            try:
                observed = experiment_research.advance(receipt, node)
                if observed["state"] in FINISHED:
                    retain(
                        receipt,
                        state=observed["state"],
                        outputs=observed["outputs"],
                        error=observed.get("error", ""),
                    )
            except (
                InputValidationError,
                ValidationError,
                ServiceValidationError,
                ValueError,
            ) as exc:
                retain(receipt, state="failed", error=str(exc))
            continue
        if receipt.state == "waiting" and node["kind"] in CONTROL_SETTINGS:
            observed = experiment_scopes.advance(receipt, node)
            if observed["state"] in FINISHED:
                retain(
                    receipt,
                    state=observed["state"],
                    outputs=observed["outputs"],
                    error=observed.get("error", ""),
                )
        if receipt.action_id:
            experiment_execution.reconcile(receipt.action)
            experiment_execution.poll(receipt.action)
            observed = experiment_execution.observe(receipt.action)
            if observed["state"] == "awaiting_output" and receipt.action.tool == "workspace":
                try:
                    observed = experiment_artifacts.collect(receipt.action, node)
                except (
                    InputValidationError,
                    ValidationError,
                    ServiceValidationError,
                    ValueError,
                ) as exc:
                    retain(receipt, state="failed", error=str(exc))
                    continue
            if (
                node["kind"] in {"publish", "verify_deployment"}
                and observed["state"] == "completed"
            ):
                try:
                    observed = experiment_serving.advance(receipt.action, node, observed)
                except (
                    InputValidationError,
                    ValidationError,
                    ServiceValidationError,
                    ValueError,
                ) as exc:
                    retain(receipt, state="failed", error=str(exc))
                    continue
            if observed["state"] == "completed":
                retain(receipt, state="completed", outputs=observed["outputs"])
            elif observed["state"] in FAILED:
                stopped = observed["state"] in STOPPED
                # Serving returns its deployments as a list, which carries no error of its own.
                recorded = receipt.action.result
                retain(
                    receipt,
                    state="cancelled" if stopped else "failed",
                    error=observed.get("error")
                    or experiment_reports.workspace_error(receipt.action)
                    or (recorded.get("error") if isinstance(recorded, dict) else None)
                    or ("Stopped before it finished" if stopped else "The native operation failed"),
                )
    ready = []
    for node in scope.document["nodes"]:
        receipt = receipts[node["id"]]
        if receipt.state != "pending":
            continue
        edges = [edge for edge in scope.document["edges"] if edge["target"] == node["id"]]
        parents = [receipts[edge["source"]] for edge in edges]
        if any(parent.state in {"failed", "cancelled"} for parent in parents):
            retain(receipt, state="cancelled", error="Not run: an upstream stage did not complete")
            continue
        if node["kind"] == "qualify" and research_science.pending(
            scope.execution.assignment, receipt
        ):
            continue
        if (node.get("operation") or {}).get("tool") == "workspace" and workspace_busy(
            scope.execution
        ):
            continue
        if any(receipts[other].state not in FINISHED for other in precedes(scope.document, node)):
            continue
        if all(parent.state in {"completed", "skipped"} for parent in parents):
            available = [
                bool(receipts[edge["source"]].outputs.get(edge["output"])) for edge in edges
            ]
            if edges and (not any(available) if node["kind"] == "join" else not all(available)):
                retain(receipt, state="skipped")
            elif node["kind"] == "publish" and experiment_serving.stopping(
                scope.execution.assignment,
                next(
                    (
                        receipts[edge["source"]].outputs.get(edge["output"])
                        for edge in edges
                        if edge["input"] == "model"
                    ),
                    None,
                ),
            ):
                # Its checkpoint's earlier deployment is still ending; this starts after it.
                continue
            else:
                ready.append(str(receipt.pk))
    if all(node.state in FINISHED for node in receipts.values()):
        try:
            if any(node.state in {"failed", "cancelled"} for node in receipts.values()):
                raise InputValidationError("A required flow operation failed")
            scope.outputs = experiment_scopes.outputs(scope, receipts)
            scope.state = "completed"
        except InputValidationError as exc:
            scope.state, scope.error = "failed", str(exc)
            scope.outputs = {
                name: receipts[reference["node"]].outputs[reference["port"]]
                for name, reference in scope.document.get("outputs", {}).items()
                if reference["port"] in receipts[reference["node"]].outputs
            }
        scope.save(update_fields=["outputs", "state", "error"])
    return ready


def inspect(state):
    execution = ExperimentExecution.objects.select_related("assignment", "revision").get(
        pk=state["execution"]
    )
    assignment = execution.assignment
    if assignment.state != "running":
        return {"ready": [], "disposition": "end"}
    if not research.authorized(assignment) or assignment.deadline <= timezone.now():
        research.stop(assignment)
        return {"ready": [], "disposition": "end"}
    scopes = list(execution.scopes.filter(state="running"))
    ready = []
    for scope in scopes:
        ready.extend(inspect_scope(scope))
    root = execution.scopes.get(parent__isnull=True)
    if root.state != "running":
        return {"ready": [], "disposition": "finish"}
    if (
        ready
        or any(scope.state != "running" for scope in scopes)
        or execution.scopes.filter(state="running")
        .exclude(pk__in=[scope.pk for scope in scopes])
        .exists()
    ):
        return {"ready": ready, "disposition": "execute"}
    return {"ready": [], "disposition": "wait"}


def builtin(execution, node, inputs):
    # Source admission is shared with native domain operations.
    from overbae.services.research_tools import source_cell

    kind, config = node["kind"], node["config"]
    if kind == "suite" or kind == "model" and config.get("asset"):
        from overbae.services import (
            experiment_assets,  # Builtin bindings resolve retained definitions.
        )

        asset = experiment_assets.get(
            execution.assignment.project,
            config["asset"],
            "suite" if kind == "suite" else "candidate",
        )
        if asset.fingerprint != config["fingerprint"]:
            raise InputValidationError("The pinned asset fingerprint changed")
        if kind == "model" and asset.definition["kind"] == "checkpoint":
            binding = asset.definition["checkpoint"]
            if not research_evidence.verified_model(execution.assignment.project, binding):
                raise InputValidationError("The retained checkpoint is no longer verified")
            return {"model": {"kind": "model", **binding}}
        return {kind: {"kind": kind, "asset": str(asset.pk), "fingerprint": asset.fingerprint}}
    if kind == "data":
        cell = (
            experiment_partitions.source(execution, node)
            if config.get("_metadata_only")
            # The flow binds the version; the stage that reads its rows is checked.
            else source_cell(execution.assignment, config["cell"], platform_reads=True)
        )
        if cell.fingerprint != config["fingerprint"]:
            raise InputValidationError("The admitted dataset version changed")
        return {
            "data": experiment_execution.cell_output(
                cell, sealed=bool(config.get("_metadata_only"))
            )
        }
    if kind == "split" and config.get("_cached_partition"):
        return experiment_partitions.outputs(execution, node)
    if kind == "model":
        # Training receipts, never editable input metadata, grant campaign authority.
        binding = {key: config[key] for key in ("model", "name", "instructions") if key in config}
        return {
            "model": {"kind": "model", **binding, "fingerprint": context_graph.fingerprint(binding)}
        }
    if kind == "join":
        reports = inputs["scores"]
        return {
            "scores": {
                "kind": "scores",
                "reports": reports,
                "fingerprint": context_graph.fingerprint(reports),
            }
        }
    if kind == "condition":
        passed = matches(inputs["scores"], config["predicate"])
        return {"passed" if passed else "otherwise": inputs["scores"]}
    if kind == "compare":
        return compare(inputs, config)
    raise InputValidationError("Configure this component's executable implementation")


def execute(state):
    execution = ExperimentExecution.objects.select_related("assignment__project", "revision").get(
        pk=state["execution"]
    )
    principal = execution.assignment.agents.get(parent__isnull=True)
    for identifier in state["ready"]:
        execution.assignment.refresh_from_db(fields=["state"])
        if execution.assignment.state != "running":
            return {}
        receipt = execution.nodes.select_related("scope").get(pk=identifier)
        node = next(node for node in receipt.scope.document["nodes"] if node["id"] == receipt.node)
        receipts = latest_nodes(receipt.scope)
        if receipt.state != "pending":
            continue
        if (node.get("operation") or {}).get("tool") == "workspace" and workspace_busy(execution):
            continue
        receipt.started_at = timezone.now()
        receipt.save(update_fields=["started_at"])
        try:
            receipt.inputs = inputs_for(receipt.scope, node, receipts)
            receipt.save(update_fields=["inputs"])
            if node["kind"] == "research":
                experiment_research.start(receipt, node)
            elif node["kind"] in CONTROL_SETTINGS:
                observed = experiment_scopes.advance(receipt, node)
                retain(
                    receipt,
                    state=observed["state"],
                    outputs=observed["outputs"],
                    error=observed.get("error", ""),
                )
            elif node["kind"] == "split" and node["config"].get("_cached_partition"):
                retain(receipt, state="completed", outputs=builtin(execution, node, receipt.inputs))
            elif node.get("operation"):
                action = experiment_execution.submit(
                    principal,
                    execution.revision,
                    node,
                    receipt.inputs,
                    key=f"flow:{receipt.pk}",
                    node_receipt=receipt,
                )
                receipt.action = action
                receipt.state = "waiting"
                receipt.save(update_fields=["action", "state"])
                execution.assignment.refresh_from_db(fields=["state"])
                if execution.assignment.state in research.TERMINAL:
                    # A stop settled while this operation was being submitted: it closed the
                    # stages it saw, and this one and its work are closed here.
                    from overbae.services import research_tools  # lazy: its tools start flows

                    research_tools.stop_work(execution.assignment)
                    settle_stop(execution.assignment)
                    return {}
            else:
                outputs = builtin(execution, node, receipt.inputs)
                retain(receipt, state="completed", outputs=outputs)
        except (
            InputValidationError,
            ValidationError,
            ServiceValidationError,
            ValueError,
            RowStoreError,
        ) as exc:
            receipt.action = principal.actions.filter(request_key=f"flow:{receipt.pk}").first()
            receipt.save(update_fields=["action"])
            retain(receipt, state="failed", error=str(exc))
        # A stage that finished here was announced when its result was retained.
        if receipt.state not in FINISHED:
            research.event(
                execution.assignment,
                "flow_node",
                {
                    "node": receipt.node,
                    "scope": str(receipt.scope_id),
                    "state": receipt.state,
                    "attempt": receipt.attempt,
                    "receipt": str(receipt.pk),
                },
            )
    return {}


@transaction.atomic
def finish(state):
    execution = ExperimentExecution.objects.select_related("assignment").get(pk=state["execution"])
    assignment = ResearchAssignment.objects.select_for_update().get(pk=execution.assignment_id)
    if assignment.state != "running":
        return {"disposition": "end"}
    scope = execution.scopes.get(parent__isnull=True)
    receipts = latest_nodes(scope)
    failures = [node.node for node in receipts.values() if node.state in {"failed", "cancelled"}]
    outputs = {}
    for name, binding in execution.document.get("outputs", {}).items():
        output = receipts[binding["node"]].outputs.get(binding["port"])
        if output is None and scope.state != "completed":
            failures.append(binding["node"])
        elif output is not None:
            outputs[name] = output
    assignment.state = "unmet" if failures or scope.state != "completed" else "completed"
    assignment.completed_at = timezone.now()
    assignment.refresh_from_db(fields=["result"])
    assignment.result = {
        **assignment.result,
        "execution": "flow",
        "revision": execution.revision.number,
        "outputs": outputs,
        "failed_nodes": sorted(set(failures)),
        "summary": f"Flow r{execution.revision.number} completed."
        if assignment.state == "completed"
        else f"Flow r{execution.revision.number} incomplete: {', '.join(sorted(set(failures)))}.",
    }
    assignment.save(update_fields=["state", "completed_at", "result"])
    research.event(assignment, "flow_finished", assignment.result)
    experiment_operator.notify(assignment)
    return {"disposition": "end"}


def settle_stop(assignment):
    if not hasattr(assignment, "execution"):
        return
    assignment.execution.nodes.exclude(state__in=FINISHED).update(
        state="cancelled",
        error="Run stopped",
        completed_at=timezone.now(),
    )
    assignment.execution.scopes.filter(state="running").update(
        state="cancelled",
        error="Run stopped",
    )


def wait(state):
    interrupt({"execution": state["execution"], "reason": "native_operation"})
    return {}


def graph(checkpointer):
    builder = StateGraph(State)
    builder.add_node("inspect", inspect)
    builder.add_node("execute", execute)
    builder.add_node("finish", finish)
    builder.add_node("wait", wait)
    builder.add_edge(START, "inspect")
    builder.add_conditional_edges(
        "inspect",
        lambda state: state["disposition"],
        {"execute": "execute", "finish": "finish", "wait": "wait", "end": END},
    )
    builder.add_edge("execute", "inspect")
    builder.add_edge("wait", "inspect")
    builder.add_edge("finish", END)
    return builder.compile(checkpointer=checkpointer)


@transaction.atomic
def acquire(identifier):
    execution = (
        ExperimentExecution.objects.select_for_update()
        .select_related("assignment")
        .get(pk=identifier)
    )
    if (
        execution.assignment.state != "running"
        or execution.lease
        and execution.lease_expires_at > timezone.now()
    ):
        return None
    execution.lease = uuid.uuid4()
    execution.lease_expires_at = timezone.now() + timedelta(minutes=5)
    execution.save(update_fields=["lease", "lease_expires_at"])
    return execution


def advance(identifier):
    lock = int(uuid.UUID(str(identifier))) % (2**63 - 1)
    with connection.cursor() as cursor:
        cursor.execute("SELECT pg_try_advisory_lock(%s)", [lock])
        if not cursor.fetchone()[0]:
            return
    try:
        run_locked(identifier)
    finally:
        with connection.cursor() as cursor:
            cursor.execute("SELECT pg_advisory_unlock(%s)", [lock])


def run_locked(identifier):
    execution = acquire(identifier)
    if execution is None:
        return
    try:
        with experiment_checkpoints.store() as checkpointer:
            workflow = graph(checkpointer)
            config = {
                "configurable": {"thread_id": f"flow:{execution.pk}"},
                "recursion_limit": 3000,
            }
            snapshot = workflow.get_state(config)
            value = (
                Command(resume=True)
                if snapshot.interrupts
                else None
                if snapshot.next
                else {"execution": str(execution.pk), "ready": [], "disposition": "inspect"}
            )
            workflow.invoke(value, config, durability="sync")
    finally:
        ExperimentExecution.objects.filter(pk=execution.pk, lease=execution.lease).update(
            lease=None, lease_expires_at=None
        )