Skip to content

The platform for continuously improving AI agents.

48.8 KB
Raw Blame
from copy import deepcopy
from uuid import UUID

from overbae.core import model_registry
from overbae.core.errors import InputValidationError
from overbae.modal.model_registry import get_model_config_any_backend
from overbae.models import (
    DataPartitionPlan,
    DatasetPipeline,
    DatasetPipelinePackage,
    DatasetPipelineRun,
    ExperimentAsset,
    ExperimentExecution,
    ExperimentNodeExecution,
    ResearchAction,
    ResearchAssignment,
    ResearchExperimentRevision,
    WorkshopAction,
)
from overbae.services import context_graph, research_notes
from overbae.services.datasets import pipeline_graph, pipeline_packages

FIELDS = {
    "experiment_asset": ("name", "definition"),
    "experiment_revision": ("document", "note"),
    "flow_execution": ("parameters",),
    "research_assignment": ("specification",),
    "partition": ("recipe",),
    "transformation_package": ("manifest", "inventory", "files", "file", "steps"),
    "transformation": ("name", "steps", "flow"),
    "transformation_run": (
        "pipeline_name",
        "result",
        "error",
        "operation",
        "parameters",
        "provenance",
    ),
}
UNRESOLVED = {"unresolved_evidence"}
MODELS = {
    "experiment_asset": (ExperimentAsset, "project"),
    "experiment_revision": (ResearchExperimentRevision, "experiment__project"),
    "flow_execution": (ExperimentExecution, "assignment__project"),
    "research_assignment": (ResearchAssignment, "project"),
    "partition": (DataPartitionPlan, "project"),
    "transformation_package": (DatasetPipelinePackage, "project"),
    "transformation": (DatasetPipeline, "project"),
    "transformation_run": (DatasetPipelineRun, "dataset__project"),
}


def retained(action):
    sources = research_notes.retained_sources(action, "authoring_sources")
    return sources if sources is not None else UNRESOLVED


def action_for(project, identifier):
    try:
        identifier = UUID(str(identifier))
    except (ValueError, TypeError, AttributeError):
        return None
    return (
        ResearchAction.objects.filter(pk=identifier, agent__assignment__project=project)
        .select_related("agent__assignment")
        .first()
    )


def asset_fields(asset, seen):
    values = {("name",): asset.name}
    definition = asset.definition
    metadata = {"kind"} if asset.kind == "candidate" else set()
    if asset.kind == "candidate" and definition.get("kind") in {"catalogue", "agent"}:
        metadata.add("model")
    for key, value in definition.items():
        if key not in metadata and value is not None:
            values[("definition", key)] = value
    sources = set()
    if asset.request_key.startswith("research:"):
        action = action_for(asset.project_id, asset.request_key.removeprefix("research:"))
        if (
            action is None
            or action.tool != "asset"
            or action.arguments.get("operation") != "publish"
        ):
            sources = UNRESOLVED
        else:
            arguments = action.arguments
            bound = context_graph.fingerprint(
                {
                    "kind": arguments.get("kind"),
                    "name": arguments.get("name"),
                    "specification": arguments.get("definition"),
                    "parent": str(arguments["parent"]) if arguments.get("parent") else None,
                }
            )
            sources = retained(action) if bound == asset.request_fingerprint else UNRESOLVED
    identity = context_graph.fingerprint(
        {
            "kind": asset.kind,
            "name": asset.name,
            "definition": definition,
            "parent": str(asset.parent_id) if asset.parent_id else None,
        }
    )
    if identity != asset.fingerprint:
        sources = UNRESOLVED
    result = {path: set(sources) for path in values}
    if asset.parent_id:
        parent = ExperimentAsset.objects.filter(
            pk=asset.parent_id, project_id=asset.project_id
        ).first()
        if parent:
            inherited = record_fields(parent, "experiment_asset", seen)
            for path, value in values.items():
                if at({"name": parent.name, "definition": parent.definition}, path) == value:
                    result[path] |= inherited.get(path, set())
    return result


def at(value, path):
    for key in path:
        if isinstance(value, dict):
            value = value.get(key)
        elif isinstance(value, list) and isinstance(key, int) and key < len(value):
            value = value[key]
        else:
            return None
    return value


def public_model(value):
    return isinstance(value, str) and (
        model_registry.model(value) is not None or get_model_config_any_backend(value) is not None
    )


def document_fields(document, prefix=(), identity=()):
    for name, parameter in document.get("parameters", {}).items():
        for field in ("default", "description", "enum"):
            if parameter.get(field) is not None:
                yield (
                    identity + ("parameters", name, field),
                    prefix + ("parameters", name, field),
                    parameter[field],
                )
    for index, node in enumerate(document.get("nodes", [])):
        path = prefix + ("nodes", index)
        key = identity + ("nodes", node["id"])
        for field in ("title", "notes"):
            if node.get(field):
                yield key + (field,), path + (field,), node[field]
        config = node.get("config", {})
        metadata = {
            "data": {"cell", "dataset", "fingerprint", "version"},
            "model": {"asset", "fingerprint"},
            "component": {"asset", "fingerprint", "ports"},
            "suite": {"asset", "fingerprint"},
        }.get(node["kind"], set())
        for field, value in config.items():
            if field in metadata or value is None:
                continue
            if node["kind"] == "map" and field == "recipe" and isinstance(value, dict):
                yield from document_fields(value, path + ("config", field), key + (field,))
            elif field == "model" and isinstance(value, dict):
                for name, setting in value.items():
                    if name in {"asset", "fingerprint"} or setting is None:
                        continue
                    if name == "model" and public_model(setting):
                        continue
                    suffix = ("config", field, name)
                    yield key + suffix, path + suffix, setting
            elif field != "model" or not public_model(value):
                suffix = ("config", field)
                yield key + suffix, path + suffix, value
        operation = node.get("operation") or {}
        arguments = operation.get("arguments", {})
        selector = "name" if operation.get("tool") == "platform" else "operation"
        for field, value in arguments.items():
            if field in {selector, "describe"} or value is None:
                continue
            suffix = ("operation", "arguments", field)
            if field == "arguments" and operation.get("tool") in {"platform", "training"}:
                for name, setting in value.items():
                    if setting is not None:
                        yield key + suffix + (name,), path + suffix + (name,), setting
            else:
                yield key + suffix, path + suffix, value


def revision_origin(revision):
    if not revision.agent_id:
        return None, revision.number - 1
    if revision.request_key.startswith("source:"):
        actions = ResearchAction.objects.filter(
            agent_id=revision.agent_id, tool="experiment", arguments__operation="save_source"
        ).select_related("agent__assignment")
        for action in actions.iterator():
            if revision.request_key == f"source:{context_graph.fingerprint(str(action.pk))}":
                return action, action.arguments.get("expected_version")
        return None, None
    action = action_for(revision.experiment.project_id, revision.request_key)
    if action is None or action.agent_id != revision.agent_id or action.tool != "experiment":
        return None, None
    return action, action.result.get("previous_revision")


def revision_fields(revision, seen, base=None):
    fields = list(document_fields(revision.document))
    action, number = revision_origin(revision)
    authored = retained(action) if action else UNRESOLVED if revision.agent_id else set()
    if revision.fingerprint != context_graph.fingerprint(revision.document):
        authored = UNRESOLVED
    previous = (base if base and base.pk != revision.pk else None) or (
        ResearchExperimentRevision.objects.filter(
            experiment_id=revision.experiment_id, number=number
        )
        .select_related("experiment")
        .first()
        if number
        else None
    )
    before = (
        {key: (path, value) for key, path, value in document_fields(previous.document)}
        if previous
        else {}
    )
    inherited = record_fields(previous, "experiment_revision", seen) if previous else {}
    result = {}
    for key, path, value in fields:
        old = before.get(key)
        result[("document",) + path] = (
            inherited.get(("document",) + old[0], set())
            if old and old[1] == value
            else set(authored)
        )
        if revision.agent_id and previous is None and number != 0:
            result[("document",) + path] |= UNRESOLVED
    if revision.note:
        result[("note",)] = set(authored)
    return result


def execution_fields(execution, seen):
    parameters = execution.parameters
    if not parameters:
        return {}
    task = execution.assignment.specification.get("task", {})
    action = action_for(execution.assignment.project_id, task.get("controller_action"))
    supplied = action.arguments.get("parameters", {}) if action else {}
    sources = set()
    if task.get("controller_action") and action is None:
        sources |= UNRESOLVED
    for name, value in parameters.items():
        if name in supplied:
            sources |= retained(action) if supplied[name] == value else UNRESOLVED
        else:
            default = execution.revision.document.get("parameters", {}).get(name, {})
            if default.get("default") == value:
                sources |= record_fields(execution.revision, "experiment_revision", seen).get(
                    ("document", "parameters", name, "default"), set()
                )
            elif action:
                sources |= UNRESOLVED
    if task.get("parameters") != parameters:
        sources |= UNRESOLVED
    return {("parameters",): sources}


def flow_revision_fields(revision, seen, cache):
    key = f"flow_revision:{revision.pk}"
    if key not in cache:
        cache[key] = record_fields(revision, "experiment_revision", seen)
    return cache[key]


def scope_output_sources(scope, seen, cache):
    sources = set()
    for name, output in scope.document.get("outputs", {}).items():
        if name not in scope.outputs:
            continue
        candidates = (
            ExperimentNodeExecution.objects.filter(scope=scope, node=output["node"])
            .select_related(
                "scope",
                "execution__assignment",
                "execution__revision__experiment",
                "action__agent__assignment",
            )
            .order_by("-attempt")
        )
        producer = next(
            (
                candidate
                for candidate in candidates
                if candidate.outputs.get(output["port"]) == scope.outputs[name]
            ),
            None,
        )
        sources |= output_sources(producer, seen, cache) if producer else UNRESOLVED
    return sources


def output_sources(receipt, seen, cache):
    # Evidence projection calls this module for retained authorship.
    from overbae.services import research_evidence

    key = f"flow_output:{receipt.pk}"
    if key in cache:
        return cache[key]
    cache[key] = set(UNRESOLVED)
    if key in seen or len(seen) >= 200:
        return cache[key]
    seen = {*seen, key}
    sources = set().union(*node_fields(receipt, seen, cache).values())
    sources |= set().union(*input_fields(receipt, seen, cache).values())
    if receipt.action_id:
        sources |= research_evidence.action_sources(receipt.execution.assignment, receipt.action)
    for scope in receipt.scopes.all():
        sources |= scope_output_sources(scope, seen, cache)
    cache[key] = sources
    return sources


def node_fields(receipt, seen, cache):
    # Experiment authoring imports this field-provenance resolver.
    from overbae.services import experiment_compiler, research_experiments

    key = f"flow_node:{receipt.pk}"
    if key in cache:
        return cache[key]
    cache[key] = {(): UNRESOLVED}
    if key in seen or len(seen) >= 200:
        return cache[key]
    seen = {*seen, key}
    execution, scope = receipt.execution, receipt.scope
    if (
        scope.execution_id != execution.pk
        or execution.fingerprint
        != context_graph.fingerprint(
            {"document": execution.document, "parameters": execution.parameters}
        )
        or receipt.identity != research_experiments.node_identity(scope.document, receipt.node)
    ):
        return {(): UNRESOLVED}
    ancestry, root = [], scope
    while root.parent_id:
        if len(ancestry) >= 5:
            return {(): UNRESOLVED}
        parent = ExperimentNodeExecution.objects.select_related(
            "scope", "execution__assignment", "execution__revision__experiment"
        ).get(pk=root.parent_id)
        if parent.execution_id != execution.pk:
            return {(): UNRESOLVED}
        ancestry.append((parent, root))
        root = parent.scope
    if root.document != execution.document or root.parameters != execution.parameters:
        return {(): UNRESOLVED}
    revision = execution.revision
    document, prefix = revision.document, ("document",)
    parameter_key = f"flow_parameters:{execution.pk}"
    if parameter_key not in cache:
        cache[parameter_key] = execution_fields(execution, seen)
    parameter_sources = set(cache[parameter_key].get(("parameters",), set()))
    for parent, nested in reversed(ancestry):
        index = next(
            (i for i, node in enumerate(document["nodes"]) if node["id"] == parent.node), None
        )
        if index is None:
            return {(): UNRESOLVED}
        config = document["nodes"][index]["config"]
        parameter_sources |= set().union(*node_fields(parent, seen, cache).values())
        parameter_sources |= set().union(*input_fields(parent, seen, cache).values())
        if document["nodes"][index]["kind"] == "iterate" and nested.index:
            for previous in parent.scopes.filter(index__lt=nested.index):
                parameter_sources |= scope_output_sources(previous, seen, cache)
        if isinstance(config.get("recipe"), dict):
            document = config["recipe"]
            prefix += ("nodes", index, "config", "recipe")
        else:
            bound = next(
                node for node in parent.scope.document["nodes"] if node["id"] == parent.node
            )
            revision = (
                ResearchExperimentRevision.objects.filter(
                    experiment__project_id=execution.assignment.project_id,
                    experiment_id=bound["config"].get("experiment"),
                    number=bound["config"].get("revision"),
                )
                .select_related("experiment")
                .first()
            )
            if revision is None:
                return {(): UNRESOLVED}
            document, prefix = revision.document, ("document",)
        fields = flow_revision_fields(revision, seen, cache)
        parameter_sources |= set().union(
            *(
                sources
                for path, sources in fields.items()
                if path[: len(prefix) + 1] == prefix + ("parameters",)
            )
        )
    index = next(
        (i for i, node in enumerate(document["nodes"]) if node["id"] == receipt.node), None
    )
    current = next((node for node in scope.document["nodes"] if node["id"] == receipt.node), None)
    if index is None or current is None or document["nodes"][index]["kind"] != current["kind"]:
        return {(): UNRESOLVED}
    prefix += ("nodes", index)
    fields = flow_revision_fields(revision, seen, cache)
    result = {}
    for path, sources in fields.items():
        if prefix[: len(path)] == path:
            result.setdefault((), set()).update(sources)
            continue
        if path[: len(prefix)] != prefix:
            continue
        suffix = path[len(prefix) :]
        if current["kind"] == "map" and suffix[:2] == ("config", "recipe"):
            continue
        original = at({"document": revision.document}, path)
        try:
            expected = experiment_compiler.substitute(original, scope.parameters)
        except InputValidationError:
            result[suffix] = UNRESOLVED
            continue
        result[suffix] = set(sources) if expected == at(current, suffix) else set(UNRESOLVED)
        if list(experiment_compiler.references(original)):
            result[suffix] |= parameter_sources
    cache[key] = result
    return result


def input_fields(receipt, seen, cache):
    # Evidence projection calls this module for retained authorship.
    from overbae.services import research_evidence

    key = f"flow_inputs:{receipt.pk}"
    if key in cache:
        return cache[key]
    cache[key] = {(): UNRESOLVED}
    recursive = key in seen or len(seen) >= 200
    seen = {*seen, key}
    result = {}
    metadata = {
        "kind",
        "cell",
        "dataset",
        "version",
        "fingerprint",
        "asset",
        "artifact",
        "job",
        "deployment",
        "campaign",
        "trial",
        "plan",
        "partition",
        "phase",
        "role",
        "sealed",
    }
    for port, value in receipt.inputs.items():
        bindings = enumerate(value) if isinstance(value, list) else [(None, value)]
        for index, binding in bindings:
            path = (port,) if index is None else (port, index)
            if not isinstance(binding, dict):
                result[path] = UNRESOLVED
                continue
            payload = {
                name: value
                for name, value in binding.items()
                if name not in metadata and not (name == "model" and public_model(value))
            }
            if not payload:
                continue
            sources = set(UNRESOLVED) if recursive else set()
            if not recursive:
                sources |= research_evidence.input_sources(
                    receipt.execution.assignment.project_id, {port: binding}
                )
                sources |= research_evidence.review_sources(receipt.execution.assignment, binding)
                edges = [
                    edge
                    for edge in receipt.scope.document["edges"]
                    if edge["target"] == receipt.node and edge["input"] == port
                ]
                producers = []
                for edge in edges:
                    candidates = (
                        ExperimentNodeExecution.objects.filter(
                            scope=receipt.scope, node=edge["source"]
                        )
                        .select_related(
                            "scope",
                            "execution__assignment",
                            "execution__revision__experiment",
                            "action__agent__assignment",
                        )
                        .order_by("-attempt")
                    )
                    producer = next(
                        (
                            candidate
                            for candidate in candidates
                            if candidate.outputs.get(edge["output"]) == binding
                        ),
                        None,
                    )
                    if producer:
                        producers.append(producer)
                if producers:
                    for producer in producers:
                        sources |= output_sources(producer, seen, cache)
                elif not edges and port == "model":
                    sources |= set().union(
                        *(
                            values
                            for key, values in node_fields(receipt, seen, cache).items()
                            if not key or key[:2] == ("config", "model")
                        )
                    )
                else:
                    sources |= UNRESOLVED
            result.update({path + (name,): set(sources) for name in payload})
    cache[key] = result
    return result


def adaptive_assignment_fields(assignment, seen):
    if not assignment.request_key.startswith("flow-research:"):
        return {}
    specification = assignment.specification
    task = specification.get("task", {})
    fields = {
        ("specification", "objective"): set(UNRESOLVED),
        ("specification", "acceptance"): set(UNRESOLVED),
    }
    try:
        identifier = UUID(assignment.request_key.removeprefix("flow-research:"))
    except ValueError:
        return fields | {("specification", "task", "inputs"): UNRESOLVED}
    receipt = (
        ExperimentNodeExecution.objects.filter(
            pk=identifier, execution__assignment__project_id=assignment.project_id
        )
        .select_related(
            "scope",
            "execution__assignment",
            "execution__revision__experiment",
            "action__agent__assignment",
        )
        .first()
    )
    node = (
        next((item for item in receipt.scope.document["nodes"] if item["id"] == receipt.node), None)
        if receipt
        else None
    )
    action = receipt.action if receipt else None
    if (
        receipt is None
        or node is None
        or node["kind"] != "research"
        or action is None
        or action.tool != "adaptive_research"
        or action.agent.assignment_id != receipt.execution_id
        or action.agent.parent_id is not None
        or action.request_key != f"flow:{receipt.pk}"
        or action.result.get("assignment") != str(assignment.pk)
        or action.arguments != {"config": node["config"], "inputs": receipt.inputs}
        or action.fingerprint
        != context_graph.fingerprint({"tool": action.tool, "arguments": action.arguments})
        or task.get("flow_run") != str(receipt.execution_id)
        or task.get("node") != receipt.node
        or task.get("inputs") != receipt.inputs
    ):
        return fields | {("specification", "task", "inputs"): UNRESOLVED}
    cache = {}
    authored = node_fields(receipt, seen, cache)
    for field, default in (("objective", None), ("acceptance", {})):
        if specification.get(field) == node["config"].get(field, default):
            fields[("specification", field)] = authored.get((), set()) | authored.get(
                ("config", field), set()
            )
    fields.update(
        {
            ("specification", "task", "inputs") + path: sources
            for path, sources in input_fields(receipt, seen, cache).items()
        }
    )
    return fields


def pipeline_title_sources(pipeline, revisions, seen, *, preview=None):
    result = set()
    found = False
    for revision in revisions:
        for _, path, value in document_fields(revision.document):
            if path[-1] != "title":
                continue
            node = at(revision.document, path[:-1])
            operation = node.get("operation") or {}
            recipe = operation.get("arguments", {})
            if recipe.get("name") != "run_dataset_pipeline":
                continue
            if preview:
                matched = (
                    node["id"] == preview.get("node")
                    and recipe.get("arguments", {}).get("pipeline") == str(pipeline.derived_from_id)
                    and pipeline.name == f"{value} · {preview.get('step')}"
                )
            else:
                matched = (
                    recipe.get("arguments", {}).get("pipeline") == str(pipeline.pk)
                    and value == pipeline.name
                )
            if matched:
                found = True
                result |= record_fields(revision, "experiment_revision", seen).get(
                    ("document",) + path, set()
                )
    return result if found else UNRESOLVED


def pipeline_fields(pipeline, seen):
    sources = (
        pipeline_packages.authored_sources(pipeline.package) if pipeline.package_id else UNRESOLVED
    )
    result = {("steps",): set(sources), ("flow",): set(sources)}
    name_sources = set()
    if pipeline.request_key.startswith("research:"):
        action = action_for(pipeline.project_id, pipeline.request_key.removeprefix("research:"))
        name_sources = (
            retained(action)
            if action
            and action.tool == "platform"
            and action.arguments.get("name") in {"save_dataset_pipeline", "prepare_dataset"}
            else UNRESOLVED
        )
    elif pipeline.request_key.startswith("workshop:"):
        parts = pipeline.request_key.split(":")
        try:
            task, turn = UUID(parts[1]), int(parts[2])
        except (IndexError, ValueError):
            name_sources = UNRESOLVED
        else:
            action = (
                WorkshopAction.objects.filter(
                    task_id=task,
                    task__project_id=pipeline.project_id,
                    sequence=2 + 2 * turn,
                    name__in=["publish_package", "prepare"],
                )
                .select_related("task")
                .first()
            )
            if action and action.arguments.get("name") == pipeline.name:
                # Workshop publication imports package provenance through this module.
                from overbae.services.workshop_agent import conversation

                name_sources = conversation.source_cells(action.task, before=action.created_at)
            else:
                name_sources = UNRESOLVED
    elif pipeline.request_key.startswith("experiment:"):
        parts = pipeline.request_key.split(":")
        try:
            experiment_id, key = UUID(parts[1]), parts[2]
        except (IndexError, ValueError):
            name_sources = UNRESOLVED
        else:
            revisions = ResearchExperimentRevision.objects.filter(
                experiment_id=experiment_id,
                experiment__project_id=pipeline.project_id,
                request_key__startswith=f"source:{key}",
            ).select_related("experiment")
            name_sources = pipeline_title_sources(pipeline, revisions, seen)
    elif pipeline.request_key.startswith("preview:"):
        run = DatasetPipelineRun.objects.filter(
            pipeline=pipeline, request_key=pipeline.request_key
        ).first()
        context = run.specification.get("context", {}) if run else {}
        revisions = (
            ResearchExperimentRevision.objects.filter(
                experiment_id=context.get("experiment"),
                experiment__project_id=pipeline.project_id,
                number=context.get("revision"),
            ).select_related("experiment")
            if context.get("experiment") and isinstance(context.get("revision"), int)
            else []
        )
        name_sources = set(sources) | pipeline_title_sources(
            pipeline, revisions, seen, preview=context
        )
    for parent_id in (pipeline.parent_id, pipeline.derived_from_id):
        if parent_id:
            parent = (
                DatasetPipeline.objects.filter(pk=parent_id, project_id=pipeline.project_id)
                .select_related("package")
                .first()
            )
            if parent and parent.name == pipeline.name:
                name_sources |= record_fields(parent, "transformation", seen).get(("name",), set())
    result[("name",)] = name_sources
    return result


def preparation_packet(project, value):
    if not isinstance(value, dict):
        return None
    if (
        value.get("execution") == "not_run"
        and {"valid", "warnings", "missing_columns", "pipeline"} <= value.keys()
        and isinstance(value["pipeline"], dict)
    ):
        captured = value["pipeline"]
        pipeline = resolve(project, f"transformation:{captured.get('id')}")
        matched = (
            pipeline
            and pipeline.package_id
            and captured.get("fingerprint") == pipeline.fingerprint
            and captured.get("package") == str(pipeline.package_id)
        )
        return (
            f"transformation_package:{pipeline.package_id}"
            if matched
            else "transformation_package:unresolved",
            pipeline_packages.authored_sources(pipeline.package) if matched else UNRESOLVED,
            ("warnings", "missing_columns"),
        )
    if (
        value.get("kind") == "preparation"
        and value.get("package")
        and {"files", "file", "inventory", "manifest", "steps"} & value.keys()
    ):
        reference = f"transformation_package:{value['package']}"
        package = resolve(project, reference)
        if package is None:
            return reference, UNRESOLVED, FIELDS["transformation_package"]
        files = pipeline_packages.files(package)
        files.pop("manifest.json", None)
        matched = context_graph.source_matches(value, files, package.manifest)
        if "steps" in value:
            matched = (
                matched
                and value["steps"] == pipeline_graph.describe(package.manifest["steps"])["nodes"]
            )
        sources = pipeline_packages.authored_sources(package) if matched else UNRESOLVED
        return reference, sources, FIELDS["transformation_package"]
    if {"id", "sha256", "manifest", "inventory"} <= value.keys():
        reference = f"transformation_package:{value['id']}"
        package = resolve(project, reference)
        matched = (
            package is not None
            and value["sha256"] == package.sha256
            and value["manifest"] == package.manifest
            and value["inventory"] == package.inventory
        )
        return (
            reference,
            pipeline_packages.authored_sources(package) if matched else UNRESOLVED,
            FIELDS["transformation_package"],
        )
    if {"id", "pipeline_id", "package", "fingerprint"} <= value.keys():
        reference = f"transformation:{value['id']}"
        pipeline = resolve(project, reference)
        if (
            pipeline
            and pipeline.fingerprint == value["fingerprint"]
            and str(pipeline.package_id) == value["package"]
        ):
            return reference, None, FIELDS["transformation"]
        return reference, UNRESOLVED, FIELDS["transformation"]
    if {"id", "pipeline", "source_cell", "source_fingerprint", "result"} <= value.keys():
        reference = f"transformation_run:{value['id']}"
        run = resolve(project, reference)
        if (
            run
            and str(run.pipeline_id) == value["pipeline"]
            and str(run.source_id) == value["source_cell"]
            and run.source_fingerprint == value["source_fingerprint"]
        ):
            return reference, None, FIELDS["transformation_run"]
        return reference, UNRESOLVED, FIELDS["transformation_run"]
    return None


def require_pipeline(assignment, identifier):
    reference = f"transformation:{identifier}"
    pipeline = resolve(assignment.project, reference)
    sources = (
        pipeline_packages.authored_sources(pipeline.package)
        if pipeline and pipeline.package_id
        else UNRESOLVED
    )
    if not context_permitted(assignment, reference, sources):
        raise InputValidationError(
            "This transformation's retained source is outside the admitted inputs"
        )


def record_fields(record, kind, seen=None, base=None):
    seen = set(seen or ())
    reference = f"{kind}:{record.pk}"
    if reference in seen or len(seen) >= 200:
        return {(field,): UNRESOLVED for field in FIELDS[kind]}
    seen.add(reference)
    if kind == "transformation_package":
        return {(field,): pipeline_packages.authored_sources(record) for field in FIELDS[kind]}
    if kind == "transformation":
        return pipeline_fields(record, seen)
    if kind == "transformation_run":
        sources = pipeline_packages.run_sources(record)
        result = {(field,): set(sources) for field in FIELDS[kind]}
        if record.pipeline_id:
            result[("pipeline_name",)] = record_fields(record.pipeline, "transformation", seen).get(
                ("name",), set()
            )
        return result
    if kind == "experiment_asset":
        return asset_fields(record, seen)
    if kind == "experiment_revision":
        return revision_fields(record, seen, base=base)
    if kind == "flow_execution":
        return execution_fields(record, seen)
    if kind == "research_assignment":
        execution = (
            ExperimentExecution.objects.filter(assignment=record)
            .select_related("assignment", "revision__experiment")
            .first()
        )
        return (
            {
                ("specification", "task", "parameters"): execution_fields(execution, seen).get(
                    ("parameters",), set()
                )
            }
            if execution
            else adaptive_assignment_fields(record, seen)
        )
    if kind == "partition":
        return {
            ("recipe", "holdouts", index, "values"): {str(record.source_cell_id)}
            for index, rule in enumerate(record.recipe.get("holdouts", []))
            if rule.get("values")
        }
    return {}


def resolve(project, reference):
    kind, _, identifier = str(reference).partition(":")
    if kind not in MODELS:
        return None
    try:
        identifier = UUID(identifier)
    except (TypeError, ValueError):
        return None
    model, project_path = MODELS[kind]
    filters = {"pk": identifier}
    if project is not None:
        filters[project_path] = project
    related = {
        "experiment_revision": ("experiment",),
        "flow_execution": ("assignment", "revision__experiment"),
        "transformation": ("package",),
        "transformation_run": ("pipeline__package",),
    }.get(kind, ())
    return model.objects.filter(**filters).select_related(*related).first()


def context_record_sources(project, reference, *, seen=None):
    record = resolve(project, reference)
    if record is None:
        return UNRESOLVED if str(reference).partition(":")[0] in FIELDS else set()
    return set().union(*record_fields(record, reference.partition(":")[0], seen).values())


def redact(facts, paths):
    result = deepcopy(facts)
    for path in paths:
        parent = at(result, path[:-1])
        if isinstance(parent, dict):
            if path[-1] == "title" and "kind" in parent:
                parent["title"] = parent["kind"]
            else:
                parent.pop(path[-1], None)
    result["access"] = "sealed_data"
    return result


def context_record_metadata(reference, facts):
    record = resolve(None, reference)
    kind = reference.partition(":")[0]
    fields = (
        record_fields(record, kind)
        if record
        else {(key,): UNRESOLVED for key in FIELDS.get(kind, ())}
    )
    return redact(facts, [path for path, sources in fields.items() if sources])


def context_permitted(assignment, reference, sources):
    # Native reads and graph projection share source seals and exact asset grants.
    from overbae.services.research_tools import source_boundary, sources_permitted

    boundary = source_boundary(assignment)
    if sources_permitted(assignment, sources, boundary=boundary):
        return True
    if not reference.startswith("experiment_asset:"):
        return False
    _, denied, _, _ = boundary
    if sources & (denied | UNRESOLVED):
        return False
    asset = resolve(assignment.project, reference)
    return bool(
        asset
        and any(
            grant.get("kind") == "asset"
            and grant.get("id") == str(asset.pk)
            and grant.get("fingerprint") in {None, asset.fingerprint}
            for grant in assignment.execution_mandate.get("sources", [])
        )
    )


def asset_use_sources(asset, seen=None):
    seen = set(seen or ())
    if asset.pk in seen:
        return UNRESOLVED
    seen.add(asset.pk)
    sources = context_record_sources(asset.project_id, f"experiment_asset:{asset.pk}")
    if asset.kind == "candidate" and asset.definition.get("kind") == "component":
        component = ExperimentAsset.objects.filter(
            project_id=asset.project_id,
            pk=asset.definition["component"],
            kind="component",
            fingerprint=asset.definition["component_fingerprint"],
        ).first()
        sources |= asset_use_sources(component, seen) if component else UNRESOLVED
    return sources


def require_asset(assignment, asset):
    if not context_permitted(assignment, f"experiment_asset:{asset.pk}", asset_use_sources(asset)):
        raise InputValidationError("This asset's retained source is outside the admitted inputs")


def project_record(assignment, reference, facts, *, base=None):
    record = resolve(assignment.project, reference)
    fields = (
        record_fields(record, reference.partition(":")[0], base=base)
        if record
        else {(key,): UNRESOLVED for key in FIELDS.get(reference.partition(":")[0], ())}
    )
    denied = [
        path
        for path, sources in fields.items()
        if sources and not context_permitted(assignment, reference, sources)
    ]
    return redact(facts, denied) if denied else deepcopy(facts)


def project_asset(assignment, asset, facts):
    result = project_record(assignment, f"experiment_asset:{asset.pk}", facts)
    if "name" not in result:
        result["name"] = f"{asset.kind} {asset.pk}"
    return result


def project_document(assignment, revision, *, base=None):
    return project_record(
        assignment, f"experiment_revision:{revision.pk}", {"document": revision.document}, base=base
    )["document"]


def revision_packet_sources(revision, value):
    preparation = preparation_packet(revision.experiment.project_id, value)
    if preparation:
        reference, sources, _ = preparation
        if value.get("access") == "sealed_data":
            return set()
        return (
            sources
            if sources is not None
            else context_record_sources(revision.experiment.project_id, reference)
        )
    sources = set()
    facts = {"document": revision.document, "note": revision.note}
    fields = record_fields(revision, "experiment_revision")
    for path, dependencies in fields.items():
        if not dependencies:
            continue
        exposed = None
        if path[:2] == ("document", "parameters") and path[-1] == "default":
            exposed = ("parameters", path[2])
        elif path[:2] == ("document", "nodes"):
            suffix = path[3:]
            if suffix[:1] in {("title",), ("notes",)}:
                exposed = ("stages", path[2]) + suffix
            elif suffix[:1] == ("config",):
                exposed = ("stages", path[2], "settings") + suffix[1:]
                if suffix == ("config", "model", "model") and isinstance(
                    at(value, exposed[:-1]), str
                ):
                    exposed = exposed[:-1]
            elif suffix[:2] == ("operation", "arguments"):
                suffix = suffix[2:]
                if suffix[:1] == ("arguments",):
                    suffix = suffix[1:]
                if suffix[:1] == ("defaults",):
                    suffix = ("hyperparameters",) + suffix[1:]
                if suffix:
                    exposed = ("stages", path[2], "settings") + suffix
        if exposed and at(value, exposed) == at(facts, path):
            sources |= dependencies
        if path[-2:] in {("config", "files"), ("config", "manifest")} and (
            at(facts, path[:-2]).get("id") == value.get("owner")
        ):
            config = at(facts, path[:-1])
            expected = context_graph.fingerprint(
                {"files": config.get("files", {}), "manifest": config.get("manifest", {})}
            )
            if value.get("fingerprint") != expected:
                return sources | UNRESOLVED
            if (
                path[-1] == "manifest"
                and "manifest" in value
                or path[-1] == "files"
                and {"files", "file", "inventory"} & value.keys()
            ):
                sources |= dependencies
    page = value.get("file")
    if isinstance(page, dict) and page.get("content"):
        candidates = [
            (path, dependencies)
            for path, dependencies in fields.items()
            if path[-2:] == ("config", "files")
            and at(facts, path[:-2]).get("id") == value.get("owner")
        ]
        if len(candidates) != 1:
            return sources | UNRESOLVED
        path, dependencies = candidates[0]
        files = at(facts, path)
        source = files.get(page.get("path"))
        offset, content = page.get("offset"), page["content"]
        manifest = at(facts, path[:-1] + ("manifest",))
        if (
            not isinstance(source, str)
            or not isinstance(offset, int)
            or offset < 0
            or page.get("total") != len(source)
            or source[offset : offset + len(content)] != content
            or value.get("fingerprint")
            != context_graph.fingerprint({"files": files, "manifest": manifest})
        ):
            return sources | UNRESOLVED
        sources |= dependencies
    return sources


def identity_sources(project, value):
    if not isinstance(value, dict):
        return set()
    preparation = preparation_packet(project, value)
    if preparation:
        if value.get("access") == "sealed_data":
            return set()
        reference, sources, _ = preparation
        return sources if sources is not None else context_record_sources(project, reference)
    if (
        value.get("id")
        and value.get("kind") in {"candidate", "component", "suite"}
        and value.get("fingerprint")
    ):
        asset = resolve(project, f"experiment_asset:{value['id']}")
        if asset is None or asset.fingerprint != value["fingerprint"]:
            return UNRESOLVED
        facts = {"name": asset.name, "definition": asset.definition}
        return set().union(
            *(
                sources
                for path, sources in record_fields(asset, "experiment_asset").items()
                if at(value, path) == at(facts, path)
            )
        )
    if (
        value.get("experiment")
        and isinstance(value.get("revision"), int)
        and {"stages", "file", "inventory", "manifest", "parameters"} & value.keys()
    ):
        revision = (
            ResearchExperimentRevision.objects.filter(
                experiment_id=value["experiment"],
                experiment__project=project,
                number=value["revision"],
            )
            .select_related("experiment")
            .first()
        )
        return revision_packet_sources(revision, value) if revision else UNRESOLVED
    if value.get("run") and "parameters" in value:
        execution = ExperimentExecution.objects.filter(
            assignment_id=value["run"], assignment__project=project
        ).first()
        if execution is None or execution.parameters != value["parameters"]:
            return UNRESOLVED
        return context_record_sources(project, f"flow_execution:{execution.pk}")
    return set()


def project_packets(assignment, value, permitted_sources):
    if isinstance(value, list):
        return [project_packets(assignment, child, permitted_sources) for child in value]
    if not isinstance(value, dict):
        return value
    result = {
        key: project_packets(assignment, child, permitted_sources) for key, child in value.items()
    }
    preparation = preparation_packet(assignment.project, value)
    if preparation:
        reference, sources, fields = preparation
        if sources is None:
            return project_record(assignment, reference, result)
        permitted = (
            permitted_sources(sources)
            if permitted_sources is not None
            else context_permitted(assignment, reference, sources)
        )
        return result if permitted else redact(result, [(field,) for field in fields])
    if (
        value.get("id")
        and value.get("kind") in {"candidate", "component", "suite"}
        and value.get("fingerprint")
    ):
        asset = resolve(assignment.project, f"experiment_asset:{value['id']}")
        if asset and asset.fingerprint == value["fingerprint"]:
            result = project_asset(assignment, asset, result)
    elif value.get("run") and "parameters" in value:
        execution = ExperimentExecution.objects.filter(
            assignment_id=value["run"], assignment__project=assignment.project
        ).first()
        if execution:
            result = project_record(assignment, f"flow_execution:{execution.pk}", result)
    return result


def project_issue_titles(document, projected, issues):
    titles = {node["id"]: node["title"] for node in projected["nodes"]}
    result = list(issues)
    for node in document["nodes"]:
        title = titles.get(node["id"], node["kind"])
        if title != node["title"]:
            for prefix in ("Connect evaluation data to ", "Select a model for "):
                result = [issue.replace(prefix + node["title"], prefix + title) for issue in result]
    return result


def project_action(assignment, action, value, *, base=None):
    result = project_packets(assignment, value, None)
    if action.tool != "experiment" or not isinstance(result, dict) or not result.get("revision"):
        return result
    pinned = action.agent.assignment.experiment_revision
    revision = (
        ResearchExperimentRevision.objects.filter(
            experiment_id=pinned.experiment_id, number=result["revision"]
        )
        .select_related("experiment")
        .first()
        if pinned
        else None
    )
    if revision is None:
        return redact(
            result,
            [(field,) for field in ("stages", "files", "file", "content", "manifest", "inventory")],
        )
    projected = project_document(assignment, revision, base=base)
    if result.get("changed"):
        # Mutation replies retain both old and new values from their exact revisions.
        from overbae.services import experiment_stages

        previous = (
            ResearchExperimentRevision.objects.filter(
                experiment_id=revision.experiment_id, number=result.get("previous_revision")
            )
            .select_related("experiment")
            .first()
        )
        documents = {"after": (revision.document, projected)}
        if previous:
            documents["before"] = (previous.document, project_document(assignment, previous))
        for side, (original, visible) in documents.items():
            original_stages = {
                stage["id"]: stage for stage in experiment_stages.describe(original)["stages"]
            }
            visible_stages = {
                stage["id"]: stage for stage in experiment_stages.describe(visible)["stages"]
            }
            for change in result["changed"]:
                identifier = change.get("stage", result.get("stage"))
                path = tuple(change.get("path", ()))
                original_value = at(original_stages.get(identifier, {}), path)
                visible_value = at(visible_stages.get(identifier, {}), path)
                if side in change and original_value != visible_value:
                    change[side] = visible_value
        if previous is None:
            for change in result["changed"]:
                change.pop("before", None)
    if "parameters" in result:
        # Resolved defaults belong to the pinned revision; explicit values to this action.
        from overbae.services.research_tools import sources_permitted

        defaults = record_fields(revision, "experiment_revision")
        supplied = action.arguments.get("parameters", {})
        for name, value in list(result["parameters"].items()):
            sources = (
                retained(action)
                if name in supplied and supplied[name] == value
                else defaults.get(("document", "parameters", name, "default"), set())
            )
            if sources and not sources_permitted(assignment, sources):
                result["parameters"].pop(name)
                result["access"] = "sealed_data"
    if projected != revision.document:
        if "issues" in result:
            result["issues"] = project_issue_titles(revision.document, projected, result["issues"])
        if "stages" in result:
            # Stage presentation consumes this projection at native read time too.
            from overbae.services import experiment_stages

            result.update(experiment_stages.describe(projected))
        titles = {node["id"]: node["title"] for node in projected["nodes"]}
        for entry in result.get("entries", []):
            entry["title"] = titles.get(entry.get("node"), entry.get("kind", "stage"))
        for key in ("files", "file", "content", "manifest", "inventory"):
            result.pop(key, None)
        result["access"] = "sealed_data"
    return result