Skip to content

The platform for continuously improving AI agents.

21.3 KB
Raw Blame
import hashlib
import json
import math
import re
from collections import Counter

from django.utils import timezone

from overbae.services.datasets.examples import decode, missing

VERSION = 3
FAMILY_LIMIT = 8
OPTION_LIMIT = 32
FIELD_LIMIT = 100
# An input value is evidence about the label once five rows share it; one input that gives
# the label on 99% of those rows, when they are half the family, nearly determines it.
SHARED_ROWS = 5
DETERMINED_SHARE = 0.99
COVERED_SHARE = 0.5
# Distinct values counted per input and family; an input with more is not assessed.
VALUE_LIMIT = 1_000
# An input names the label when, on 98% of at least 50 judged rows, its text holds a word
# of the row's own option and none of another option's.
NAMED_SHARE = 0.98
NAMED_ROWS = 50
WORD = re.compile(r"[a-z]{4,}")


def digest(value):
    return hashlib.sha256(json.dumps(value, sort_keys=True, default=str).encode()).hexdigest()


class Analytics:
    def __init__(self):
        self.rows = self.decisions = self.invalid = self.unlisted = self.unknown = 0
        self.fields = {}
        self.field_overflow = False
        self.input_rows = 0
        self.structured_input_rows = self.weighted_rows = 0
        self.families = {}
        self.keys = {}
        self.leaks = {}

    def observe(self, decision, *, valid):
        self.rows += 1
        if not isinstance(decision, dict):
            return
        self.decisions += 1
        if not valid:
            self.invalid += 1
            return
        self.input_rows += 1
        state = decode(decision["state"])
        values = state if isinstance(state, dict) else {"state": decision["state"]}
        self.structured_input_rows += isinstance(state, dict)
        self.weighted_rows += decision.get("weight", 1.0) != 1.0
        for name, value in values.items():
            key = str(name)
            if key not in self.fields and len(self.fields) >= FIELD_LIMIT:
                self.field_overflow = True
                continue
            field = self.fields.setdefault(key, {"present": 0, "empty": 0, "varies": False})
            field["present"] += 1
            if missing(value):
                field["empty"] += 1
            elif "first" not in field:
                field["first"] = value
            elif not field["varies"]:
                first = field["first"]
                field["varies"] = type(value) is not type(first) or value != first
        semantics = decision.get("target_semantics") or "unknown"
        self.unknown += semantics == "unknown"
        options = decision["options"]
        identity = (decision["question"], decision["kind"], tuple(options), semantics)
        key = self.keys.get(identity)
        if key is None:
            # Only tracked families are cached: a frame of distinct questions stays small.
            if len(options) > OPTION_LIMIT or len(self.families) >= FAMILY_LIMIT:
                self.unlisted += 1
                return
            key = self.keys[identity] = digest(
                [decision["question"], decision["kind"], options, semantics]
            )
        family = self.families.setdefault(
            key,
            {
                "id": key,
                "question": decision["question"][:160],
                "labels": [label[:120] for label in options],
                "labels_truncated": any(len(label) > 120 for label in options),
                "semantics": semantics,
                "rows": 0,
                "weight_sum": 0.0,
                "counts": [0] * len(options) if semantics == "categorical_gold" else None,
                "target_mass": [0.0] * len(options) if "target_probabilities" in decision else None,
                "majority_baseline": None,
            },
        )
        family["rows"] += 1
        weight = decision.get("weight", 1.0)
        family["weight_sum"] += weight
        probabilities = decision.get("target_probabilities")
        if probabilities is not None:
            for index, probability in enumerate(probabilities):
                family["target_mass"][index] += weight * probability
            if family["counts"] is not None:
                label = probabilities.index(1)
                family["counts"][label] += 1
                self._observe_leaks(key, family, label, state)

    def _observe_leaks(self, key, family, label, state):
        leak = self.leaks.get(key)
        if leak is None:
            words = [set(WORD.findall(option.lower())) for option in family["labels"]]
            shared = {w for w, uses in Counter(w for f in words for w in f).items() if uses > 1}
            words = [found - shared for found in words]
            leak = self.leaks[key] = {
                "own": words,
                "others": [set().union(*words[:i], *words[i + 1 :]) for i in range(len(words))],
                "judged": 0,
                "judged_labels": set(),
                "named": Counter(),
                "values": {},
                "unassessed": set(),
            }
        values = state if isinstance(state, dict) else {"state": state}
        own, others = leak["own"][label], leak["others"][label]
        if own:
            leak["judged"] += 1
            leak["judged_labels"].add(label)
            for name, value in values.items():
                if isinstance(value, str) and str(name) in self.fields:
                    found = set(WORD.findall(value.lower()))
                    if found & own and not found & others:
                        leak["named"][str(name)] += 1
        if not isinstance(state, dict):
            return
        for name, value in state.items():
            name = str(name)
            if missing(value) or name in leak["unassessed"] or name not in self.fields:
                continue
            counted = leak["values"].setdefault(name, {})
            text = json.dumps(value, sort_keys=True, default=str)
            identity = text if len(text) <= 64 else hashlib.sha256(text.encode()).hexdigest()
            if identity not in counted and len(counted) >= VALUE_LIMIT:
                leak["unassessed"].add(name)
                del leak["values"][name]
                continue
            counted.setdefault(identity, Counter())[label] += 1

    def _leak_findings(self):
        determined, named, unassessed = [], [], set()
        assessed = judged = False
        for key, leak in self.leaks.items():
            family = self.families[key]
            if sum(1 for count in family["counts"] if count) < 2:
                continue
            unassessed |= leak["unassessed"]
            for name, counted in leak["values"].items():
                assessed = True
                shared = [labels for labels in counted.values() if labels.total() >= SHARED_ROWS]
                covered = sum(labels.total() for labels in shared)
                agreeing = sum(max(labels.values()) for labels in shared)
                if (
                    covered >= COVERED_SHARE * family["rows"]
                    and agreeing >= DETERMINED_SHARE * covered
                ):
                    determined.append(
                        {"family": key, "field": name[:120], "rows": covered, "agreeing": agreeing}
                    )
            if leak["judged"] < NAMED_ROWS or len(leak["judged_labels"]) < 2:
                continue
            judged = True
            for name, count in sorted(leak["named"].items()):
                if count >= NAMED_SHARE * leak["judged"]:
                    named.append(
                        {"family": key, "field": name[:120], "rows": leak["judged"], "named": count}
                    )
        return determined, named, sorted(unassessed), assessed, judged

    def report(self):
        families = [dict(family) for family in self.families.values()]
        gold = [family for family in families if family["counts"] is not None]
        overflow = False
        for family in families:
            if not math.isfinite(family["weight_sum"]):
                family["weight_sum"] = None
                family["target_mass"] = None
                overflow = True
        for family in gold:
            family["majority_baseline"] = max(family["counts"]) / family["rows"]
        imbalanced = [f["id"] for f in gold if min(f["counts"]) / f["rows"] < 0.05]
        rare = [f["id"] for f in gold if min(f["counts"]) < 20]
        absent = [f["id"] for f in gold if 0 in f["counts"]]
        minority_findings = []
        for family in gold:
            if family["id"] in imbalanced:
                count = min(family["counts"])
                label = family["labels"][family["counts"].index(count)]
                minority_findings.append(
                    f"“{label}” accounts for {count:,} of {family['rows']:,} rows ({count / family['rows']:.2%})."
                )
        missing_fields = []
        constants = []
        for name, field in self.fields.items():
            count = self.input_rows - field["present"] + field["empty"]
            if count:
                missing_fields.append({"field": name[:120], "rows": count})
            if "first" in field and not field["varies"]:
                constants.append(name[:120])

        determined, named, unassessed, assessed, judged = self._leak_findings()
        labelled = any(sum(1 for count in f["counts"] if count) > 1 for f in gold)
        unassessed_note = (
            f" {len(unassessed):,} inputs with more than {VALUE_LIMIT:,} distinct values were "
            "not assessed."
            if unassessed
            else ""
        )

        def check(identifier, title, status, summary, metrics=None):
            return {
                "id": identifier,
                "title": title,
                "status": status,
                "summary": summary,
                "metrics": metrics or {},
            }

        checks = [
            check(
                "targets.validity",
                "Target validity",
                "error" if self.invalid else "pass" if self.decisions else "not_applicable",
                f"{self.invalid:,} of {self.decisions:,} decision rows have invalid options or targets; they are excluded from class counts."
                if self.invalid
                else f"All {self.decisions:,} decision rows have valid options and targets."
                if self.decisions
                else "No decision targets were found in these rows.",
                {"invalid_rows": self.invalid},
            ),
            check(
                "targets.class_balance",
                "Class imbalance",
                "warning" if imbalanced else "pass" if gold else "not_applicable",
                " ".join(minority_findings)
                + " Overall accuracy can hide errors on the rare class; compare per-class precision and recall."
                if imbalanced
                else "Every observed class has at least 5% of the rows in its decision family."
                if gold
                else "Class balance needs declared observed labels; probability targets are not counted as labels.",
                {"threshold": 0.05, "families": imbalanced},
            ),
            check(
                "targets.class_coverage",
                "Rare or missing classes",
                "warning" if rare else "pass" if gold else "not_applicable",
                f"{len(rare):,} decision families have a class with fewer than 20 examples; {len(absent):,} have a class with no examples."
                if rare
                else "Every declared class has at least 20 examples."
                if gold
                else "No observed-label counts are available for this check.",
                {"minimum_count": 20, "rare_families": rare, "missing_class_families": absent},
            ),
            check(
                "targets.semantics",
                "Target encoding",
                "warning" if self.unknown else "pass" if self.input_rows else "not_checked",
                f"{self.unknown:,} rows do not declare whether targets are observed labels or probability estimates."
                if self.unknown
                else f"{self.input_rows:,} rows declare their target meaning. The source labels have not been independently verified."
                if self.input_rows
                else "No valid decision targets are available to assess.",
            ),
            check(
                "targets.weights",
                "Observation weights",
                "warning"
                if self.weighted_rows or overflow
                else "pass"
                if self.input_rows
                else "not_applicable",
                f"{self.weighted_rows:,} of {self.input_rows:,} valid rows use weights other than 1. Class counts stay unweighted."
                + (
                    " Weighted totals exceed the supported numeric range and are unavailable."
                    if overflow
                    else ""
                )
                if self.weighted_rows or overflow
                else f"All {self.input_rows:,} valid rows have weight 1; each contributes equally.",
                {"nonunit_weight_rows": self.weighted_rows, "aggregate_overflow": overflow},
            ),
            check(
                "inputs.missing",
                "Missing input values",
                "warning" if missing_fields else "pass" if self.input_rows else "not_checked",
                "Missing values: "
                + "; ".join(
                    f"{field['field']} ({field['rows']:,} rows)" for field in missing_fields[:5]
                )
                + (
                    f"; and {len(missing_fields) - 5} more fields."
                    if len(missing_fields) > 5
                    else "."
                )
                if missing_fields
                else f"All {self.input_rows:,} state texts are nonempty. Feature values inside the text were not checked."
                if self.input_rows and not self.structured_input_rows
                else f"No missing values detected in {len(self.fields):,} measured inputs across {self.input_rows:,} rows."
                if self.input_rows
                else "No valid decision inputs are available to assess.",
                {
                    "input_rows": self.input_rows,
                    "affected_fields": len(missing_fields),
                    "fields": missing_fields[:20],
                },
            ),
            check(
                "inputs.constant",
                "Constant input fields",
                "warning" if constants else "pass" if self.input_rows else "not_checked",
                "Unchanged across nonempty values: "
                + ", ".join(constants[:5])
                + (f"; and {len(constants) - 5} more fields." if len(constants) > 5 else ".")
                if constants
                else "State text varies between rows. Individual features inside the text were not checked."
                if self.input_rows and not self.structured_input_rows
                else f"No constant fields among {len(self.fields):,} measured inputs."
                if self.input_rows
                else "No valid decision inputs are available to assess.",
                {"affected_fields": len(constants), "fields": constants[:20]},
            ),
            check(
                "inputs.structured_fields",
                "Feature-level checks",
                "not_checked"
                if self.structured_input_rows < self.input_rows or not self.input_rows
                else "pass",
                f"{self.input_rows - self.structured_input_rows:,} rows store features as text. Missing or constant values inside that text were not checked."
                if self.structured_input_rows < self.input_rows
                else f"All {self.structured_input_rows:,} valid rows expose JSON fields for input checks."
                if self.input_rows
                else "No valid decision inputs are available to assess.",
                {
                    "structured_rows": self.structured_input_rows,
                    "whole_text_rows": self.input_rows - self.structured_input_rows,
                },
            ),
            check(
                "coverage.analytics",
                "Scan coverage",
                "warning" if self.unlisted or self.field_overflow else "pass",
                f"All {self.rows:,} rows scanned; {len(families):,} decision families summarized. "
                + (
                    f"{self.unlisted:,} rows fall outside the family detail limit; their class balance is not assessed. "
                    + (
                        "Only the first 100 input fields were assessed."
                        if self.field_overflow
                        else "All input fields were included."
                    )
                    if self.unlisted or self.field_overflow
                    else "No family or input-field detail limits were reached."
                ),
                {
                    "unlisted_family_rows": self.unlisted,
                    "fields_truncated": self.field_overflow,
                    "family_limit": FAMILY_LIMIT,
                    "option_limit": OPTION_LIMIT,
                    "field_limit": FIELD_LIMIT,
                },
            ),
            check(
                "leakage.input_determines_label",
                "Label given by one input",
                "warning"
                if determined
                else "pass"
                if assessed
                else "not_checked"
                if labelled
                else "not_applicable",
                " ".join(
                    f"{item['field']} alone gives the label on {item['agreeing']:,} of the "
                    f"{item['rows']:,} rows that share its value with at least "
                    f"{SHARED_ROWS - 1} others."
                    for item in determined[:3]
                )
                + (f" And {len(determined) - 3} more inputs." if len(determined) > 3 else "")
                + unassessed_note
                if determined
                else "No single input gives the label on 99% of the rows that share its value "
                f"with at least {SHARED_ROWS - 1} others.{unassessed_note}"
                if assessed
                else "No JSON input fields were available to compare with the labels."
                if labelled
                else "Needs at least two observed labels.",
                {
                    "shared_rows": SHARED_ROWS,
                    "determined_share": DETERMINED_SHARE,
                    "covered_share": COVERED_SHARE,
                    "findings": determined[:20],
                    "unassessed_fields": unassessed[:20],
                },
            ),
            check(
                "leakage.label_in_input",
                "Label named in the input",
                "warning"
                if named
                else "pass"
                if judged
                else "not_checked"
                if labelled
                else "not_applicable",
                " ".join(
                    f"{item['field']} names the row's own label on {item['named']:,} of "
                    f"{item['rows']:,} rows."
                    for item in named[:3]
                )
                + (f" And {len(named) - 3} more inputs." if len(named) > 3 else "")
                if named
                else "No input names the row's own label on 98% of the rows."
                if judged
                else f"Fewer than {NAMED_ROWS} rows have a label with a word of 4 or more letters "
                "that no other label shares, so inputs were not searched for labels."
                if labelled
                else "Needs at least two observed labels.",
                {"named_share": NAMED_SHARE, "minimum_rows": NAMED_ROWS, "findings": named[:20]},
            ),
            check(
                "leakage.cross_split",
                "Duplicates and split leakage",
                "not_checked",
                "No comparison with other dataset splits was run. Shared records or entities between training and evaluation have not been ruled out.",
            ),
            check(
                "inputs.availability",
                "Feature availability and outliers",
                "not_checked",
                "No prediction-time rules or valid field ranges were supplied. Future-only features and out-of-range values were not checked.",
            ),
            check(
                "evaluation.readiness",
                "Evaluation strategy",
                "not_checked",
                "No model was evaluated by this scan. Model quality and task-specific acceptance criteria remain unassessed.",
            ),
        ]
        return {
            "version": VERSION,
            "status": "completed",
            "measured_at": timezone.now().isoformat(),
            "rows_scanned": self.rows,
            "population": "full",
            "decision_rows": self.decisions,
            "invalid_decision_rows": self.invalid,
            "unlisted_family_rows": self.unlisted,
            "families": families,
            "checks": checks,
        }


def describe(cell):
    report = (cell.stats or {}).get("analytics") or {}
    current = report.get("version") == VERSION and report.get("fingerprint") == cell.fingerprint
    return {
        **(report if current else {}),
        "status": report.get("status", "unmeasured") if current else "unmeasured",
        "cell": str(cell.pk),
        "dataset": str(cell.dataset_id),
        "fingerprint": cell.fingerprint,
        "checks": report.get("checks", []) if current else [],
        "families": report.get("families", []) if current else [],
    }