The platform for continuously improving AI agents.
"""A declarative data preparation: what to predict, from which expressions over the source
columns, and which rows must stay together.
An agent states the decisions; the platform writes the program from them. Each expression is
parsed before anything runs, so what it may do and which columns it reads are known.
"""
import json
from typing import Literal
import duckdb
from pydantic import BaseModel, ConfigDict, Field, model_validator
from overbae.core.errors import DatasetError
IDENTIFIER = r"^[A-Za-z][A-Za-z0-9_]{0,63}$"
# Scalar functions only: an aggregate, a window or a table function reads other rows, and a
# clock or a random number makes the same input give a different output.
FUNCTIONS = frozenset(
{
*("+", "-", "*", "/", "//", "%", "**", "^", "||", "->", "->>"),
*("~~", "!~~", "~~*", "!~~*", "~~~"),
*("lower", "upper", "trim", "ltrim", "rtrim", "length", "strlen", "reverse"),
*("substr", "substring", "left", "right", "replace", "lpad", "rpad", "repeat"),
*("concat", "concat_ws", "contains", "starts_with", "prefix", "suffix", "ends_with"),
*("split_part", "strpos", "instr", "position"),
*("regexp_extract", "regexp_replace", "regexp_matches", "regexp_full_match"),
*("coalesce", "nullif", "ifnull"),
*("abs", "round", "floor", "ceil", "ceiling", "trunc", "sign", "sqrt", "exp"),
*("ln", "log", "log2", "log10", "power", "pow", "greatest", "least"),
*("date_part", "datepart", "date_trunc", "datetrunc", "date_diff", "datediff"),
*("year", "month", "day", "hour", "minute", "second", "quarter", "week"),
*("dayofweek", "dayofyear", "epoch", "strftime", "strptime", "try_strptime"),
*("json_extract", "json_extract_string"),
}
)
STRUCTURE = frozenset(
{
*("FUNCTION", "COLUMN_REF", "CONSTANT", "CAST", "CASE"),
*("OPERATOR", "COMPARISON", "CONJUNCTION", "BETWEEN"),
}
)
CAST_TYPES = frozenset(
{
*("VARCHAR", "BOOLEAN", "DOUBLE", "FLOAT", "DECIMAL"),
*("TINYINT", "SMALLINT", "INTEGER", "BIGINT", "HUGEINT"),
*("DATE", "TIME", "TIMESTAMP", "TIMESTAMP WITH TIME ZONE"),
}
)
RESERVED = frozenset({"source_row", "decision"})
# How each stored column type is declared to the engine that binds an expression.
STORED = {"string": "VARCHAR", "integer": "BIGINT", "number": "DOUBLE", "boolean": "BOOLEAN"}
def quote(name):
return '"' + name.replace('"', '""') + '"'
class Model(BaseModel):
model_config = ConfigDict(extra="forbid")
class Option(Model):
value: str = Field(
max_length=255, description="The target column's value, as text, exactly as stored."
)
label: str | None = Field(
default=None, min_length=1, max_length=255, description="The option a model chooses."
)
meaning: str | None = Field(default=None, min_length=1, max_length=500)
class Target(Model):
column: str = Field(min_length=1, max_length=255)
question: str = Field(min_length=1, max_length=2000)
options: list[Option] = Field(min_length=2, max_length=255)
@model_validator(mode="after")
def distinct(self):
values = [option.value for option in self.options]
labels = [option.label or option.value for option in self.options]
if len(set(values)) != len(values) or len(set(labels)) != len(labels):
raise ValueError("Options need distinct values and distinct labels")
if any(not label.strip() for label in labels):
raise ValueError("An option whose value is blank needs a label")
return self
class Expression(Model):
name: str = Field(pattern=IDENTIFIER)
sql: str = Field(
min_length=1,
max_length=2000,
description='One scalar SQL expression over the source columns, each quoted as "Name".',
)
class Excluded(Model):
column: str = Field(min_length=1, max_length=255)
reason: Literal["identifier", "outcome", "redundant", "unusable"]
class Sample(Model):
fraction: float = Field(gt=0, lt=1)
seed: int = Field(ge=0, le=2**32 - 1)
class TransformSpec(Model):
consumer: Literal["decision_train"] = "decision_train"
target: Target
inputs: list[Expression] = Field(min_length=1, max_length=200)
excluded: list[Excluded] = Field(default_factory=list, max_length=200)
filter: str | None = Field(default=None, min_length=1, max_length=2000)
sample: Sample | None = None
group_keys: list[Expression] = Field(default_factory=list, max_length=20)
@model_validator(mode="before")
@classmethod
def target_needs_no_exclusion(cls, data):
# The target is never an input. A spec that also lists it as excluded, under whatever
# reason, says nothing more, so the entry is dropped instead of sent back.
if isinstance(data, dict) and isinstance(data.get("excluded"), list):
target = (
(data.get("target") or {}).get("column")
if isinstance(data.get("target"), dict)
else None
)
kept = [
item
for item in data["excluded"]
if not (isinstance(item, dict) and target and item.get("column") == target)
]
return {**data, "excluded": kept}
return data
@model_validator(mode="after")
def named(self):
# Inputs are fields of the decision's state and group keys are columns beside it, so
# a group key may carry the name of the input it repeats.
for group, items in (("Inputs", self.inputs), ("Group keys", self.group_keys)):
names = [item.name for item in items]
if len(set(names)) != len(names):
raise ValueError(f"{group} need distinct names")
if RESERVED & {item.name for item in self.group_keys}:
raise ValueError("A group key cannot be named source_row or decision")
return self
def invalid(detail, issues):
error = DatasetError(detail, code="transform_spec")
error.issues = issues
return error
def columns_read(sql, available):
"""The source columns an expression reads. Raises ``ValueError`` when it is anything but
one scalar expression over columns that exist."""
with duckdb.connect() as connection:
tree = json.loads(
connection.execute(
"select json_serialize_sql(?)", [f"SELECT ({sql}) AS value"]
).fetchone()[0]
)
if tree.get("error"):
raise ValueError(str(tree.get("error_message") or "The expression does not parse")[:300])
statements = tree["statements"]
node = statements[0]["node"] if len(statements) == 1 else {}
if (
node.get("type") != "SELECT_NODE"
or len(node["select_list"]) != 1
or node["from_table"]["type"] != "EMPTY"
or node["where_clause"]
or node["group_expressions"]
or node["having"]
or node["qualify"]
or node["sample"]
or node["modifiers"]
or node["cte_map"]["map"]
):
raise ValueError("Write one expression: no FROM, WHERE, grouping or second statement")
read = set()
def walk(value):
if isinstance(value, list):
for item in value:
walk(item)
return
if not isinstance(value, dict):
return
kind = value.get("class")
if kind is not None:
if kind not in STRUCTURE:
raise ValueError(f"{kind.lower().replace('_', ' ')} is not available here")
if kind == "FUNCTION":
name = value["function_name"].lower()
if name not in FUNCTIONS or value.get("distinct") or value.get("filter"):
raise ValueError(f"The function {name} is not available here")
if kind == "CAST" and value["cast_type"]["id"] not in CAST_TYPES:
raise ValueError(f"A cast to {value['cast_type']['id']} is not available here")
if kind == "COLUMN_REF":
names = value["column_names"]
if len(names) != 1 or names[0] not in available:
raise ValueError(f"There is no source column {'.'.join(names)}")
read.add(names[0])
for item in value.values():
walk(item)
walk(node["select_list"])
return read
def lineage(spec, columns, profile=None):
"""Which source columns each part of the spec reads, after checking the whole spec
against the source. ``columns`` are the source cell's, without platform columns;
``profile`` is its measured profile, when the target's stored values are to be checked."""
available = {column["name"] for column in columns}
issues = []
read = {}
if spec.target.column not in available:
issues.append({"path": "target.column", "detail": "There is no such source column."})
with duckdb.connect() as connection:
# An empty table with the source's column types: an expression that parses can still
# apply a function to a type it does not take, which only binding it shows.
connection.execute(
"CREATE TABLE source ("
+ ", ".join(
f"{quote(column['name'])} {STORED.get(column['type'], 'VARCHAR')}"
for column in columns
)
+ ")"
)
def checked(sql):
used = columns_read(sql, available)
try:
connection.execute(f"SELECT ({sql}) FROM source LIMIT 0")
except duckdb.Error as error:
raise ValueError(str(error).splitlines()[0][:300]) from error
return used
for group, items in (("inputs", spec.inputs), ("group_keys", spec.group_keys)):
for index, item in enumerate(items):
try:
read[f"{group}.{item.name}"] = checked(item.sql)
except ValueError as error:
issues.append({"path": f"{group}[{index}].sql", "detail": str(error)})
if spec.filter:
try:
read["filter"] = checked(spec.filter)
except ValueError as error:
issues.append({"path": "filter", "detail": str(error)})
# The row identity and platform columns are never inputs: excluding one says nothing new.
excluded = {item.column for item in spec.excluded if not platform_column(item.column)}
for column in sorted(excluded - available):
issues.append({"path": "excluded", "detail": f"There is no source column {column}."})
for name, used in read.items():
part = name.partition(".")[0]
if part != "filter" and spec.target.column in used:
issues.append({"path": name, "detail": "It reads the target column."})
if part == "inputs":
for column in sorted(used & excluded):
issues.append({"path": name, "detail": f"It reads {column}, which is excluded."})
accounted = set().union(*read.values(), excluded, {spec.target.column})
for column in sorted(available - accounted):
issues.append(
{
"path": "excluded",
"detail": f"{column} is neither read nor excluded. Use it, or exclude it with a reason.",
}
)
if profile and not spec.filter and spec.target.column in profile.get("columns", {}):
# Every stored label needs an option, or the run would refuse those rows later.
observed = profile["columns"][spec.target.column]
named = {option.value for option in spec.target.options}
missing = [
item["value"] for item in observed.get("values", []) if item["value"] not in named
]
if observed.get("null"):
missing.append(None)
if "values" not in observed and observed.get("distinct", 0) > len(named):
issues.append(
{
"path": "target.options",
"detail": f"{spec.target.column} holds {observed['distinct']} distinct "
f"values and the options name {len(named)}. Choose a column with a fixed "
"set of values, or filter the rows.",
}
)
elif missing:
issues.append(
{
"path": "target.options",
"detail": "Rows hold target values that no option names: "
f"{json.dumps(missing)}. Add an option for each (value is the stored "
"text), or filter those rows out.",
}
)
if issues:
raise invalid(
"The preparation does not fit its source: "
+ " ".join(f"{issue['path']}: {issue['detail']}" for issue in issues),
issues,
)
return {name: sorted(used) for name, used in read.items()}
def platform_column(name):
return name == "source_row" or name.startswith("_overmind_")
def source_columns(cell):
return [column for column in cell.columns if not platform_column(column["name"])]