Skip to content

The platform for continuously improving AI agents.

42.7 KB
Raw Blame
import hashlib
import json
import math
import re
from dataclasses import dataclass
from datetime import datetime
from functools import cached_property

from django.apps import apps
from django.core.exceptions import ValidationError
from django.core.serializers.json import DjangoJSONEncoder
from django.db import connection, transaction
from django.db.models import DateTimeField, F, Q
from django.utils import timezone

from overbae.core.errors import InputValidationError
from overbae.models import (
    ContextEdge,
    ContextGraph,
    ContextNode,
    ContextSnapshot,
    DataPartitionMember,
    NativeEvaluationPlan,
    Project,
    ResearchAgent,
    ResearchAssignment,
    ResearchExperiment,
)
from overbae.services import training_plans


@dataclass(frozen=True)
class Source:
    model: str
    kind: str
    scope: str
    fields: str
    exposure: str = "metadata"

    @cached_property
    def field_names(self):
        names = self.fields.split()
        model = apps.get_model("overbae", self.model)
        if "created_at" not in names and any(
            field.name == "created_at" and isinstance(field, DateTimeField)
            for field in model._meta.concrete_fields
        ):
            names.append("created_at")
        return names


SOURCES = (
    Source(
        "ConnectorSyncRun",
        "connector_sync",
        "credential__project",
        "credential_id config_version mode status traces_seen spans_created error started_at finished_at",
    ),
    Source(
        "DecisionPerformanceRun",
        "serving_performance",
        "project",
        "name evaluation_id state results error created_at updated_at",
    ),
    Source(
        "InferenceRequest",
        "inference_request",
        "project",
        "deployment_id state error_code created_at completed_at",
    ),
    Source(
        "ComponentExecution",
        "component_execution",
        "action__agent__assignment__project",
        "state receipt outputs error expires_at created_at completed_at",
    ),
    Source(
        "ExperimentAsset",
        "experiment_asset",
        "project",
        "kind name definition fingerprint parent_id created_at",
    ),
    Source(
        "PredictionSet",
        "prediction_set",
        "project",
        "fingerprint request_key state created_at completed_at",
    ),
    Source(
        "PredictionRow",
        "prediction_row",
        "prediction_set__project",
        "index input_digest state usage error",
    ),
    Source(
        "PredictionAttempt",
        "prediction_attempt",
        "row__prediction_set__project",
        "state receipt usage error started_at expires_at completed_at",
    ),
    Source(
        "PredictionEvaluation",
        "prediction_evaluation",
        "run__project",
        "fingerprint request_key created_at",
    ),
    Source("Project", "agent", "pk", "name slug integration_type"),
    Source(
        "Capability",
        "capability",
        "project",
        "name description source_path entrypoint_fn model status input_schema output_schema output_fields tool_config policy_markdown tools_summary decision_logic",
    ),
    Source(
        "Prompt",
        "prompt",
        "capability__project",
        "label version system_prompt tools_json model full_capability_code",
    ),
    Source("Conversation", "conversation", "project", "name external_id"),
    Source(
        "Span",
        "span",
        "project",
        "name span_type operation trace_id parent_span_id start_time_ns end_time_ns duration_ns status_code service_name usage eval_attributes",
    ),
    Source("SignalEvent", "signal", "project", "signal_type trace_id occurred_at"),
    Source("Dataset", "dataset", "project", "name brief source_kind intent state"),
    Source(
        "Cell",
        "cell",
        "dataset__project",
        "title position state fingerprint input_fingerprint columns rows stats intent_report used_at",
    ),
    Source(
        "DatasetContext",
        "data_profile",
        "dataset__project",
        "task_type task_type_source sample_count extracted_at",
    ),
    Source(
        "DatasetPipeline", "transformation", "project", "name family revision fingerprint steps"
    ),
    Source(
        "DatasetPipelinePackage",
        "transformation_package",
        "project",
        "sha256 size manifest inventory",
    ),
    Source(
        "DatasetPipelineRun",
        "transformation_run",
        "dataset__project",
        "fingerprint source_fingerprint artifact_fingerprint state mode",
    ),
    Source(
        "DatasetPipelineBinding", "source_binding", "project", "fingerprint version trigger enabled"
    ),
    Source("DataPartitionPlan", "partition", "project", "name source_fingerprint recipe state"),
    Source("DataPartitionMember", "partition_member", "plan__project", "role"),
    Source(
        "TrainingPlan",
        "training_plan",
        "project",
        "name specification bindings design_identity state",
    ),
    Source(
        "TrainingPreparation",
        "training_preparation",
        "cell__dataset__project",
        "signature config state report",
    ),
    Source("TrainingExperiment", "training_experiment", "project", "name purpose state variants"),
    Source(
        "TrainingCampaign",
        "training_campaign",
        "project",
        "arguments max_trials state summary created_at completed_at",
    ),
    Source(
        "ResearchExperiment",
        "experiment",
        "project",
        "name objective version created_at updated_at",
    ),
    Source(
        "ResearchExperimentRevision",
        "experiment_revision",
        "experiment__project",
        "number fingerprint document note created_at",
    ),
    Source(
        "ResearchAssignment",
        "research_assignment",
        "project",
        "state specification created_at completed_at",
    ),
    Source(
        "ExperimentExecution",
        "flow_execution",
        "assignment__project",
        "fingerprint engine_version parameters created_at",
    ),
    Source("ExperimentScope", "flow_scope", "execution__assignment__project", "index state error"),
    Source(
        "ExperimentNodeExecution",
        "node_execution",
        "execution__assignment__project",
        "node identity attempt state inputs outputs error started_at completed_at",
    ),
    Source(
        "ResearchAction",
        "research_action",
        "agent__assignment__project",
        "tool state experiment_node error cost_usd created_at completed_at",
    ),
    Source(
        "ResearchAgent",
        "research_agent",
        "assignment__project",
        "task role work_order state notes created_at completed_at",
    ),
    Source(
        "ResearchArtifact",
        "research_artifact",
        "assignment__project",
        "kind title sha256 size metadata created_at",
    ),
    Source("TrainingTrial", "training_trial", "campaign__project", "index recipe reason"),
    Source(
        "FinetuningJob",
        "training_run",
        "project",
        "name use_case group_id base_model baseline_model provider status requested_configuration effective_configuration hyperparameters output_model_name cost_usd started_at completed_at",
    ),
    Source(
        "TrainingCheckpoint",
        "checkpoint",
        "job__project",
        "key attempt step state identity manifest verification metrics selected",
    ),
    Source(
        "TrainingControl",
        "training_control",
        "job__project",
        "operation arguments step author reason state result resolved_at",
    ),
    Source(
        "TrainingReview",
        "training_review",
        "job__project",
        "decision reason state summary evidence completed_at",
    ),
    Source(
        "TrainingValidationRun",
        "training_validation",
        "job__project",
        "key attempt stream step state policy_fingerprint sample_fingerprint receipt_fingerprint metrics coverage observed_at",
    ),
    Source("EvalMatrix", "evaluator", "project", "name type source span_type span_name enabled"),
    Source("EvalSet", "evaluation_set", "project", "name description"),
    Source(
        "EvalRun",
        "evaluation_run",
        "project",
        "name description judge_model model_name is_baseline status summary completed_at",
        "evaluation",
    ),
    Source(
        "EvalScore",
        "evaluation_score",
        "project",
        "source_type source_id score metrics",
        "evaluation",
    ),
    Source(
        "NativeEvaluationPlan", "native_evaluation", "project", "name state config", "evaluation"
    ),
    Source("ModelRef", "model", "project", "label provider model_id"),
    Source(
        "DeployedModel",
        "deployment",
        "project",
        "model_id inference_contract status base_model_id gpu_type is_lora lora_rank checkpoint_hash max_model_len quantization serving_runtime",
    ),
    Source(
        "ModelActivation",
        "activation",
        "capability__project",
        "generation stage started_at completed_at",
    ),
    Source(
        "InferenceCall",
        "inference",
        "project",
        "prompt_tokens completion_tokens cost tokens_per_second latency_ms end_to_end_ms is_cold outcome requested_model created_at",
    ),
)
BY_KIND = {source.kind: source for source in SOURCES}
BY_MODEL = {source.model.lower(): source for source in SOURCES}
# Recorded telemetry: too many records to follow from an agent's view of the project.
TELEMETRY = frozenset({"span", "conversation", "signal", "inference", "evaluation_score"})
PRIVATE_KEY = re.compile(
    r"(^|[_\-.])(password|secret|credential|authorization|cookie|api_key|access_token|refresh_token|private_key)([_\-.]|$)",
    re.I,
)


def canonical(value):
    try:
        return json.dumps(
            value, cls=DjangoJSONEncoder, sort_keys=True, separators=(",", ":"), allow_nan=False
        )
    except ValueError as exc:
        # A JSON body may spell infinity as 1e999; no identity or stored record can hold it.
        raise InputValidationError("Numbers must be finite") from exc


def require_storable(value):
    """jsonb refuses a NUL in text and stores a non-finite number as null."""
    if isinstance(value, str) and "\x00" in value:
        raise InputValidationError("Text cannot contain the NUL character")
    if isinstance(value, float) and not math.isfinite(value):
        raise InputValidationError("Numbers must be finite")
    if isinstance(value, dict):
        for key, item in value.items():
            require_storable(key)
            require_storable(item)
    if isinstance(value, list):
        for item in value:
            require_storable(item)


def source_matches(value, files, manifest):
    if value.get("fingerprint") != fingerprint({"files": files, "manifest": manifest}):
        return False
    for key, expected in (("files", files), ("manifest", manifest)):
        if key in value and value[key] != expected:
            return False
    page = value.get("file")
    if page is not None:
        text = files.get(page.get("path")) if isinstance(page, dict) else None
        if (
            not isinstance(text, str)
            or type(page.get("offset")) is not int
            or page["offset"] < 0
            or not isinstance(page.get("content"), str)
            or page.get("total") != len(text)
            or text[page["offset"] : page["offset"] + len(page["content"])] != page["content"]
        ):
            return False
    return "inventory" not in value or value["inventory"] == [
        {
            "path": path,
            "characters": len(text),
            "sha256": hashlib.sha256(text.encode()).hexdigest(),
        }
        for path, text in sorted(files.items())
    ]


def fingerprint(value):
    return hashlib.sha256(canonical(value).encode()).hexdigest()


def public_facts(value):
    if isinstance(value, dict):
        return {
            key: public_facts(item) for key, item in value.items() if not PRIVATE_KEY.search(key)
        }
    if isinstance(value, list):
        return [public_facts(item) for item in value]
    return value


def reference(node):
    return f"{node.kind}:{node.object_id}"


def snapshot_receipt(snapshot):
    return {
        "id": str(snapshot.pk),
        "project": str(snapshot.project_id),
        "purpose": snapshot.purpose,
        "fingerprint": snapshot.fingerprint,
        "roots": snapshot.roots,
        "created_at": snapshot.created_at,
        "resource": {
            "uri": f"overmind://context/snapshots/{snapshot.pk}?project_id={snapshot.project_id}",
            "title": "Retained context snapshot",
            "mimeType": "application/json",
        },
    }


def source_rows(source, project):
    model = apps.get_model("overbae", source.model)
    fields = [model._meta.pk.attname, *source.field_names]
    relations = [
        field
        for field in model._meta.concrete_fields
        if field.is_relation and field.related_model._meta.model_name in BY_MODEL
    ]
    fields.extend(field.attname for field in relations)
    query = model.objects.filter(**{source.scope: project.pk})
    if source.kind == "capability":
        query = query.exclude(status="deleted")
    if source.kind == "native_evaluation":
        query = query.filter(deleted_at__isnull=True)
    if source.kind == "research_action":
        query = query.exclude(tool__in=["model", "explore_context", "inspect_action", "history"])
        query = query.annotate(error=F("result__error"))
    return model, relations, query.order_by(model._meta.pk.name).values(*fields)


def chunks(query, size=100):
    batch = []
    for item in query.iterator(chunk_size=size):
        batch.append(item)
        if len(batch) == size:
            yield batch
            batch = []
    if batch:
        yield batch


def binding_references(value):
    result = []
    if isinstance(value, list):
        for item in value:
            result.extend(binding_references(item))
    elif isinstance(value, dict):
        for key, kind in {
            "cell": "cell",
            "data": "cell",
            "campaign": "training_campaign",
            "job": "training_run",
            "evaluation": "native_evaluation",
            "artifact": "research_artifact",
            "deployment": "deployment",
            "partition": "partition",
            "sync": "connector_sync",
            "inference": "inference_request",
            "performance": "serving_performance",
        }.items():
            if isinstance(value.get(key), str):
                result.append(
                    {"reference": f"{kind}:{value[key]}", "fingerprint": value.get("fingerprint")}
                )
        for item in value.values():
            if isinstance(item, (dict, list)):
                result.extend(binding_references(item))
    return list({canonical(item): item for item in result}.values())


JSON_RELATION_FIELDS = {
    "node_execution": ("inputs", "outputs"),
    "training_campaign": ("arguments",),
}
# The start_finetune argument that names each cell a campaign trains or checks on.
CAMPAIGN_CELLS = {"cell": "train", "validation_cell": "development", "eval_cell": "evaluation"}


def record_links(kind, row):
    if kind == "training_campaign":
        arguments = row.get("arguments") or {}
        return [
            {"reference": f"cell:{arguments[key]}", "relationship": role}
            for key, role in CAMPAIGN_CELLS.items()
            if isinstance(arguments.get(key), str)
        ]
    if kind == "node_execution":
        return [
            {**binding, "relationship": "consumes" if direction == "inputs" else "produces"}
            for direction in JSON_RELATION_FIELDS[kind]
            for binding in binding_references(row.get(direction))
        ]
    return []


def json_neighbors(project, references, *, incoming=True, outgoing=True, kind=None):
    wanted = {f"{source}:{identity}" for source, identity in references}
    found = {}
    for source, fields in JSON_RELATION_FIELDS.items():
        _, _, rows = source_rows(BY_KIND[source], project)
        for row in rows.values("pk", *fields).iterator():
            origin = f"{source}:{row['pk']}"
            for link in record_links(source, row):
                target, identity = link["reference"].split(":", 1)
                if outgoing and origin in wanted and (kind is None or target == kind):
                    found.setdefault(target, set()).add(identity)
                if incoming and link["reference"] in wanted and (kind is None or source == kind):
                    found.setdefault(source, set()).add(str(row["pk"]))
    return found


def sealed(project, additional=()):
    """Every cell of the project whose rows are held out, as strings."""
    return (
        set(map(str, additional))
        | {
            str(cell)
            for spec in ResearchAssignment.objects.filter(project=project).values_list(
                "specification", flat=True
            )
            for cell in spec.get("sealed_cells", [])
        }
        | {
            str(value)
            for value in DataPartitionMember.objects.filter(
                plan__project=project, role="final"
            ).values_list("cell_id", flat=True)
        }
        | {
            str(value)
            for value in NativeEvaluationPlan.objects.filter(project=project)
            .exclude(config__purpose="development", config__purpose__isnull=False)
            .values_list("final_cell_id", flat=True)
        }
    )


def hold_project(project):
    """Every write to the graph adds rows that reference the project, and each takes a
    key-share lock on the project's row. A work-starting operation locks that row first and
    reads the graph after. Taken in the other order here, with the graph's lock already held,
    the two wait on each other and one is aborted; so the project's row comes first here too."""
    with connection.cursor() as cursor:
        cursor.execute(
            f"SELECT 1 FROM {Project._meta.db_table} WHERE id = %s FOR KEY SHARE", [project.pk]
        )


def final_assignments(project):
    frozen = [
        str(key)
        for key in ResearchExperiment.objects.filter(project=project)
        .exclude(scientific_lock={})
        .values_list("pk", flat=True)
    ]
    return ResearchAssignment.objects.filter(project=project).filter(
        Q(result__has_key="selection_locked")
        | Q(experiment_revision__experiment_id__in=frozen)
        | Q(execution_mandate__experiment__in=frozen)
    )


@transaction.atomic
def refresh(project, *, kinds=None, additional_sealed_cells=(), object_ids=None):
    hold_project(project)
    ContextGraph.objects.get_or_create(project=project)
    graph = ContextGraph.objects.select_for_update().get(project=project)
    generation = graph.generation + 1
    started = timezone.now()
    sealed_cells = sealed(project, additional_sealed_cells)
    final_owners = set(final_assignments(project).values_list("pk", flat=True))
    final_experiments = set(
        ResearchExperiment.objects.filter(project=project)
        .exclude(scientific_lock={})
        .values_list("pk", flat=True)
    )
    if kinds is not None and set(kinds) - BY_KIND.keys():
        raise InputValidationError("Unknown context source kind")
    sources = [source for source in SOURCES if kinds is None or source.kind in kinds]
    coverage = dict(graph.coverage)
    for source in sources:
        model, relations, query = source_rows(source, project)
        if object_ids is not None:
            query = query.filter(pk__in=object_ids.get(source.kind, ()))
        count = 0
        for batch in chunks(query):
            nodes = []
            for row in batch:
                object_id = str(row[model._meta.pk.attname])
                facts = public_facts({name: row[name] for name in source.field_names})
                if isinstance(facts.get("created_at"), datetime):
                    # Ordering must retain microseconds that DjangoJSONEncoder truncates.
                    facts["created_at"] = facts["created_at"].isoformat()
                if source.kind == "training_plan":
                    facts["bindings"] = training_plans.public_bindings(facts["bindings"])
                if source.kind == "node_execution":
                    facts["inputs"] = binding_references(facts["inputs"])
                    facts["outputs"] = binding_references(facts["outputs"])
                facts = json.loads(canonical(facts))
                identities = {
                    field.name: str(row[field.attname]) if row[field.attname] is not None else None
                    for field in relations
                }
                exposure = (
                    "final_data"
                    if (source.kind == "cell" and object_id in sealed_cells)
                    or (
                        source.kind == "research_artifact"
                        and facts.get("metadata", {}).get("access") == "final_data"
                    )
                    else source.exposure
                )
                if (
                    source.kind == "research_artifact"
                    and (
                        facts.get("metadata", {}).get("phase") == "final"
                        or facts.get("metadata", {}).get("access") == "final_results"
                        or row.get("assignment_id") in final_owners
                    )
                    or source.kind == "research_agent"
                    and row.get("assignment_id") in final_owners
                    or source.kind == "research_assignment"
                    and row[model._meta.pk.attname] in final_owners
                    or source.kind == "experiment_revision"
                    and row.get("experiment_id") in final_experiments
                    or source.kind == "experiment"
                    and row[model._meta.pk.attname] in final_experiments
                ):
                    exposure = "final_results"
                presentation = facts
                if source.kind == "training_campaign":
                    presentation = {**facts, "name": (facts.get("arguments") or {}).get("name")}
                label = next(
                    (
                        presentation[name]
                        for name in (
                            "name",
                            "title",
                            "label",
                            "model_id",
                            "key",
                            "node",
                            "task",
                            "hypothesis",
                            "objective",
                            "tool",
                        )
                        if presentation.get(name)
                    ),
                    f"{source.kind} {object_id}",
                )
                nodes.append(
                    ContextNode(
                        project=project,
                        kind=source.kind,
                        object_id=object_id,
                        label=str(label)[:512],
                        facts=facts,
                        fingerprint=fingerprint(
                            {"facts": facts, "relations": identities, "exposure": exposure}
                        ),
                        exposure=exposure,
                        generation=generation,
                        observed_at=timezone.now(),
                    )
                )
            ContextNode.objects.bulk_create(
                nodes,
                update_conflicts=True,
                unique_fields=["project", "kind", "object_id"],
                update_fields=[
                    "label",
                    "facts",
                    "fingerprint",
                    "exposure",
                    "generation",
                    "observed_at",
                ],
            )
            count += len(nodes)
        coverage[source.kind] = count
    for source in sources:
        model, relations, query = source_rows(source, project)
        if object_ids is not None:
            query = query.filter(pk__in=object_ids.get(source.kind, ()))
        fields = [model._meta.pk.attname, *(field.attname for field in relations)]
        if source.kind == "span":
            fields.append("parent_span_id")
        elif source.kind == "training_run":
            fields.append("group_id")
        elif source.kind == "evaluation_score":
            fields.extend(["source_type", "source_id"])
        fields.extend(JSON_RELATION_FIELDS.get(source.kind, ()))
        query = query.values(*fields)
        for batch in chunks(query):
            requests = []
            for row in batch:
                origin = (source.kind, str(row[model._meta.pk.attname]))
                for field in relations:
                    if row[field.attname] is not None:
                        target = BY_MODEL[field.related_model._meta.model_name]
                        requests.append(
                            (origin, (target.kind, str(row[field.attname])), field.name)
                        )
                if source.kind == "span" and row["parent_span_id"]:
                    requests.append((origin, ("span", row["parent_span_id"]), "parent"))
                if source.kind == "training_run" and row["group_id"]:
                    requests.append(
                        (origin, ("training_experiment", str(row["group_id"])), "experiment")
                    )
                if source.kind == "evaluation_score" and row["source_type"] == "span":
                    requests.append((origin, ("span", row["source_id"]), "scored"))
                for binding in record_links(source.kind, row):
                    kind, identity = binding["reference"].split(":", 1)
                    requests.append((origin, (kind, identity), binding["relationship"]))
            identities = {item for origin, target, _ in requests for item in (origin, target)}
            nodes = {
                (node.kind, node.object_id): node.pk
                for node in ContextNode.objects.filter(
                    project=project,
                    object_id__in={item[1] for item in identities},
                ).only("kind", "object_id", "id")
            }
            edges = {
                (nodes[origin], nodes[target], relation)
                for origin, target, relation in requests
                if origin in nodes and target in nodes
            }
            ContextEdge.objects.bulk_create(
                [
                    ContextEdge(
                        project=project,
                        source_id=origin,
                        target_id=target,
                        relationship=relation,
                        generation=generation,
                    )
                    for origin, target, relation in edges
                ],
                update_conflicts=True,
                unique_fields=["source", "target", "relationship"],
                update_fields=["generation"],
            )
    for source in sources:
        nodes = ContextNode.objects.filter(project=project, kind=source.kind)
        if object_ids is not None:
            nodes = nodes.filter(object_id__in=object_ids.get(source.kind, ()))
        ContextEdge.objects.filter(project=project, source__in=nodes).exclude(
            generation=generation
        ).delete()
        nodes.exclude(generation=generation).delete()
        coverage[source.kind] = ContextNode.objects.filter(
            project=project, kind=source.kind
        ).count()
    graph.generation = generation
    graph.coverage = coverage
    graph.started_at = started
    graph.completed_at = timezone.now()
    graph.save()
    return describe(project)


def refresh_operational(project, *, additional_sealed_cells=()):
    return refresh(
        project,
        additional_sealed_cells=additional_sealed_cells,
        kinds=[source.kind for source in SOURCES if source.kind not in TELEMETRY],
    )


def adjacent(project, references):
    """What is one relationship away from these objects, by kind.

    Read from the source tables, so a relationship the graph has not indexed yet is found, and
    from the graph's own edges, so one that has since been removed is looked at again.
    """
    found = {}
    grouped = {}
    for kind, identity in references:
        grouped.setdefault(kind, set()).add(identity)
    for kind, identities in grouped.items():
        known = ContextNode.objects.filter(project=project, kind=kind, object_id__in=identities)
        for link in (
            ContextEdge.objects.filter(project=project)
            .filter(Q(source__in=known) | Q(target__in=known))
            .values_list("source__kind", "source__object_id", "target__kind", "target__object_id")
        ):
            found.setdefault(link[0], set()).add(link[1])
            found.setdefault(link[2], set()).add(link[3])
        model, relations, rows = source_rows(BY_KIND[kind], project)
        bound = JSON_RELATION_FIELDS.get(kind, ())
        for row in rows.filter(pk__in=identities).values(
            *(field.attname for field in relations), *bound
        ):
            for field in relations:
                if row[field.attname] is not None:
                    target = BY_MODEL[field.related_model._meta.model_name].kind
                    found.setdefault(target, set()).add(str(row[field.attname]))
            for binding in record_links(kind, row):
                target, _, identity = binding["reference"].partition(":")
                found.setdefault(target, set()).add(identity)
        for candidate in SOURCES:
            if candidate.kind in TELEMETRY:
                continue
            candidate_model, fields, candidates = source_rows(candidate, project)
            condition = Q()
            for field in fields:
                if field.related_model is model:
                    condition |= Q(**{f"{field.attname}__in": identities})
            if condition:
                found.setdefault(candidate.kind, set()).update(
                    map(
                        str,
                        candidates.filter(condition).values_list(
                            candidate_model._meta.pk.name, flat=True
                        ),
                    )
                )
    for kind, identities in json_neighbors(project, references, outgoing=False).items():
        found.setdefault(kind, set()).update(identities)
    return {
        kind: identities
        for kind, identities in found.items()
        if kind in BY_KIND and kind not in TELEMETRY
    }


def observe(project, *, roots, depth=2, additional_sealed_cells=()):
    """Bring what a capture of these roots reads up to date without rebuilding the project.

    A full refresh reads every record of the project, so its cost grows with the project and
    not with the request. The periodic refresh keeps the rest of the graph current.
    """
    graph = ContextGraph.objects.filter(project=project).first()
    if graph is None or not graph.completed_at:
        return refresh_operational(project, additional_sealed_cells=additional_sealed_cells)
    # Held-out rows are hidden by a cell's exposure: that is made exact for every cell first.
    held = sealed(project, additional_sealed_cells)
    recorded = dict(
        ContextNode.objects.filter(project=project, kind="cell").values_list(
            "object_id", "exposure"
        )
    )
    cells = BY_KIND["cell"]
    current = set(
        map(
            str,
            apps.get_model("overbae", cells.model)
            .objects.filter(**{cells.scope: project.pk})
            .values_list("pk", flat=True),
        )
    )
    changed = {
        identity
        for identity in current | recorded.keys()
        if recorded.get(identity) is None
        or identity not in current
        or (recorded[identity] == "final_data") != (identity in held)
    }
    frontier = {
        (kind, identity)
        for kind, separator, identity in (root.partition(":") for root in roots)
        if separator and kind in BY_KIND
    }
    selected = {"cell": changed} if changed else {}
    for kind, identity in frontier:
        selected.setdefault(kind, set()).add(identity)
    seen = set(frontier)
    try:
        for remaining in range(depth, -1, -1):
            refresh(
                project,
                kinds=list(selected),
                object_ids=selected,
                additional_sealed_cells=additional_sealed_cells,
            )
            if not remaining:
                break
            # A capture does not walk on from the project's own node either.
            found = adjacent(project, [item for item in frontier if item[0] != "agent"])
            ring = {
                (kind, identity) for kind, identities in found.items() for identity in identities
            } - seen
            # A capture refuses a view this large, so nothing further would be read.
            if not ring or len(seen) + len(ring) > 2000:
                break
            # Refreshed together with the records that lead to them: a relationship is only
            # kept once both of its ends are in the graph.
            selected = {}
            for kind, identity in frontier | ring:
                selected.setdefault(kind, set()).add(identity)
            seen |= ring
            frontier = ring
    except (ValueError, ValidationError):
        raise InputValidationError("A context reference is unavailable in this project") from None
    return describe(project)


def describe(project):
    graph = ContextGraph.objects.filter(project=project).first()
    return {
        "project": str(project.pk),
        "generation": graph.generation if graph else 0,
        "coverage": graph.coverage if graph else {},
        "started_at": graph.started_at if graph else None,
        "completed_at": graph.completed_at if graph else None,
        "nodes": ContextNode.objects.filter(project=project).count(),
        "edges": ContextEdge.objects.filter(project=project).count(),
    }


def agent_publication(node, *, include_notes=False):
    if node.kind != "research_agent":
        return None
    # Research context reads use the same authoring receipt as the native helper packet.
    from overbae.services import research_notes

    agent = (
        ResearchAgent.objects.select_related("assignment")
        .filter(pk=node.object_id, assignment__project_id=node.project_id)
        .first()
    )
    if agent is None:
        return None
    publication = research_notes.project_delegation(
        agent.assignment,
        {
            "task": node.facts.get("task", ""),
            "work_order": node.facts.get("work_order", {}),
            "delegation_provenance": research_notes.delegation(agent),
        },
    )
    if include_notes:
        note = research_notes.context_record(agent)
        publication.update(
            notes=note["text"],
            notes_provenance={key: value for key, value in note.items() if key != "text"},
            context_delegation=research_notes.context_delegation(agent),
        )
    return publication


def node_payload(node, purpose):
    facts = node.facts
    if purpose in {"training", "workshop"} and (
        authored := agent_publication(node, include_notes=True)
    ):
        facts = {**facts, **authored}
    if node.kind == "training_plan":
        facts = {**facts, "bindings": training_plans.public_bindings(facts.get("bindings", {}))}
    if purpose in {"training", "workshop"} and node.exposure in {
        "evaluation",
        "final_data",
        "final_results",
    }:
        facts = {
            key: value
            for key, value in facts.items()
            if key
            in {
                "state",
                "status",
                "is_baseline",
                "source_type",
                "fingerprint",
            }
        }
    return {**node_metadata(node, purpose=purpose), "facts": facts}


def node_metadata(node, *, purpose="inspection"):
    authored = agent_publication(node) if purpose in {"training", "workshop"} else None
    return {
        "reference": reference(node),
        "label": node.kind
        if purpose in {"training", "workshop"}
        and (
            node.exposure in {"evaluation", "final_data", "final_results"}
            or authored
            and authored.get("access") == "sealed_data"
        )
        else node.label,
        "fingerprint": node.fingerprint,
        "exposure": node.exposure,
        "observed_at": node.observed_at,
        "source": {"model": BY_KIND[node.kind].model, "id": node.object_id},
        "authority": "agent_report"
        if node.kind
        in {"research_agent", "research_artifact", "experiment_revision", "training_investigation"}
        else "recorded",
    }


def inspect(project, *, roots=None, kind=None, query="", offset=0, limit=100, purpose="inspection"):
    if purpose not in {"inspection", "training", "workshop"}:
        raise InputValidationError("Unknown context purpose")
    if kind and kind not in BY_KIND:
        raise InputValidationError("Unknown context kind")
    if offset < 0 or not 1 <= limit <= 500:
        raise InputValidationError("Use a nonnegative offset and a limit between 1 and 500")
    nodes = ContextNode.objects.filter(project=project).order_by("kind", "object_id")
    if kind:
        nodes = nodes.filter(kind=kind)
    if query:
        nodes = nodes.filter(label__icontains=query)
    if roots:
        root_ids = resolve(project, roots)
        edges = ContextEdge.objects.filter(project=project).filter(
            Q(source_id__in=root_ids) | Q(target_id__in=root_ids)
        )
        ids = (
            root_ids
            | set(edges.values_list("source_id", flat=True))
            | set(edges.values_list("target_id", flat=True))
        )
        nodes = nodes.filter(pk__in=ids)
    total = nodes.count()
    page = list(nodes[offset : offset + limit])
    ids = {node.pk for node in page}
    edges = (
        ContextEdge.objects.filter(project=project, source_id__in=ids, target_id__in=ids)
        .select_related("source", "target")
        .defer("source__facts", "target__facts")
        .order_by("source_id", "target_id", "relationship")
    )
    return {
        "graph": describe(project),
        "nodes": [node_payload(node, purpose) for node in page],
        "edges": [
            {
                "source": reference(edge.source),
                "target": reference(edge.target),
                "relationship": edge.relationship,
                "evidence": edge.evidence,
            }
            for edge in edges
        ],
        "total": total,
        "next_offset": offset + limit if offset + limit < total else None,
    }


def resolve(project, roots):
    ids = set()
    for root in roots:
        kind, separator, object_id = root.partition(":")
        if not separator or kind not in BY_KIND:
            raise InputValidationError("Use typed context references returned by the graph")
        node = ContextNode.objects.filter(project=project, kind=kind, object_id=object_id).first()
        if node is None:
            raise InputValidationError("A context reference is unavailable in this project")
        ids.add(node.pk)
    return ids


def changes(snapshot):
    current = {
        reference(node): node.fingerprint
        for node in ContextNode.objects.filter(project_id=snapshot.project_id).only(
            "kind", "object_id", "fingerprint"
        )
    }
    return [
        {
            "reference": node["reference"],
            "state": "changed" if node["reference"] in current else "removed",
        }
        for node in snapshot.manifest["nodes"]
        if current.get(node["reference"]) != node["fingerprint"]
    ]


@transaction.atomic
def capture(project, *, roots, purpose, request_key, depth=2):
    if (
        not roots
        or len(roots) > 32
        or purpose not in {"training", "workshop", "inspection"}
        or not 0 <= depth <= 4
    ):
        raise InputValidationError("Select 1–32 context roots, a supported purpose and depth 0–4")
    if not request_key or len(request_key) > 128:
        raise InputValidationError("Supply a context request key of at most 128 characters")
    request = fingerprint({"roots": sorted(set(roots)), "purpose": purpose, "depth": depth})
    hold_project(project)
    graph = ContextGraph.objects.select_for_update().filter(project=project).first()
    if not graph or not graph.completed_at:
        raise InputValidationError("Populate the project context graph first")
    previous = ContextSnapshot.objects.filter(project=project, request_key=request_key).first()
    if previous:
        if previous.request_fingerprint != request:
            raise InputValidationError("This request key identifies a different context capture")
        return previous
    selected = frontier = resolve(project, roots)
    excluded = set(TELEMETRY) if purpose != "inspection" else set()
    for _ in range(depth):
        traversable = (
            ContextNode.objects.filter(pk__in=frontier, project=project)
            .exclude(kind="agent")
            .values_list("pk", flat=True)
        )
        links = (
            ContextEdge.objects.filter(project=project)
            .filter(Q(source_id__in=traversable) | Q(target_id__in=traversable))
            .exclude(source__kind__in=excluded)
            .exclude(target__kind__in=excluded)
        )
        adjacent = set(links.values_list("source_id", flat=True)) | set(
            links.values_list("target_id", flat=True)
        )
        frontier = adjacent - selected
        selected = selected | adjacent
        if len(selected) > 2000:
            raise InputValidationError(
                "This view exceeds 2000 entities; use narrower roots or depth"
            )
    nodes = list(
        ContextNode.objects.filter(project=project, pk__in=selected).order_by("kind", "object_id")
    )
    links = (
        ContextEdge.objects.filter(project=project, source_id__in=selected, target_id__in=selected)
        .select_related("source", "target")
        .defer("source__facts", "target__facts")
        .order_by(
            "source__kind", "source__object_id", "target__kind", "target__object_id", "relationship"
        )
    )
    manifest = json.loads(
        canonical(
            {
                "project": str(project.pk),
                "generation": graph.generation,
                "observation_window": {
                    "started_at": graph.started_at,
                    "completed_at": graph.completed_at,
                },
                "purpose": purpose,
                "excluded_detail_kinds": sorted(excluded),
                "project_coverage": graph.coverage,
                "roots": sorted(set(roots)),
                "nodes": [node_payload(node, purpose) for node in nodes],
                "edges": [
                    {
                        "source": reference(edge.source),
                        "target": reference(edge.target),
                        "relationship": edge.relationship,
                        "evidence": edge.evidence,
                    }
                    for edge in links
                ],
            }
        )
    )
    return ContextSnapshot.objects.create(
        project=project,
        request_key=request_key,
        request_fingerprint=request,
        purpose=purpose,
        roots=sorted(set(roots)),
        manifest=manifest,
        fingerprint=fingerprint(manifest),
    )