Skip to content

Executor

Module containing the actual check execution logic.

CheckExecutor

CheckExecutor(config: Config, duckdb_client: DuckDBPyConnection | None = None, verbose: bool | None = None, **kwargs: object)

Provide all the logic to actually run checks.

Contains methods to execute checks, to create the failed checks log, and to export DQM results to a database table.

Parameters:

Name Type Description Default
config Config

Koality configuration object

required
duckdb_client DuckDBPyConnection | None

DuckDB client for interacting with DuckDB (optional). If not provided, an in-memory connection will be created, with the config's extensions loaded and its database_setup run; a provided client is used as it is.

None
Source code in src/koality/executor.py
def __init__(
    self,
    config: Config,
    duckdb_client: duckdb.DuckDBPyConnection | None = None,
    verbose: bool | None = None,  # noqa: FBT001
    **kwargs: object,
) -> None:
    """Initialize the check executor with configuration and optional DuckDB client."""
    self.verbose = config.defaults.verbose if verbose is None else verbose
    if self.verbose:
        log.setLevel(logging.DEBUG)
    self.config = config
    # Checked before connecting, since it needs no database
    self.result_table = self.config.defaults.result_table
    if self.result_table is not None:
        validate_table_name(self.result_table, "result_table")
    # A connection created here only lives as long as the executor, so in-memory results would be lost
    self._owns_connection = duckdb_client is None
    self.duckdb_client = duckdb_client if duckdb_client is not None else connect(self.config.extension_directory)
    self.database_provider = None
    try:
        if self._owns_connection:
            load_extensions(self.duckdb_client, self.config.extensions)
            self.duckdb_client.query(self.config.database_setup)
        if self.config.database_accessor:
            self.database_provider = identify_database_provider(self.duckdb_client, self.config.database_accessor)
    except BaseException:
        # Nobody gets the executor, so its own connection would stay open
        if self._owns_connection:
            self.duckdb_client.close()
        raise
    self._backend: Backend | None = None
    self._backend_key: tuple = ()
    self._backend_assigned = False

    self.kwargs = kwargs

    self.checks: list[DataQualityCheck] = []
    self.check_failed = False
    self.check_errored = False

    self.jobs_: list = []

    self.result_dicts: list[dict] = []
    self.persist_results = self.config.defaults.persist_results
    self.log_path = self.config.defaults.log_path

    self._data_existence_cache: dict[tuple, dict] = {}
    # Unique per executor, so it never collides with user catalogs or concurrent executors
    self.staging_catalog = f"koality_stage_{uuid.uuid4().hex}"

backend property writable

backend: Backend

The backend that reads source tables and writes results for the attached database.

It follows duckdb_client, database_provider and config.database_accessor, so it is rebuilt if any of them changes, unless a backend was assigned explicitly.

__call__

__call__() -> list[dict]

Execute all checks and return results.

Source code in src/koality/executor.py
def __call__(self) -> list[dict]:
    """Execute all checks and return results."""
    self.execute_checks()
    log.info("Ran %d checks", len(self.checks))

    if self.check_failed:
        log.info(self.get_failed_checks_msg())

    if self.persist_results:
        self.load_to_database()

    if self.log_path:
        failed_checks_msg = self.get_failed_checks_msg()
        if not failed_checks_msg:
            log.info("No failed checks, so no log file was written.")
        else:
            with Path(self.log_path).open("w", encoding="utf-8") as file:
                file.write(self.get_failed_checks_msg())
        log.info("DQM outputs were written to %s", self.log_path)

    return self.result_dicts

aggregate_values staticmethod

aggregate_values(value_list: list[str]) -> str

Join a list of values into a comma-separated, sorted, deduplicated string.

Source code in src/koality/executor.py
@staticmethod
def aggregate_values(value_list: list[str]) -> str:
    """Join a list of values into a comma-separated, sorted, deduplicated string."""
    return ", ".join(sorted(set(value_list)))

execute_checks

execute_checks() -> None

Instantiate and execute all checks.

When walking through the different checks, parameters are updated using global defaults, check defaults of bundles, and a check's parameters. Check results are stored in a results dict for further processing.

Source code in src/koality/executor.py
def execute_checks(self) -> None:
    """Instantiate and execute all checks.

    When walking through the different checks, parameters are updated using global
    defaults, check defaults of bundles, and a check's parameters. Check results
    are stored in a results dict for further processing.
    """
    self.checks.extend(self._instantiate_checks())

    # Now, fetch all data into memory if using a database accessor
    # this is required so that we can run all checks against the in-memory data and rely solely on
    # DuckDB functionality like regexp_matches and others
    try:
        if self.config.database_accessor:
            data_requirements = self.get_data_requirements()
            self.fetch_data_into_memory(data_requirements)

        # Then, execute the checks against the in-memory data
        results = self._run_checks()
    finally:
        self._detach_staging_catalog()

    self.check_errored = any(check.status == "ERROR" for check in self.checks)
    self.check_failed = self.check_errored or any(check.status == "FAIL" for check in self.checks)

    self.result_dicts = results

fetch_data_into_memory

fetch_data_into_memory(data_requirements: defaultdict[str, defaultdict[str, set]]) -> None

Fetch all required data into DuckDB memory before executing checks.

This method aggregates all data requirements (tables, columns, filters) from the checks, constructs efficient bulk-SELECT queries, and executes them to populate in-memory DuckDB tables. This avoids executing a separate query for each check.

Data is written to this executor's own in-memory staging catalog, never to the session's default catalog, so source tables are not modified.

Source code in src/koality/executor.py
def fetch_data_into_memory(self, data_requirements: defaultdict[str, defaultdict[str, set]]) -> None:
    """Fetch all required data into DuckDB memory before executing checks.

    This method aggregates all data requirements (tables, columns, filters) from the checks,
    constructs efficient bulk-SELECT queries, and executes them to populate in-memory DuckDB tables.
    This avoids executing a separate query for each check.

    Data is written to this executor's own in-memory staging catalog, never to
    the session's default catalog, so source tables are not modified.
    """
    try:
        # READ_WRITE allows staging even when the session itself is read-only
        self.duckdb_client.sql(f"ATTACH IF NOT EXISTS ':memory:' AS \"{self.staging_catalog}\" (READ_WRITE)")
    except duckdb.Error as e:
        msg = f"Could not attach staging catalog {self.staging_catalog}"
        raise DatabaseError(msg) from e
    backend = self.backend
    for table, requirements in data_requirements.items():
        try:
            select_query = fetch_query(table, requirements, backend)
            if self.verbose:
                log.debug("Fetching data for table %s\nQuery:\n%s", table, format_sql(select_query))
            # Execute the query to get the data as a DuckDB relation
            relation = backend.query(select_query)  # noqa: F841
            # Create a table in the staging catalog from the relation
            staged_table = staged_table_ref(self.staging_catalog, table)
            self.duckdb_client.sql(f"CREATE OR REPLACE TABLE {staged_table} AS SELECT * FROM relation")  # noqa: S608
            msg = f"Successfully loaded data for table {table} into memory."
            log.info(msg)
        except duckdb.Error as e:
            msg = f"Failed to load data for table {table}"
            log.exception(msg)
            # Decide if we should raise the error or continue
            raise DatabaseError(msg) from e

    for check in self.checks:
        check.staging_catalog = self.staging_catalog

find_missing_columns

find_missing_columns() -> list[str]

Return a problem for each source table or column the checks read that the database doesn't have.

Every check's check, filter, join and date columns are looked up in its tables through the backend (Backend.columns), and each problem names the bundle, the check (its index in the bundle) and the table or column, so all of them can be reported at once. Names are compared case-insensitively; for a struct field such as info.shop, only the column (info) is looked up.

Source code in src/koality/executor.py
def find_missing_columns(self) -> list[str]:
    """Return a problem for each source table or column the checks read that the database doesn't have.

    Every check's check, filter, join and date columns are looked up in its tables through the backend
    (`Backend.columns`), and each problem names the bundle, the check (its index in the bundle) and the
    table or column, so all of them can be reported at once. Names are compared case-insensitively; for a
    struct field such as `info.shop`, only the column (`info`) is looked up.
    """
    labels = [
        f"bundle '{bundle.name}', check {index} ({check.check_type})"
        for bundle in self.config.check_bundles
        for index, check in enumerate(bundle.checks)
    ]
    tables: dict[str, set[str] | str] = {}
    problems = []
    fetched = bool(self.config.database_accessor)
    for label, check in zip(labels, self._instantiate_checks(), strict=True):
        for table, columns in _required_columns(check, fetched=fetched).items():
            if table not in tables:
                try:
                    tables[table] = {column.lower() for column in self.backend.columns(table)}
                except (duckdb.Error, DatabaseError) as e:
                    cause = f": {e.__cause__}" if isinstance(e, DatabaseError) and e.__cause__ else ""
                    tables[table] = (f"{e}{cause}".splitlines() or [type(e).__name__])[0]
            available = tables[table]
            if isinstance(available, str):
                problems.append(f"{label}: table '{table}' can't be read: {available}")
                continue
            problems.extend(
                f"{label}: column '{column}' not found in table '{table}'"
                for column in sorted(columns)
                if _top_level_column(column) not in available
            )
    return problems

get_data_requirements

get_data_requirements() -> defaultdict[str, defaultdict[str, set]]

Aggregate the data requirements of all checks (see data_requirements).

Source code in src/koality/executor.py
def get_data_requirements(self) -> defaultdict[str, defaultdict[str, set]]:
    """Aggregate the data requirements of all checks (see `data_requirements`)."""
    return data_requirements(self.checks)

get_failed_checks_msg

get_failed_checks_msg() -> str

Get an aggregated message for all failed checks.

Uses the message attribute of all checks and aggregates it.

Returns:

Type Description
str

Aggregated, sorted, newline separated messages of failed checks.

Source code in src/koality/executor.py
def get_failed_checks_msg(self) -> str:
    """Get an aggregated message for all failed checks.

    Uses the message attribute of all checks and aggregates it.

    Returns:
        Aggregated, sorted, newline separated messages of failed checks.

    """
    failed_checks_msgs = [check.message for check in self.checks if check.message]
    failed_checks_msgs = self._aggregate_checks_msgs(failed_checks_msgs)
    failed_checks_msgs.sort()

    return "\n".join(failed_checks_msgs)

load_to_database

load_to_database() -> None

Append koality's DQM results to result_table.

The backend of the attached database writes them (see koality.backends): for DuckDB-attached databases, result_table is created if needed and resolved like a check's table; for BigQuery, it is written through BigQuery itself.

Source code in src/koality/executor.py
def load_to_database(self) -> None:
    """Append koality's DQM results to `result_table`.

    The backend of the attached database writes them (see `koality.backends`): for DuckDB-attached
    databases, `result_table` is created if needed and resolved like a check's `table`; for BigQuery,
    it is written through BigQuery itself.
    """
    result_table = self.result_table
    if result_table is None:
        log.info("result_table is None. Results were not persisted.")
        return

    if len(self.result_dicts) == 0:
        log.info("No entries in results from checks, so no results were persisted.")
        return

    # Get the identifier column name from the first check (all checks have the same column name)
    identifier_column = self.checks[0].identifier_column if self.checks else "IDENTIFIER"
    rows = self._aggregate_result_dicts(self.result_dicts)
    now = dt.datetime.now(tz=dt.UTC)

    target = self.backend.write_results(result_table, rows, identifier_column, now)
    log.info("%d entries were persisted to %s", len(rows), target)

create_checks

create_checks(config: Config, database_provider: DatabaseProvider | None = None) -> list[DataQualityCheck]

Create the checks of all bundles of config, with their merged defaults; no database is needed.

Raises:

Type Description
KoalityError

If a check's settings don't work together (e.g. a distinct count of *).

Source code in src/koality/executor.py
def create_checks(config: Config, database_provider: DatabaseProvider | None = None) -> list[DataQualityCheck]:
    """Create the checks of all bundles of `config`, with their merged defaults; no database is needed.

    Raises:
        KoalityError: If a check's settings don't work together (e.g. a distinct count of `*`).

    """
    checks = []
    for check_bundle in config.check_bundles:
        for check_config in check_bundle.checks:
            check_factory = CHECK_MAP[check_config.check_type]
            check_kwargs = check_config.model_dump(exclude={"check_type"}, exclude_none=True)

            if check_config.check_type == "IqrOutlierCheck":
                check_kwargs.pop("lower_threshold", None)
                check_kwargs.pop("upper_threshold", None)

            check_kwargs["database_accessor"] = config.database_accessor
            check_kwargs["database_provider"] = database_provider
            check_kwargs["identifier_format"] = config.defaults.identifier_format
            check_kwargs["identifier_placeholder"] = config.defaults.identifier_placeholder
            checks.append(check_factory(**check_kwargs))
    return checks

data_requirements

data_requirements(checks: Iterable[DataQualityCheck]) -> defaultdict[str, defaultdict[str, set]]

Aggregate the tables, columns and filter groups that checks read, which a run fetches into memory.

Returns:

Type Description
defaultdict[str, defaultdict[str, set]]

A mapping of each table to its required "columns" and its unique "filters" groups (see fetch_query).

Source code in src/koality/executor.py
def data_requirements(checks: Iterable[DataQualityCheck]) -> defaultdict[str, defaultdict[str, set]]:
    """Aggregate the tables, columns and filter groups that `checks` read, which a run fetches into memory.

    Returns:
        A mapping of each table to its required "columns" and its unique "filters" groups (see `fetch_query`).

    """
    data_requirements = defaultdict(lambda: defaultdict(set))
    for check in checks:
        for table, columns in _required_columns(check).items():
            data_requirements[table]["columns"].update(columns)
        # Skip synthetic JOIN table entries created for MatchRateCheck; handle left/right tables explicitly
        if isinstance(check, MatchRateCheck):
            # Store unique filter configurations for both tables
            filter_key_left = _filter_key(check.filters_left)
            filter_key_right = _filter_key(check.filters_right)
            data_requirements[check.left_table]["filters"].add(filter_key_left)
            data_requirements[check.right_table]["filters"].add(filter_key_right)
            continue

        table_name = check.table
        check_filters = check.filters
        date_filter: dict[str, Any] | None = getattr(check, "date_filter", None)

        if isinstance(check, IqrOutlierCheck):
            check_filters = {k: v for k, v in check.filters.items() if v.get("type") != "date"}

        # Store unique filter configurations for each table
        filter_key = _filter_key(check_filters)
        data_requirements[table_name]["filters"].add(filter_key)

        # For rolling-style checks we also need to ensure historic date ranges are fetched.
        # Add an explicit BETWEEN-style filter group so fetch_data_into_memory can restrict rows.
        if date_filter:
            date_col = date_filter.get("column")
            date_val = date_filter.get("value")
            if date_col and date_val is not None:
                window_days = _date_window_days(check)

                if window_days > 0:
                    # For hashability store the concrete date strings as tuple (start_iso, end_iso)
                    # compute actual ISO dates by naive arithmetic here (date_val is already ISO string)
                    try:
                        end_iso = str(date_val)
                        start_iso = (
                            (dt.datetime.fromisoformat(str(date_val)) - dt.timedelta(days=window_days))
                            .date()
                            .isoformat()
                        )
                    except (ValueError, TypeError):
                        start_iso = None
                        end_iso = str(date_val)

                    between_config = {
                        "column": date_col,
                        "operator": "BETWEEN",
                        "value": (start_iso, end_iso),
                        "type": "date",
                    }
                    data_requirements[table_name]["filters"].add(_filter_key({"__date_range__": between_config}))
    return data_requirements

fetch_query

fetch_query(table: str, requirements: Mapping[str, set], backend: Backend) -> str

Return the SELECT that fetches table's required columns and rows from the source, in backend's SQL.

requirements is the table's entry of data_requirements: its filter groups are combined into one WHERE clause, which ORs the date conditions and ANDs them with the other filters.

Source code in src/koality/executor.py
def fetch_query(table: str, requirements: Mapping[str, set], backend: Backend) -> str:  # noqa: C901, PLR0912, PLR0915
    """Return the SELECT that fetches `table`'s required columns and rows from the source, in `backend`'s SQL.

    `requirements` is the table's entry of `data_requirements`: its filter groups are combined into one WHERE
    clause, which ORs the date conditions and ANDs them with the other filters.
    """
    # Use configured column names when building the SELECT list. For columns that
    # reference nested fields (e.g., "value.shopId") keep the configured expression
    # in the SELECT but alias it to the flattened in-memory column name ("shopId").
    # This preserves the configured prefix in the SELECT while ensuring checks can
    # reference the flattened column name when querying the in-memory table.
    raw_cols = sorted(set(requirements["columns"]))
    if not raw_cols:
        columns = "*"
    else:
        seen_flats: dict[str, str] = {}
        select_parts: list[str] = []
        for col in raw_cols:
            if col == "*":
                select_parts.append("*")
                continue
            if isinstance(col, str) and "." in col:
                # Replace dots with underscores for deterministic aliasing
                # e.g., "value.shopId" becomes "value_shopId"
                flat = col.replace(".", "_")
                # Make flattened name unique if duplicate arises
                base = flat
                idx = 1
                while flat in seen_flats:
                    flat = f"{base}_{idx}"
                    idx += 1
                seen_flats[flat] = col
                select_parts.append(f"{col} AS {flat}")
            # Non-nested column, ensure uniqueness
            elif col in seen_flats:
                base = col
                idx = 1
                new_col = col
                while new_col in seen_flats:
                    new_col = f"{base}_{idx}"
                    idx += 1
                seen_flats[new_col] = col
                select_parts.append(f"{col} AS {new_col}")
            else:
                seen_flats[col] = col
                select_parts.append(col)
        columns = ", ".join(select_parts)

    # Combine all unique filter groups. Separate date filters from other filters.
    # All date-related conditions (BETWEEN ranges and date equality) should be ORed.
    # Non-date filters should be ANDed with the date conditions.
    date_filters_sql = set()
    other_filters_sql = set()

    for filter_group in requirements["filters"]:
        filter_dict = {}
        date_filter_dict = {}
        for item in filter_group:
            # Expect each item to be a (name, frozenset(cfg_items)) tuple
            if not (isinstance(item, tuple) and len(item) == _DATE_RANGE_TUPLE_SIZE):
                # Skip unexpected shapes
                continue
            name, cfg_items = item
            # Back to lists, the type filter values have everywhere else (e.g. in a backend's literals)
            cfg = {key: list(value) if isinstance(value, tuple) else value for key, value in cfg_items}
            if name == "__date_range__":
                col = str(cfg.get("column") or "")
                val = cfg.get("value")
                is_range = bool(col) and isinstance(val, list) and len(val) == _DATE_RANGE_TUPLE_SIZE
                if is_range and val[0]:
                    start_iso, end_iso = val
                    start, end = backend.date_literal(start_iso), backend.date_literal(end_iso)
                    cond = f"{backend.date_column(col)} BETWEEN {start} AND {end}"
                    date_filters_sql.add(f"({cond})")
                elif is_range:
                    cond = f"{backend.date_column(col)} <= {backend.date_literal(val[1])}"
                    date_filters_sql.add(f"({cond})")
                # date_range handled; continue to next group
                continue
            # Separate date-type filters from other filters
            if cfg.get("type") == "date":
                date_filter_dict[name] = dict(cfg)
            else:
                filter_dict[name] = dict(cfg)

        # Process date filters separately and add to date_filters_sql
        if date_filter_dict:
            where_clause = DataQualityCheck.assemble_where_statement(
                date_filter_dict,
                strip_dotted_columns=False,
                dialect=backend,
            )
            if where_clause.strip().startswith("WHERE"):
                conditions = where_clause.strip()[len("WHERE") :].strip()
                if conditions:
                    date_filters_sql.add(f"({conditions})")

        # Process non-date filters
        if filter_dict:
            # When fetching from the source DB, preserve dotted column expressions
            # (e.g., "value.shopId") in the WHERE so the source provider sees the
            # original column reference. The assemble_where_statement default strips
            # dotted prefixes; pass strip_dotted_columns=False here to keep them.
            where_clause = DataQualityCheck.assemble_where_statement(
                filter_dict,
                strip_dotted_columns=False,
                dialect=backend,
            )
            if where_clause.strip().startswith("WHERE"):
                conditions = where_clause.strip()[len("WHERE") :].strip()
                if conditions:
                    other_filters_sql.add(f"({conditions})")

    # Build final WHERE clause: OR all date filters together, AND with other filters.
    final_where_clause = ""
    if date_filters_sql and other_filters_sql:
        date_part = " OR ".join(sorted(date_filters_sql))
        other_part = " OR ".join(sorted(other_filters_sql))
        final_where_clause = f"WHERE ({date_part}) AND ({other_part})"
    elif date_filters_sql:
        final_where_clause = "WHERE " + " OR ".join(sorted(date_filters_sql))
    elif other_filters_sql:
        final_where_clause = "WHERE " + " OR ".join(sorted(other_filters_sql))
    return f"""
            SELECT {columns}
            FROM {backend.table_ref(table)}
            {final_where_clause}
            """  # noqa: S608