Skip to content

The platform for continuously improving AI agents.

25.5 KB
Raw Blame
import hashlib
import json
import math
import sqlite3
import tempfile
import uuid
from collections import Counter, defaultdict
from contextlib import closing
from pathlib import Path

from django.db import transaction
from django.db.models import F, Q
from django.utils import timezone

from overbae.core.errors import DatasetError, InputValidationError
from overbae.models import (
    Cell,
    DataPartitionMember,
    DataPartitionPlan,
    Dataset,
    Project,
    ResearchAction,
    WorkshopTask,
)
from overbae.services import research_wakes
from overbae.services.datasets import heartbeat, land, lineage, paths, rows, store, use
from overbae.services.datasets.examples import field_value, native_decision, prepare_native_record
from overbae.services.datasets.partition import GROUP_ALIASES

ROLES = ("train", "development", "calibration", "final")


class SealedHoldoutError(InputValidationError):
    """A final holdout's rows were asked for outside its one Qualify stage."""


def sealed(cells):
    """The final holdouts among ``cells``."""
    return DataPartitionMember.objects.filter(role="final", cell__in=list(cells)).values_list(
        "cell_id", flat=True
    )


def refuse_sealed(cells) -> None:
    """Agents read no final holdout row: neither in a workspace, a query, an exploration nor
    a Your system stage."""
    found = sealed(cells).first()
    if found is not None:
        raise SealedHoldoutError(
            f"Version {found} is a sealed final holdout: only a Qualify stage reads it, once."
        )


def validate_recipe(recipe):
    if not isinstance(recipe, dict) or set(recipe) - {
        "seed",
        "fractions",
        "group_by",
        "stratify_by",
        "holdouts",
    }:
        raise InputValidationError("Unknown partition rule")
    fractions = recipe.get("fractions", {})
    if (
        not isinstance(fractions, dict)
        or not 2 <= len(fractions) <= 4
        or set(fractions) - set(ROLES)
    ):
        raise InputValidationError(
            "Choose two to four training, development, calibration or final roles"
        )
    if any(
        type(v) not in {int, float} or not math.isfinite(v) or not 0 < v < 1
        for v in fractions.values()
    ) or not math.isclose(sum(fractions.values()), 1, abs_tol=1e-9):
        raise InputValidationError("Positive partition fractions must sum to one")
    if type(recipe.get("seed")) is not int or not 0 <= recipe["seed"] <= 2**32 - 1:
        raise InputValidationError("Supply a seed between zero and 4294967295")
    groups = recipe.get("group_by", [])
    if (
        not isinstance(groups, list)
        or len(groups) > 20
        or any(not isinstance(x, str) or not x for x in groups)
    ):
        raise InputValidationError("Group fields must be a list of at most twenty names")
    strata = recipe.get("stratify_by")
    if strata is not None and (not isinstance(strata, str) or not strata):
        raise InputValidationError("Stratification requires a field name")
    holdouts = recipe.get("holdouts", [])
    if not isinstance(holdouts, list) or len(holdouts) > 20:
        raise InputValidationError("Supply at most twenty holdout rules")
    for rule in holdouts:
        if (
            not isinstance(rule, dict)
            or set(rule) != {"field", "values", "role"}
            or rule["role"] not in fractions
            or not isinstance(rule["field"], str)
            or not rule["field"]
            or not isinstance(rule["values"], list)
            or not rule["values"]
        ):
            raise InputValidationError(
                "A holdout requires a field, nonempty values and a selected role"
            )
    json.dumps(recipe, allow_nan=False)
    return {
        "seed": recipe["seed"],
        "fractions": {r: fractions[r] for r in ROLES if r in fractions},
        "group_by": sorted(set(groups)),
        "stratify_by": strata,
        "holdouts": holdouts,
    }


@transaction.atomic
def request_plan(project, *, name, request_key, source_cell, recipe):
    if source_cell.dataset.project_id != project.pk:
        raise InputValidationError("The source must belong to this project")
    recipe = validate_recipe(recipe)
    Project.objects.select_for_update().get(pk=project.pk)
    Dataset.objects.select_for_update().get(pk=source_cell.dataset_id)
    existing = DataPartitionPlan.objects.filter(project=project, request_key=request_key).first()
    if existing:
        if (
            existing.recipe != recipe
            or existing.source_cell_id != source_cell.pk
            or existing.name != name
        ):
            raise InputValidationError(
                "This request key already identifies a different partition plan"
            )
        return existing
    rows.verify(source_cell)
    if not source_cell.ran or not source_cell.rows:
        raise InputValidationError("Partitioning requires a nonempty readable version")
    use.freeze(source_cell)
    return DataPartitionPlan.objects.create(
        project=project,
        name=name,
        request_key=request_key,
        source_cell=source_cell,
        source_fingerprint=source_cell.fingerprint,
        recipe=recipe,
    )


def related_cells(cell):
    """The versions that hold this one's bytes: itself and the same file landed again."""
    same = Q(pk=cell.pk) | (Q(fingerprint=cell.fingerprint) if cell.fingerprint else Q())
    return set(
        Cell.objects.filter(same, dataset__project_id=cell.dataset.project_id).values_list(
            "pk", flat=True
        )
    )


def held_out_keys(plan):
    """Published final members stay sealed even when their plan never completes."""
    members = DataPartitionMember.objects.filter(
        plan__project_id=plan.project_id,
        plan__source_cell_id__in=related_cells(plan.source_cell),
        role="final",
    )
    keys = set()
    for member in members.select_related("cell__dataset"):
        if member.cell.dataset.project_id != plan.project_id:
            raise InputValidationError("A retained final member belongs to another project")
        rows.verify(member.cell)
        for row in lineage.stream(member.cell):
            keys |= row
    return keys


def assign(cell, recipe, destination, *, progress=None, held=frozenset()):
    """Assign the cell's rows to roles. A row that shares a key in ``held`` goes to final:
    what one partition sealed stays sealed in every later partition of the same data."""
    if held and "final" not in recipe["fractions"]:
        raise InputValidationError(
            "An earlier partition of this data holds rows out for final evaluation. "
            "Give this partition a final role."
        )
    inherited_final = 0
    parents = []
    unresolved_groups = set(recipe["group_by"])

    def root(index):
        while parents[index] != index:
            parents[index] = parents[parents[index]]
            index = parents[index]
        return index

    with closing(sqlite3.connect(destination / "groups.sqlite")) as db, db:
        db.execute(
            "CREATE TABLE identities (kind TEXT, value TEXT, owner INTEGER, PRIMARY KEY(kind,value))"
        )
        db.execute("CREATE TABLE observations (row INTEGER PRIMARY KEY, stratum TEXT, forced TEXT)")
        for index, (record, (_, keys)) in enumerate(
            zip(
                store.iter_rows(rows.frame_path(cell)),
                lineage.with_groups(cell, recipe["group_by"]),
                strict=True,
            )
        ):
            if progress and index % 10000 == 0:
                progress("grouping", index, cell.rows)
            parents.append(index)
            if unresolved_groups:
                group_kinds = {kind for kind, _ in keys if kind != "content"}
                unresolved_groups = {
                    field
                    for field in unresolved_groups
                    if GROUP_ALIASES.get(field, field) not in group_kinds
                }
            for field in tuple(unresolved_groups):
                try:
                    field_value(record, field)
                except ValueError:
                    continue
                unresolved_groups.remove(field)
            for kind, value in keys:
                found = db.execute(
                    "SELECT owner FROM identities WHERE kind=? AND value=?", (kind, value)
                ).fetchone()
                if found:
                    a, b = root(index), root(found[0])
                    parents[max(a, b)] = min(a, b)
                else:
                    db.execute("INSERT INTO identities VALUES(?,?,?)", (kind, value, index))
            forced = {
                rule["role"]
                for rule in recipe["holdouts"]
                if field_value(record, rule["field"]) in rule["values"]
            }
            if held and not keys.isdisjoint(held):
                forced.add("final")
                inherited_final += 1
            if len(forced) > 1:
                raise InputValidationError("Conflicting holdout roles apply to one observation")
            label = (
                json.dumps(field_value(record, recipe["stratify_by"]), sort_keys=True)
                if recipe["stratify_by"]
                else "all"
            )
            db.execute(
                "INSERT INTO observations VALUES(?,?,?)", (index, label, next(iter(forced), None))
            )
        if unresolved_groups:
            raise InputValidationError(
                "Unknown partition group fields: " + ", ".join(sorted(unresolved_groups))
            )
        if progress:
            progress("assigning", len(parents), cell.rows)
        components = defaultdict(lambda: {"count": 0, "strata": Counter(), "forced": set()})
        totals = Counter()
        for index, label, forced in db.execute(
            "SELECT row,stratum,forced FROM observations ORDER BY row"
        ):
            component = components[root(index)]
            component["count"] += 1
            component["strata"][label] += 1
            totals[label] += 1
            if forced:
                component["forced"].add(forced)
        fractions = recipe["fractions"]
        if len(components) < len(fractions):
            raise InputValidationError(
                "Too few independent content/group clusters for the selected roles"
            )
        counts, group_counts = Counter(), Counter()
        strata = {role: Counter() for role in fractions}
        assignments = {}
        ordered = sorted(
            components,
            key=lambda key: (
                not components[key]["forced"],
                hashlib.sha256(f"{recipe['seed']}:{key}".encode()).hexdigest(),
            ),
        )
        for key in ordered:
            component = components[key]
            if len(component["forced"]) > 1:
                raise InputValidationError("Related observations require conflicting holdout roles")

            def change(role, component=component):
                score = 0.0
                for label, size in component["strata"].items():
                    target = totals[label] * fractions[role]
                    before = strata[role][label] - target
                    score += ((before + size) ** 2 - before**2) / max(1, target)
                return score

            role = (
                next(iter(component["forced"]))
                if component["forced"]
                else min(fractions, key=change)
            )
            assignments[key] = role
            counts[role] += component["count"]
            group_counts[role] += 1
            strata[role].update(component["strata"])
        if any(not counts[role] for role in fractions):
            raise InputValidationError(
                "Grouping and holdout rules leave an empty role; revise the fractions or rules"
            )
        with (destination / "assignments.jsonl").open("w") as output:
            for index in range(len(parents)):
                output.write(
                    json.dumps(
                        {"row": index, "group": root(index), "role": assignments[root(index)]}
                    )
                    + "\n"
                )
        return {
            "source_rows": len(parents),
            "counts": dict(counts),
            "groups": dict(group_counts),
            "strata": {r: dict(s) for r, s in strata.items()},
            "duplicates_removed": 0,
            "inherited_final_rows": inherited_final,
            "overlap": {
                "content_and_declared_groups": 0,
                "near_duplicates": "not_checked",
                "pretraining": "unknown",
            },
        }


def prepared_member_rows(source, role):
    for line in source:
        record = json.loads(line)
        decision = native_decision(record)
        if role in {"calibration", "final"} and decision is not None:
            # This is a lossless native wire projection; interpretation remains Workshop-owned.
            yield prepare_native_record(record, decision, "eval")
        else:
            yield record


def require_owner(plan):
    """A partition that Research or a Workshop task requested is built only while that owner
    may still prepare data from its source."""
    if not plan.request_key.startswith(("research:", "workshop:")):
        return
    # Lazy: research and Workshop services admit partitions through this module.
    from overbae.services import execution_mandates, research_tools  # noqa: PLC0415
    from overbae.services.workshop_agent import lifecycle  # noqa: PLC0415

    if plan.source_cell.fingerprint != plan.source_fingerprint:
        raise InputValidationError("The retained partition source changed")
    try:
        owner = uuid.UUID(plan.request_key.split(":")[1])
    except (ValueError, IndexError) as exc:
        raise InputValidationError("The partition's execution owner is invalid") from exc
    if plan.request_key.startswith("workshop:"):
        task = WorkshopTask.objects.filter(pk=owner, project_id=plan.project_id).first()
        if task is None:
            raise InputValidationError("The partition's Workshop owner is unavailable")
        lifecycle.mutation(task, continuation=True)
        lifecycle.source(task, plan.source_cell, platform_reads=True, continuation=True)
        return
    action = (
        ResearchAction.objects.select_related("agent__assignment")
        .filter(pk=owner, agent__assignment__project_id=plan.project_id, tool="platform")
        .first()
    )
    arguments = action.arguments.get("arguments", {}) if action else {}
    if (
        action is None
        or action.arguments.get("name") != "create_data_partition"
        or str(arguments.get("source_cell")) != str(plan.source_cell_id)
        or arguments.get("name") != plan.name
        or validate_recipe(arguments.get("recipe")) != plan.recipe
    ):
        raise InputValidationError("The partition differs from its admitted Research request")
    execution_mandates.require_action_continuation(action, "prepare")
    research_tools.source_cell(action.agent.assignment, plan.source_cell_id, platform_reads=True)


def build(plan_id):
    with transaction.atomic():
        plan = (
            DataPartitionPlan.objects.select_for_update(of=("self",))
            .select_related("source_cell__dataset", "project")
            .get(pk=plan_id)
        )
        if plan.state in {"completed", "cancelled"}:
            return
        taken = heartbeat.take(plan, running=plan.state == "running")
        if taken == "held":
            return
        if taken == "exhausted":
            plan.state, plan.error = "failed", heartbeat.STOPPED
            plan.save(update_fields=["state", "error", "attempt", "lease_until", "updated_at"])
            return
        plan.state, plan.error = "running", ""
        plan.save(
            update_fields=["state", "error", "attempt", "attempts", "lease_until", "updated_at"]
        )
    owned = DataPartitionPlan.objects.filter(pk=plan.pk, attempt=plan.attempt)
    beat = heartbeat.hold(owned, owner=f"partition plan {plan.pk}")

    def progress(stage, completed, total, **extra):
        if not DataPartitionPlan.objects.filter(pk=plan.pk, state="running").exists():
            raise InputValidationError("Partition construction was stopped")
        require_owner(plan)
        value = {
            "stage": stage,
            "completed": completed,
            "total": total,
            **extra,
            "updated_at": timezone.now().isoformat(),
        }
        owned.filter(state="running").update(report={"progress": value}, updated_at=timezone.now())
        return value

    try:
        progress("verifying", 0, plan.source_cell.rows)
        rows.verify(plan.source_cell)
        if plan.source_cell.fingerprint != plan.source_fingerprint:
            raise InputValidationError("The frozen partition source changed")
        directory = paths.media_root() / "data-partitions" / str(plan.id)
        directory.mkdir(parents=True, exist_ok=True)
        with tempfile.TemporaryDirectory(dir=directory) as temporary:
            work = Path(temporary)

            report = assign(
                plan.source_cell, plan.recipe, work, progress=progress, held=held_out_keys(plan)
            )
            progress("writing", 0, plan.source_cell.rows)
            streams = {
                role: (work / f"{role}.jsonl").open("w") for role in plan.recipe["fractions"]
            }
            inherited = {role: [] for role in plan.recipe["fractions"]}
            try:
                with (work / "assignments.jsonl").open() as assignments:
                    for index, (record, (_, keys), line) in enumerate(
                        zip(
                            store.iter_rows(rows.frame_path(plan.source_cell)),
                            lineage.with_groups(plan.source_cell, plan.recipe["group_by"]),
                            assignments,
                            strict=True,
                        )
                    ):
                        if index % 10000 == 0:
                            progress("writing", index, plan.source_cell.rows)
                        role = json.loads(line)["role"]
                        streams[role].write(json.dumps(record) + "\n")
                        inherited[role].append(keys)
            finally:
                for stream in streams.values():
                    stream.close()
            # Members, the assignment file and completion land in one transaction while the
            # plan and its project are locked: a revoked owner, a stop or a failure publishes
            # nothing, and related partitions publish one at a time.
            with transaction.atomic():
                Project.objects.select_for_update().get(pk=plan.project_id)
                current = (
                    DataPartitionPlan.objects.select_for_update(of=("self",))
                    .select_related("source_cell__dataset")
                    .get(pk=plan.pk)
                )
                if current.state != "running" or current.attempt != plan.attempt:
                    raise InputValidationError("Partition construction was stopped")
                require_owner(current)
                held = held_out_keys(current)
                if any(
                    not row_keys.isdisjoint(held)
                    for role, records in inherited.items()
                    if role != "final"
                    for row_keys in records
                ):
                    raise InputValidationError(
                        "Final row identities changed while this partition was prepared. "
                        "Rebuild the partition before publishing its members."
                    )
                for role in plan.recipe["fractions"]:
                    progress("preparing_member", 0, report["counts"][role], role=role)
                    existing = (
                        plan.members.select_related("cell__dataset").filter(role=role).first()
                    )
                    if existing:
                        rows.verify(existing.cell)
                        existing_keys = list(lineage.stream(existing.cell))
                        if len(existing_keys) != len(inherited[role]) or any(
                            not expected <= actual
                            or (role != "final" and not actual.isdisjoint(held))
                            for expected, actual in zip(inherited[role], existing_keys, strict=True)
                        ):
                            raise InputValidationError(
                                "A retained partition member differs from the prepared assignment"
                            )
                        continue
                    dataset, _ = Dataset.objects.get_or_create(
                        pk=uuid.uuid5(plan.pk, role),
                        defaults={
                            "project": plan.project,
                            "name": f"{plan.name[: 252 - len(role)]} · {role}",
                            "brief": plan.source_cell.dataset.brief,
                            "intent": "eval" if role in {"calibration", "final"} else "train",
                            "state": Dataset.State.LANDING,
                        },
                    )
                    with (work / f"{role}.jsonl").open() as source:
                        land.commit(
                            dataset,
                            land.Landing(
                                prepared_member_rows(source, role),
                                inherited=inherited[role],
                                spec={
                                    "partition_plan": str(plan.pk),
                                    "role": role,
                                    "source_cell": str(plan.source_cell_id),
                                    "fingerprint": plan.source_fingerprint,
                                },
                            ),
                            infer_capability=False,
                        )
                    DataPartitionMember.objects.get_or_create(
                        plan=plan, role=role, defaults={"cell": dataset.active_cell}
                    )
                assignment_path = directory / "assignments.jsonl"
                (work / "assignments.jsonl").replace(assignment_path)
                report["assignments_sha256"] = store.file_sha256(assignment_path)
                report["fingerprint"] = plan.source_fingerprint
                report["progress"] = {
                    "stage": "completed",
                    "completed": plan.source_cell.rows,
                    "total": plan.source_cell.rows,
                    "updated_at": timezone.now().isoformat(),
                }
                require_owner(plan)
                if not owned.filter(state="running").update(
                    state="completed", report=report, error="", updated_at=timezone.now()
                ):
                    raise InputValidationError("Partition construction was stopped")
    except Exception as exc:
        owned.exclude(state="cancelled").update(
            state="failed", error=str(exc)[:1000], updated_at=timezone.now()
        )
    finally:
        beat.set()
        research_wakes.native_request(plan.request_key)


def describe(plan):
    return {
        "id": str(plan.pk),
        "project": str(plan.project_id),
        "name": plan.name,
        "source_cell": str(plan.source_cell_id),
        "recipe": plan.recipe,
        "report": plan.report,
        "state": plan.state,
        "error": plan.error,
        "members": [
            {"role": member.role, "cell": use.describe(member.cell)}
            for member in plan.members.select_related("cell__dataset")
        ],
    }


def retry(plan):
    if not DataPartitionPlan.objects.filter(pk=plan.pk, state="failed").update(
        state="queued", error=""
    ):
        raise InputValidationError("Only failed partition construction can be retried")


def verified_plan(cell, recipe, *, exclude_partition=None):
    candidates = (
        DataPartitionPlan.objects.filter(
            project_id=cell.dataset.project_id,
            source_cell__dataset__project_id=cell.dataset.project_id,
            source_fingerprint=cell.fingerprint,
            source_cell__fingerprint=F("source_fingerprint"),
            source_cell__state="ok",
            state="completed",
            recipe=recipe,
        )
        .exclude(pk=exclude_partition)
        .select_related("source_cell__dataset")
        .prefetch_related("members__cell__dataset")
        .order_by("created_at")[:100]
    )
    for candidate in candidates:
        members = list(candidate.members.all())
        if (
            {member.role for member in members} != recipe["fractions"].keys()
            or candidate.report.get("fingerprint") != cell.fingerprint
            or any(
                member.cell.dataset.project_id != cell.dataset.project_id
                or member.cell.rows != candidate.report.get("counts", {}).get(member.role)
                for member in members
            )
        ):
            continue
        try:
            rows.verify(candidate.source_cell)
            for member in members:
                rows.verify(member.cell)
            assignment = (
                paths.media_root() / "data-partitions" / str(candidate.pk) / "assignments.jsonl"
            )
            if store.file_sha256(assignment) != candidate.report.get("assignments_sha256"):
                continue
        except (DatasetError, OSError, ValueError, rows.RowStoreError):
            continue
        return candidate
    return None


@transaction.atomic
def cancel(plan):
    current = (
        DataPartitionPlan.objects.select_for_update(of=("self",))
        .select_related("source_cell__dataset")
        .get(pk=plan.pk)
    )
    if current.state in {"queued", "running"}:
        current.state = "cancelled"
        current.save(update_fields=["state", "updated_at"])
    return current