The platform for continuously improving AI agents.
"""Pick a readable version and freeze it; quality findings do not prevent use."""
from __future__ import annotations
import logging
from typing import Any
from django.db import transaction
from django.utils import timezone
from overbae.core.errors import DatasetError
from overbae.models import Cell, Dataset
from overbae.services.datasets import rows
from overbae.services.datasets.contract import public_intent
logger = logging.getLogger(__name__)
def check(dataset: Dataset, intent: str, *, cell: Cell | None = None, verify: bool = True) -> Cell:
if cell is not None and cell.dataset_id != dataset.id:
raise DatasetError("That version belongs to another dataset.", code="cell_mismatch")
stored = public_intent(dataset.intent)
if intent == "development":
# Loss evaluation reads labelled training-format examples without training on them.
if stored not in {"train", "eval"}:
raise DatasetError(
"Choose a training or evaluation dataset for development.", code="intent"
)
return check_content(dataset, "train", cell=cell, verify=verify)
if stored != intent:
raise DatasetError(
f"{dataset.name} is a {stored} dataset; this needs {intent}.", code="intent"
)
if cell is None:
cell = dataset.active_cell
else:
cell.refresh_from_db()
if cell is None:
if dataset.state == Dataset.State.ERROR:
raise DatasetError(
f"The last run of {dataset.name} failed. Run it again in the data workshop.",
code="run_failed",
)
if dataset.state == Dataset.State.RUNNING:
raise DatasetError(f"{dataset.name} is running. Wait for it to finish.", code="running")
raise DatasetError(f"{dataset.name} has no version that ran.", code="no_version")
ok, reason = cell.fits(intent)
if not ok:
raise DatasetError(f"{dataset.name} · {label(dataset, cell)}: {reason}", code="contract")
try:
if verify:
rows.verify(cell)
except (ValueError, rows.RowStoreError) as exc:
logger.exception("Could not verify dataset cell %s", cell.pk)
raise DatasetError(
f"{dataset.name}: this version is unreadable or has changed. Run it again in the data workshop.",
code="workshop_validation",
) from exc
return cell
@transaction.atomic
def use(dataset: Dataset, intent: str, *, cell: Cell | None = None, verify: bool = True) -> Cell:
"""``check``, then set ``used_at`` the first time, which freezes the cell
and every cell it reads and starts a new major version."""
# Share generation's lock so a consumed version cannot change between batches.
dataset = (
Dataset.objects.select_for_update(of=("self",))
.select_related("capability")
.get(pk=dataset.pk)
)
cell = check(dataset, intent, cell=cell, verify=verify)
freeze(cell)
return cell
def freeze(*cells: Cell | None) -> None:
for cell in cells:
if cell is not None and cell.used_at is None:
Cell.objects.filter(pk=cell.pk, used_at__isnull=True).update(used_at=timezone.now())
cell.refresh_from_db()
def label(dataset: Dataset, cell: Cell) -> str:
return dataset.versions().get(cell.id, cell.title)
def describe(cell: Cell | None, *, chain: list[Cell] | None = None) -> dict[str, Any] | None:
if cell is None:
return None
return {
"id": str(cell.id),
"version": cell.dataset.versions(chain=chain).get(cell.id, ""),
"title": cell.title,
"rows": cell.rows,
"fingerprint": cell.fingerprint,
"dataset_id": str(cell.dataset_id),
}
def check_content(
dataset: Dataset, intent: str, *, cell: Cell | None = None, verify: bool = True
) -> Cell:
if cell is not None and cell.dataset_id != dataset.id:
raise DatasetError("That version belongs to another dataset.", code="cell_mismatch")
if cell is None:
cell = dataset.active_cell
else:
cell.refresh_from_db()
if cell is None:
if dataset.state == Dataset.State.ERROR:
raise DatasetError(
f"The last run of {dataset.name} failed. Run it again in the data workshop.",
code="run_failed",
)
if dataset.state == Dataset.State.RUNNING:
raise DatasetError(f"{dataset.name} is running. Wait for it to finish.", code="running")
raise DatasetError(f"{dataset.name} has no version that ran.", code="no_version")
ok, reason = cell.fits(intent)
if not ok:
raise DatasetError(f"{dataset.name} · {label(dataset, cell)}: {reason}", code="contract")
try:
if verify:
rows.verify(cell)
except (ValueError, rows.RowStoreError) as exc:
logger.exception("Could not verify dataset cell %s", cell.pk)
raise DatasetError(
f"{dataset.name}: this version is unreadable or has changed. Run it again in the data workshop.",
code="workshop_validation",
) from exc
return cell
def check_held_out(train: Cell, final: Cell) -> None:
"""A model's final evaluation says nothing once it has trained on the rows it is
evaluated on. Rows match on their content and on every row they were derived from."""
overlap = rows.contamination(train, final)["overlap_count"]
if overlap:
raise DatasetError(
f"{overlap} of {train.rows} rows of {train.dataset.name} are also in "
f"{final.dataset.name}, the data held out for final evaluation.",
code="held_out",
)