Skip to content

The platform for continuously improving AI agents.

7.1 KB
Raw Blame
"""What the platform verifies about a compiled preparation's output before it is published.

Read from the stored source and output files, not from the program that wrote the output, so
a fault in that program is found rather than repeated.
"""

import json
import re
from collections import Counter

from overbae.services.datasets import store, transform_compiler
from overbae.services.datasets.transform_spec import TransformSpec

# An input value is only evidence about the label once several rows share it.
SUPPORT_ROWS = 5
DETERMINED_SHARE = 0.99
COVERED_SHARE = 0.5
# An input names the label when nearly every sampled row's text holds a word of its own
# option and of no other.
NAMED_SHARE = 0.98
NAMED_ROWS = 50
WORD = re.compile(r"[a-z]{4,}")
COLUMN = re.compile(r'\s*"([^"]+)"\s*')


def label_named(spec, rows):
    """Inputs that pass one source column through unchanged and whose text names the row's
    own target option: the answer written into the question. ``rows`` is a sample of the
    source. Options told apart only by numbers or by words they share are not judged."""
    words = {
        option.value: set(WORD.findall(f"{option.value} {option.label or ''}".lower()))
        for option in spec.target.options
    }
    shared = {
        word
        for word, uses in Counter(w for found in words.values() for w in found).items()
        if uses > 1
    }
    words = {value: found - shared for value, found in words.items()}
    columns = {
        item.name: match.group(1) for item in spec.inputs if (match := COLUMN.fullmatch(item.sql))
    }
    judged, labels, named = 0, set(), Counter()
    for row in rows:
        value = str(row.get(spec.target.column))
        own = words.get(value)
        if not own:
            continue
        judged += 1
        labels.add(value)
        others = set().union(*(found for other, found in words.items() if other != value))
        for name, column in columns.items():
            text = set(WORD.findall(str(row.get(column) or "").lower()))
            if text & own and not text & others:
                named[name] += 1
    if judged < NAMED_ROWS or len(labels) < 2:
        return []
    return [
        {"input": name, "rows": judged, "share": count / judged}
        for name, count in sorted(named.items())
        if count / judged >= NAMED_SHARE
    ]


def plan(files):
    """The plan of a package the platform compiled, or ``None`` for any other package: only
    the platform's own program, unchanged, makes its plan a statement of what ran."""
    if files.get(transform_compiler.ENTRYPOINT) != transform_compiler.PROGRAM:
        return None
    try:
        value = json.loads(files["plan.json"])
        TransformSpec.model_validate(value["spec"])
    except (KeyError, ValueError):
        return None
    return value


def verify(plan, source, output):
    """Checks of ``output`` against ``source``. ``failed`` findings refuse publication;
    ``flagged`` ones are for whoever asked for the preparation to decide."""
    spec = TransformSpec.model_validate(plan["spec"])
    quote = store.quote_identifier
    labels = [option.label or option.value for option in spec.target.options]
    values = [option.value for option in spec.target.options]
    failed, flagged = [], []
    with store.connect_sandboxed(source=source, output=output) as connection:
        connection.execute(
            "CREATE TEMP TABLE prepared AS SELECT o.source_row, "
            "list_position(CAST(json_extract(o.decision, '$.target_probabilities') AS DOUBLE[]), 1.0) AS chosen, "
            "CAST(json_extract(o.decision, '$.options') AS VARCHAR[]) AS options, "
            "json_extract_string(o.decision, '$.state') AS state, "
            f"CAST(s.{quote(spec.target.column)} AS VARCHAR) AS stored "
            "FROM output o LEFT JOIN source s USING (source_row)"
        )
        connection.execute(
            "CREATE TEMP TABLE expected AS SELECT * FROM (SELECT unnest(?) AS label, unnest(?) AS stored)",
            [labels, values],
        )
        rows, differing, first = connection.execute(
            "SELECT count(*), count(*) FILTER (WHERE e.label IS NULL), "
            "min(p.source_row) FILTER (WHERE e.label IS NULL) "
            "FROM prepared p LEFT JOIN expected e "
            "ON e.label = p.options[p.chosen] AND e.stored IS NOT DISTINCT FROM p.stored"
        ).fetchone()
        if differing:
            failed.append(
                {
                    "check": "labels_equal_source",
                    "rows": differing,
                    "first_source_row": first,
                    "detail": f"{differing} of {rows} rows carry a label that differs from the source column {spec.target.column}.",
                }
            )
        present = dict(
            connection.execute(
                "SELECT options[chosen], count(*) FROM prepared GROUP BY 1"
            ).fetchall()
        )
        absent = [label for label in labels if not present.get(label)]
        if rows and absent:
            flagged.append(
                {
                    "check": "every_option_observed",
                    "options": absent,
                    "detail": f"No row has the label {', '.join(absent)}.",
                }
            )
        for item in spec.inputs:
            value = f"json_extract(state, '$.{quote(item.name)}')"
            covered, agreeing = connection.execute(
                f"WITH counted AS (SELECT {value} AS value, options[chosen] AS label, count(*) AS n "
                "FROM prepared GROUP BY 1, 2), "
                "grouped AS (SELECT value, sum(n) AS total, max(n) AS majority FROM counted GROUP BY 1) "
                "SELECT coalesce(sum(total), 0), coalesce(sum(majority), 0) FROM grouped WHERE total >= ?",
                [SUPPORT_ROWS],
            ).fetchone()
            if (
                rows
                and len(present) > 1
                and covered >= COVERED_SHARE * rows
                and agreeing >= DETERMINED_SHARE * covered
            ):
                flagged.append(
                    {
                        "check": "input_determines_label",
                        "input": item.name,
                        "reads": plan["reads"].get(f"inputs.{item.name}", []),
                        "rows": int(covered),
                        "agreeing_rows": int(agreeing),
                        "detail": f"{item.name} alone gives the label on {int(agreeing)} of the {int(covered)} rows that share a value with at least {SUPPORT_ROWS - 1} others.",
                    }
                )
        for item in spec.group_keys:
            missing = connection.execute(
                f"SELECT count(*) FROM output WHERE {quote(item.name)} IS NULL"
            ).fetchone()[0]
            if missing:
                flagged.append(
                    {
                        "check": "group_key_present",
                        "key": item.name,
                        "rows": missing,
                        "detail": f"{missing} rows have no value for the group key {item.name}.",
                    }
                )
    return {"rows": rows, "labels": present, "failed": failed, "flagged": flagged}