Skip to content

Checks

Module containing data quality check classes.

AverageCheck

AverageCheck(database_accessor: str, database_provider: DatabaseProvider | None, table: str, check_column: str, lower_threshold: float = -inf, upper_threshold: float = inf, *, transformation_name: str | None = None, **options: Unpack[CheckOptions])

Bases: ColumnTransformationCheck

Compute the average (AVG) of a numeric column for the filtered rows.

Takes the arguments of ColumnTransformationCheck and the options in CheckOptions. Thresholds apply to the computed average.

Source code in src/koality/checks.py
def __init__(
    self,
    database_accessor: str,
    database_provider: DatabaseProvider | None,
    table: str,
    check_column: str,
    lower_threshold: float = -math.inf,
    upper_threshold: float = math.inf,
    *,
    transformation_name: str | None = None,
    **options: Unpack[CheckOptions],
) -> None:
    """Initialize the column transformation check."""
    if transformation_name is not None:
        self.transformation_name = transformation_name
    if not getattr(self, "transformation_name", None):
        msg = f"{type(self).__name__} must set 'transformation_name'"
        raise KoalityError(msg)

    super().__init__(
        database_accessor=database_accessor,
        database_provider=database_provider,
        table=table,
        check_column=check_column,
        lower_threshold=lower_threshold,
        upper_threshold=upper_threshold,
        **options,
    )

transformation_statement

transformation_statement() -> str

Return the SQL statement for computing the average.

Source code in src/koality/checks.py
def transformation_statement(self) -> str:
    """Return the SQL statement for computing the average."""
    return f"AVG({self.in_memory_column}) AS {self.name}"

CheckOptions

Bases: TypedDict

Keyword options shared by all checks, passed as **options.

Attributes:

Name Type Description
filters dict[str, Any] | None

The check's filters by name, each with column, value and optionally operator and type (see FilterConfig).

identifier_format str

How the identifier filter appears in results: "identifier" (column=value), "filter_name" or "column_name".

identifier_placeholder str

The identifier shown when the identifier filter has no value (default "ALL").

date_info str | None

Text shown after the date in the failure message.

extra_info str | None

Text appended to the failure message.

monitor_only bool

If True, the result isn't compared to the thresholds, so the check doesn't fail the run (missing data and query errors still do).

ColumnTransformationCheck

ColumnTransformationCheck(database_accessor: str, database_provider: DatabaseProvider | None, table: str, check_column: str, lower_threshold: float = -inf, upper_threshold: float = inf, *, transformation_name: str | None = None, **options: Unpack[CheckOptions])

Bases: DataQualityCheck, ABC

Abstract class for data quality checks performing checks on a specific column of a table.

Subclasses set transformation_name as a class attribute and implement transformation_statement.

Parameters:

Name Type Description Default
database_accessor str

The attached database the check reads from (e.g. "bq"); empty for tables in DuckDB itself.

required
database_provider DatabaseProvider | None

The attached database, which picks the backend (None for DuckDB itself).

required
table str

The table to check, in the database_accessor's catalog (e.g. "orders"); in BigQuery, as BigQuery names it (e.g. "dataset.table").

required
check_column str

The column to check (e.g. "category").

required
lower_threshold float

The check fails if its result is below this.

-inf
upper_threshold float

The check fails if its result is above this.

inf
transformation_name str | None

Overrides the class's transformation_name.

None

Further keyword options: see CheckOptions.

Source code in src/koality/checks.py
def __init__(
    self,
    database_accessor: str,
    database_provider: DatabaseProvider | None,
    table: str,
    check_column: str,
    lower_threshold: float = -math.inf,
    upper_threshold: float = math.inf,
    *,
    transformation_name: str | None = None,
    **options: Unpack[CheckOptions],
) -> None:
    """Initialize the column transformation check."""
    if transformation_name is not None:
        self.transformation_name = transformation_name
    if not getattr(self, "transformation_name", None):
        msg = f"{type(self).__name__} must set 'transformation_name'"
        raise KoalityError(msg)

    super().__init__(
        database_accessor=database_accessor,
        database_provider=database_provider,
        table=table,
        check_column=check_column,
        lower_threshold=lower_threshold,
        upper_threshold=upper_threshold,
        **options,
    )

assemble_data_exists_query

assemble_data_exists_query() -> str

Assemble the SQL query to check if data exists in the table.

Source code in src/koality/checks.py
def assemble_data_exists_query(self) -> str:
    """Assemble the SQL query to check if data exists in the table."""
    data_exists_query = f"""
    SELECT
        IF(COUNT(*) > 0, '', {sql_literal(self.table)}) AS empty_table
    FROM
        {self.table_ref(self.table)}
    """

    if where_statement := self.assemble_where_statement(self.filters, database_accessor=self.database_accessor):
        return f"{data_exists_query}\n{where_statement}"

    return data_exists_query

assemble_name

assemble_name() -> str

Return the check name combining column and transformation.

Source code in src/koality/checks.py
def assemble_name(self) -> str:
    """Return the check name combining column and transformation."""
    return f"{self.check_column.split('.')[-1]}_{self.transformation_name}"

assemble_query

assemble_query() -> str

Assemble the complete SQL query for this check.

Source code in src/koality/checks.py
def assemble_query(self) -> str:
    """Assemble the complete SQL query for this check."""
    main_query = self.query_boilerplate(self.transformation_statement())

    filters = self.filters.copy()
    if isinstance(self, IqrOutlierCheck):
        filters = {name: cfg for name, cfg in filters.items() if cfg.get("type") != "date"}

    if where_statement := self.assemble_where_statement(filters, database_accessor=self.database_accessor):
        return main_query + "\n" + where_statement

    return main_query

query_boilerplate

query_boilerplate(metric_statement: str) -> str

Return the base SQL query structure with the given metric statement.

Source code in src/koality/checks.py
def query_boilerplate(self, metric_statement: str) -> str:
    """Return the base SQL query structure with the given metric statement."""
    return f"""
    SELECT
        {metric_statement}
    FROM
        {self.table_ref(self.table)}
    """

transformation_statement abstractmethod

transformation_statement() -> str

Return the SQL transformation statement for this check.

Source code in src/koality/checks.py
@abc.abstractmethod
def transformation_statement(self) -> str:
    """Return the SQL transformation statement for this check."""

CountCheck

CountCheck(database_accessor: str, database_provider: DatabaseProvider | None, table: str, check_column: str, lower_threshold: float = -inf, upper_threshold: float = inf, *, distinct: bool = False, **options: Unpack[CheckOptions])

Bases: ColumnTransformationCheck

Check the number of rows or distinct values of a specific column.

Takes the arguments of ColumnTransformationCheck (except transformation_name) and the options in CheckOptions.

Parameters:

Name Type Description Default
distinct bool

Indicates if the count should count all rows or only distinct values of a specific column.

Note: distinct=True cannot be used with check_column="*".

False
Example
from koality.checks import CountCheck

CountCheck(
    database_accessor="",
    database_provider=None,
    table="skufeed_latest",
    check_column="sku_id",
    distinct=True,
    filters={
        "identifier": {"column": "shop_code", "value": "SHOP01", "type": "identifier"},
        "date": {"column": "DATE", "value": "2023-01-01", "type": "date"},
    },
    lower_threshold=10000.0,
    upper_threshold=99999.0,
)
Source code in src/koality/checks.py
def __init__(
    self,
    database_accessor: str,
    database_provider: DatabaseProvider | None,
    table: str,
    check_column: str,
    lower_threshold: float = -math.inf,
    upper_threshold: float = math.inf,
    *,
    distinct: bool = False,
    **options: Unpack[CheckOptions],
) -> None:
    """Initialize the count check."""
    if check_column == "*" and distinct:
        msg = "Cannot COUNT(DISTINCT *)! Either set check_column != '*' or distinct = False."
        raise KoalityError(msg)

    self.distinct = distinct

    super().__init__(
        database_accessor=database_accessor,
        database_provider=database_provider,
        transformation_name="distinct_count" if distinct else "count",
        table=table,
        check_column=check_column,
        lower_threshold=lower_threshold,
        upper_threshold=upper_threshold,
        **options,
    )

assemble_name

assemble_name() -> str

Return the check name, using 'row_' prefix for wildcard columns.

Source code in src/koality/checks.py
def assemble_name(self) -> str:
    """Return the check name, using 'row_' prefix for wildcard columns."""
    if self.check_column == "*":
        return f"row_{self.transformation_name}"

    return super().assemble_name()

transformation_statement

transformation_statement() -> str

Return the SQL statement for counting rows or distinct values.

Source code in src/koality/checks.py
def transformation_statement(self) -> str:
    """Return the SQL statement for counting rows or distinct values."""
    if self.distinct:
        return f"COUNT(DISTINCT {self.in_memory_column}) AS {self.name}"

    return f"COUNT({self.in_memory_column}) AS {self.name}"

DataQualityCheck

DataQualityCheck(database_accessor: str, database_provider: DatabaseProvider | None, table: str, check_column: str | None = None, lower_threshold: float = -inf, upper_threshold: float = inf, *, filters: dict[str, Any] | None = None, identifier_format: str = 'identifier', identifier_placeholder: str = 'ALL', date_info: str | None = None, extra_info: str | None = None, monitor_only: bool = False)

Bases: ABC

Abstract class for all data quality checks.

Provides generic methods relevant to all data quality check classes. koality run creates the checks from the YAML configuration (see create_checks); the checks' examples create one directly, for a table in DuckDB itself (an empty database_accessor).

Parameters:

Name Type Description Default
database_accessor str

The attached database the check reads from (e.g. "bq"); empty for tables in DuckDB itself.

required
database_provider DatabaseProvider | None

The attached database, which picks the backend (None for DuckDB itself).

required
table str

The table to check, in the database_accessor's catalog (e.g. "orders"); in BigQuery, as BigQuery names it (e.g. "dataset.table").

required
check_column str | None

The column to check (e.g. "category").

None
lower_threshold float

The check fails if its result is below this.

-inf
upper_threshold float

The check fails if its result is above this.

inf

The keyword-only arguments are the options in CheckOptions.

Source code in src/koality/checks.py
def __init__(
    self,
    database_accessor: str,
    database_provider: DatabaseProvider | None,
    table: str,
    check_column: str | None = None,
    lower_threshold: float = -math.inf,
    upper_threshold: float = math.inf,
    *,
    filters: dict[str, Any] | None = None,
    identifier_format: str = "identifier",
    identifier_placeholder: str = "ALL",
    date_info: str | None = None,
    extra_info: str | None = None,
    monitor_only: bool = False,
) -> None:
    """Initialize the data quality check with configuration parameters."""
    self.database_provider = database_provider
    self.database_accessor = database_accessor
    self.table = table
    self._validate_table_names()
    self.lower_threshold = lower_threshold
    self.upper_threshold = upper_threshold
    self.monitor_only = monitor_only
    self.extra_info_string = f" {extra_info}" if extra_info else ""
    self.date_info_string = f" ({date_info})" if date_info else ""

    self.status = "NOT_EXECUTED"
    self.message: str | None = None
    # Set by the executor once the check's data has been staged (see `table_ref`)
    self.staging_catalog: str | None = None

    # Identifier format configuration
    self.identifier_format = identifier_format
    self.identifier_placeholder = identifier_placeholder

    # for where filter handling
    self.filters = self.get_filters(filters or {})

    # Find identifier filter by type and format based on identifier_format setting
    identifier_filter_result = self.get_identifier_filter(self.filters)
    if identifier_filter_result:
        filter_name, filter_config = identifier_filter_result
        # If value key is missing or explicitly None, treat as identifier_placeholder (meaning "no specific value")
        if "value" in filter_config and filter_config["value"] is not None:
            value = filter_config["value"]
        else:
            value = self.identifier_placeholder
        column = filter_config.get("column", "")

        if self.identifier_format == "identifier":
            # Format as "column=value"
            self.identifier = f"{column}={value}" if column else str(value)
            self.identifier_column = "IDENTIFIER"
        elif self.identifier_format == "filter_name":
            # Use filter name as column, value as-is
            self.identifier = str(value)
            self.identifier_column = filter_name.upper()
        else:  # column_name
            # Use database column name as column, value as-is
            self.identifier = str(value)
            self.identifier_column = column.upper() if column else "IDENTIFIER"
    else:
        self.identifier = "ALL"
        self.identifier_column = "IDENTIFIER"

    # Find date filter by type and store the filter dict
    date_filter_result = self.get_date_filter(self.filters)
    if date_filter_result:
        self.date_filter = date_filter_result[1]
    else:
        self.date_filter = None

    if check_column is None:
        self.check_column = "*"
    else:
        self.check_column = check_column

    self.name = self.assemble_name()
    self.result: dict[str, Any] | None = None

in_memory_column property

in_memory_column: str

Return the column name to reference in in-memory queries.

If a configured column references a nested field (e.g. "value.shopId"): - When querying data loaded via database_accessor: uses underscores ("value_shopId") because the executor flattens struct columns with underscore aliases - When querying existing DuckDB tables (no accessor): keeps dots ("value.shopId") to support native DuckDB struct column syntax

This property provides the appropriate name without modifying the original configured self.check_column which is still used for result writing.

query property

query: str

Return the assembled SQL query for this check.

__call__

__call__(duckdb_client: DuckDBPyConnection) -> dict

Execute the data quality check and return results.

Source code in src/koality/checks.py
def __call__(self, duckdb_client: duckdb.DuckDBPyConnection) -> dict:
    """Execute the data quality check and return results."""
    data_check_result = self.data_check(duckdb_client)
    if data_check_result:
        return data_check_result

    return self.check(duckdb_client)

__repr__

__repr__() -> str

Return string representation combining identifier and check name.

Source code in src/koality/checks.py
def __repr__(self) -> str:
    """Return string representation combining identifier and check name."""
    if not hasattr(self, "identifier"):
        return self.name

    return f"{self.identifier}_{self.name}"

assemble_data_exists_query abstractmethod

assemble_data_exists_query() -> str

Assemble and return the SQL query to check if data exists.

Source code in src/koality/checks.py
@abc.abstractmethod
def assemble_data_exists_query(self) -> str:
    """Assemble and return the SQL query to check if data exists."""

assemble_name abstractmethod

assemble_name() -> str

Assemble and return the name for this check.

Source code in src/koality/checks.py
@abc.abstractmethod
def assemble_name(self) -> str:
    """Assemble and return the name for this check."""

assemble_query abstractmethod

assemble_query() -> str

Assemble and return the SQL query for this check.

Source code in src/koality/checks.py
@abc.abstractmethod
def assemble_query(self) -> str:
    """Assemble and return the SQL query for this check."""

assemble_where_statement staticmethod

assemble_where_statement(filters: dict[str, dict[str, Any]], *, strip_dotted_columns: bool = True, database_accessor: str | None = None, dialect: SqlDialect = DUCKDB_DIALECT) -> str

Generate the where statement for the check query using the specified filters.

Parameters:

Name Type Description Default
filters dict[str, dict[str, Any]]

A dict containing filter specifications (see the example below).

required
strip_dotted_columns bool

When True (default), dotted column names (e.g. "a.b") are transformed based on the data source:

  • With database_accessor: converted to underscores ("a_b") for flattened data
  • Without database_accessor: kept as dots ("a.b") for native DuckDB structs

If False, the full dotted expression is preserved regardless (used when querying source databases that expect the original dotted column syntax).

True
database_accessor str | None

Optional database accessor string. When provided and non-empty, indicates data was loaded from external source and dotted columns should be converted to underscores.

None
dialect SqlDialect

How values, date columns and date literals are written (DuckDB by default; the fetch query uses the source's backend, e.g. BigQuery literals).

DUCKDB_DIALECT
Example
from koality.checks import DataQualityCheck

filters = {
    "identifier": {"column": "shop_code", "value": "SHOP01", "operator": "=", "type": "identifier"},
    "date": {"column": "date", "value": "2023-01-01", "operator": "=", "type": "date"},
    "revenue": {"column": "total_revenue", "value": 1000, "operator": ">="},
    "category": {"column": "category", "value": ["toys", "electronics"], "operator": "IN"},
}
DataQualityCheck.assemble_where_statement(filters)

Returns:

Type Description
str

A WHERE statement to restrict the data being used for the check, e.g. for the example WHERE shop_code = 'SHOP01' AND CAST(date AS DATE) = DATE '2023-01-01' AND total_revenue >= 1000 AND category IN ('toys', 'electronics')

Source code in src/koality/checks.py
@staticmethod
def assemble_where_statement(  # noqa: C901
    filters: dict[str, dict[str, Any]],
    *,
    strip_dotted_columns: bool = True,
    database_accessor: str | None = None,
    dialect: SqlDialect = DUCKDB_DIALECT,
) -> str:
    """Generate the where statement for the check query using the specified filters.

    Args:
        filters: A dict containing filter specifications (see the example below).
        strip_dotted_columns: When True (default), dotted column names (e.g. "a.b") are
            transformed based on the data source:

            - With database_accessor: converted to underscores ("a_b") for flattened data
            - Without database_accessor: kept as dots ("a.b") for native DuckDB structs

            If False, the full dotted expression is preserved regardless (used when
            querying source databases that expect the original dotted column syntax).
        database_accessor: Optional database accessor string. When provided and non-empty,
            indicates data was loaded from external source and dotted columns should be
            converted to underscores.
        dialect: How values, date columns and date literals are written (DuckDB by default; the fetch
            query uses the source's backend, e.g. BigQuery literals).

    Example:
        ```python
        from koality.checks import DataQualityCheck

        filters = {
            "identifier": {"column": "shop_code", "value": "SHOP01", "operator": "=", "type": "identifier"},
            "date": {"column": "date", "value": "2023-01-01", "operator": "=", "type": "date"},
            "revenue": {"column": "total_revenue", "value": 1000, "operator": ">="},
            "category": {"column": "category", "value": ["toys", "electronics"], "operator": "IN"},
        }
        DataQualityCheck.assemble_where_statement(filters)
        ```

    Returns:
        A WHERE statement to restrict the data being used for the check, e.g. for the example
            `WHERE shop_code = 'SHOP01' AND CAST(date AS DATE) = DATE '2023-01-01' AND total_revenue >= 1000
            AND category IN ('toys', 'electronics')`

    """
    if len(filters) == 0:
        return ""

    filters_statements = []
    for filter_dict in filters.values():
        column = filter_dict.get("column")
        value = filter_dict.get("value")
        # Skip identifier filters that do not specify a concrete value (used only for naming)
        if filter_dict.get("type") == "identifier" and (value is None or value == "*"):
            continue
        # If column is not provided we cannot build a WHERE condition
        if column is None:
            continue
        # If the column references a nested field (e.g. "value.shopId"):
        # - With database_accessor: convert to underscores (value_shopId) for flattened data
        # - Without database_accessor: keep dots (value.shopId) for native DuckDB structs
        # Callers can disable this by setting `strip_dotted_columns=False`
        # (used when querying source DBs where the original dotted expression is needed).
        if isinstance(column, str) and "." in column and strip_dotted_columns and database_accessor:
            column = column.replace(".", "_")
            # else: keep dotted notation for native DuckDB struct support

        operator = filter_dict.get("operator", "=")

        # Cast date columns for proper comparison
        is_date_filter = filter_dict.get("type") == "date"
        if is_date_filter:
            column = dialect.date_column(column)

        # Handle NULL values with IS NULL / IS NOT NULL
        if value is None:
            if operator == "!=":
                filters_statements.append(f"    {column} IS NOT NULL")
            else:
                filters_statements.append(f"    {column} IS NULL")
            continue

        if is_date_filter and operator not in ("BETWEEN", "IN", "NOT IN"):
            formatted_value = dialect.date_literal(value)
        else:
            formatted_value = dialect.format_filter_value(value, operator)
        filters_statements.append(f"    {column} {operator} {formatted_value}")

    if len(filters_statements) == 0:
        return ""

    return "WHERE\n" + "\nAND\n".join(filters_statements)

check

check(duckdb_client: DuckDBPyConnection) -> dict

Perform the data quality check and return results.

If the check is set to monitor_only, the results of the check will be documented without comparison to the lower and upper thresholds.

Parameters:

Name Type Description Default
duckdb_client DuckDBPyConnection

DuckDB client for interacting with DuckDB

required

Returns:

Type Description
dict

A dict containing all information and the result of the check

Source code in src/koality/checks.py
def check(self, duckdb_client: duckdb.DuckDBPyConnection) -> dict:
    """Perform the data quality check and return results.

    If the check is set to `monitor_only`, the results of the
    check will be documented without comparison to the lower and
    upper thresholds.

    Args:
        duckdb_client: DuckDB client for interacting with DuckDB

    Returns:
        A dict containing all information and the result of the check

    """
    result, error = self._check(duckdb_client, self.query)

    check_value = result[0][self.name] if result else None
    check_value = float(check_value) if check_value is not None else None

    date = self.date_filter["value"] if self.date_filter else dt.datetime.now(tz=dt.UTC).date().isoformat()

    if error:
        # Map BigQuery binder "dataset not found" errors to a table existence failure
        err_str = str(error)
        # "not found" / "does not exist" errors (BigQuery Binder or DuckDB) map to table_exists, except for
        # a misspelled column, which is a query error, not missing data
        lowered = err_str.lower()
        if ("not found" in lowered or "does not exist" in lowered) and "referenced column" not in lowered:
            self.status = "FAIL"
            result_dict = {
                "DATE": date,
                "METRIC_NAME": "table_exists",
                self.identifier_column: self.identifier,
                "TABLE": self.table,
                "COLUMN": None,
                "VALUE": None,
                "LOWER_THRESHOLD": None,
                "UPPER_THRESHOLD": None,
                "RESULT": "FAIL",
            }
            self.result = result_dict
            return result_dict
        result = "ERROR"
        self.message = f"{self.identifier}: Metric {self.name} query errored with {error}"
    elif self.monitor_only:
        result = "MONITOR_ONLY"
    else:
        success = check_value is not None and self.lower_threshold <= check_value <= self.upper_threshold
        result = "SUCCESS" if success else "FAIL"

    result_dict = {
        "DATE": date,
        "METRIC_NAME": self.name,
        self.identifier_column: self.identifier,
        "TABLE": self.table,
        "COLUMN": self.check_column,
        "VALUE": check_value,
        "LOWER_THRESHOLD": self.lower_threshold,
        "UPPER_THRESHOLD": self.upper_threshold,
        "RESULT": result,
    }

    if result_dict["RESULT"] == "FAIL":
        value_string = f"{result_dict['VALUE']:.{FLOAT_PRECISION}f}" if result_dict["VALUE"] is not None else "NULL"
        self.message = (
            f"{self.identifier}: Metric {self.name} failed on {date}{self.date_info_string} "
            f"for {self.table}. Value {value_string} is not between {self.lower_threshold} and "
            f"{self.upper_threshold}.{self.extra_info_string}"
        )
    self.status = result_dict["RESULT"]
    self.result = result_dict

    return result_dict

data_check

data_check(duckdb_client: DuckDBPyConnection) -> dict

Check if database tables used in the actual check contain data.

Note: The returned result dict and failure message will be later aggregated in order to avoid duplicates in the reported failures.

Parameters:

Name Type Description Default
duckdb_client DuckDBPyConnection

DuckDB client for interacting with DuckDB

required

Returns:

Type Description
dict

If there is a table without data, a dict containing information about

dict

missing data will be returned, otherwise an empty dict indicating that

dict

data exists.

Source code in src/koality/checks.py
def data_check(self, duckdb_client: duckdb.DuckDBPyConnection) -> dict:
    """Check if database tables used in the actual check contain data.

    Note: The returned result dict and failure message will be later
    aggregated in order to avoid duplicates in the reported failures.

    Args:
        duckdb_client: DuckDB client for interacting with DuckDB

    Returns:
        If there is a table without data, a dict containing information about
        missing data will be returned, otherwise an empty dict indicating that
        data exists.

    """
    try:
        rows = execute_query(
            self.assemble_data_exists_query(),
            duckdb_client,
            None,
            None,
        ).fetchall()
    except duckdb.Error as e:
        msg = f"Error while executing data check query on {self.table}"
        raise DatabaseError(msg) from e
    else:
        empty_table = rows[0][0] if rows else self.table
        is_empty_table = bool(empty_table)

    if not is_empty_table:
        return {}

    date = self.date_filter["value"] if self.date_filter else dt.datetime.now(tz=dt.UTC).date().isoformat()
    self.message = f"No data in {empty_table} on {date} for: {self.identifier}"
    self.status = "FAIL"
    return {
        "DATE": date,
        "METRIC_NAME": "data_exists",
        self.identifier_column: self.identifier,
        "TABLE": empty_table,
    }

get_date_filter staticmethod

get_date_filter(filters: dict[str, dict[str, Any]]) -> tuple[str, dict[str, Any]] | None

Find the date filter (type='date') from the filters dict.

Parameters:

Name Type Description Default
filters dict[str, dict[str, Any]]

The filters dict from get_filters().

required

Returns:

Type Description
tuple[str, dict[str, Any]] | None

A tuple of (filter_name, filter_config) if found, None otherwise.

Source code in src/koality/checks.py
@staticmethod
def get_date_filter(filters: dict[str, dict[str, Any]]) -> tuple[str, dict[str, Any]] | None:
    """Find the date filter (type='date') from the filters dict.

    Args:
        filters: The filters dict from get_filters().

    Returns:
        A tuple of (filter_name, filter_config) if found, None otherwise.

    """
    for name, config in filters.items():
        if config.get("type") == "date":
            return name, config
    return None

get_filters staticmethod

get_filters(filters_config: dict[str, Any]) -> dict[str, dict[str, Any]]

Generate a filter dict from filter configurations.

Parameters:

Name Type Description Default
filters_config dict[str, Any]

Dictionary containing filter configurations.

required
Example
filters:
  partition_date:
    column: BQ_PARTITIONTIME
    value: yesterday-2  # 2 days before yesterday
    type: date  # auto-parses value as date
  shop_id:
    column: shopId
    value: EC0601
    type: identifier
  revenue:
    column: total_revenue
    value: 1000
    operator: ">="
  category:
    column: category
    value: ["toys", "electronics"]
    operator: "IN"

Returns:

Type Description
dict[str, dict[str, Any]]

A dict of the format {"partition_date": {"column": "DATE", "value": "2020-01-01", "operator": "=", "type": "date"}, ...}

Source code in src/koality/checks.py
@staticmethod
def get_filters(filters_config: dict[str, Any]) -> dict[str, dict[str, Any]]:
    """Generate a filter dict from filter configurations.

    Args:
        filters_config: Dictionary containing filter configurations.

    Example:
        ```yaml
        filters:
          partition_date:
            column: BQ_PARTITIONTIME
            value: yesterday-2  # 2 days before yesterday
            type: date  # auto-parses value as date
          shop_id:
            column: shopId
            value: EC0601
            type: identifier
          revenue:
            column: total_revenue
            value: 1000
            operator: ">="
          category:
            column: category
            value: ["toys", "electronics"]
            operator: "IN"
        ```

    Returns:
        A dict of the format
            `{"partition_date": {"column": "DATE", "value": "2020-01-01", "operator": "=", "type": "date"}, ...}`

    """
    filters: dict[str, dict[str, Any]] = {}

    for filter_name, config in filters_config.items():
        if isinstance(config, FilterConfig):
            config_dict = config.model_dump()
        elif isinstance(config, dict):
            config_dict = config
        else:
            config_dict = {"value": config}

        column = config_dict.get("column")

        value = config_dict.get("value")
        filter_type = config_dict.get("type", "other")

        # Auto-parse date values when type is "date" or parse_as_date is True
        should_parse = filter_type == "date" or config_dict.get("parse_as_date", False)
        if should_parse and value is not None:
            value = parse_date(str(value))

        operator = config_dict.get("operator", "=")

        # If no column is provided, only allow identifier-type filters (used for naming);
        # otherwise skip the filter entirely.
        if column is None and filter_type != "identifier":
            continue

        # Build filter entry; omit 'column' key if column is not provided so
        # downstream code can distinguish filters intended only for naming.
        entry: dict[str, Any] = {
            "value": value,
            "operator": operator,
            "type": filter_type,
        }
        if column is not None:
            entry["column"] = column

        filters[filter_name] = entry

    return filters

get_identifier_filter staticmethod

get_identifier_filter(filters: dict[str, dict[str, Any]]) -> tuple[str, dict[str, Any]] | None

Find the identifier filter (type='identifier') from the filters dict.

Parameters:

Name Type Description Default
filters dict[str, dict[str, Any]]

The filters dict from get_filters().

required

Returns:

Type Description
tuple[str, dict[str, Any]] | None

A tuple of (filter_name, filter_config) if found, None otherwise.

Source code in src/koality/checks.py
@staticmethod
def get_identifier_filter(filters: dict[str, dict[str, Any]]) -> tuple[str, dict[str, Any]] | None:
    """Find the identifier filter (type='identifier') from the filters dict.

    Args:
        filters: The filters dict from get_filters().

    Returns:
        A tuple of (filter_name, filter_config) if found, None otherwise.

    """
    for name, config in filters.items():
        if config.get("type") == "identifier":
            return (name, config)
    return None

source_tables

source_tables() -> list[str]

Return the names of the tables this check reads.

Source code in src/koality/checks.py
def source_tables(self) -> list[str]:
    """Return the names of the tables this check reads."""
    return [self.table]

table_ref

table_ref(table: str) -> str

Return the reference to use for table in in-memory queries.

Data fetched by the executor lives in the staging catalog (see CheckExecutor.fetch_data_into_memory); otherwise the table is queried as-is.

Source code in src/koality/checks.py
def table_ref(self, table: str) -> str:
    """Return the reference to use for `table` in in-memory queries.

    Data fetched by the executor lives in the staging catalog (see
    `CheckExecutor.fetch_data_into_memory`); otherwise the table is queried as-is.
    """
    if self.staging_catalog:
        return staged_table_ref(self.staging_catalog, table)
    return qualify_table_name("", table)

DuplicateCheck

DuplicateCheck(database_accessor: str, database_provider: DatabaseProvider | None, table: str, check_column: str, lower_threshold: float = -inf, upper_threshold: float = inf, *, transformation_name: str | None = None, **options: Unpack[CheckOptions])

Bases: ColumnTransformationCheck

Check the number of duplicates for a specific column.

Counts all rows minus distinct counts. Takes the arguments of ColumnTransformationCheck and the options in CheckOptions.

Example
from koality.checks import DuplicateCheck

DuplicateCheck(
    database_accessor="",
    database_provider=None,
    table="skufeed_latest",
    check_column="sku_id",
    filters={
        "identifier": {"column": "shop_code", "value": "SHOP01", "type": "identifier"},
        "date": {"column": "DATE", "value": "2023-01-01", "type": "date"},
    },
    lower_threshold=0.0,
    upper_threshold=0.0,
)
Source code in src/koality/checks.py
def __init__(
    self,
    database_accessor: str,
    database_provider: DatabaseProvider | None,
    table: str,
    check_column: str,
    lower_threshold: float = -math.inf,
    upper_threshold: float = math.inf,
    *,
    transformation_name: str | None = None,
    **options: Unpack[CheckOptions],
) -> None:
    """Initialize the column transformation check."""
    if transformation_name is not None:
        self.transformation_name = transformation_name
    if not getattr(self, "transformation_name", None):
        msg = f"{type(self).__name__} must set 'transformation_name'"
        raise KoalityError(msg)

    super().__init__(
        database_accessor=database_accessor,
        database_provider=database_provider,
        table=table,
        check_column=check_column,
        lower_threshold=lower_threshold,
        upper_threshold=upper_threshold,
        **options,
    )

transformation_statement

transformation_statement() -> str

Return the SQL statement for counting duplicates.

Source code in src/koality/checks.py
def transformation_statement(self) -> str:
    """Return the SQL statement for counting duplicates."""
    return f"COUNT(*) - COUNT(DISTINCT {self.in_memory_column}) AS {self.name}"

IqrOutlierCheck

IqrOutlierCheck(database_accessor: str, database_provider: DatabaseProvider | None, check_column: str, table: str, interval_days: int, how: Literal['both', 'upper', 'lower'], iqr_factor: float, **options: Unpack[CheckOptions])

Bases: ColumnTransformationCheck

Check if a column value is an outlier based on the interquartile range (IQR) method.

Takes the arguments of ColumnTransformationCheck (except lower_threshold, upper_threshold and transformation_name) and the options in CheckOptions. Its filters must include a filter with type: date.

The IQR method is based on the 25th and 75th percentiles of the data. The thresholds are calculated as follows:

  • lower_threshold = q25 - iqr_factor * (q75 - q25)
  • upper_threshold = q75 + iqr_factor * (q75 - q25)

Note: lower_threshold and upper_threshold are calculated internally and should not be provided directly in the configuration for IqrOutlierCheck.

Parameters:

Name Type Description Default
interval_days int

Number of historic days to use for IQR calculation.

required
how Literal['both', 'upper', 'lower']

Check mode - 'both', 'upper', or 'lower' outliers.

required
iqr_factor float

Multiplier for IQR range (minimum 1.5).

required
Example
from koality.checks import IqrOutlierCheck

IqrOutlierCheck(
    database_accessor="",
    database_provider=None,
    check_column="num_orders",
    table="orders",
    interval_days=14,
    how="both",
    iqr_factor=1.5,
    filters={
        "partition_date": {"column": "DATE", "value": "2023-01-01", "type": "date"},
        "identifier": {"column": "shop_code", "value": "SHOP01", "type": "identifier"},
    },
)
Source code in src/koality/checks.py
def __init__(
    self,
    database_accessor: str,
    database_provider: DatabaseProvider | None,
    check_column: str,
    table: str,
    interval_days: int,
    how: Literal["both", "upper", "lower"],
    iqr_factor: float,
    **options: Unpack[CheckOptions],
) -> None:
    """Initialize the IQR outlier check."""
    if interval_days < 1:
        msg = "interval_days must be at least 1"
        raise KoalityError(msg)
    self.interval_days = int(interval_days)
    if how not in ["both", "upper", "lower"]:
        msg = "how must be one of 'both', 'upper', 'lower'"
        raise KoalityError(msg)
    self.how = how
    # reasonable lower bound for iqr_factor
    if iqr_factor < self.MIN_IQR_FACTOR:
        msg = f"iqr_factor must be at least {self.MIN_IQR_FACTOR}"
        raise KoalityError(msg)
    self.iqr_factor = float(iqr_factor)

    super().__init__(
        database_accessor=database_accessor,
        database_provider=database_provider,
        transformation_name=f"outlier_iqr_{self.how}_{str(self.iqr_factor).replace('.', '_')}",
        table=table,
        check_column=check_column,
        lower_threshold=-math.inf,
        upper_threshold=math.inf,
        **options,
    )
    self._require_date_filter("IqrOutlierCheck")

assemble_data_exists_query

assemble_data_exists_query() -> str

Assemble the query to check if data exists for IQR outlier detection.

Source code in src/koality/checks.py
def assemble_data_exists_query(self) -> str:
    """Assemble the query to check if data exists for IQR outlier detection."""
    data_exists_query = f"""
    SELECT
        IF(COUNTIF({self.in_memory_column} IS NOT NULL) > 0, '', {sql_literal(self.table)}) AS empty_table
    FROM
        {self.table_ref(self.table)}
    """
    filters = {k: v for k, v in self.filters.items() if v["type"] != "date"}

    where_statement = self.assemble_where_statement(filters, database_accessor=self.database_accessor)
    if self.date_filter:
        date_col = self.date_filter["column"]
        date_val = self.date_filter["value"]
        if where_statement:
            where_statement = f"{where_statement} AND CAST({date_col} AS DATE) = DATE '{date_val}'"
        else:
            where_statement = f"WHERE CAST({date_col} AS DATE) = DATE '{date_val}'"
    return f"{data_exists_query}\n{where_statement}"

query_boilerplate

query_boilerplate(metric_statement: str) -> str

Return the query structure for IQR outlier detection.

Source code in src/koality/checks.py
def query_boilerplate(self, metric_statement: str) -> str:
    """Return the query structure for IQR outlier detection."""
    return f"""
        {metric_statement}

        SELECT
            *
        FROM
            stats
    """

transformation_statement

transformation_statement() -> str

Return the SQL statement for IQR-based outlier detection.

Source code in src/koality/checks.py
def transformation_statement(self) -> str:
    """Return the SQL statement for IQR-based outlier detection."""
    # TODO: currently we only raise an error if there is no data for the date
    #       we could also raise an error if there is not enough data for the
    #       IQR calculation
    where_statement = ""
    filter_columns = ""
    if not self.date_filter:
        msg = "IqrOutlierCheck requires a date filter for the IQR calculation."
        raise KoalityError(msg)

    date_col = self.date_filter["column"]
    date_val = self.date_filter["value"]

    filters = {k: v for k, v in self.filters.items() if v["type"] != "date"}

    # Naming-only identifier filters have no column and produce no condition
    if columns := [v["column"] for v in filters.values() if "column" in v]:
        filter_columns = ",\n" + ",\n".join(columns)
    if where_statement := self.assemble_where_statement(filters, database_accessor=self.database_accessor):
        where_statement = "\nAND\n" + where_statement.removeprefix("WHERE\n")
    return f"""
    WITH
        base AS (
            SELECT
                DATE({date_col}) AS {date_col},
                {self.in_memory_column}
                {filter_columns}
            FROM
                {self.table_ref(self.table)}
            WHERE
                DATE({date_col}) BETWEEN (DATE '{date_val}' - INTERVAL {self.interval_days} DAY)
                AND DATE '{date_val}'
                {where_statement}
        ),
        compare AS (
            SELECT * FROM base WHERE {date_col} < DATE '{date_val}'
        ),
        slice AS (
            SELECT * FROM base WHERE {date_col} = DATE '{date_val}'
        ),
        percentiles AS (
            SELECT
              QUANTILE_CONT(CAST({self.in_memory_column} AS FLOAT), 0.25) AS q25,
              QUANTILE_CONT(CAST({self.in_memory_column} AS FLOAT), 0.75) AS q75
            FROM
              compare
        ),
        stats AS (
            SELECT
              * exclude ({self.in_memory_column}),
              {self.in_memory_column} AS {self.name},
              (percentiles.q25 - {self.iqr_factor} * (percentiles.q75 - percentiles.q25)) AS lower_threshold,
              (percentiles.q75 + {self.iqr_factor} * (percentiles.q75 - percentiles.q25)) AS upper_threshold,
            FROM
              slice
            LEFT JOIN percentiles
            ON TRUE
        )
    """

MatchRateCheck

MatchRateCheck(database_accessor: str, database_provider: DatabaseProvider | None, left_table: str, right_table: str, check_column: str, join_columns: list[str] | None = None, join_columns_left: list[str] | None = None, join_columns_right: list[str] | None = None, lower_threshold: float = -inf, upper_threshold: float = inf, *, filters_left: dict[str, Any] | None = None, filters_right: dict[str, Any] | None = None, **options: Unpack[CheckOptions])

Bases: DataQualityCheck

Checks the match rate between two tables after joining on specific columns.

If left_join_columns (or right_join_columns) is defined, these columns will be used for joining the data. If not, join_columns will be used as fallback.

Parameters:

Name Type Description Default
left_table str

The table whose rows are matched, the left side of the join (e.g. "pdp_views", or "dataset.pdp_views" in BigQuery).

required
right_table str

The table they are matched against, the right side of the join (e.g. "skufeed_latest").

required
check_column str

Name of column to be checked (e.g., "product_number")

required
join_columns list[str] | None

List of columns to join data on (e.g., ["PREDICTION_DATE", "product_number"])

None
join_columns_left list[str] | None

List of columns of left table to join data on (e.g., ["BQ_PARTITIONTIME", "productId"])

None
join_columns_right list[str] | None

List of columns of right table to join data on (e.g., ["PREDICTION_DATE", "product_number"])

None
lower_threshold float

The check fails if its result is below this.

-inf
upper_threshold float

The check fails if its result is above this.

inf
filters_left dict[str, Any] | None

Filters for the left table only, applied on top of filters.

None
filters_right dict[str, Any] | None

Filters for the right table only, applied on top of filters.

None

database_accessor and database_provider are as in DataQualityCheck. Further keyword options (e.g. filters, applied to both tables): see CheckOptions.

Example
from koality.checks import MatchRateCheck

MatchRateCheck(
    database_accessor="",
    database_provider=None,
    left_table="pdp_views",
    right_table="skufeed_latest",
    join_columns_left=["DATE", "product_number_v2"],
    join_columns_right=["DATE", "product_number"],
    check_column="product_number",
    filters={
        "identifier": {"column": "shop_code", "value": "SHOP01", "type": "identifier"},
        "date": {"column": "DATE", "value": "2023-01-01", "type": "date"},
    },
    filters_left={
        "status": {"column": "order_status", "value": "completed"},
    },
    filters_right={
        "active": {"column": "is_active", "value": True},
    },
)
Source code in src/koality/checks.py
def __init__(
    self,
    database_accessor: str,
    database_provider: DatabaseProvider | None,
    left_table: str,
    right_table: str,
    check_column: str,
    join_columns: list[str] | None = None,
    join_columns_left: list[str] | None = None,
    join_columns_right: list[str] | None = None,
    lower_threshold: float = -math.inf,
    upper_threshold: float = math.inf,
    *,
    filters_left: dict[str, Any] | None = None,
    filters_right: dict[str, Any] | None = None,
    **options: Unpack[CheckOptions],
) -> None:
    """Initialize the match rate check."""
    self.left_table = left_table
    self.right_table = right_table

    if not (join_columns or (join_columns_left and join_columns_right)):
        msg = "No join_columns was provided. Use either join_columns or join_columns_left and join_columns_right"
        raise KoalityError(msg)

    # mypy typing does not understand that None is not possible, thus, we
    # add `or []`
    self.join_columns_left: list[str] = join_columns_left or join_columns or []
    self.join_columns_right: list[str] = join_columns_right or join_columns or []

    if not self.join_columns_right or not self.join_columns_left:
        msg = "No join_columns was provided. Use join_columns, join_columns_left, and/or join_columns_right"
        raise KoalityError(msg)

    if len(self.join_columns_left) != len(self.join_columns_right):
        msg = (
            f"join_columns_left and join_columns_right need to have equal length"
            f" ({len(self.join_columns_left)} vs. {len(self.join_columns_right)})."
        )
        raise KoalityError(msg)

    super().__init__(
        database_accessor=database_accessor,
        database_provider=database_provider,
        table=f"{self.left_table}_JOIN_{self.right_table}",
        check_column=check_column,
        lower_threshold=lower_threshold,
        upper_threshold=upper_threshold,
        **options,
    )

    # Support table-specific filters via filters_left and filters_right
    self.filters_left = self.filters | self.get_filters(filters_left or {})
    self.filters_right = self.filters | self.get_filters(filters_right or {})

assemble_data_exists_query

assemble_data_exists_query() -> str

First checks left, then right table for data.

Returns:

Type Description
str

Empty table name or empty string

Source code in src/koality/checks.py
def assemble_data_exists_query(self) -> str:
    """First checks left, then right table for data.

    Returns:
        Empty table name or empty string

    """
    return f"""
    WITH
    righty AS (
        SELECT
            COUNT(*) AS right_counter,
        FROM
            {self.table_ref(self.right_table)}
        {self.assemble_where_statement(self.filters_right, database_accessor=self.database_accessor)}
    ),

    lefty AS (
        SELECT
            COUNT(*) AS left_counter,
        FROM
            {self.table_ref(self.left_table)}
        {self.assemble_where_statement(self.filters_left, database_accessor=self.database_accessor)}
    )

    SELECT
        IF(
            (SELECT * FROM lefty) > 0,
            IF((SELECT * FROM righty) > 0, '', {sql_literal(self.right_table)}),
            {sql_literal(self.left_table)}
        ) AS empty_table
    """

assemble_name

assemble_name() -> str

Return the check name for match rate.

Source code in src/koality/checks.py
def assemble_name(self) -> str:
    """Return the check name for match rate."""
    return f"{self.check_column.split('.')[-1]}_matchrate"

assemble_query

assemble_query() -> str

Assemble the SQL query for calculating match rate between tables.

Source code in src/koality/checks.py
def assemble_query(self) -> str:
    """Assemble the SQL query for calculating match rate between tables."""
    # Transform dotted column names based on data source:
    # - With database_accessor: convert to underscores (value.shopId → value_shopId) for flattened data
    # - Without database_accessor: keep dots for SELECT (value.shopId), use last part for JOIN (shopId)
    if self.database_accessor:
        right_column_statement = ",\n    ".join([col.replace(".", "_") for col in self.join_columns_right])
        join_on_statement = "\n    AND\n    ".join(
            [
                f"lefty.{left_col.replace('.', '_')} = righty.{right_col.replace('.', '_')}"
                for left_col, right_col in zip(self.join_columns_left, self.join_columns_right, strict=False)
            ],
        )
    else:
        # For native DuckDB struct columns: SELECT uses dotted notation,
        # but DuckDB names the result column as just the last part
        right_column_statement = ",\n    ".join(self.join_columns_right)
        join_on_statement = "\n    AND\n    ".join(
            [
                f"lefty.{left_col.split('.')[-1]} = righty.{right_col.split('.')[-1]}"
                for left_col, right_col in zip(self.join_columns_left, self.join_columns_right, strict=False)
            ],
        )

    return f"""
    WITH
        righty AS (
            SELECT DISTINCT
                {right_column_statement},
                TRUE AS in_right_table
            FROM
                {self.table_ref(self.right_table)}
            {self.assemble_where_statement(self.filters_right, database_accessor=self.database_accessor)}
        ),
        lefty AS (
            SELECT
                *
            FROM
                {self.table_ref(self.left_table)}
            {self.assemble_where_statement(self.filters_left, database_accessor=self.database_accessor)}
        )

        SELECT
            CASE
                WHEN COUNT(*) = 0 THEN 0.0
                ELSE ROUND(COUNTIF(in_right_table IS TRUE) / COUNT(*), 3)
            END AS {self.name}
        FROM
            lefty
        LEFT JOIN
            righty
        ON
            {join_on_statement}
    """

source_tables

source_tables() -> list[str]

Return the left and right tables; table is only a label for the join.

Source code in src/koality/checks.py
def source_tables(self) -> list[str]:
    """Return the left and right tables; `table` is only a label for the join."""
    return [self.left_table, self.right_table]

MaxCheck

MaxCheck(database_accessor: str, database_provider: DatabaseProvider | None, table: str, check_column: str, lower_threshold: float = -inf, upper_threshold: float = inf, *, transformation_name: str | None = None, **options: Unpack[CheckOptions])

Bases: ColumnTransformationCheck

Compute the maximum (MAX) of a column for the filtered rows.

Takes the arguments of ColumnTransformationCheck and the options in CheckOptions. Thresholds apply to the computed maximum.

Source code in src/koality/checks.py
def __init__(
    self,
    database_accessor: str,
    database_provider: DatabaseProvider | None,
    table: str,
    check_column: str,
    lower_threshold: float = -math.inf,
    upper_threshold: float = math.inf,
    *,
    transformation_name: str | None = None,
    **options: Unpack[CheckOptions],
) -> None:
    """Initialize the column transformation check."""
    if transformation_name is not None:
        self.transformation_name = transformation_name
    if not getattr(self, "transformation_name", None):
        msg = f"{type(self).__name__} must set 'transformation_name'"
        raise KoalityError(msg)

    super().__init__(
        database_accessor=database_accessor,
        database_provider=database_provider,
        table=table,
        check_column=check_column,
        lower_threshold=lower_threshold,
        upper_threshold=upper_threshold,
        **options,
    )

transformation_statement

transformation_statement() -> str

Return the SQL statement for computing the maximum.

Source code in src/koality/checks.py
def transformation_statement(self) -> str:
    """Return the SQL statement for computing the maximum."""
    return f"MAX({self.in_memory_column}) AS {self.name}"

MinCheck

MinCheck(database_accessor: str, database_provider: DatabaseProvider | None, table: str, check_column: str, lower_threshold: float = -inf, upper_threshold: float = inf, *, transformation_name: str | None = None, **options: Unpack[CheckOptions])

Bases: ColumnTransformationCheck

Compute the minimum (MIN) of a column for the filtered rows.

Takes the arguments of ColumnTransformationCheck and the options in CheckOptions. Thresholds apply to the computed minimum.

Source code in src/koality/checks.py
def __init__(
    self,
    database_accessor: str,
    database_provider: DatabaseProvider | None,
    table: str,
    check_column: str,
    lower_threshold: float = -math.inf,
    upper_threshold: float = math.inf,
    *,
    transformation_name: str | None = None,
    **options: Unpack[CheckOptions],
) -> None:
    """Initialize the column transformation check."""
    if transformation_name is not None:
        self.transformation_name = transformation_name
    if not getattr(self, "transformation_name", None):
        msg = f"{type(self).__name__} must set 'transformation_name'"
        raise KoalityError(msg)

    super().__init__(
        database_accessor=database_accessor,
        database_provider=database_provider,
        table=table,
        check_column=check_column,
        lower_threshold=lower_threshold,
        upper_threshold=upper_threshold,
        **options,
    )

transformation_statement

transformation_statement() -> str

Return the SQL statement for computing the minimum.

Source code in src/koality/checks.py
def transformation_statement(self) -> str:
    """Return the SQL statement for computing the minimum."""
    return f"MIN({self.in_memory_column}) AS {self.name}"

NullRatioCheck

NullRatioCheck(database_accessor: str, database_provider: DatabaseProvider | None, table: str, check_column: str, lower_threshold: float = -inf, upper_threshold: float = inf, *, transformation_name: str | None = None, **options: Unpack[CheckOptions])

Bases: ColumnTransformationCheck

Check the share of NULL values in a specific column of a table.

Takes the arguments of ColumnTransformationCheck and the options in CheckOptions.

Example
from koality.checks import NullRatioCheck

NullRatioCheck(
    database_accessor="",
    database_provider=None,
    table="orders",
    check_column="order_id",
    filters={
        "identifier": {"column": "shop_code", "value": "SHOP01", "type": "identifier"},
        "date": {"column": "date", "value": "2023-01-01", "type": "date"},
    },
    lower_threshold=0.9,
    upper_threshold=1.0,
)
Source code in src/koality/checks.py
def __init__(
    self,
    database_accessor: str,
    database_provider: DatabaseProvider | None,
    table: str,
    check_column: str,
    lower_threshold: float = -math.inf,
    upper_threshold: float = math.inf,
    *,
    transformation_name: str | None = None,
    **options: Unpack[CheckOptions],
) -> None:
    """Initialize the column transformation check."""
    if transformation_name is not None:
        self.transformation_name = transformation_name
    if not getattr(self, "transformation_name", None):
        msg = f"{type(self).__name__} must set 'transformation_name'"
        raise KoalityError(msg)

    super().__init__(
        database_accessor=database_accessor,
        database_provider=database_provider,
        table=table,
        check_column=check_column,
        lower_threshold=lower_threshold,
        upper_threshold=upper_threshold,
        **options,
    )

transformation_statement

transformation_statement() -> str

Return the SQL statement for calculating null ratio.

Source code in src/koality/checks.py
def transformation_statement(self) -> str:
    """Return the SQL statement for calculating null ratio."""
    return f"""
        CASE
            WHEN COUNT(*) = 0 THEN 0.0
            ELSE ROUND(COUNTIF({self.in_memory_column} IS NULL) / COUNT(*), 3)
        END AS {self.name}
    """

OccurrenceCheck

OccurrenceCheck(database_accessor: str, database_provider: DatabaseProvider | None, max_or_min: Literal['max', 'min'], table: str, check_column: str, lower_threshold: float = -inf, upper_threshold: float = inf, **options: Unpack[CheckOptions])

Bases: ColumnTransformationCheck

Check how often any value in a column occurs.

Useful e.g. to check for a single product occurring unusually often (likely an error). Takes the arguments of ColumnTransformationCheck (except transformation_name) and the options in CheckOptions.

Parameters:

Name Type Description Default
max_or_min Literal['max', 'min']

Check either the maximum or minimum occurrence of any value.

  • If you want to check if any value occurs more than x times, use 'max' and upper_threshold=x
  • If you want to check if any value occurs less than y times, use 'min' and lower_threshold=y
required
Example
from koality.checks import OccurrenceCheck

OccurrenceCheck(
    database_accessor="",
    database_provider=None,
    max_or_min="max",
    table="skufeed_latest",
    check_column="sku_id",
    filters={
        "identifier": {"column": "shop_code", "value": "SHOP01", "type": "identifier"},
        "date": {"column": "DATE", "value": "2023-01-01", "type": "date"},
    },
    lower_threshold=0,
    upper_threshold=500,
)
Source code in src/koality/checks.py
def __init__(
    self,
    database_accessor: str,
    database_provider: DatabaseProvider | None,
    max_or_min: Literal["max", "min"],
    table: str,
    check_column: str,
    lower_threshold: float = -math.inf,
    upper_threshold: float = math.inf,
    **options: Unpack[CheckOptions],
) -> None:
    """Initialize the occurrence check."""
    if max_or_min not in ("max", "min"):
        msg = "'max_or_min' must be one of supported modes 'min' or 'max'"
        raise KoalityError(msg)
    self.max_or_min = max_or_min
    super().__init__(
        database_accessor=database_accessor,
        database_provider=database_provider,
        transformation_name=f"occurrence_{max_or_min}",
        table=table,
        check_column=check_column,
        lower_threshold=lower_threshold,
        upper_threshold=upper_threshold,
        **options,
    )

assemble_query

assemble_query() -> str

Assemble query to find max or min occurrence of any value.

Source code in src/koality/checks.py
def assemble_query(self) -> str:
    """Assemble query to find max or min occurrence of any value."""
    # Since koality checks only the first entry, the table with value + count_occurence is
    # ordered DESC/ASC depending on whether max/min occurence is supposed to be checked.
    order = {"max": "DESC", "min": "ASC"}[self.max_or_min]
    return f"""
        {self.query_boilerplate(self.transformation_statement())}
        {self.assemble_where_statement(self.filters, database_accessor=self.database_accessor)}
        GROUP BY {self.in_memory_column}
        ORDER BY {self.name} {order}
        LIMIT 1  -- only the first entry is needed
    """

transformation_statement

transformation_statement() -> str

Return the SQL statement for counting occurrences.

Source code in src/koality/checks.py
def transformation_statement(self) -> str:
    """Return the SQL statement for counting occurrences."""
    return f"{self.in_memory_column}, COUNT(*) AS {self.name}"

RegexMatchCheck

RegexMatchCheck(database_accessor: str, database_provider: DatabaseProvider | None, table: str, check_column: str, regex_to_match: str, lower_threshold: float = -inf, upper_threshold: float = inf, **options: Unpack[CheckOptions])

Bases: ColumnTransformationCheck

Check the share of values matching a regex in a specific column of a table.

Takes the arguments of ColumnTransformationCheck (except transformation_name) and the options in CheckOptions.

Parameters:

Name Type Description Default
regex_to_match str

The regular expression to be checked on check_column (e.g., "SHOP[0-9]{2}-.*" to check for a shop code prefix like "SHOP01-")

required
Example
from koality.checks import RegexMatchCheck

RegexMatchCheck(
    database_accessor="",
    database_provider=None,
    table="orders",
    check_column="order_id",
    regex_to_match="^SHOP[0-9]{2}-.*",
    filters={"date": {"column": "date", "value": "2023-01-01", "type": "date"}},
    lower_threshold=0.9,
    upper_threshold=1.0,
)
Source code in src/koality/checks.py
def __init__(
    self,
    database_accessor: str,
    database_provider: DatabaseProvider | None,
    table: str,
    check_column: str,
    regex_to_match: str,
    lower_threshold: float = -math.inf,
    upper_threshold: float = math.inf,
    **options: Unpack[CheckOptions],
) -> None:
    """Initialize the regex match check."""
    self.regex_to_match = regex_to_match

    super().__init__(
        database_accessor=database_accessor,
        database_provider=database_provider,
        table=table,
        check_column=check_column,
        lower_threshold=lower_threshold,
        upper_threshold=upper_threshold,
        **options,
    )

transformation_statement

transformation_statement() -> str

Return the SQL statement for calculating regex match ratio.

Source code in src/koality/checks.py
def transformation_statement(self) -> str:
    """Return the SQL statement for calculating regex match ratio."""
    regex = sql_literal(self.regex_to_match)
    return f"""AVG(IF(regexp_matches({self.in_memory_column}, {regex}), 1, 0)) AS {self.name}"""

RelCountChangeCheck

RelCountChangeCheck(database_accessor: str, database_provider: DatabaseProvider | None, table: str, check_column: str, rolling_days: int, lower_threshold: float = -inf, upper_threshold: float = inf, **options: Unpack[CheckOptions])

Bases: DataQualityCheck

Check the relative change of a count compared to historic average.

Compares the count to the average counts of a number of historic days before the check date.

Parameters:

Name Type Description Default
table str

The table to check (e.g. "feature_category", or "dataset.feature_category" in BigQuery).

required
check_column str

The column whose distinct values are counted per day (e.g. "category"), or "*" to count rows.

required
rolling_days int

The number of historic days to be taken into account for the historic average baseline for the comparison (e.g., 7).

required
lower_threshold float

The check fails if its result is below this.

-inf
upper_threshold float

The check fails if its result is above this.

inf

database_accessor and database_provider are as in DataQualityCheck. Further keyword options: see CheckOptions; filters must include a filter with type: date, with column and value.

Example
from koality.checks import RelCountChangeCheck

RelCountChangeCheck(
    database_accessor="",
    database_provider=None,
    table="skufeed_latest",
    check_column="sku_id",
    rolling_days=7,
    filters={
        "partition_date": {"column": "DATE", "value": "2023-01-01", "type": "date"},
        "identifier": {"column": "shop_code", "value": "SHOP01", "type": "identifier"},
    },
    lower_threshold=-0.15,
    upper_threshold=0.15,
)
Source code in src/koality/checks.py
def __init__(
    self,
    database_accessor: str,
    database_provider: DatabaseProvider | None,
    table: str,
    check_column: str,
    rolling_days: int,
    lower_threshold: float = -math.inf,
    upper_threshold: float = math.inf,
    **options: Unpack[CheckOptions],
) -> None:
    """Initialize the relative count change check."""
    self.rolling_days = rolling_days

    super().__init__(
        database_accessor=database_accessor,
        database_provider=database_provider,
        table=table,
        check_column=check_column,
        lower_threshold=lower_threshold,
        upper_threshold=upper_threshold,
        **options,
    )
    self._require_date_filter("RelCountChangeCheck")

    # Remove date filter from WHERE clause (it's used in the rolling window SQL, not WHERE)
    self.filters = {name: cfg for name, cfg in self.filters.items() if cfg.get("type") != "date"}

assemble_data_exists_query

assemble_data_exists_query() -> str

Assemble the SQL query to check if data exists for the check date.

Source code in src/koality/checks.py
def assemble_data_exists_query(self) -> str:
    """Assemble the SQL query to check if data exists for the check date."""
    data_exists_query = f"""
    SELECT
        IF(COUNT(*) > 0, '', {sql_literal(self.table)}) AS empty_table
    FROM
        {self.table_ref(self.table)}
    """
    if not self.date_filter:
        msg = "RelCountChangeCheck requires a filter with type='date'"
        raise KoalityError(msg)

    date_col = self.date_filter["column"]
    date_val = self.date_filter["value"]

    where_statement = self.assemble_where_statement(self.filters, database_accessor=self.database_accessor)
    if where_statement:
        return f"{data_exists_query}\n{where_statement} AND CAST({date_col} AS DATE) = DATE '{date_val}'"
    return f"{data_exists_query}\nWHERE CAST({date_col} AS DATE) = DATE '{date_val}'"

assemble_name

assemble_name() -> str

Return the check name for count change, row_count_change for a row count ("*").

Source code in src/koality/checks.py
def assemble_name(self) -> str:
    """Return the check name for count change, `row_count_change` for a row count ("*")."""
    if self.check_column == "*":
        return "row_count_change"
    return f"{self.check_column.split('.')[-1]}_count_change"

assemble_query

assemble_query() -> str

Assemble the SQL query for calculating relative count change.

Source code in src/koality/checks.py
def assemble_query(self) -> str:
    """Assemble the SQL query for calculating relative count change."""
    # The filters extend the WHERE below; only the leading keyword is replaced, not "WHERE" inside a value
    where_statement = self.assemble_where_statement(self.filters, database_accessor=self.database_accessor)
    where_statement = "AND\n" + where_statement.removeprefix("WHERE\n") if where_statement else ""
    if not self.date_filter:
        msg = "RelCountChangeCheck requires a filter with type='date'"
        raise KoalityError(msg)

    date_col = self.date_filter["column"]
    date_val = self.date_filter["value"]

    return f"""
    WITH
        base AS (
            SELECT
                CAST({date_col} AS DATE) AS date_col_cast,
                {"COUNT(*)" if self.check_column == "*" else f"COUNT(DISTINCT {self.in_memory_column})"} AS dist_cnt
            FROM
                {self.table_ref(self.table)}
            WHERE
                CAST({date_col} AS DATE) BETWEEN (DATE '{date_val}' - INTERVAL {self.rolling_days} DAY)
                AND DATE '{date_val}'
            {where_statement}
            GROUP BY
                CAST({date_col} AS DATE)
        ),
        rolling_avgs AS (
            SELECT
                AVG(dist_cnt) AS rolling_avg
            FROM
                base
            WHERE
                date_col_cast BETWEEN (DATE '{date_val}' - INTERVAL {self.rolling_days} DAY)
            AND
                (DATE '{date_val}' - INTERVAL 1 DAY)
        ),

        -- Helper is needed to cover case where no current data is available
        dist_cnt_helper AS (
            SELECT
                MAX(dist_cnt) AS dist_cnt
            FROM
                (
                    SELECT dist_cnt FROM base WHERE date_col_cast = DATE '{date_val}'
                    UNION ALL
                    SELECT 0 AS dist_cnt
                )
        )

        SELECT
            CASE
                WHEN rolling_avg = 0 THEN 0.0
                ELSE ROUND((dist_cnt - rolling_avg) / rolling_avg, 3)
            END AS {self.name}
        FROM
            dist_cnt_helper
        JOIN
            rolling_avgs
        ON TRUE
    """

RollingValuesInSetCheck

RollingValuesInSetCheck(database_accessor: str, database_provider: DatabaseProvider | None, table: str, check_column: str, value_set: str | bytes | Iterable, lower_threshold: float = -inf, upper_threshold: float = inf, **options: Unpack[CheckOptions])

Bases: ValuesInSetCheck

Check share of values matching a value set over a rolling time period.

Similar to ValuesInSetCheck, but the share is computed for a longer time period (currently also including data of the 14 days before the actual check date). Takes the arguments of ValuesInSetCheck (except transformation_name) and the options in CheckOptions; filters must include a filter with type: date, with column and value.

Example
from koality.checks import RollingValuesInSetCheck

RollingValuesInSetCheck(
    database_accessor="",
    database_provider=None,
    table="orders",
    check_column="category",
    value_set='("toys", "shoes")',
    filters={
        "partition_date": {"column": "DATE", "value": "2023-01-01", "type": "date"},
        "identifier": {"column": "shop_code", "value": "SHOP01", "type": "identifier"},
    },
    lower_threshold=0.9,
    upper_threshold=1.0,
)
Source code in src/koality/checks.py
def __init__(
    self,
    database_accessor: str,
    database_provider: DatabaseProvider | None,
    table: str,
    check_column: str,
    value_set: str | bytes | Iterable,
    lower_threshold: float = -math.inf,
    upper_threshold: float = math.inf,
    **options: Unpack[CheckOptions],
) -> None:
    """Initialize the rolling values in set check."""
    super().__init__(
        database_accessor=database_accessor,
        database_provider=database_provider,
        table=table,
        value_set=value_set,
        check_column=check_column,
        lower_threshold=lower_threshold,
        upper_threshold=upper_threshold,
        **options,
    )
    self._require_date_filter("RollingValuesInSetCheck")

    # Remove date filter from WHERE clause (it's used in the rolling window SQL, not WHERE)
    self.filters = {name: cfg for name, cfg in self.filters.items() if cfg.get("type") != "date"}

assemble_query

assemble_query() -> str

Assemble query with rolling date range for values in set check.

Source code in src/koality/checks.py
def assemble_query(self) -> str:
    """Assemble query with rolling date range for values in set check."""
    main_query = self.query_boilerplate(self.transformation_statement())
    if not self.date_filter:
        msg = "RollingValuesInSetCheck requires a filter with type='date'"
        raise KoalityError(msg)

    date_col = self.date_filter["column"]
    date_val = self.date_filter["value"]

    main_query += (
        "WHERE\n    "
        f"CAST({date_col} AS DATE) BETWEEN (DATE '{date_val}' - INTERVAL 14 DAY) AND DATE '{date_val}'"
    )  # TODO: maybe parameterize interval days

    if where_statement := self.assemble_where_statement(self.filters, database_accessor=self.database_accessor):
        return main_query + "\nAND\n" + where_statement.removeprefix("WHERE\n")

    return main_query

ValuesInSetCheck

ValuesInSetCheck(database_accessor: str, database_provider: DatabaseProvider | None, table: str, check_column: str, value_set: str | bytes | Iterable, lower_threshold: float = -inf, upper_threshold: float = inf, *, transformation_name: str | None = None, **options: Unpack[CheckOptions])

Bases: ColumnTransformationCheck

Check the share of values that match any value of a value set in a column.

Takes the arguments of ColumnTransformationCheck and the options in CheckOptions.

Parameters:

Name Type Description Default
value_set str | bytes | Iterable

A list of values (or a string representation of such a list) to be checked. Single values are also allowed. Examples for valid inputs:

  • ["shoes", "clothing"]
  • "clothing"
  • '("shoes", "toys")'
required
Example
from koality.checks import ValuesInSetCheck

ValuesInSetCheck(
    database_accessor="",
    database_provider=None,
    table="orders",
    check_column="category",
    value_set='("toys", "shoes")',
    filters={
        "identifier": {"column": "shop_code", "value": "SHOP01", "type": "identifier"},
        "date": {"column": "date", "value": "2023-01-01", "type": "date"},
    },
    lower_threshold=0.9,
    upper_threshold=1.0,
)
Source code in src/koality/checks.py
def __init__(
    self,
    database_accessor: str,
    database_provider: DatabaseProvider | None,
    table: str,
    check_column: str,
    value_set: str | bytes | Iterable,
    lower_threshold: float = -math.inf,
    upper_threshold: float = math.inf,
    *,
    transformation_name: str | None = None,
    **options: Unpack[CheckOptions],
) -> None:
    """Initialize the values in set check."""
    self.value_set = to_set(value_set)
    if not self.value_set:
        msg = "'value_set' must not be empty"
        raise KoalityError(msg)
    self.value_set_string = format_filter_value(self.value_set, "IN")

    super().__init__(
        database_accessor=database_accessor,
        database_provider=database_provider,
        transformation_name=transformation_name or None,
        table=table,
        check_column=check_column,
        lower_threshold=lower_threshold,
        upper_threshold=upper_threshold,
        **options,
    )

transformation_statement

transformation_statement() -> str

Return the SQL statement for calculating values in set ratio.

Source code in src/koality/checks.py
def transformation_statement(self) -> str:
    """Return the SQL statement for calculating values in set ratio."""
    return f"""AVG(IF({self.in_memory_column} IN {self.value_set_string}, 1, 0)) AS {self.name}"""

staged_table_ref

staged_table_ref(staging_catalog: str, table: str) -> str

Return the fully qualified reference of table in a staging catalog.

Source code in src/koality/checks.py
def staged_table_ref(staging_catalog: str, table: str) -> str:
    """Return the fully qualified reference of `table` in a staging catalog."""
    return f"{quote_identifier(staging_catalog)}.main.{quote_identifier(table)}"

validate_table_name

validate_table_name(name: str, label: str = 'table name') -> None

Raise KoalityError if name cannot be parsed or has more than catalog.schema.table parts.

Source code in src/koality/checks.py
def validate_table_name(name: str, label: str = "table name") -> None:
    """Raise KoalityError if `name` cannot be parsed or has more than catalog.schema.table parts."""
    try:
        parts = split_table_name(name)
    except ValueError as e:
        msg = f"Invalid {label}: {name!r} cannot be parsed"
        raise KoalityError(msg) from e
    if len(parts) > MAX_TABLE_NAME_PARTS:
        msg = f"Invalid {label}: {name!r} has more than {MAX_TABLE_NAME_PARTS} parts (catalog.schema.table)"
        raise KoalityError(msg)