Skip to content

The platform for continuously improving AI agents.

13.1 KB
Raw Blame
from graphlib import CycleError, TopologicalSorter
from uuid import UUID

from overbae.core.errors import DatasetError
from overbae.models import (
    Cell,
    DataExploration,
    DataPartitionMember,
    DataPartitionPlan,
    DatasetPipelineRun,
    WorkshopTask,
)


def describe(dataset, *, cell=None, include_siblings=True):
    selected = cell or dataset.active_cell
    nodes, edges, visited_plans, visited_runs = {}, {}, set(), set()

    def visit(current, role=""):
        identity = str(current.pk)
        if identity in nodes:
            if role:
                nodes[identity]["role"] = role
            return
        if len(nodes) >= 200:
            raise DatasetError(
                "This preparation exceeds 200 cells. Inspect its source datasets separately.",
                code="preparation_limit",
            )
        nodes[identity] = {
            "cell": current,
            "dataset": str(current.dataset_id),
            "dataset_name": current.dataset.name,
            "intent": current.dataset.intent,
            "train_format": current.dataset.train_format,
            "role": role,
        }
        member = (
            DataPartitionMember.objects.filter(
                cell=current,
                plan__project_id=dataset.project_id,
                plan__state="completed",
                plan__source_cell__dataset__project_id=dataset.project_id,
            )
            .select_related("plan__source_cell__dataset")
            .first()
        )
        if member and member.plan.source_fingerprint == member.plan.source_cell.fingerprint:
            nodes[identity]["role"] = member.role
            parent = member.plan.source_cell
            visit(parent)
            edges[(str(parent.pk), identity)] = {
                "source": str(parent.pk),
                "target": identity,
                "kind": "split",
                "value": member.role,
            }
            if include_siblings:
                add_members(member.plan)
            return
        derivation = (
            DataExploration.objects.filter(
                output_dataset_id=current.dataset_id,
                project_id=dataset.project_id,
                state="completed",
                kind="derive",
                report__output__id=identity,
                report__output__fingerprint=current.fingerprint,
                source_cell__dataset__project_id=dataset.project_id,
            )
            .select_related("source_cell__dataset")
            .first()
        )
        if derivation and derivation.source_fingerprint == derivation.source_cell.fingerprint:
            parent = derivation.source_cell
            visit(parent)
            edges[(str(parent.pk), identity)] = {
                "source": str(parent.pk),
                "target": identity,
                "kind": "derived",
                "value": "",
            }
            return
        if (current.review or {}).get("kind") == "attachment" and current.input_fingerprint:
            parent = (
                Cell.objects.filter(
                    dataset_id=current.dataset_id,
                    state="ok",
                    position__lt=current.position,
                    fingerprint=current.input_fingerprint,
                )
                .select_related("dataset")
                .order_by("-position")
                .first()
            )
            if parent:
                visit(parent)
                edges[(str(parent.pk), identity)] = {
                    "source": str(parent.pk),
                    "target": identity,
                    "kind": "attachment",
                    "value": "",
                }
            return
        try:
            run_id = UUID(str((current.review or {}).get("run")))
        except ValueError:
            return
        run = DatasetPipelineRun.objects.filter(
            pk=run_id,
            dataset_id=current.dataset_id,
            state="completed",
            mode="publish",
        ).first()
        if run is None:
            return
        step = next(
            (
                step
                for step in run.result.get("steps", [])
                if step.get("output_cell") == identity
                and step.get("output_fingerprint") == current.fingerprint
            ),
            None,
        )
        if step is None:
            return
        for entry in step.get("inputs", []):
            parent = (
                Cell.objects.filter(
                    pk=entry["cell"],
                    fingerprint=entry["fingerprint"],
                    state="ok",
                    dataset__project_id=dataset.project_id,
                )
                .select_related("dataset")
                .first()
            )
            if parent:
                visit(parent)
                edges[(str(parent.pk), identity)] = {
                    "source": str(parent.pk),
                    "target": identity,
                    "kind": "condition" if step.get("condition") else "step",
                    "value": step.get("condition", ""),
                }
            else:
                nodes[identity]["unresolved_inputs"] = (
                    nodes[identity].get("unresolved_inputs", 0) + 1
                )
        if include_siblings and current.pk == run.output_id and run.pk not in visited_runs:
            visited_runs.add(run.pk)
            fingerprints = {
                entry["output_cell"]: entry["output_fingerprint"]
                for entry in run.result.get("steps", [])
                if entry.get("output_cell") and entry.get("output_fingerprint")
            }
            for sibling in (
                Cell.objects.filter(dataset_id=current.dataset_id, pk__in=fingerprints, state="ok")
                .select_related("dataset")
                .order_by("position")
            ):
                if sibling.fingerprint == fingerprints[str(sibling.pk)]:
                    visit(sibling)

    def add_members(plan):
        if plan.pk in visited_plans:
            return
        visited_plans.add(plan.pk)
        for member in (
            plan.members.filter(cell__dataset__project_id=dataset.project_id)
            .select_related("cell__dataset")
            .order_by("pk")
        ):
            visit(member.cell, member.role)

    if selected:
        visit(selected)
        if include_siblings and not visited_plans:
            plan = (
                DataPartitionPlan.objects.filter(
                    project_id=dataset.project_id,
                    source_cell=selected,
                    source_fingerprint=selected.fingerprint,
                    state="completed",
                )
                .order_by("-created_at", "-pk")
                .first()
            )
            if plan:
                add_members(plan)
    return {
        "selected": str(selected.pk) if selected else None,
        "nodes": list(nodes.values()),
        "edges": list(edges.values()),
    }


def with_task_cells(process, dataset):
    nodes = {str(node["cell"].pk): node for node in process["nodes"]}
    edges = {(edge["source"], edge["target"]): edge for edge in process["edges"]}
    outputs = {
        identifier
        for published in WorkshopTask.objects.filter(dataset=dataset).values_list(
            "result__outputs", flat=True
        )
        for identifier in published or []
    }
    for cell in Cell.objects.filter(
        pk__in=outputs, state="ok", dataset__project_id=dataset.project_id
    ).select_related("dataset"):
        branch = describe(dataset, cell=cell)
        nodes.update((str(node["cell"].pk), node) for node in branch["nodes"])
        edges.update(((edge["source"], edge["target"]), edge) for edge in branch["edges"])
    visited = set()
    while frontier := set(nodes) - visited:
        visited.update(frontier)
        for run in DatasetPipelineRun.objects.filter(
            source_id__in=frontier,
            dataset__project_id=dataset.project_id,
            mode="publish",
            state="completed",
            output__state="ok",
        ).select_related("output__dataset"):
            if str(run.output_id) in nodes:
                continue
            branch = describe(dataset, cell=run.output)
            nodes.update((str(node["cell"].pk), node) for node in branch["nodes"])
            edges.update(((edge["source"], edge["target"]), edge) for edge in branch["edges"])
            if len(nodes) > 200:
                raise DatasetError("This preparation exceeds 200 cells.", code="preparation_limit")
    if len(nodes) > 200:
        raise DatasetError("This preparation exceeds 200 cells.", code="preparation_limit")
    process = {**process, "nodes": list(nodes.values()), "edges": list(edges.values())}
    task = WorkshopTask.objects.filter(dataset=dataset).order_by("-created_at", "-pk").first()
    if task is None or not task.context_sources:
        return process
    pins = {item["cell"]: item["fingerprint"] for item in task.context_sources}
    shown = {str(node["cell"].pk) for node in process["nodes"]}
    sources = [
        {
            "cell": cell,
            "dataset": str(cell.dataset_id),
            "dataset_name": cell.dataset.name,
            "intent": cell.dataset.intent,
            "train_format": cell.dataset.train_format,
            "role": "",
        }
        for cell in Cell.objects.filter(
            pk__in=pins, state="ok", dataset__project_id=dataset.project_id
        ).select_related("dataset")
        if str(cell.pk) not in shown and cell.fingerprint == pins[str(cell.pk)]
    ]
    return {**process, "nodes": [*process["nodes"], *sources]}


def record(process):
    return {
        **process,
        "nodes": [
            {
                **node,
                "cell": str(node["cell"].pk),
                "title": node["cell"].title,
                "rows": node["cell"].rows,
                "fingerprint": node["cell"].fingerprint,
            }
            for node in process["nodes"]
        ],
    }


def input_cells(cell):
    process = describe(cell.dataset, cell=cell)
    parents = {edge["source"] for edge in process["edges"] if edge["target"] == str(cell.pk)}
    return [node["cell"] for node in process["nodes"] if str(node["cell"].pk) in parents]


def lineage(cell):
    try:
        process = describe(cell.dataset, cell=cell, include_siblings=False)
    except DatasetError as error:
        if error.code != "preparation_limit":
            raise
        return {"stage": "unknown", "status": "incomplete", "parents": [], "source_cells": []}
    cells = {str(node["cell"].pk): node["cell"] for node in process["nodes"]}
    incoming = {}
    for edge in process["edges"]:
        incoming.setdefault(edge["target"], []).append(edge)

    def identity(value):
        return {
            "cell": str(value.pk),
            "dataset": str(value.dataset_id),
            "fingerprint": value.fingerprint,
        }

    stages, incomplete = {}, any(node.get("unresolved_inputs") for node in process["nodes"])
    try:
        tuple(
            TopologicalSorter(
                {
                    identifier: [edge["source"] for edge in incoming.get(identifier, [])]
                    for identifier in cells
                }
            ).static_order()
        )
    except CycleError:
        incomplete = True
    ambiguous = set()
    for identifier, value in cells.items():
        links = incoming.get(identifier, [])
        if links:
            kinds = {edge["kind"] for edge in links}
            stages[identifier] = (
                "partition_member"
                if "split" in kinds
                else "attachment"
                if "attachment" in kinds
                else "derived"
                if "derived" in kinds
                else "prepared"
            )
            if (
                "attachment" in kinds
                and value.dataset.cells.filter(
                    position__lt=value.position, fingerprint=value.input_fingerprint, state="ok"
                ).count()
                != 1
            ):
                incomplete = True
                ambiguous.add(identifier)
        elif (
            value.position == 0
            and not value.input_fingerprint
            and not value.review
            and not value.dataset.source_spec.get("partition_plan")
            and not DataPartitionMember.objects.filter(cell=value).exists()
            and not DataExploration.objects.filter(
                output_dataset=value.dataset, kind="derive"
            ).exists()
        ):
            stages[identifier] = "source"
        else:
            stages[identifier] = "unknown"
            incomplete = True
    return {
        "stage": stages[str(cell.pk)],
        "status": "incomplete" if incomplete else "resolved_links",
        "parents": [
            {
                **identity(cells[edge["source"]]),
                "relationship": edge["kind"],
                "certainty": "ambiguous" if str(cell.pk) in ambiguous else "retained",
            }
            for edge in incoming.get(str(cell.pk), [])
        ],
        "source_cells": [
            {**identity(value), "certainty": "ambiguous" if ambiguous else "retained"}
            for identifier, value in cells.items()
            if stages[identifier] == "source"
        ],
    }