> For the complete documentation index, see [llms.txt](https://docs.dataspace.ch/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.dataspace.ch/api-reference/health-checks.md).

# Health Checks

`pyrunner_lib` provides a declarative and fluent API for defining health checks on your data transformations. These checks are designed to be efficient, working lazily on Polars `LazyFrame` objects to collect only the necessary aggregate statistics without loading the entire dataset into memory.

Health checks are defined using the `Check` class, which allows you to chain multiple validation methods for a specific column.

### Severity Levels

Each check can have an optional `severity` level:

* **`warn`** (Default): If the check fails, it is recorded in the health report, but the transformation continues and no exception is raised.
* **`fail`**: If any check with `fail` severity fails, a `HealthCheckFailure` exception is raised after all checks have been executed, preventing the build from succeeding.

### API Reference

```py
Check(column_name: str)
```

Initializes a check builder for the specified column.

***

#### Basic Checks

```py
.no_nulls(severity=None)
```

Ensures that the column contains no null values.

```py
.non_empty_strings(severity=None)
```

Ensures that all string values in the column are non-empty after stripping whitespace.

```py
.unique(severity=None)
```

Ensures that all values in the column are unique. Note: This defaults to `warn` in many contexts as it can be a common occurrence.

***

#### Range & Value Checks

```py
.valid_range(min_val=None, max_val=None, severity=None)
```

Checks if all values are within the specified inclusive range.

```py
.in_values(allowed: list, severity=None, ignore_case=False)
```

Checks if all values in the column are present in the `allowed` list.

```py
.regex_match(pattern: str, severity=None)
```

Ensures that all string values match the provided regular expression pattern.

```py
.null_percentage(max_pct: float, severity=None)
```

Allows up to `max_pct` (0-100) of the values in the column to be null.

***

#### Numeric Checks

```py
.numeric_check(
    eq=None, gt=None, gte=None, lt=None, lte=None, not_eq=None, sum_eq=None, severity=None
)
```

Provides various numeric comparisons:

* `eq`: Equal to
* `gt`: Greater than
* `gte`: Greater than or equal to
* `lt`: Less than
* `lte`: Less than or equal to
* `not_eq`: Not equal to
* `sum_eq`: The sum of the column must equal this value.

***

#### Aggregate Checks

```py
.distinct_count(expected_count: int, severity=None)
```

Ensures the column has exactly the specified number of distinct values.

***

#### Custom Checks

```py
.custom_check(name: str, severity: str, func: callable)
```

Allows you to provide a custom validation function. The function should have the signature `func(lf: pl.LazyFrame, col: str)` and should raise a `ValueError` with a descriptive message if the check fails.

### Examples

```python
import polars as pl
import pyrunner_lib.health_check as hc

def transform(data):
    lf = data

    # Define checks declaratively
    health_checks = [
        hc.Check("name")
            .no_nulls()
            .non_empty_strings()
            .unique(severity="warn"),

        hc.Check("age")
            .no_nulls()
            .valid_range(0, 120),

        hc.Check("city").no_nulls(),
        hc.Check("occupation").no_nulls(),
        hc.Check("country")
            .no_nulls()
            .non_empty_strings(),
    ]

    return lf, health_checks
```

### Health Report

When health checks are run (usually handled by the runner), a `health_report.json` file is generated in the `META_FOLDER`. This report contains a summary of passed and failed checks, along with error messages for any failures.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.dataspace.ch/api-reference/health-checks.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
