The platform for continuously improving AI agents.
from contextlib import contextmanager
from contextvars import ContextVar
from copy import deepcopy
from threading import get_ident
from types import SimpleNamespace
from typing import Literal
from uuid import UUID
from django.utils import timezone
from pydantic import Field, model_validator
from agent_runtime.contracts import Contract
from overbae.core.errors import InputValidationError
from overbae.models import (
Cell,
DataPartitionMember,
DeployedModel,
ExperimentExecution,
ExperimentNodeExecution,
ResearchAction,
ResearchArtifact,
ResearchAssignment,
)
from overbae.services.context_graph import fingerprint
Family = Literal["read", "author", "prepare", "train", "evaluate", "serve", "qualify"]
FAMILIES = ("read", "author", "prepare", "train", "evaluate", "serve", "qualify")
_NODE_CONTINUATION = ContextVar("research_node_continuation", default=None)
class SourceGrant(Contract):
kind: Literal[
"cell", "artifact", "campaign", "dataset", "capability", "asset", "run", "connector"
]
id: UUID
fingerprint: str | None = Field(default=None, pattern="^[a-f0-9]{64}$")
descendants: bool = False
class ExecutionMandate(Contract):
authority: Literal["observe", "act"]
families: list[Family] = Field(min_length=1, max_length=7)
experiment: UUID | None = None
sources: list[SourceGrant] = Field(default_factory=list)
constraints: dict = Field(default_factory=dict)
@model_validator(mode="after")
def unique_permissions(self):
if len(self.families) != len(set(self.families)):
raise ValueError("Operation families must be distinct")
if self.authority == "observe" and set(self.families) - {"read", "author"}:
raise ValueError("Observation permits read and author operations only")
if any(source.kind == "connector" and not source.fingerprint for source in self.sources):
raise ValueError("Connector source grants require a pinned configuration")
identities = [(source.kind, source.id) for source in self.sources]
if len(identities) != len(set(identities)):
raise ValueError("Source grants must be distinct")
return self
def normalize(value):
mandate = ExecutionMandate.model_validate(value)
result = mandate.model_dump(mode="json")
result["families"] = sorted(result["families"])
result["sources"] = sorted(result["sources"], key=lambda item: (item["kind"], item["id"]))
return result
def constraints(parent, child):
result = deepcopy(parent)
for key, value in child.items():
if key not in result:
result[key] = deepcopy(value)
elif isinstance(result[key], dict) and isinstance(value, dict):
result[key] = constraints(result[key], value)
elif (
isinstance(result[key], list)
and isinstance(value, list)
and all(item in result[key] for item in value)
):
result[key] = deepcopy(value)
elif result[key] != value:
raise InputValidationError("Execution constraints conflict with the parent mandate")
return result
def intersect(parent, child, *, parent_assignment=None, project=None):
parent, child = normalize(parent), normalize(child)
if parent["experiment"] and child["experiment"] not in {None, parent["experiment"]}:
raise InputValidationError("A child cannot change its admitted experiment")
sources = []
for source in child["sources"]:
admitted = next(
(
item
for item in parent["sources"]
if (item["kind"], item["id"]) == (source["kind"], source["id"])
),
None,
)
if admitted is None and source["kind"] == "cell":
cell = Cell.objects.select_related("dataset").filter(pk=source["id"]).first()
if cell is not None:
require_cell(parent, cell, assignment=parent_assignment, project=project)
if source["fingerprint"] not in {None, cell.fingerprint}:
raise InputValidationError("The child source fingerprint changed")
sources.append({**source, "fingerprint": cell.fingerprint})
continue
if admitted is None:
raise InputValidationError("A child cannot broaden its admitted sources")
if admitted["fingerprint"] and source["fingerprint"] not in {None, admitted["fingerprint"]}:
raise InputValidationError("A child cannot change its pinned source identity")
sources.append(
{
**source,
"fingerprint": admitted["fingerprint"] or source["fingerprint"],
"descendants": source["descendants"] and admitted["descendants"],
}
)
authority = "observe" if "observe" in {parent["authority"], child["authority"]} else "act"
families = set(parent["families"]) & set(child["families"])
if authority == "observe":
families &= {"read", "author"}
return normalize(
{
"authority": authority,
"families": sorted(families),
"experiment": parent["experiment"] or child["experiment"],
"sources": sources,
"constraints": constraints(parent["constraints"], child["constraints"]),
}
)
def admission(
*, roots=(), experiment=None, families=FAMILIES, authority="act", explicit=None, sources=()
):
sources = deepcopy(list(sources))
for reference in roots:
kind, _, identifier = str(reference).partition(":")
kind = "artifact" if kind == "research_artifact" else kind
if kind in {"cell", "artifact", "campaign", "dataset", "capability", "asset", "run"}:
sources.append({"kind": kind, "id": identifier, "descendants": True})
if kind == "cell":
pin = (
Cell.objects.filter(pk=identifier).values_list("fingerprint", flat=True).first()
)
if pin:
sources[-1]["fingerprint"] = pin
if kind == "artifact":
pin = (
ResearchArtifact.objects.filter(pk=identifier)
.values_list("sha256", flat=True)
.first()
)
if pin:
sources[-1]["fingerprint"] = pin
return normalize(
{
"authority": authority,
"families": list(families) if authority == "act" else ["read", "author"],
"experiment": str(experiment) if experiment else None,
"sources": list({(item["kind"], item["id"]): item for item in sources}.values()),
"constraints": explicit or {},
}
)
def connector_source(project, identifier):
from overbae.services.connectors import imports # Native imports use mandate admission.
credential, config = imports.connector(project, identifier)
return {
"kind": "connector",
"id": str(credential.pk),
"fingerprint": imports.configuration_fingerprint(credential, config),
"descendants": True,
}
def flow_sources(project, document, *, allow_unbound=False):
# The compiler imports research contracts, including mandate schemas.
from overbae.services.experiment_compiler import compile_document
from overbae.services.experiment_settings import CONTROL_SETTINGS
sources = {}
def visit(definition):
for node in definition.get("nodes", []):
operation = node.get("operation") or {}
arguments = operation.get("arguments") or {}
if operation.get("tool") == "platform" and arguments.get("name") == "import_traces":
identifier = arguments.get("arguments", {}).get("connector")
if allow_unbound and isinstance(identifier, dict) and "$parameter" in identifier:
continue
try:
identifier = UUID(str(identifier))
except ValueError as exc:
if allow_unbound:
continue
raise InputValidationError(
"Bind the import connector before admission"
) from exc
try:
source = connector_source(project, identifier)
except InputValidationError:
if allow_unbound:
continue
raise
sources[source["id"]] = source
if node.get("kind") in CONTROL_SETTINGS and node.get("config", {}).get("_definition"):
settings = CONTROL_SETTINGS[node["kind"]].model_validate(node["config"])
bindings = settings.bindings if node["kind"] == "map" else [{}]
for binding in bindings:
child, _ = compile_document(
settings.definition,
{**settings.parameters, **binding},
deferred=settings.inputs,
)
visit(child)
visit(document)
return list(sources.values())
def require_import(assignment, identifier, *, action=None):
if action is not None and action.agent.assignment_id != assignment.pk:
raise InputValidationError("The import action belongs to another assignment")
mandate = (
require_action_continuation(action, "prepare") if action else require(assignment, "prepare")
)
grant = next(
(
source
for source in mandate["sources"]
if source["kind"] == "connector" and source["id"] == str(identifier)
),
None,
)
if grant is None:
raise InputValidationError("The connector is outside the admitted execution mandate")
return grant["fingerprint"]
def includes_sources(value, previous):
current, prior = normalize(value), normalize(previous)
try:
inherited = intersect(
{**current, "experiment": None, "constraints": {}},
{**prior, "experiment": None, "constraints": {}},
)
except InputValidationError:
return False
return inherited["sources"] == prior["sources"]
def require(assignment, family):
scope = _NODE_CONTINUATION.get()
continuation = bool(
scope
and scope.active
and scope.thread == get_ident()
and scope.assignment == assignment.pk
and family in {"read", scope.family}
)
return check_authority(assignment, family, continuation=continuation)
def require_action(action, family):
scope = _NODE_CONTINUATION.get()
if scope and scope.action != action.pk:
return check_authority(action.agent.assignment, family, continuation=False)
return require(action.agent.assignment, family)
def require_action_continuation(action, family):
# Deferred workers retain their action; direct admission never calls this path.
from overbae.services import experiment_execution
action.refresh_from_db()
if ExperimentExecution.objects.filter(pk=action.agent.assignment_id).exists():
experiment_execution.admitted_node(action)
if family not in {"read", operation_family(action.tool, action.arguments)}:
raise InputValidationError("The operation differs from its pinned node family")
return require_continuation(action.agent.assignment, family)
@contextmanager
def continuing_node(action):
# Native services import the mandate contract, so resolve its receipt after import.
from overbae.services import experiment_execution
node = experiment_execution.admitted_node(action)
family = operation_family(action.tool, action.arguments)
require_continuation(action.agent.assignment, family)
scope = SimpleNamespace(
action=action.pk,
assignment=action.agent.assignment_id,
family=family,
thread=get_ident(),
active=True,
)
token = _NODE_CONTINUATION.set(scope)
try:
yield node
finally:
# Copied async contexts cannot retain authority after this synchronous call returns.
scope.active = False
_NODE_CONTINUATION.reset(token)
def require_continuation(assignment, family):
# Only retained operation owners use this; new scientific admission still uses require.
return check_authority(assignment, family, continuation=True)
def require_serving_lease(deployed):
current = DeployedModel.objects.filter(
pk=deployed.pk,
project_id=deployed.project_id,
deployment_generation=deployed.deployment_generation,
).first()
lease = (current.serving_runtime or {}).get("lease") if current else None
expected = (deployed.serving_runtime or {}).get("lease") or {}
if not lease or any(
lease.get(key) != expected.get(key) for key in ("assignment", "allocation")
):
raise InputValidationError("This serving allocation has been superseded")
try:
owner_id = UUID(lease["assignment"])
except (KeyError, TypeError, ValueError, AttributeError) as exc:
raise InputValidationError("This serving allocation has no retained owner") from exc
owner = ResearchAssignment.objects.filter(pk=owner_id, project_id=current.project_id).first()
if owner is None:
raise InputValidationError("This serving allocation has no retained owner")
return check_authority(
owner,
"serve",
continuation=True,
ready_lease=current if current.status == "ready" else None,
)
def check_authority(assignment, family, *, continuation, ready_lease=None):
from overbae.services import research # Research admission imports the mandate contract.
admitted, visited = None, {assignment.pk}
while True:
assignment.refresh_from_db(
fields=["execution_mandate", "state", "deadline", "specification", "result"]
)
continuing = continuation and research.continues_admitted_work(assignment)
# A ready allocation outlives ordinary completion until its lease expires;
# its inference requester and any new deployment retain separate authority.
if ready_lease is not None and family == "serve":
continuing = continuing or assignment.state in {"completed", "unmet"}
if (
not research.authorized(assignment)
or assignment.state != "running"
and not continuing
or assignment.deadline <= timezone.now()
):
raise InputValidationError("This assignment no longer has execution authority")
mandate = normalize(assignment.execution_mandate)
if family not in mandate["families"]:
raise InputValidationError("This operation is outside the admitted execution mandate")
if family not in {"read", "author"} and mandate["authority"] != "act":
raise InputValidationError("Observation authority cannot start executing work")
if family == "train" and mandate["constraints"].get("no_training"):
raise InputValidationError("This assignment forbids training work")
if family == "serve" and mandate["constraints"].get("no_serving"):
raise InputValidationError("This assignment forbids serving work")
if family in {"prepare", "train", "evaluate"}:
from overbae.services import research_science # Scientific gates share this contract.
research_science.require_adaptive(assignment)
if admitted is None:
admitted = mandate
assignment = parent_assignment(assignment)
if assignment is None:
return admitted
if assignment.pk in visited:
raise InputValidationError("The controlling research assignment forms a cycle")
visited.add(assignment.pk)
def lock_parents(assignment):
assignment = ResearchAssignment.objects.get(pk=assignment.pk)
parents, visited = [], {assignment.pk}
while (assignment := parent_assignment(assignment)) is not None:
if assignment.pk in visited:
raise InputValidationError("The controlling research assignment forms a cycle")
visited.add(assignment.pk)
parents.append(assignment.pk)
# Cancellation walks from controller to child; model admission takes the same order.
for identifier in reversed(parents):
ResearchAssignment.objects.select_for_update().filter(pk=identifier).first()
def parent_assignment(assignment):
task = assignment.specification.get("task", {})
controller, action_id, flow = (
task.get(key) for key in ("controller_assignment", "controller_action", "flow_run")
)
if not any((controller, action_id, flow)):
return None
if (controller and flow) or (action_id and not controller) or (controller and not action_id):
raise InputValidationError("The controlling research admission is inconsistent")
try:
parent_id = UUID(str(controller or flow))
action_id = UUID(str(action_id)) if action_id else None
except ValueError as exc:
raise InputValidationError("The controlling research admission is invalid") from exc
parent = ResearchAssignment.objects.filter(
pk=parent_id, project_id=assignment.project_id
).first()
if parent is None:
raise InputValidationError("The controlling research assignment is unavailable")
if controller:
action = ResearchAction.objects.filter(
pk=action_id, agent__assignment=parent, agent__parent__isnull=True, tool="experiment"
).first()
execution = (
ExperimentExecution.objects.select_related("revision").filter(pk=assignment.pk).first()
)
if (
action is None
or action.arguments.get("operation") not in {"run", "define"}
or action.arguments.get("operation") == "define"
and not action.arguments.get("run")
or execution is None
or task.get("experiment") != str(execution.revision.experiment_id)
or task.get("revision") != execution.revision.number
):
raise InputValidationError("The controlling action does not admit this flow")
else:
receipts = list(
ExperimentNodeExecution.objects.filter(
execution_id=parent.pk,
node=task.get("node"),
action__tool="adaptive_research",
action__agent__assignment=parent,
action__result__assignment=str(assignment.pk),
).values_list("pk", flat=True)[:2]
)
if len(receipts) != 1 or assignment.request_key != f"flow-research:{receipts[0]}":
raise InputValidationError(
"The controlling node does not admit this research assignment"
)
return parent
def require_published_cell(cell, *, project_id):
if cell.dataset.project_id != project_id or cell.state != "ok" or not cell.fingerprint:
raise InputValidationError("The source cell is unavailable in this project")
members = DataPartitionMember.objects.filter(cell=cell)
if members.exclude(plan__project_id=project_id, plan__state="completed").exists():
raise InputValidationError("The partition is not published in this project yet")
return cell
def require_cell(value, cell, *, project=None, assignment=None):
mandate = normalize(value)
if assignment is not None:
if project is not None and project.pk != assignment.project_id:
raise InputValidationError("Source authority belongs to another project")
project_id = assignment.project_id
elif project is not None:
project_id = project.pk
else:
raise InputValidationError("Source admission requires project authority")
require_published_cell(cell, project_id=project_id)
# Cell references pin selected content; attachments do not restrict project discovery.
for source in mandate["sources"]:
if (
source["kind"] == "cell"
and source["id"] == str(cell.pk)
and source["fingerprint"]
and source["fingerprint"] != cell.fingerprint
):
raise InputValidationError("The selected source fingerprint changed")
return cell
def operation_family(tool, arguments):
operation = arguments.get("operation")
if tool == "workspace":
return (
"read"
if operation in {"read", "status"}
else None
if operation == "interrupt"
else "prepare"
)
if arguments.get("describe") or operation in {
"inspect",
"list",
"catalog",
"runtime",
"source",
"plan",
"validate",
}:
return "read"
if operation in {"stop", "cancel"}:
return None
if tool == "training":
if operation == "experiment":
return "read"
if operation in {"program", "select"}:
return "author"
return "qualify" if operation == "qualify" else "train"
if tool == "benchmark":
return "qualify" if arguments.get("phase") == "final" else "evaluate"
if tool in {"prediction", "score"}:
return "evaluate"
if tool == "serving":
return "serve"
if tool in {"component", "workshop", "import_dataset"}:
return "prepare"
if tool == "experiment":
return "prepare" if operation == "preview" else "author"
if tool == "supervise":
return "author" if operation == "retry" else "read"
if tool == "platform":
from overbae.services import research_services # Services import Research contracts.
name = arguments.get("name")
if name in research_services.READS or name in {"check_data", "export_data"}:
return "read"
if name in {"verify_deployment", "measure_serving"}:
return "serve"
if name in {"save_training_plan", "save_dataset_pipeline", "update_dataset"}:
return "author"
return "prepare"
return (
"author"
if tool
in {
"asset",
"eval_set",
"retain_artifact",
"retain_pipeline",
"remember",
"experiment_decision",
}
else "read"
)
def identity(value):
return fingerprint(normalize(value))
def require_flow(value, document):
mandate = normalize(value)
if mandate["authority"] != "act":
raise InputValidationError("Observation authority cannot execute a flow")
families = {
"ingest": "prepare",
"trace_dataset": "prepare",
"transform": "prepare",
"split": "prepare",
"component": "prepare",
"train": "train",
"predict": "evaluate",
"evaluate": "evaluate",
"qualify": "qualify",
"publish": "serve",
"inference": "serve",
"verify_deployment": "serve",
"performance": "serve",
}
def check(value):
if isinstance(value, dict):
for node in value.get("nodes", []):
family = families.get(node.get("kind"))
if family and family not in mandate["families"]:
raise InputValidationError(f"The flow requires unadmitted {family} authority")
if (
family == "train"
and mandate["constraints"].get("no_training")
or family == "serve"
and mandate["constraints"].get("no_serving")
):
raise InputValidationError(
"The flow conflicts with an explicit execution constraint"
)
for child in value.values():
check(child)
elif isinstance(value, list):
for child in value:
check(child)
check(document)