Skip to content

The platform for continuously improving AI agents.

28.4 KB
Raw Blame
import json
from functools import cache

from overbae.core.errors import InputValidationError
from overbae.services.experiment_catalog import resolved

# These are executor bindings, not user-authored claims about artifact contents.
BINDINGS = {
    "variant.results": {
        "fields": ["variants", "fingerprint"],
        "description": "Independent candidate scopes with stable keys, typed outputs and retained errors.",
    },
    "trace.selection": {
        "fields": ["sync", "fingerprint"],
        "description": "Exact trace identities retained by a completed native connector import.",
    },
    "inference.response": {
        "fields": ["inference", "deployment", "generation"],
        "description": "Native inference receipt for a pinned deployment generation.",
    },
    "serving.performance": {
        "fields": ["performance", "evaluation"],
        "description": "Native decision performance measurements with qualified model identities.",
    },
    "deployment.retirement": {
        "fields": ["deployment", "generation"],
        "description": "Closed serving lease and native deployment retirement receipt.",
    },
    "candidate.definition": {
        "fields": ["asset", "fingerprint"],
        "description": "Immutable candidate configuration with an admitted execution adapter.",
    },
    "benchmark.suite": {
        "fields": ["asset", "fingerprint"],
        "description": "Immutable benchmark test definitions and acceptance policy.",
    },
    "prediction.set": {
        "fields": ["prediction_set", "fingerprint", "candidate", "cell"],
        "description": "Retained row predictions with exact candidate, source identities, attempts and measured usage.",
    },
    "dataset.cell": {
        "fields": ["cell", "dataset", "fingerprint", "sealed"],
        "description": "Registered immutable project data. Native transformation, partition, training and evaluation consume this identity; final data remains sealed.",
    },
    "model.catalogue": {
        "fields": ["model"],
        "description": "Training catalogue identity. Starts native training; it is not a trained checkpoint and not a benchmark participant.",
    },
    "model.checkpoint": {
        "fields": ["model", "campaign", "job", "checkpoint", "fingerprint"],
        "description": "The checkpoint of a campaign's kept run. Supports development inspection, trained-model benchmarking and deployment. Starting another training run does not resume this checkpoint.",
    },
    "evaluation.scores": {
        "fields": ["data", "phase", "protocol", "report", "fingerprint"],
        "description": "Measured report, or reports collection, with exact dataset, evaluation protocol and coverage. Metric selectors are relative to each report binding, for example /report/eval_loss.",
    },
    "deployment.receipt": {
        "fields": ["deployment", "job", "generation", "allocation"],
        "description": "Verified deployment generation and serving allocation.",
    },
    "artifact.file": {
        "fields": ["artifact", "path", "fingerprint"],
        "description": "Retained bytes staged at path for downstream Python. A file is not a registered dataset, native checkpoint or measured evaluation receipt. Use a native Data Workshop pipeline for transformations that must feed native training.",
    },
}

NATIVE = {
    ("platform", "import_traces"): {
        "consumes": {},
        "requires": [],
        "produces": {"traces": ["trace.selection"]},
    },
    ("platform", "create_trace_dataset"): {
        "consumes": {"traces": ["trace.selection"]},
        "requires": ["traces"],
        "produces": {"data": ["dataset.cell"]},
    },
    ("platform", "check_data"): {
        "consumes": {"data": ["dataset.cell"]},
        "requires": ["data"],
        "produces": {"data": ["dataset.cell"], "report": ["artifact.file"]},
    },
    ("platform", "export_data"): {
        "consumes": {"data": ["dataset.cell"]},
        "requires": ["data"],
        "produces": {"artifact": ["artifact.file"]},
    },
    ("platform", "verify_deployment"): {
        "consumes": {"deployment": ["deployment.receipt"]},
        "requires": ["deployment"],
        "produces": {"deployment": ["deployment.receipt"]},
    },
    ("platform", "measure_serving"): {
        "consumes": {"scores": ["evaluation.scores"]},
        "requires": ["scores"],
        "produces": {"performance": ["serving.performance"]},
    },
    ("serving", "infer"): {
        "consumes": {"deployment": ["deployment.receipt"]},
        "requires": ["deployment"],
        "produces": {"response": ["inference.response"]},
    },
    ("serving", "stop"): {
        "consumes": {"deployment": ["deployment.receipt"]},
        "requires": ["deployment"],
        "produces": {"receipt": ["deployment.retirement"]},
    },
    ("prediction", "run"): {
        "consumes": {"model": ["candidate.definition"], "data": ["dataset.cell"]},
        "requires": ["model", "data"],
        "produces": {"predictions": ["prediction.set"]},
    },
    ("score", "run"): {
        "consumes": {"predictions": ["prediction.set"], "suite": ["benchmark.suite"]},
        "requires": ["predictions", "suite"],
        "produces": {"scores": ["evaluation.scores"]},
    },
    ("score", "native"): {
        "consumes": {"scores": ["evaluation.scores"], "suite": ["benchmark.suite"]},
        "requires": ["scores", "suite"],
        "produces": {"scores": ["evaluation.scores"]},
    },
    ("platform", "run_dataset_pipeline"): {
        "consumes": {"data": ["dataset.cell"]},
        "requires": ["data"],
        "produces": {"data": ["dataset.cell"]},
    },
    ("platform", "prepare_dataset"): {
        "consumes": {"data": ["dataset.cell"]},
        "requires": ["data"],
        "produces": {"data": ["dataset.cell"]},
    },
    ("platform", "create_data_partition"): {
        "consumes": {"data": ["dataset.cell"]},
        "requires": ["data"],
        "produces": {port: ["dataset.cell"] for port in ("train", "development", "final")},
    },
    ("training", "create"): {
        "consumes": {
            "data": ["dataset.cell"],
            "development": ["dataset.cell"],
            "model": ["model.catalogue"],
        },
        "requires": ["data", "model"],
        "produces": {"model": ["model.checkpoint"]},
    },
    ("training", "inspect"): {
        "consumes": {"model": ["model.checkpoint"], "data": ["dataset.cell"]},
        "requires": ["model"],
        "produces": {"scores": ["evaluation.scores"]},
    },
    ("benchmark", "run"): {
        "consumes": {
            "data": ["dataset.cell"],
            "model": ["model.checkpoint"],
            "suite": ["benchmark.suite"],
        },
        "requires": ["data"],
        "produces": {"scores": ["evaluation.scores"]},
        "score_selector": "/report/metrics/{metric}/mean (one report per participant and benchmark; metrics come from the selected eval set or native benchmark)",
    },
    ("serving", "deploy"): {
        "consumes": {"model": ["model.checkpoint"], "scores": ["evaluation.scores"]},
        "requires": ["model", "scores"],
        "produces": {"deployment": ["deployment.receipt"]},
    },
}


def bound_arguments(tool, operation):
    return {
        ("platform", "create_trace_dataset"): {"arguments.sync": "traces.sync"},
        ("platform", "check_data"): {"arguments.source_cell": "data.cell"},
        ("platform", "export_data"): {"arguments.source_cell": "data.cell"},
        ("platform", "measure_serving"): {"arguments.evaluation": "scores.evaluation"},
        ("platform", "verify_deployment"): {"arguments.deployment": "deployment.deployment"},
        ("serving", "infer"): {"deployment": "deployment.deployment"},
        ("serving", "stop"): {"deployment": "deployment.deployment"},
        ("prediction", "run"): {"candidate": "model.asset", "cell": "data.cell"},
        ("score", "run"): {"prediction_set": "predictions.prediction_set", "suite": "suite.asset"},
        ("score", "native"): {"evaluation": "scores.evaluation", "suite": "suite.asset"},
        ("component", "run"): {"component": "config.asset", "inputs": "inputs"},
        ("component", "validate"): {"inputs": "inputs"},
        **{
            ("platform", name): {
                "arguments.source_cell": "data.cell",
                "arguments.source_fingerprint": "data.fingerprint",
                "arguments.dataset": "data.dataset",
            }
            for name in ("run_dataset_pipeline", "prepare_dataset")
        },
        ("platform", "create_data_partition"): {"arguments.source_cell": "data.cell"},
        ("training", "create"): {
            "arguments.train_cell": "data.cell",
            "arguments.development_cell": "development.cell",
            "arguments.final_cell": "final.cell",
            "arguments.allowed_models": "model.model",
        },
        **{
            ("training", operation): {"campaign": "model.campaign"}
            for operation in ("inspect", "qualify")
        },
        ("benchmark", "run"): {"cell": "data.cell"},
        ("serving", "deploy"): {"campaign": "model.campaign"},
    }.get((tool, operation), {})


def binding_format(binding):
    if not isinstance(binding, dict):
        return None
    if binding.get("artifact"):
        return "artifact.file"
    kind = binding.get("kind")
    if kind == "model":
        return (
            "model.checkpoint"
            if binding.get("job")
            else "candidate.definition"
            if binding.get("asset")
            else "model.catalogue"
            if binding.get("model")
            else None
        )
    return {
        "data": "dataset.cell" if binding.get("cell") else None,
        "traces": "trace.selection" if binding.get("sync") else None,
        "response": "inference.response" if binding.get("inference") else None,
        "performance": "serving.performance" if binding.get("performance") else None,
        "retirement": "deployment.retirement" if binding.get("deployment") else None,
        "predictions": "prediction.set" if binding.get("prediction_set") else None,
        "scores": "evaluation.scores",
        "variants": "variant.results",
        "suite": "benchmark.suite" if binding.get("asset") else None,
        "deployment": "deployment.receipt",
    }.get(kind)


def validate_inputs(node, inputs):
    contract = interface(node)
    if contract is None:
        return
    missing = sorted(port for port in contract["requires"] if not inputs.get(port))
    if missing:
        raise InputValidationError("Missing resolved inputs: " + ", ".join(missing))
    for port, value in inputs.items():
        accepted = contract["consumes"].get(port, [])
        for binding in value if isinstance(value, list) else [value]:
            supplied = binding_format(binding)
            if supplied not in accepted:
                raise InputValidationError(
                    f"{port}: received {supplied or 'unregistered output'}; accepts {accepted}"
                )


def operation_key(node):
    operation = node.get("operation") or {}
    tool, arguments = operation.get("tool"), operation.get("arguments", {})
    return tool, arguments.get("name" if tool == "platform" else "operation")


def interface(node):
    key = operation_key(node)
    if key in NATIVE:
        return NATIVE[key]
    if node["kind"] == "component" and not node["config"].get("asset"):
        return {
            "consumes": {},
            "requires": [],
            "produces": {},
            "definition": "Read the retained component's named input and output contracts",
        }
    component = resolved(node)
    if key == ("component", "run"):
        return {
            "consumes": {port: ["dataset.cell", "artifact.file"] for port in component.inputs},
            "requires": list(component.required),
            "produces": {port: ["artifact.file"] for port in component.outputs},
        }
    if key == ("component", "validate"):
        return {
            "consumes": {"artifact": ["artifact.file"]},
            "requires": ["artifact"],
            "produces": {"artifact": ["artifact.file"]},
        }
    if key == ("workspace", "python"):
        return {
            "consumes": {port: list(BINDINGS) for port in component.inputs},
            "requires": list(component.required),
            "produces": {port: ["artifact.file"] for port in node["config"].get("outputs", {})},
        }
    if node["kind"] == "compare" and not node.get("operation"):
        return {
            "consumes": {port: ["evaluation.scores"] for port in component.inputs},
            "requires": ["scores"],
            "produces": {"scores": ["evaluation.scores"], "model": ["model.checkpoint"]},
        }
    return None


def output_formats(document, node_id, port):
    nodes = {node["id"]: node for node in document["nodes"]}
    node = nodes[node_id]
    kind = node["kind"]
    if kind == "suite":
        return ["benchmark.suite"]
    if kind == "model" and node["config"].get("asset"):
        if isinstance(node["config"]["asset"], dict):
            return None
        return (
            ["model.checkpoint"] if node["config"].get("_checkpoint") else ["candidate.definition"]
        )
    if kind in {"data", "model"}:
        return {"data": ["dataset.cell"], "model": ["model.catalogue"]}[kind]
    if kind in {"subflow", "map", "iterate"}:
        if kind == "map" and port == "variants":
            return ["variant.results"]
        child = node["config"].get("_definition")
        if child is None:
            return None
        name = node["config"].get("outputs", {}).get(port)
        reference = child.get("outputs", {}).get(name)
        return output_formats(child, reference["node"], reference["port"]) if reference else []
    if kind == "research":
        if port not in node["config"].get("outputs", []):
            return []
        return ["artifact.file"]
    if kind == "compare" and not node.get("operation") and port == "model":
        upstream = [
            item
            for item in document["edges"]
            if item["target"] == node_id and item["input"] == "scores"
        ]
        if upstream and all(
            candidate_scores(document, item["source"], item["output"]) for item in upstream
        ):
            return ["candidate.definition"]
        bound = checkpoint_scores(document, node_id, "scores")
        return None if bound is None else ["model.checkpoint"] if bound else []
    if kind in {"condition", "join"}:
        formats = [
            output_formats(document, edge["source"], edge["output"])
            for edge in document["edges"]
            if edge["target"] == node_id
        ]
        return (
            sorted({item for group in formats for item in group})
            if all(group is not None for group in formats)
            else None
        )
    contract = interface(node)
    if contract is None:
        return None
    if operation_key(node) == ("platform", "create_data_partition"):
        fractions = (
            node["operation"]["arguments"].get("arguments", {}).get("recipe", {}).get("fractions")
        )
        if isinstance(fractions, dict) and "$parameter" not in fractions and port not in fractions:
            return []
    return contract["produces"].get(port, [])


def candidate_scores(document, node_id, port):
    node = next(item for item in document["nodes"] if item["id"] == node_id)
    if operation_key(node) == ("score", "run"):
        return True
    if node["kind"] in {"subflow", "map", "iterate"}:
        child = node["config"].get("_definition")
        if child is None:
            return False
        reference = child.get("outputs", {}).get(node["config"].get("outputs", {}).get(port))
        return bool(reference) and candidate_scores(child, reference["node"], reference["port"])
    if node["kind"] in {"compare", "condition", "join"} and not node.get("operation"):
        edges = [edge for edge in document["edges"] if edge["target"] == node_id]
        return bool(edges) and all(
            candidate_scores(document, edge["source"], edge["output"]) for edge in edges
        )
    return False


def checkpoint_scores(document, node_id, port):
    node = next(item for item in document["nodes"] if item["id"] == node_id)
    if operation_key(node) == ("training", "inspect"):
        return True
    if node["kind"] in {"subflow", "map", "iterate"}:
        child = node["config"].get("_definition")
        if child is None:
            return None
        name = node["config"].get("outputs", {}).get(port)
        reference = child.get("outputs", {}).get(name)
        return bool(reference) and checkpoint_scores(child, reference["node"], reference["port"])
    if node["kind"] in {"compare", "condition", "join"} and not node.get("operation"):
        edges = [edge for edge in document["edges"] if edge["target"] == node_id]
        sources = [checkpoint_scores(document, edge["source"], edge["output"]) for edge in edges]
        return False if not sources or False in sources else None if None in sources else True
    return False


def validate(document, *, executable=False):
    problems = []
    for node in document["nodes"]:
        contract = interface(node)
        if contract is None:
            continue
        edges = [edge for edge in document["edges"] if edge["target"] == node["id"]]
        if executable:
            bound = {"model"} if isinstance(node["config"].get("model"), dict) else set()
            missing = set(contract["requires"]) - {edge["input"] for edge in edges} - bound
            if missing:
                problems.append(f"{node['id']}: connect {', '.join(sorted(missing))}")
        selection = node["config"].get("model")
        if isinstance(selection, dict):
            supplied = (
                "model.checkpoint"
                if selection.get("_checkpoint")
                else "candidate.definition"
                if selection.get("asset")
                else "model.catalogue"
            )
            if supplied not in contract["consumes"].get("model", []):
                problems.append(
                    f"{node['id']}: selected {supplied}; accepts {contract['consumes'].get('model', [])}"
                )
        for edge in edges:
            supplied = output_formats(document, edge["source"], edge["output"])
            accepted = contract["consumes"].get(edge["input"], [])
            if (
                not accepted
                or supplied is not None
                and (not supplied or set(supplied) - set(accepted))
            ):
                problems.append(
                    f"{edge['source']}.{edge['output']} -> {node['id']}.{edge['input']}: "
                    f"produces {', '.join(supplied or []) or 'no output'}; "
                    f"accepts {', '.join(accepted) or 'no input'}. "
                    "Choose a compatible implementation or add an explicit conversion."
                )
        if node["kind"] == "compare" and not node.get("operation"):
            metric = node["config"].get("metric")
            if isinstance(metric, str) and not metric.startswith(("/report/", "report.")):
                problems.append(f"{node['id']}: use a score selector such as /report/eval_loss")
    if problems:
        raise InputValidationError("Incompatible execution interfaces:\n" + "\n".join(problems))
    if executable:
        for name, reference in document.get("outputs", {}).items():
            if output_formats(document, reference["node"], reference["port"]) == []:
                raise InputValidationError(
                    f"Flow output {name}: {reference['node']}.{reference['port']} produces no output"
                )
        validate_availability(document)
        validate_selection_order(document)
        validate_final_data(document)
        validate_final_measurements(document)


def unconditional_outputs(document):
    nodes = {node["id"]: node for node in document["nodes"]}
    ports = {(key, port) for key, node in nodes.items() for port in resolved(node).outputs}
    conditions, predicates = {}, {}
    for key, node in sorted(nodes.items()):
        if node["kind"] != "condition":
            continue
        signature = (
            json.dumps(node.get("config", {}), sort_keys=True, allow_nan=False),
            tuple(
                sorted(
                    (edge["source"], edge["output"], edge["input"])
                    for edge in document["edges"]
                    if edge["target"] == key
                )
            ),
        )
        conditions[key] = predicates.setdefault(signature, len(predicates))
    if not conditions:
        return ports
    # Reduced decision diagrams keep branch proofs bounded without enumerating
    # every combination of condition outcomes.
    decisions, unique = {}, {}
    work = 0

    def decision(variable, low, high):
        if low == high:
            return low
        key = (variable, low, high)
        if key not in unique:
            if len(decisions) >= 10000:
                raise InputValidationError(
                    "Simplify conditional branches before executing this flow"
                )
            unique[key] = len(decisions) + 2
            decisions[unique[key]] = key
        return unique[key]

    @cache
    def combine(disjunction, left, right):
        nonlocal work
        work += 1
        if work > 100000:
            raise InputValidationError("Simplify conditional branches before executing this flow")
        if left == right:
            return left
        neutral, absorbing = (0, 1) if disjunction else (1, 0)
        if absorbing in (left, right):
            return absorbing
        if left == neutral:
            return right
        if right == neutral:
            return left
        variable = min(decisions[left][0], decisions[right][0])
        a = decisions[left][1:] if decisions[left][0] == variable else (left, left)
        b = decisions[right][1:] if decisions[right][0] == variable else (right, right)
        return decision(
            variable, combine(disjunction, a[0], b[0]), combine(disjunction, a[1], b[1])
        )

    visiting = set()

    @cache
    def runnable(key):
        if key in visiting:
            raise InputValidationError("Flow connections must be acyclic")
        visiting.add(key)
        node = nodes[key]
        edges = [edge for edge in document["edges"] if edge["target"] == key]
        disjunction = node["kind"] == "join"
        result = 0 if disjunction and edges else 1
        for edge in edges:
            result = combine(disjunction, result, available(edge["source"], edge["output"]))
        visiting.remove(key)
        return result

    @cache
    def available(key, port):
        result = runnable(key)
        if key in conditions:
            branch = decision(conditions[key], int(port == "otherwise"), int(port == "passed"))
            result = combine(False, result, branch)
        return result

    for key in nodes:
        if runnable(key) == 0:
            raise InputValidationError(
                f"{key}: required inputs belong to mutually exclusive conditional branches. "
                "Join alternative inputs before this operation."
            )
    return {port for port in ports if available(*port) == 1}


def validate_availability(document):
    available = unconditional_outputs(document)
    for name, reference in document.get("outputs", {}).items():
        if (reference["node"], reference["port"]) not in available:
            raise InputValidationError(
                f"Flow output {name} is unavailable on a conditional branch. "
                "Join every branch before exposing a required output."
            )


def validate_final_data(document):
    """A qualify stage of a trained model reads data its train stage neither trains nor
    selects on."""
    nodes = {node["id"]: node for node in document["nodes"]}

    def source(target, port):
        return next(
            (
                f"{edge['source']}.{edge['output']}"
                for edge in document["edges"]
                if edge["target"] == target and edge["input"] == port
            ),
            None,
        )

    for node in document["nodes"]:
        if node["kind"] != "qualify":
            continue
        data, model = source(node["id"], "data"), source(node["id"], "model")
        trained = model.partition(".")[0] if model else None
        if trained is None or nodes[trained]["kind"] != "train":
            continue
        if data in {source(trained, "data"), source(trained, "development")}:
            raise InputValidationError(
                f"{node['id']}: {data} is data {trained} trains or selects on. Qualify on a "
                "partition training never reads."
            )


def validate_final_measurements(document):
    """What can follow sealed measurements. Each qualify stage is one evaluation, so a compare
    stage cannot rank several of them; and sealed data admits one comparison, so a shared
    benchmark of several models cannot read data a qualify stage reads. Both were refused only
    when the stage ran."""
    nodes = {node["id"]: node for node in document["nodes"]}
    readers = {}
    for edge in document["edges"]:
        source, target = nodes[edge["source"]], nodes[edge["target"]]
        if target["kind"] == "compare" and source["kind"] == "qualify":
            raise InputValidationError(
                f"{target['id']}: {edge['source']}.{edge['output']} is a qualify stage's scores. "
                "A qualify stage is its own evaluation of one model and its base, and a compare "
                "stage ranks measurements of one evaluation. Remove this stage and report each "
                "arm's qualify scores side by side: they are measured on the same sealed rows."
            )
        if target["kind"] == "qualify" and edge["input"] == "data":
            readers.setdefault(f"{edge['source']}.{edge['output']}", []).append(target)
    for target in nodes.values():
        if operation_key(target) != ("training", "qualify") or any(
            edge["target"] == target["id"] and edge["input"] == "data" for edge in document["edges"]
        ):
            continue
        model = next(
            (
                edge
                for edge in document["edges"]
                if edge["target"] == target["id"] and edge["input"] == "model"
            ),
            None,
        )
        reserved = next(
            (
                edge
                for edge in document["edges"]
                if model and edge["target"] == model["source"] and edge["input"] == "final"
            ),
            None,
        )
        if reserved:
            readers.setdefault(f"{reserved['source']}.{reserved['output']}", []).append(target)
    for data, stages in readers.items():
        shared = [stage for stage in stages if operation_key(stage) == ("benchmark", "run")]
        others = [stage["id"] for stage in stages if stage not in shared]
        if shared and (others or len(shared) > 1):
            raise InputValidationError(
                f"{shared[0]['id']}: {data} is sealed data that "
                f"{', '.join(others or [stage['id'] for stage in shared[1:]])} also reads, and "
                "sealed data admits one comparison. Keep each arm's own qualify stage and report "
                "their scores side by side, or remove them and keep this shared comparison."
            )


def validate_selection_order(document):
    nodes = {node["id"]: node for node in document["nodes"]}
    parents = {
        key: {edge["source"] for edge in document["edges"] if edge["target"] == key}
        for key in nodes
    }

    def ancestors(key):
        visited, pending = set(), list(parents[key])
        while pending:
            parent = pending.pop()
            if parent not in visited:
                visited.add(parent)
                pending.extend(parents[parent])
        return visited

    qualifications = {
        key
        for key, node in nodes.items()
        if operation_key(node) == ("training", "qualify")
        or operation_key(node) == ("benchmark", "run")
        and node["operation"]["arguments"].get("phase") == "final"
    }
    for key in qualifications:
        upstream = ancestors(key)
        training = {source for source in upstream if nodes[source]["kind"] == "train"}
        for comparison, node in nodes.items():
            if node["kind"] != "compare" or comparison in upstream:
                continue
            dependencies = ancestors(comparison)
            if training & dependencies and not qualifications & dependencies:
                raise InputValidationError(
                    f"{key}: qualification must depend on development selection {comparison}. "
                    "Connect the comparison's selected model output before opening final evaluation."
                )