Skip to content

The platform for continuously improving AI agents.

5.1 KB
Raw Blame
"""The program every compiled preparation runs. It carries no decisions of its own: the
plan beside it, plan.json, states what to compute. Retained with the package, so what ran can
be read and run again.
"""

import hashlib
import json
import math
import sys
from datetime import date, datetime, time
from decimal import Decimal
from pathlib import Path

import duckdb
import pyarrow

TYPES = {
    "string": pyarrow.string(),
    "integer": pyarrow.int64(),
    "number": pyarrow.float64(),
    "boolean": pyarrow.bool_(),
    "json": pyarrow.string(),
}
TARGET = "__target"


class RefusedError(Exception):
    pass


def plain(value, name, row):
    if isinstance(value, Decimal):
        value = float(value)
    if isinstance(value, float) and not math.isfinite(value):
        raise RefusedError(f"{name} is not a finite number on source row {row}.")
    if isinstance(value, (datetime, date, time)):
        return value.isoformat()
    return value


def kept(row, sample):
    if sample is None:
        return True
    digest = hashlib.sha256(f"{sample['seed']}:{row}".encode()).digest()
    return int.from_bytes(digest[:8], "big") / 2**64 < sample["fraction"]


def load(path, columns):
    values = {name: [] for name in ("source_row", *columns)}
    with open(path) as rows:
        for line in rows:
            row = json.loads(line)
            values["source_row"].append(row["source_row"])
            for name, kind in columns.items():
                value = row.get(name)
                if kind == "json" and value is not None:
                    value = json.dumps(value, ensure_ascii=False, sort_keys=True)
                values[name].append(value)
    return pyarrow.table(
        {
            "source_row": pyarrow.array(values["source_row"], pyarrow.int64()),
            **{name: pyarrow.array(values[name], TYPES[kind]) for name, kind in columns.items()},
        }
    )


def transform(source, plan):
    spec = plan["spec"]
    options = spec["target"]["options"]
    labels = [option["label"] or option["value"] for option in options]
    index = {option["value"]: position for position, option in enumerate(options)}
    question = "\n".join(
        [
            spec["target"]["question"],
            *(
                f"{label}: {option['meaning']}"
                for label, option in zip(labels, options, strict=True)
                if option["meaning"]
            ),
        ]
    )
    inputs = [item["name"] for item in spec["inputs"]]
    keys = [item["name"] for item in spec["group_keys"]]
    with duckdb.connect() as connection:
        connection.register("source", source)
        # The plan's expressions read the registered rows and nothing else.
        connection.execute("SET enable_external_access = false")
        connection.execute("SET lock_configuration = true")
        cursor = connection.execute(plan["select"])
        names = [column[0] for column in cursor.description]
        unmatched = {}
        while batch := cursor.fetchmany(4096):
            for values in batch:
                record = dict(zip(names, values, strict=True))
                row = record["source_row"]
                if not kept(row, spec["sample"]):
                    continue
                position = index.get(record[TARGET])
                if position is None:
                    unmatched[record[TARGET]] = unmatched.get(record[TARGET], 0) + 1
                    continue
                yield {
                    "source_row": row,
                    "decision": {
                        "state": json.dumps(
                            {name: plain(record[name], name, row) for name in inputs},
                            ensure_ascii=False,
                            sort_keys=True,
                        ),
                        "question": question,
                        "kind": "choice",
                        "options": labels,
                        "target_probabilities": [
                            1 if position == other else 0 for other in range(len(labels))
                        ],
                        "target_semantics": "categorical_gold",
                        "target_provenance": {"source_column": spec["target"]["column"]},
                    },
                    **{name: plain(record[name], name, row) for name in keys},
                }
        if unmatched:
            found = sorted(unmatched.items(), key=lambda item: (-item[1], str(item[0])))[:20]
            listed = [{"value": value, "rows": count} for value, count in found]
            raise RefusedError(
                f"Rows hold target values that no option names: {json.dumps(listed)}. "
                "Add an option for each, or filter those rows out."
            )


def main(source, output):
    plan = json.loads((Path(__file__).parent / "plan.json").read_text())
    try:
        with open(output, "w") as lines:
            for row in transform(load(source, plan["columns"]), plan):
                lines.write(json.dumps(row, ensure_ascii=False, allow_nan=False) + "\n")
    except (RefusedError, duckdb.Error, pyarrow.ArrowException) as error:
        sys.exit(str(error))


if __name__ == "__main__":
    main(sys.argv[1], sys.argv[2])