Skip to content

The platform for continuously improving AI agents.

4.9 KB
Raw Blame
"""What a version's columns hold, measured once when the version lands.

An agent chooses a target, inputs and group keys from these facts instead of writing code to
find them. Every count is of the stored rows, or says how many rows it was taken from.
"""

from pathlib import Path

from overbae.models import Cell
from overbae.services.datasets import paths, store

VERSION = 1
# Beyond this the facts come from a fixed sample, and say so.
MEASURED_ROWS = 1_000_000
# A column with at most this many distinct values lists them all.
LISTED_VALUES = 30
TOP_VALUES = 8
VALUE_CHARS = 120
# A wider version's profile is not sent with a request: it is read on demand.
SHOWN_COLUMNS = 80


def text(value):
    # PostgreSQL JSON cannot hold NUL.
    return str(value)[:VALUE_CHARS].replace("\x00", "\\u0000")


def measure(path: Path, manifest: list[dict]) -> dict:
    """The profile of the frame at ``path``."""
    quote = store.quote_identifier
    columns = [
        column
        for column in manifest
        if column["name"] != store.SOURCE_ROW and not column["name"].startswith("_overmind_")
    ]
    literal = str(Path(path).resolve()).replace("'", "''")
    with store.connect() as connection:
        total = connection.execute(f"SELECT count(*) FROM read_parquet('{literal}')").fetchone()[0]
        sample = (
            f" USING SAMPLE reservoir({MEASURED_ROWS} ROWS) REPEATABLE (73491)"
            if total > MEASURED_ROWS
            else ""
        )
        connection.execute(
            f"CREATE TEMP TABLE measured AS SELECT * FROM read_parquet('{literal}'){sample}"
        )
        rows = min(total, MEASURED_ROWS)
        described = {}
        for column in columns:
            name, kind = quote(column["name"]), column["type"]
            as_text = f"CAST({name} AS VARCHAR)"
            nulls, distinct = connection.execute(
                f"SELECT count(*) FILTER (WHERE {name} IS NULL), count(DISTINCT {name}) FROM measured"
            ).fetchone()
            entry = {"type": kind, "null": nulls, "distinct": distinct}
            if kind in {"string", "json"}:
                blank, mean, longest = connection.execute(
                    f"SELECT count(*) FILTER (WHERE trim({as_text}) = ''), "
                    f"avg(length({as_text})), max(length({as_text})) FROM measured"
                ).fetchone()
                entry.update(
                    blank=blank,
                    mean_length=round(mean, 1) if mean is not None else None,
                    max_length=longest,
                )
            elif kind in {"integer", "number"}:
                low, high, mean = connection.execute(
                    f"SELECT min({name}), max({name}), avg({name}) FROM measured "
                    f"WHERE isfinite(CAST({name} AS DOUBLE))"
                ).fetchone()
                entry.update(min=low, max=high, mean=mean)
            if kind != "json" and distinct:
                top = connection.execute(
                    f"SELECT {as_text}, count(*) AS n FROM measured WHERE {name} IS NOT NULL "
                    "GROUP BY 1 ORDER BY n DESC, 1 LIMIT ?",
                    [LISTED_VALUES if distinct <= LISTED_VALUES else TOP_VALUES],
                ).fetchall()
                found = [{"value": text(value), "rows": count} for value, count in top]
                if distinct <= LISTED_VALUES:
                    entry["values"] = found
                else:
                    entry["most_common"] = found
                    # Rows whose value another row has too: what makes a column a way to
                    # tell which rows belong together.
                    entry["rows_sharing_a_value"] = connection.execute(
                        f"SELECT coalesce(sum(n), 0) FROM (SELECT count(*) AS n FROM measured "
                        f"WHERE {name} IS NOT NULL GROUP BY {name} HAVING count(*) > 1)"
                    ).fetchone()[0]
            entry["unique"] = bool(rows) and nulls == 0 and distinct == rows
            described[column["name"]] = entry
        compared = ", ".join(quote(column["name"]) for column in columns)
        duplicates = (
            connection.execute(
                f"SELECT count(*) - count(DISTINCT hash({compared})) FROM measured"
            ).fetchone()[0]
            if compared
            else 0
        )
    return {
        "version": VERSION,
        "rows": total,
        "rows_measured": rows,
        "duplicate_rows": duplicates,
        "columns": described,
    }


def of(cell: Cell) -> dict:
    """The cell's profile, measured now for a version that landed before profiles were."""
    stored = (cell.stats or {}).get("profile")
    if stored and stored.get("version") == VERSION:
        return stored
    path = paths.cell_path(cell.dataset_id, cell.pk)
    measured = measure(path, store.read_manifest(path))
    cell.stats = {**(cell.stats or {}), "profile": measured}
    Cell.objects.filter(pk=cell.pk).update(stats=cell.stats)
    return measured