Skip to content

The platform for continuously improving AI agents.

2.8 KB
Raw Blame
from overbae.core.errors import InputValidationError
from overbae.models import Cell, DataPartitionPlan
from overbae.services.datasets import partition_assignment, partition_plans

# How a source may be read once rows of it are held out. They say nothing of what the data
# is, so a stage's identity leaves them out: a run before the hold and one after reuse the
# same results.
ACCESS_PINS = ("_cached_partition", "_metadata_only")


def pin(project, document):
    for node in document["nodes"]:
        for name in ACCESS_PINS:
            node["config"].pop(name, None)
    return document


def member_cell(project, document, edge):
    """The cell behind a connected output when it is already known: a dataset stage's cell, or
    the member of a partition that exists for a split stage's source and recipe."""
    nodes = {node["id"]: node for node in document["nodes"]}
    producer = nodes[edge["source"]]
    if producer["kind"] == "data":
        return producer["config"].get("cell")
    feeding = next(
        (nodes[item["source"]] for item in document["edges"] if item["target"] == producer["id"]),
        None,
    )
    if producer["kind"] != "split" or feeding is None or feeding["kind"] != "data":
        return None
    recipe = (
        (producer.get("operation") or {}).get("arguments", {}).get("arguments", {}).get("recipe")
    )
    try:
        recipe = partition_assignment.validate_recipe(recipe)
    except (InputValidationError, ValueError):
        return None
    cell = (
        Cell.objects.select_related("dataset")
        .filter(
            pk=feeding["config"].get("cell"),
            fingerprint=feeding["config"].get("fingerprint"),
            dataset__project=project,
        )
        .first()
    )
    plan = partition_plans.verified_plan(cell, recipe) if cell else None
    member = plan and plan.members.filter(role=edge["output"]).first()
    return str(member.cell_id) if member else None


def source(execution, node):
    cell = Cell.objects.select_related("dataset").get(
        pk=node["config"]["cell"], dataset__project=execution.assignment.project
    )
    if cell.fingerprint != node["config"]["fingerprint"]:
        raise InputValidationError("The retained partition source changed")
    return cell


def outputs(execution, node):
    # The executor owns the shared binding shape, including sealed output roles.
    from overbae.services.experiment_execution import cell_output

    plan = DataPartitionPlan.objects.get(
        pk=node["config"]["_cached_partition"],
        project=execution.assignment.project,
        state="completed",
    )
    return {
        member.role: {
            **cell_output(member.cell, sealed=member.role == "final"),
            "partition": str(plan.pk),
        }
        for member in plan.members.select_related("cell__dataset")
    }