Skip to content

The platform for continuously improving AI agents.

20.4 KB
Raw Blame
from django.core import signing
from django.core.exceptions import ValidationError
from django.db.models import DateTimeField, Max, Q
from django.db.models.fields.json import KeyTextTransform
from django.db.models.functions import Cast

from overbae.core.errors import InputValidationError
from overbae.models import ContextEdge, ContextNode, EvalSet
from overbae.services import context_graph, research_evidence
from overbae.services.datasets.context import CONSUMERS
from overbae.services.experiment_catalog import COMPONENTS
from overbae.services.experiment_interfaces import BINDINGS
from overbae.services.research_contract import Explore


def identity(node):
    return context_graph.node_metadata(node, purpose="inspection")


def content_page(value, request, *, fingerprint=None):
    """One page of a record. A read that cannot continue as asked still answers: a record
    that changed restarts from its beginning, and a path that selects nothing returns the
    fields that exist where it stopped."""
    fingerprint = fingerprint or context_graph.fingerprint(value)
    offset = request.offset
    restarted = bool(request.fingerprint) and request.fingerprint != fingerprint
    if restarted:
        offset = 0
    path, missing = "", None
    for part in request.path.strip("/").split("/") if request.path.strip("/") else []:
        key = part.replace("~1", "/").replace("~0", "~")
        try:
            value = value[int(key)] if isinstance(value, list) else value[key]
        except (KeyError, IndexError, TypeError, ValueError):
            missing = key
            break
        path += "/" + part
    content = context_graph.canonical(value)
    end = offset + request.length
    return {
        "fingerprint": fingerprint,
        "format": "json",
        "path": path,
        "fields": list(value) if isinstance(value, dict) else None,
        **({"missing": missing} if missing is not None else {}),
        **({"restarted": True} if restarted else {}),
        "content": content[offset:end],
        "offset": offset,
        "next_offset": end if end < len(content) else None,
        "total_chars": len(content),
        "continuation": {
            **request.model_dump(
                mode="json", exclude_defaults=True, exclude={"cursor", "offset", "fingerprint"}
            ),
            "operation": request.operation,
            "path": path,
            "offset": end,
            "fingerprint": fingerprint,
        }
        if end < len(content)
        else None,
    }


def page_discloses(facts, page, field):
    target = (field,) if isinstance(field, str) else tuple(field)
    path = tuple(part.replace("~1", "/").replace("~0", "~") for part in page["path"].split("/")[1:])
    if not page["content"]:
        return False
    if path[: len(target)] == target:
        return True
    if target[: len(path)] != path:
        return False
    value = facts
    try:
        for part in path:
            value = value[int(part)] if isinstance(value, list) else value[part]
    except (KeyError, IndexError, TypeError, ValueError):
        return False
    start = 0
    for part in target[len(path) :]:
        if isinstance(value, dict) and part in value:
            start += 1
            for key, child in sorted(value.items()):
                start += len(context_graph.canonical(key)) + 1
                if key == part:
                    value = child
                    break
                start += len(context_graph.canonical(child)) + 1
        elif isinstance(value, list) and str(part).isdecimal() and int(part) < len(value):
            start += 1 + sum(
                len(context_graph.canonical(child)) + 1 for child in value[: int(part)]
            )
            value = value[int(part)]
        else:
            return False
    if value in (None, "", {}, []):
        return False
    end = start + len(context_graph.canonical(value))
    return page["offset"] < end and page["offset"] + len(page["content"]) > start


def cursor_key(project, request):
    return context_graph.fingerprint(
        {
            "project": str(project.pk),
            **request.model_dump(
                include={
                    "operation",
                    "kind",
                    "query",
                    "reference",
                    "direction",
                    "relationship",
                    "order",
                }
            ),
        }
    )


def decode_cursor(project, request):
    if request.cursor is None:
        return None
    try:
        cursor = signing.loads(request.cursor, salt="context-query")
        if cursor["query"] != cursor_key(project, request):
            raise ValueError
        return cursor["position"]
    except (signing.BadSignature, KeyError, TypeError, ValueError):
        raise InputValidationError(
            "The context cursor does not belong to this project and query"
        ) from None


def encode_cursor(project, request, position):
    return signing.dumps(
        {"query": cursor_key(project, request), "position": position}, salt="context-query"
    )


def search_page_identity(project, request, result):
    return {
        "query": cursor_key(project, request),
        "page": context_graph.fingerprint(
            {"nodes": result.get("nodes"), "next_cursor": result.get("next_cursor")}
        ),
    }


def verified_search_page(project, arguments, result):
    try:
        retained = signing.loads(result.get("search_receipt", ""), salt="context-search-page")
        request = Explore.model_validate(arguments)
        return retained == search_page_identity(project, request, result)
    except (signing.BadSignature, TypeError, ValueError):
        return False


def contracts(request, *, additional=None):
    """A binding format or data consumer by name, or the index of what has a contract."""
    if request.kind in BINDINGS:
        value = BINDINGS[request.kind]
    elif request.kind in CONSUMERS:
        value = CONSUMERS[request.kind]
    else:
        value = {
            "stage_kinds": [
                {"kind": kind, "description": component.description}
                for kind, component in COMPONENTS.items()
                if kind != "model"
            ],
            "binding_formats": list(BINDINGS),
            "data_consumers": list(CONSUMERS),
            **(additional or {}),
        }
    return content_page(value, request)


def refresh_neighborhood(project, request):
    kind, separator, object_id = request.reference.partition(":")
    source = context_graph.BY_KIND.get(kind)
    if not separator or source is None:
        raise InputValidationError("Use a typed context reference")
    model, relations, query = context_graph.source_rows(source, project)
    try:
        root = query.filter(pk=object_id).first()
    except (ValueError, ValidationError):
        root = None
    if root is None:
        raise InputValidationError("A context reference is unavailable in this project")
    selected = {kind: {object_id}}
    old_links = ContextEdge.objects.filter(
        project=project, target__kind=kind, target__object_id=object_id
    )
    if request.direction != "outgoing":
        if request.kind:
            old_links = old_links.filter(source__kind=request.kind)
        for previous_kind, previous_id in old_links.values_list(
            "source__kind", "source__object_id"
        ):
            selected.setdefault(previous_kind, set()).add(previous_id)
    if request.direction != "incoming":
        for field in relations:
            target = context_graph.BY_MODEL[field.related_model._meta.model_name].kind
            if root.get(field.attname) and (not request.kind or target == request.kind):
                selected.setdefault(target, set()).add(str(root[field.attname]))
    if request.direction != "outgoing":
        for candidate in context_graph.SOURCES:
            if request.kind and candidate.kind != request.kind:
                continue
            candidate_model, fields, rows = context_graph.source_rows(candidate, project)
            related = [field for field in fields if field.related_model == model]
            if related:
                condition = Q()
                for field in related:
                    condition |= Q(**{field.attname: object_id})
                selected.setdefault(candidate.kind, set()).update(
                    map(
                        str,
                        rows.filter(condition).values_list(
                            candidate_model._meta.pk.name, flat=True
                        ),
                    )
                )
    for related_kind, identities in context_graph.json_neighbors(
        project,
        [(kind, object_id)],
        incoming=request.direction != "outgoing",
        outgoing=request.direction != "incoming",
        kind=request.kind,
    ).items():
        selected.setdefault(related_kind, set()).update(identities)
    context_graph.refresh(project, kinds=list(selected), object_ids=selected)


def execute(project, request, *, assignment=None):
    if request.operation == "contracts":
        return contracts(request)
    if request.operation == "catalog":
        request = request.model_copy(update={"kind": None})
    elif request.kind and request.kind not in context_graph.BY_KIND:
        # Nothing of a kind the graph does not hold: an empty answer that names the kinds.
        return {"nodes": [], "next_cursor": None, "kinds": sorted(context_graph.BY_KIND)}
    position = decode_cursor(project, request)
    if not request.cursor:
        if request.operation == "read":
            kind = (request.reference or "").partition(":")[0]
            if kind not in context_graph.BY_KIND:
                raise InputValidationError(
                    "Read a typed reference such as cell:<id>. Kinds: "
                    + ", ".join(sorted(context_graph.BY_KIND))
                )
            try:
                context_graph.refresh(
                    project, kinds=[kind], object_ids={kind: [request.reference.partition(":")[2]]}
                )
            except (ValueError, ValidationError):
                raise InputValidationError(
                    "A context reference is unavailable in this project"
                ) from None
        elif request.operation == "traverse":
            refresh_neighborhood(project, request)
        elif request.operation == "search" and request.kind:
            context_graph.refresh(project, kinds=[request.kind])
        else:
            context_graph.refresh_operational(project)
    graph = context_graph.describe(project)
    if request.operation == "catalog":
        relationships = set(
            ContextEdge.objects.filter(project=project).values_list(
                "source__kind", "relationship", "target__kind"
            )
        )
        for source in context_graph.SOURCES:
            _, relations, _ = context_graph.source_rows(source, project)
            relationships.update(
                (
                    source.kind,
                    field.name,
                    context_graph.BY_MODEL[field.related_model._meta.model_name].kind,
                )
                for field in relations
            )
        return {
            "graph": graph,
            "relationships": [
                {"source_kind": source, "relationship": relationship, "target_kind": target}
                for source, relationship, target in sorted(relationships)
            ],
            "kinds": [
                {
                    "kind": source.kind,
                    "count": graph["coverage"].get(source.kind, 0),
                    "fields": source.field_names,
                    "search_orders": ["identity", "newest"]
                    if "created_at" in source.field_names
                    else ["identity"],
                }
                for source in context_graph.SOURCES
            ],
        }
    if request.operation == "read":
        ids = context_graph.resolve(project, [request.reference])
        node = ContextNode.objects.get(project=project, pk__in=ids)
        payload = context_graph.node_payload(node, "inspection")
        if node.kind == "evaluation_set":
            suite = EvalSet.objects.get(project=project, pk=node.object_id)
            payload["facts"] = {
                **payload["facts"],
                "matrix": suite.matrix_snapshot(),
                "publish": {
                    "tool": "asset",
                    "operation": "publish",
                    "kind": "suite",
                    "name": suite.name,
                    "definition": {"eval_set": str(suite.pk)},
                },
            }
        identity_fingerprint = node.fingerprint
        if node.kind == "evaluation_set":
            identity_fingerprint = context_graph.fingerprint(payload["facts"])
        if assignment is not None and (
            node.kind in research_evidence.CONTEXT_EXECUTION_FIELDS
            or node.kind in {"research_artifact", "research_agent"}
        ):
            payload = research_evidence.visible(assignment, payload)
            identity_fingerprint = context_graph.fingerprint(payload["facts"])
        note = delegation = None
        if node.kind == "research_agent":
            note = payload["facts"].pop("notes_provenance", None)
            delegation = payload["facts"].pop("context_delegation", None)
            identity_fingerprint = context_graph.fingerprint(payload["facts"])
        result = {
            "node": {key: value for key, value in payload.items() if key != "facts"},
            **content_page(payload["facts"], request, fingerprint=identity_fingerprint),
        }
        page_fingerprint = context_graph.fingerprint(result)
        if node.kind in research_evidence.CONTEXT_EXECUTION_FIELDS:
            result["execution_read"] = {
                "reference": context_graph.reference(node),
                "disclosed": payload["facts"].get("access") != "sealed_data"
                and any(
                    page_discloses(payload["facts"], result, field)
                    for field in (
                        research_evidence.context_authored_paths(
                            context_graph.reference(node), payload["facts"]
                        )
                        if node.kind in research_evidence.CONTEXT_AUTHORED_FIELDS
                        else research_evidence.CONTEXT_EXECUTION_FIELDS[node.kind]
                    )
                ),
                "page_fingerprint": page_fingerprint,
            }
        if (
            node.kind in research_evidence.CONTEXT_AUTHORED_FIELDS
            and result["execution_read"]["disclosed"]
        ):
            result["execution_read"]["source_receipt"] = research_evidence.context_page_receipt(
                project, context_graph.reference(node), payload["facts"], page_fingerprint
            )
        if node.kind == "research_agent" and result["path"] in {"", "/notes"}:
            note = note or {}
            result["note_read"] = {
                "agent": node.object_id,
                "identity": note.get("identity"),
                "note_receipt": note.get("note_receipt"),
                "disclosed": page_discloses(payload["facts"], result, "notes"),
                "page_fingerprint": page_fingerprint,
            }
        if node.kind == "research_agent":
            fields = {
                field: context_graph.fingerprint(payload["facts"][field])
                for field in ("task", "work_order")
                if page_discloses(payload["facts"], result, field)
            }
            if result["node"]["label"] not in {node.kind, f"{node.kind} {node.object_id}"}:
                fields["task"] = context_graph.fingerprint(payload["facts"].get("task"))
            result["delegation_read"] = {
                **(delegation or {"agent": node.object_id}),
                "fields": fields,
                "page_fingerprint": page_fingerprint,
            }
        return result
    if request.operation == "search":
        nodes = (
            ContextNode.objects.filter(project=project).defer("facts").order_by("kind", "object_id")
        )
        if request.kind:
            nodes = nodes.filter(kind=request.kind)
        if request.order == "newest":
            source = context_graph.BY_KIND.get(request.kind)
            if source is None or "created_at" not in source.field_names:
                raise InputValidationError(
                    "Newest search requires a kind with a recorded created_at field"
                )
            nodes = nodes.annotate(
                created_at_value=Cast(KeyTextTransform("created_at", "facts"), DateTimeField())
            ).order_by("-created_at_value", "object_id")
        if request.query:
            exact = nodes.filter(object_id=request.query)
            if exact.exists():
                nodes = exact
        if position:
            if request.order == "newest":
                nodes = nodes.filter(
                    Q(created_at_value__lt=position[0])
                    | Q(created_at_value=position[0], object_id__gt=position[1])
                )
            else:
                nodes = nodes.filter(
                    Q(kind__gt=position[0]) | Q(kind=position[0], object_id__gt=position[1])
                )
        page = []
        for batch in context_graph.chunks(nodes):
            candidates = {"nodes": [identity(node) for node in batch]}
            if assignment is not None:
                candidates = research_evidence.visible(assignment, candidates)
            records = {context_graph.reference(node): node for node in batch}
            for candidate in candidates["nodes"]:
                node = records[candidate["reference"]]
                if research_evidence.matches_context_search(candidate, request.query):
                    key = (
                        node.created_at_value.isoformat()
                        if request.order == "newest"
                        else node.kind
                    )
                    if request.order == "newest":
                        candidate["created_at"] = node.created_at_value
                    page.append((candidate, [key, node.object_id]))
                    if len(page) > request.limit:
                        break
            if len(page) > request.limit:
                break
        more = len(page) > request.limit
        page = page[: request.limit]
        result = {
            "graph": graph,
            "nodes": [node for node, _ in page],
            "next_cursor": encode_cursor(project, request, page[-1][1]) if more else None,
        }
        result["search_receipt"] = signing.dumps(
            search_page_identity(project, request, result), salt="context-search-page"
        )
        return result
    if request.operation != "traverse":
        raise InputValidationError("Unsupported context graph operation")
    roots = context_graph.resolve(project, [request.reference])
    links = ContextEdge.objects.filter(
        project=project, source__project=project, target__project=project
    )
    incoming = Q(target_id__in=roots)
    outgoing = Q(source_id__in=roots)
    if request.kind:
        incoming &= Q(source__kind=request.kind)
        outgoing &= Q(target__kind=request.kind)
    links = links.filter(
        incoming
        if request.direction == "incoming"
        else outgoing
        if request.direction == "outgoing"
        else incoming | outgoing
    )
    if request.relationship:
        links = links.filter(relationship=request.relationship)
    upper = position[1] if position else links.aggregate(last=Max("pk"))["last"]
    if position:
        links = links.filter(pk__gt=position[0])
    page = (
        list(
            links.filter(pk__lte=upper)
            .select_related("source", "target")
            .defer("source__facts", "target__facts")
            .order_by("pk")[: request.limit + 1]
        )
        if upper
        else []
    )
    more = len(page) > request.limit
    page = page[: request.limit]
    nodes = {
        context_graph.reference(node): identity(node)
        for link in page
        for node in (link.source, link.target)
    }
    result = {
        "graph": graph,
        "nodes": list(nodes.values()),
        "edges": [
            {
                "id": link.pk,
                "source": context_graph.reference(link.source),
                "target": context_graph.reference(link.target),
                "relationship": link.relationship,
                "evidence": link.evidence,
            }
            for link in page
        ],
        "next_cursor": encode_cursor(project, request, [page[-1].pk, upper]) if more else None,
    }
    return research_evidence.visible(assignment, result) if assignment is not None else result