Skip to content

Models

Pydantic models for koality configuration validation.

Config pydantic-model

Bases: BaseModel

Root configuration model for koality check execution.

Config:

  • extra: forbid

Fields:

  • name (str)
  • extensions (list[ExtensionConfig])
  • extension_directory (str | None)
  • database_setup (str)
  • database_accessor (str)
  • defaults (_GlobalDefaults)
  • check_bundles (list[_CheckBundle])

Validators:

extension_names_to_mappings pydantic-validator

extension_names_to_mappings(value: object) -> object

Accept an extension written as its name, e.g. httpfs for {name: httpfs}, and an empty extensions:.

Source code in src/koality/models.py
@field_validator("extensions", mode="before")
@classmethod
def extension_names_to_mappings(cls, value: object) -> object:
    """Accept an extension written as its name, e.g. `httpfs` for `{name: httpfs}`, and an empty `extensions:`."""
    if value is None:
        return []
    if isinstance(value, list):
        return [{"name": item} if isinstance(item, str) else item for item in value]
    return value

from_yaml classmethod

from_yaml(text: str) -> Self

Validate a configuration from YAML text, read as koality run reads it (see load_yaml).

Examples:

>>> Config.from_yaml(Path("checks.yaml").read_text())
Source code in src/koality/models.py
@classmethod
def from_yaml(cls, text: str) -> Self:
    """Validate a configuration from YAML text, read as `koality run` reads it (see `load_yaml`).

    Examples:
        >>> Config.from_yaml(Path("checks.yaml").read_text())  # doctest: +SKIP

    """
    return cls.model_validate(load_yaml(text) or {})

propagate_defaults_to_checks pydantic-validator

propagate_defaults_to_checks(data: dict) -> dict

Merge defaults and check_bundle.defaults into each check before validation.

Merge order (later overrides earlier): 1. defaults 2. bundle defaults 3. check-specific values

For the 'filters' dict, a deep merge is performed so that check-level filters override individual filter entries rather than replacing the whole dict.

Source code in src/koality/models.py
@model_validator(mode="before")
@classmethod
def propagate_defaults_to_checks(cls, data: dict) -> dict:
    """Merge defaults and check_bundle.defaults into each check before validation.

    Merge order (later overrides earlier):
    1. defaults
    2. bundle defaults
    3. check-specific values

    For the 'filters' dict, a deep merge is performed so that check-level
    filters override individual filter entries rather than replacing the whole dict.
    """
    if not isinstance(data, dict):
        return data

    defaults = _defaults_dict(data.get("defaults"))
    global_check_defaults = _check_defaults(defaults)
    global_filters = _valid_default_filters(defaults.get("filters"))
    check_bundles = data.get("check_bundles", [])

    if not check_bundles:
        return data

    updated_bundles = []
    for bundle in check_bundles:
        if not isinstance(bundle, dict):
            updated_bundles.append(bundle)
            continue

        checks = bundle.get("checks", [])
        if not isinstance(checks, list | tuple):
            # Reported by _CheckBundle validation
            updated_bundles.append(bundle)
            continue

        bundle_defaults = _defaults_dict(bundle.get("defaults"))
        inherited = {**global_check_defaults, **_check_defaults(bundle_defaults)}
        bundle_filters = _valid_default_filters(bundle_defaults.get("filters"))

        merged_checks = []
        for check in checks:
            if isinstance(check, dict):
                # A default only applies to check types with that argument (e.g. `table` not to MatchRateCheck)
                check_type = check.get("check_type", inherited.get("check_type"))
                accepted = (
                    _CHECK_FIELDS_BY_TYPE.get(check_type, _CHECK_FIELDS)
                    if isinstance(check_type, str)
                    else _CHECK_FIELDS
                )
                # Merge order: defaults -> check_bundle.defaults -> check
                merged = {**{key: value for key, value in inherited.items() if key in accepted}, **check}

                # Deep merge for 'filters' dict
                merged["filters"] = cls._merge_filters(global_filters, bundle_filters, check.get("filters", {}))

                merged_checks.append(merged)
            else:
                merged_checks.append(check)

        bundle["checks"] = merged_checks
        updated_bundles.append(bundle)

    data["check_bundles"] = updated_bundles
    return data

validate_defaults_apply_to_some_check pydantic-validator

validate_defaults_apply_to_some_check() -> Self

Reject a default that none of the checks it covers accepts (e.g. join_columns for CountChecks).

Source code in src/koality/models.py
@model_validator(mode="after")
def validate_defaults_apply_to_some_check(self) -> Self:
    """Reject a default that none of the checks it covers accepts (e.g. join_columns for CountChecks)."""

    def unused(defaults: BaseModel, checks: list) -> list[str]:
        if not checks:
            return []
        accepted = frozenset().union(*(_CHECK_FIELDS_BY_TYPE[check.check_type] for check in checks))
        values = {
            **{key: getattr(defaults, key) for key in defaults.model_fields_set},
            **(defaults.model_extra or {}),
        }
        # None means "not set" (e.g. in `koality print` output)
        return sorted(k for k, v in values.items() if v is not None and k in _CHECK_FIELDS and k not in accepted)

    problems = [
        f"bundle '{bundle.name}' defaults {names}"
        for bundle in self.check_bundles
        if (names := unused(bundle.defaults, bundle.checks))
    ]
    if names := unused(self.defaults, [check for bundle in self.check_bundles for check in bundle.checks]):
        problems.append(f"defaults {names}")
    if problems:
        msg = f"Not an argument of any check they apply to: {'; '.join(problems)}"
        raise ValueError(msg)
    return self

validate_filter_values_complete pydantic-validator

validate_filter_values_complete() -> Self

Validate that all filters in checks have column and value set.

Filters in defaults can omit column/value (to be set at check level), but after merging, all filters must have both column and value except for identifier-type filters which are allowed to omit a value (used for naming).

Source code in src/koality/models.py
@model_validator(mode="after")
def validate_filter_values_complete(self) -> Self:
    """Validate that all filters in checks have column and value set.

    Filters in defaults can omit column/value (to be set at check level),
    but after merging, all filters must have both column and value except for
    identifier-type filters which are allowed to omit a value (used for naming).
    """
    for bundle in self.check_bundles:
        for check in bundle.checks:
            for name, config in check.filters.items():
                # Non-identifier filters must define a column
                if config.type != "identifier" and config.column is None:
                    msg = (
                        f"Filter '{name}' in check '{check.check_type}' "
                        f"(bundle '{bundle.name}') is missing a column. "
                        f"Set column in defaults, bundle defaults, or the check itself."
                    )
                    raise ValueError(msg)
                # For identifier filters, a missing value is allowed only when the
                # global identifier_format is not 'identifier' (i.e., used solely for naming).
                if config.type == "identifier":
                    if (
                        self.defaults.identifier_format == "identifier"
                        and config.value is None
                        and config.operator == "="
                    ):
                        msg = (
                            f"Filter '{name}' in check '{check.check_type}' "
                            f"(bundle '{bundle.name}') is missing a value. "
                            f"Set value in defaults, bundle defaults, or the check itself."
                        )
                        raise ValueError(msg)
                # Require a value for non-identifier filters (unless operator explicitly allows None)
                elif config.value is None and config.operator == "=":
                    msg = (
                        f"Filter '{name}' in check '{check.check_type}' "
                        f"(bundle '{bundle.name}') is missing a value. "
                        f"Set value in defaults, bundle defaults, or the check itself."
                    )
                    raise ValueError(msg)
    return self

validate_identifier_consistency pydantic-validator

validate_identifier_consistency() -> Self

Validate identifier filter consistency based on identifier_format.

When identifier_format is 'filter_name' or 'column_name', all identifier filters across all checks must have the same filter name or column name respectively, since these are used as result column headers. Also checks that if identifier_format is 'filter_name' or 'column_name', every check has an identifier filter.

Source code in src/koality/models.py
@model_validator(mode="after")
def validate_identifier_consistency(self) -> Self:
    """Validate identifier filter consistency based on identifier_format.

    When identifier_format is 'filter_name' or 'column_name', all identifier
    filters across all checks must have the same filter name or column name
    respectively, since these are used as result column headers.
    Also checks that if identifier_format is 'filter_name' or 'column_name',
    every check has an identifier filter.
    """
    identifier_format = self.defaults.identifier_format
    if identifier_format == "identifier":
        return self

    filter_names: set[str] = set()
    column_names: set[str] = set()

    for bundle in self.check_bundles:
        for check in bundle.checks:
            has_identifier_filter = False
            for name, config in check.filters.items():
                if config.type == "identifier":
                    has_identifier_filter = True
                    filter_names.add(name)
                    if config.column:
                        column_names.add(config.column)

            if not has_identifier_filter:
                msg = (
                    f"Check '{check.check_type}' in bundle '{bundle.name}' is missing an identifier filter. "
                    f"When identifier_format is '{identifier_format}', every check must have a filter with "
                    f"type='identifier'."
                )
                raise ValueError(msg)

    if identifier_format == "filter_name" and len(filter_names) > 1:
        msg = (
            f"When identifier_format='filter_name', all identifier filters must have "
            f"the same filter name. Found different names: {sorted(filter_names)}"
        )
        raise ValueError(msg)

    if identifier_format == "column_name" and len(column_names) > 1:
        msg = (
            f"When identifier_format='column_name', all identifier filters must have "
            f"the same column name. Found different columns: {sorted(column_names)}"
        )
        raise ValueError(msg)

    return self

validate_identifier_is_not_a_result_field pydantic-validator

validate_identifier_is_not_a_result_field() -> Self

Validate that a named identifier field doesn't overwrite a fixed result field such as DATE or VALUE.

Source code in src/koality/models.py
@model_validator(mode="after")
def validate_identifier_is_not_a_result_field(self) -> Self:
    """Validate that a named identifier field doesn't overwrite a fixed result field such as DATE or VALUE."""
    identifier_format = self.defaults.identifier_format
    if identifier_format == "identifier":
        return self
    names = {
        name if identifier_format == "filter_name" else config.column or ""
        for bundle in self.check_bundles
        for check in bundle.checks
        for name, config in check.filters.items()
        if config.type == "identifier"
    }
    if clashes := sorted(name for name in names if name.upper() in RESULT_FIELDS):
        msg = (
            f"When identifier_format='{identifier_format}', the identifier is stored as a result field, "
            f"so it must not be named like one of {sorted(RESULT_FIELDS)}. Found: {clashes}"
        )
        raise ValueError(msg)
    return self

DatabaseProvider dataclass

DatabaseProvider(database_name: str, database_oid: int, path: str, comment: str | None, tags: dict, internal: bool, type: str, readonly: bool, encrypted: bool, cipher: str | None, options: str | None = None)

Data class representing a DuckDB database provider connection.

ExtensionConfig pydantic-model

Bases: BaseModel

A DuckDB extension to install (if missing) and load before database_setup runs.

In a config, an extension is written as its name (httpfs) or as a mapping with the repository to install it from ({name: bigquery, repository: community}): a repository name such as core or community, or a URL or path of a custom repository (a relative path needs a slash, e.g. ./repository, or it is read as a name). Without a repository, DuckDB's default (core) is used.

Config:

  • extra: forbid

Fields:

  • name (str)
  • repository (str | None)

FilterConfig pydantic-model

Bases: BaseModel

Configuration for a single filter.

Example
filters:
  partition_date:
    column: BQ_PARTITIONTIME
    value: yesterday-2  # 2 days before yesterday
    type: date
  shop_id:
    column: shopId
    value: EC0601
    type: identifier
  created_at:
    column: created_date
    value: today+1  # tomorrow
    parse_as_date: true  # parses date but doesn't count as the "date" filter
  revenue:
    column: total_revenue
    value: 1000
    operator: ">="

Attributes:

Name Type Description
column str | None

The database column name to filter on.

value FilterValue

The filter value (can be any type, will be converted to string in SQL). For IN/NOT IN operators, use a list of values. For date filters, supports relative dates like "today", "yesterday", and offsets like "yesterday-2" or "today+1".

operator FilterOperator

SQL comparison operator. Defaults to "=" (equality).

type FilterType

Filter type - "date" for date filters (used for rolling checks), "identifier" for identifier filters (e.g., shop_id), "other" for regular filters. Only one "date" and one "identifier" type filter is allowed per configuration. When type="date", the value is automatically parsed as a date.

parse_as_date bool

If True, the value will be parsed as a date even for type="other". Useful for filters that need date parsing but aren't the primary date filter.

Config:

  • extra: forbid

Fields:

  • column (str | None)
  • value (FilterValue)
  • operator (FilterOperator)
  • type (FilterType)
  • parse_as_date (bool)

Validators:

validate_operator_value_combination pydantic-validator

validate_operator_value_combination() -> Self

Validate that operator and value type are compatible.

Skips validation when value is None with default operator, as this indicates a partial filter in defaults that will be completed later.

Source code in src/koality/models.py
@model_validator(mode="after")
def validate_operator_value_combination(self) -> Self:
    """Validate that operator and value type are compatible.

    Skips validation when value is None with default operator, as this
    indicates a partial filter in defaults that will be completed later.
    """
    # Skip validation for partial filters (value not set, using default operator)
    if self.value is None and self.operator == "=":
        return self

    if self.value is None:
        if self.operator not in ("=", "!="):
            msg = f"None/null values can only be used with = or != operators, got: {self.operator}"
            raise ValueError(msg)
    elif isinstance(self.value, list):
        if self.operator not in ("IN", "NOT IN"):
            msg = f"List values can only be used with IN/NOT IN operators, got: {self.operator}"
            raise ValueError(msg)
    elif self.operator in ("IN", "NOT IN"):
        msg = f"IN/NOT IN operators require a list value, got: {type(self.value).__name__}"
        raise ValueError(msg)
    return self

load_yaml

load_yaml(text: str) -> Any

Parse YAML text as koality reads configurations: safely, with YAML 1.2's booleans and numbers.

Only true/false are booleans; an unquoted yes/no/on/off (e.g. the country code NO) stays text, as does 12:30, and 010 is the number 10 (see _YamlLoader).

Examples:

>>> load_yaml("country: NO\nflag: true\ntime: 12:30\ncode: 010")
{'country': 'NO', 'flag': True, 'time': '12:30', 'code': 10}
Source code in src/koality/models.py
def load_yaml(text: str) -> Any:  # noqa: ANN401
    r"""Parse YAML text as koality reads configurations: safely, with YAML 1.2's booleans and numbers.

    Only true/false are booleans; an unquoted yes/no/on/off (e.g. the country code NO) stays text, as does 12:30, and
    010 is the number 10 (see `_YamlLoader`).

    Examples:
        >>> load_yaml("country: NO\nflag: true\ntime: 12:30\ncode: 010")
        {'country': 'NO', 'flag': True, 'time': '12:30', 'code': 10}

    """
    return yaml.load(text, Loader=_YamlLoader)  # noqa: S506 (a SafeLoader)