# API reference

The full public surface of the `valgebra` package. Every name is re-exported from the top-level `valgebra` namespace.

## Compiling and checking

### Validator

A compiled, immutable schema validator.

Build one by calling `Validator(schema)`, or with a combinator such as `union`, `intersection`, or `recursive`. Then check values with `validate`, `is_valid`, or `ensure`, and JSON documents with `validate_json` or `is_valid_json`.

Validation is a membership test against the set the schema denotes: the value is never copied or coerced. A validator never changes after it is built and is safe to share across threads. Its `repr` is an expression that builds the same schema, but for the few forms the API reference lists, and it can be copied with `copy.copy`/`copy.deepcopy`.

The class names the **public** package rather than the extension underneath it, which is the path a user imports it from and the one the API reference keeps true. It cannot be subclassed: every method reads a schema this type built, and a subclass overriding one would be a validator whose answers are not the algebra's.

`Validator[T]` is the annotation a static checker reads for a validator whose members are `T`s. At runtime it is a `types.GenericAlias`, so an annotation that is evaluated finds it; the parameter changes nothing a validator does, and the alias is not a schema.

#### close

```
close() -> Validator[_T]
```

Close every record and mapping in the schema: a key no clause claims is refused, throughout, including inside recursive definitions.

Returns a new validator; this one is unchanged. A clause short of every value keeps what it says, and so does a `str: anything` clause beside declared fields; the clauses admitting every value close as one clause, so `{str: anything, complement(str): anything}` closes to `{}`. A record with no clause admits only its declared keys, `{"a": int, str: int}` closed still admits a `str` key mapped to an `int`, and `Validator(dict[str, int]).close()` is the mapping it was asked of.

Reads the schema rather than the set, and refuses a schema holding a `recursive` placeholder, for the reasons [`open`](<Self::open>) gives.

Returns:

| Type | Description |
| --- | --- |
| `Validator[_T]` | A validator whose every record and mapping refuses the keys no clause |
| `Validator[_T]` | claims. |

Raises:

| Type | Description |
| --- | --- |
| `ValueError` | If the schema holds a `recursive` placeholder. |

#### ensure

```
ensure(obj: _V) -> _V
```

```
ensure(obj: object) -> _T
```

```
ensure(obj: _V | object) -> _V | _T
```

Validate `obj` and return it unchanged.

The value-returning check. Because validation is a membership test rather than a coercion, the returned object is exactly the input; `ensure` exists so code that wants the checked value back reads distinctly from the boolean `is_valid`.

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `obj` | `_V \| object` | The object to check. | *required* |

Returns:

| Type | Description |
| --- | --- |
| `_V \| _T` | `obj` unchanged. |

Raises:

| Type | Description |
| --- | --- |
| `ValidationError` | If `obj` is not a member of the schema's set. |
| `BaseException` | If a comparison the walk performs, or a `repr` its message names, raises a fatal interpreter signal; it propagates rather than being read as a non-member. |

#### is\_empty

```
is_empty() -> bool
```

Whether the schema is unsatisfiable — provably empty, so `is_valid` returns `False` for every value.

Decided soundly: `True` only when no value can belong to the schema — an unsatisfiable intersection, a fixed sequence with an impossible position, a record with an impossible required field, a refinement whose bounds cannot hold together (a lower bound above an upper bound, or a minimum length above a maximum), or a recursive schema with no base case (a mandatory self-reference that can never bottom out). It never reports a satisfiable schema as empty; for forms it cannot decide it returns `False`. The decision is also bounded by a budget of decision steps, so on a deeply nested adversarial schema a `False` can mean "not proven empty within the bound" rather than "non-empty"; a real schema decides far inside the bound. The budget counts steps, not time.

A `False` therefore carries two cases -- a value belongs, or nothing proves none does -- and telling them apart is a relation away. Emptiness is `s <= nothing`, so [`relation_to`](<Self::relation_to>) against the bottom gives the three answers: `"subset"` where the schema is proved empty, `"not_subset"` where a value says otherwise, and `"undecided"` where no reading settles it. There is no second method for that, because it would be a second spelling of one question.

Deciding a refinement's bounds orders the two operands, which runs their rich comparison, so this can call back into Python.

Returns:

| Type | Description |
| --- | --- |
| `bool` | `True` if the schema denotes the empty set, else `False`. |

Raises:

| Type | Description |
| --- | --- |
| `BaseException` | If a comparison of the bounds raises a fatal interpreter signal; it propagates rather than being read as an answer. |

#### is\_equivalent

```
is_equivalent(other: object) -> bool
```

Whether this schema and `other` denote the same set — mutual inclusion.

`other` is any schema spec or compiled validator. Sound, like `is_subtype_of`: `True` only when the two are provably equivalent, whatever their syntax (`bool | int` is equivalent to `int`). Bounded by the same budget of decision steps as `is_subtype_of` in each direction, so on a deeply nested adversarial schema a `False` can mean "not proven equivalent within the bound".

Mutual inclusion, the two `relation_to` answers: `True` exactly where each schema is `"subset"` of the other, so it calls back into Python wherever `is_subtype_of` does.

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `other` | `object` | The schema to compare, as a spec or validator. | *required* |

Returns:

| Type | Description |
| --- | --- |
| `bool` | `True` if the two schemas are equivalent, else `False`. |

Raises:

| Type | Description |
| --- | --- |
| `NotImplementedError` | If `other` uses an unsupported form, or is a callable that is not a class. |
| `ValueError` | If a marker in `other` denotes no set, a `recursive` body in it is not contractive, or it crosses a size bound. |
| `BaseException` | If a predicate, a comparison or a class read the decision runs raises a fatal interpreter signal; it propagates rather than being read as an answer. |

#### is\_subtype\_of

```
is_subtype_of(other: object) -> bool
```

Whether every value of this schema is also a value of `other` — set inclusion, the subtyping relation.

`other` is any schema spec or compiled validator. The decision is sound: `True` only when the inclusion provably holds (`bool` is a subtype of `int`, `list[bool]` of `list[int]`, a recursive schema of a wider one, a class of a base class). For the forms it cannot decide — a predicate, a leaf relation the oracle declines, a schema past the set representation's bounds — it returns `False` rather than a relation it cannot justify. The decision is bounded by a budget of decision steps, so on a deeply nested adversarial schema a `False` can mean "not proven a subtype within the bound"; a real schema decides far inside the bound. The budget counts steps, not time.

Nothing is inferred from a predicate refinement, but one may be **called**: deciding whether a literal is a subtype of a refinement decides whether the literal's value belongs to it, and belonging runs the predicate. A slow or side-effecting predicate is one this query pays for.

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `other` | `object` | The candidate supertype, as a schema spec or validator. | *required* |

Returns:

| Type | Description |
| --- | --- |
| `bool` | `True` if this schema is a subtype of `other`, else `False`. |

Raises:

| Type | Description |
| --- | --- |
| `NotImplementedError` | If `other` uses an unsupported form, or is a callable that is not a class. |
| `ValueError` | If a marker in `other` denotes no set, a `recursive` body in it is not contractive, or it crosses a size bound. |
| `BaseException` | If a predicate, a comparison or a class read the decision runs raises a fatal interpreter signal; it propagates rather than being read as an answer. |

#### is\_valid

```
is_valid(obj: object) -> bool
```

```
is_valid(obj: object) -> TypeGuard[_T]
```

```
is_valid(obj: object) -> bool | TypeGuard[_T]
```

Whether `obj` is a member of the schema's set.

Check-only: it does not build an error and returns as soon as membership is decided. It raises only if a comparison the membership test performs raises a fatal interpreter signal (for example a KeyboardInterrupt during a long check); an ordinary exception in a comparison is folded to a non-member, as the membership contract requires.

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `obj` | `object` | The object to check. | *required* |

Returns:

| Type | Description |
| --- | --- |
| `bool \| TypeGuard[_T]` | `True` if `obj` is a member of the schema's set, else `False`. |

Raises:

| Type | Description |
| --- | --- |
| `BaseException` | If a membership comparison raises a fatal interpreter signal, it propagates rather than being read as a non-member. |

#### is\_valid\_json

```
is_valid_json(data: str | bytes) -> bool
```

Whether a JSON document parses and is a member of the schema's set.

Check-only: malformed or undecodable JSON, or input that is neither `str` nor `bytes`, is not a member and returns `False`. The raising entries (`validate_json`/`load`) report the same undecodable input as a structured `json_invalid` error. The document is validated in place against the parsed value, with no intermediate Python objects for the structure it walks. It raises only if a membership comparison raises a fatal interpreter signal.

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `data` | `str \| bytes` | The JSON document, as `str` or `bytes`. | *required* |

Returns:

| Type | Description |
| --- | --- |
| `bool` | `True` if `data` parses and is a member of the schema's set, else |
| `bool` | `False`. |

Raises:

| Type | Description |
| --- | --- |
| `BaseException` | If a membership comparison raises a fatal interpreter signal, it propagates rather than being read as a non-member. |

#### load

```
load(
    data: str | bytes, /, *, fail_fast: bool = ...
) -> object
```

```
load(data: str | bytes, /, *, fail_fast: bool = ...) -> _T
```

```
load(
    data: str | bytes, /, *, fail_fast: bool = False
) -> object | _T
```

Validate a JSON document and return the parsed value.

Like `validate_json`, but returns the parsed Python object instead of discarding it, so a caller that needs the data does not parse it again. Parsing runs in Rust (jiter), and the parsed value is validated by the same walk, reaching the same decision and errors as `validate`.

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `data` | `str \| bytes` | The JSON document, as `str` or `bytes`. | *required* |
| `fail_fast` | `bool` | Stop at the first failure instead of aggregating. | `False` |

Returns:

| Type | Description |
| --- | --- |
| `object \| _T` | The parsed Python object, once it is confirmed a member of the set. |

Raises:

| Type | Description |
| --- | --- |
| `ValidationError` | If the document is malformed or undecodable JSON (code `json_invalid`) or is not a member of the schema's set. |
| `TypeError` | If `data` is not `str` or `bytes`. |
| `BaseException` | If a comparison the walk performs, or a `repr` its message names, raises a fatal interpreter signal; it propagates rather than being read as a non-member. |

#### open

```
open() -> Validator[object]
```

Open every record and mapping in the schema: a key no clause claims is admitted with any value, throughout, including inside recursive definitions.

Returns a new validator; this one is unchanged. A clause keeps what it says: a record claims no key beyond its fields, so opening it admits every other key, while `{"a": int, str: int}` opened still maps a `str` key to an `int` and frees only the keys that are not strings. `open` and `close` are idempotent projections rather than inverses.

Opening a mapping writes the freed region as a clause keyed by the complement of the keys it claims. Over whole kinds the relations decide the result like any other map. Over literals, which is what `dict[Literal["a"], int]` claims, the complement holds part of a kind, and a relation about the result may answer `"undecided"`. Membership is exact either way.

**These two read the schema, not the set it denotes.** Every relation on this surface answers about the set, so two spellings of one set give one answer; these rewrite the records the schema is written out of, and two spellings can open into two different sets. `{"a?": int}` and `union({}, {"a": int})` admit the same dicts, and opening the first keeps `a` an integer while opening the second admits every dict -- because the branch declaring no field opens to every dict on its own. Apply them to the record you mean rather than to a union of spellings of it. One record has two spellings of the same kind: an optional field saying what the record says of every key it does not name is the record's own default, so the closed `{"a?": nothing}` is the closed `{}` and opens to every dict, while `{"a?": intersection(int, str)}`, the same set spelled as a field, opens with `a` refused. A key stays refused in the record opened where it is written beside a clause that frees the rest, as `{"a?": nothing, str: anything}` is.

**Not inside a `recursive` builder.** A fixpoint's records are reached through the reference to its definition, and the placeholder a builder is handed names a definition not built until the builder returns, so a schema holding one has nothing there to open and is refused. Open the validator `recursive` returns, or write `anything: anything` into the record you mean to open.

Returns:

| Type | Description |
| --- | --- |
| `Validator[object]` | A validator whose every record and mapping admits the keys no clause |
| `Validator[object]` | claims. |

Raises:

| Type | Description |
| --- | --- |
| `ValueError` | If the schema holds a `recursive` placeholder, or if admitting undeclared keys expands the schema past the size bound; opening a record adds a catch-all clause, so a validator near the limit can cross it. |

#### relation\_to

```
relation_to(
    other: object,
) -> Literal["subset", "not_subset", "undecided"]
```

The inclusion in three answers rather than two.

`is_subtype_of` reports a proof as `True` and everything else as `False`, which folds together the two cases a caller most often wants apart: a value of this schema that `other` rejects, and a question the decision procedure declines. This reports them separately.

`"subset"` is the proof `is_subtype_of` returns `True` for. `"not_subset"` is a refutation: some value of this schema is outside `other`. Where a class is the subject, that rests on the class holding an instance, which is the one assumption the decidability page records. `"undecided"` is neither, and the schemas it happens for are the conservative boundary that page describes -- a predicate, a leaf relation the oracle declines, a schema past the set representation's bounds, a query that spends its budget of decision steps.

What `"subset"` proves is inclusion between two sets of values, not a static checker's assignability, which is a relation between declarations. A checker holds a mutable member invariant, so it refuses a `TypedDict` declaring `x: bool` where one declaring `x: int` is wanted, and a class declaring `count: bool` where a protocol declares `count: int`; every `bool` is an `int`, so both pairs are `"subset"` here. And a plain class is below a protocol only where its instances cannot be changed out of it, which its declarations do not decide.

Runs the same work `is_subtype_of` runs and calls back into Python wherever it does.

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `other` | `object` | The candidate supertype, as a schema spec or validator. | *required* |

Returns:

| Type | Description |
| --- | --- |
| `Literal['subset', 'not_subset', 'undecided']` | One of `"subset"`, `"not_subset"` or `"undecided"`. |

Raises:

| Type | Description |
| --- | --- |
| `NotImplementedError` | If `other` uses an unsupported form, or is a callable that is not a class. |
| `ValueError` | If a marker in `other` denotes no set, a `recursive` body in it is not contractive, or it crosses a size bound. |
| `BaseException` | If a predicate, a comparison or a class read the decision runs raises a fatal interpreter signal; it propagates rather than being read as an answer. |

#### validate

```
validate(
    obj: object, /, *, fail_fast: bool = False
) -> None
```

Validate `obj`, raising `ValidationError` if it is not a member of the schema's set. Check-only: `obj` is never copied or coerced.

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `obj` | `object` | The object to check. | *required* |
| `fail_fast` | `bool` | Stop at the first failure instead of aggregating every independent failure into the error. | `False` |

Returns:

| Type | Description |
| --- | --- |
| `None` | `None` if `obj` is a member of the schema's set. |

Raises:

| Type | Description |
| --- | --- |
| `ValidationError` | If `obj` is not a member; its `errors` lists each failure with a code and a path. |
| `BaseException` | If a comparison the walk performs, or a `repr` its message names, raises a fatal interpreter signal; it propagates rather than being read as a non-member. |

#### validate\_json

```
validate_json(
    data: str | bytes, /, *, fail_fast: bool = False
) -> None
```

Validate a JSON document, parsing it on the Rust path.

Parsing runs in Rust, faster than the standard library, and the parsed value runs the same validation walk as a native object, so this reaches the same decision and the same errors as `validate` on the parsed object. `fail_fast` behaves as it does for `validate`.

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `data` | `str \| bytes` | The JSON document, as `str` or `bytes`. | *required* |
| `fail_fast` | `bool` | Stop at the first failure instead of aggregating. | `False` |

Returns:

| Type | Description |
| --- | --- |
| `None` | `None` if the document parses and is a member of the schema's set. |

Raises:

| Type | Description |
| --- | --- |
| `ValidationError` | If the document is malformed or undecodable JSON (code `json_invalid`) or is not a member of the schema's set. |
| `TypeError` | If `data` is not `str` or `bytes`. |
| `BaseException` | If a comparison the walk performs, or a `repr` its message names, raises a fatal interpreter signal; it propagates rather than being read as a non-member. |

## Combinators

### union

```
union(*schemas: Validator[_S]) -> Validator[_S]
```

```
union(*schemas: object) -> Validator[object]
```

```
union(
    *schemas: Validator[_S] | object,
) -> Validator[_S] | Validator[object]
```

The union of the given schemas: a value in at least one of their sets.

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `*schemas` | `Validator[_S] \| object` | The schema specs or validators to join. No argument at all is the empty union, which is `nothing`. | *required* |

Returns:

| Type | Description |
| --- | --- |
| `Validator[_S] \| Validator[object]` | A `Validator` for the joined schema. |

Raises:

| Type | Description |
| --- | --- |
| `` `NotImplementedError` `` | If an argument uses a form with no set (a set or tuple literal, a callable that is not a class, or a typing construct that is not a type). |
| `` `ValueError` `` | If the joined schema crosses a size bound: depth, definitions, or nodes. |

### intersection

```
intersection(*schemas: object) -> Validator[object]
```

The intersection of the given schemas: a value in every one of their sets.

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `*schemas` | `object` | The schema specs or validators to meet. No argument at all is the empty intersection, which is `anything`. | *required* |

Returns:

| Type | Description |
| --- | --- |
| `Validator[object]` | A `Validator` for the met schema. |

Raises:

| Type | Description |
| --- | --- |
| `` `NotImplementedError` `` | If an argument uses a form with no set (a set or tuple literal, a callable that is not a class, or a typing construct that is not a type). |
| `` `ValueError` `` | If the met schema crosses a size bound: depth, definitions, or nodes. |

### complement

```
complement(schema: object) -> Validator[object]
```

The complement of a schema: every value not in its set.

Membership is decided by the inner schema: a value belongs to the complement exactly when it is not a member of the inner. When deciding the inner raises an ordinary Python exception — a value whose comparison or `__eq__` throws — that value folds to a non-member of the inner, and therefore a **member** of the complement. A filter of the form `complement(P)` over values whose own methods can raise should not rely on the complement alone to exclude them; intersect with a positive type that pins the shape instead.

A walk of the inner that stops instead of deciding — past the depth bound, at a value that contains itself, at a value that changes while it is read, or at a predicate that raises — has not said the value is outside the inner, and the complement refuses the value with that walk's code (`recursion_limit`, `recursion_loop`, `mutated_during_validation`, `predicate_error`) rather than admitting it.

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `schema` | `object` | The schema spec or validator to complement. | *required* |

Returns:

| Type | Description |
| --- | --- |
| `Validator[object]` | A `Validator` for every value outside the given schema. |

Raises:

| Type | Description |
| --- | --- |
| `` `NotImplementedError` `` | If `schema` uses a form with no set (a set or tuple literal, a callable that is not a class, or a typing construct that is not a type). |
| `` `ValueError` `` | If the complemented schema crosses a size bound: depth, definitions, or nodes. |

### instance\_of

```
instance_of(cls: type[_S]) -> Validator[_S]
```

```
instance_of(cls: object) -> Validator[object]
```

```
instance_of(
    cls: type[_S] | object,
) -> Validator[_S] | Validator[object]
```

The instances of a class, whatever their fields hold.

The set `isinstance(x, cls)` answers. `Validator(cls)` reads what a dataclass or a `NamedTuple` declares and checks each field; this reads the class alone, so an instance whose field holds another type, or was never set, is a member. For any other class it is the schema `Validator(cls)` builds: a builtin kind is read by its real type, as there.

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `cls` | `type[_S] \| object` | The class. | *required* |

Returns:

| Type | Description |
| --- | --- |
| `Validator[_S] \| Validator[object]` | A `Validator` for the instances of `cls`. |

Raises:

| Type | Description |
| --- | --- |
| `` `TypeError` `` | If `cls` is not a class, or is a `TypedDict` or a `Protocol`, which have no instances of their own to check. |

The whole-schema transforms `open` and `close` are methods on the compiled validator (`Validator.open`/`close`), documented above.

What `open` and `close` move is the **key-type region no clause claims**: opening frees it and closing refuses it, and neither touches a region a clause already claims. A clause short of every value claims its keys; the clauses admitting every value are read as one clause over the union of their keys, and where that clause covers every key the others leave over, its part over keys another clause claims stays and the rest is the region, so `{str: anything, complement(str): anything}` closes to `{}` as `dict[anything, anything]` does. A closed record claims none, which is why opening one admits every key its fields do not name. A `dict[str, int]` claims the `str` region, so opening it keeps `str` keys mapping to integers and frees the rest, and an open `TypedDict` claims it too, through the `str: anything` clause its reading carries.

Opening a mapping writes the freed region as a clause keyed by the complement of the keys it claims. Where those are whole kinds -- `dict[str, int]` -- the relations decide the result like any other map. Where they are literals -- `dict[Literal["a"], int]` -- the complement is part of `str`, which the set representation has no part for, and a relation about the result may answer `"undecided"` ([decidability](<https://ppigazzini.github.io/valgebra/explanation/decidability/index.md>)). Membership is exact either way.

A fixed-length list is the native `[A, B]` literal (see the [schema language](<https://ppigazzini.github.io/valgebra/guides/schema-language/index.md>)).

## Refinement markers

### Regex

`Annotated` metadata: a string fully matches this regular expression.

Use as `Annotated[str, Regex(r"[0-9a-f]{24}")]`. The match is anchored — the whole string must match, as `re.fullmatch` does — and runs natively on the Rust path (a linear-time engine), so a pattern check stays on the validation fast path rather than crossing into Python like a predicate. The pattern is read in that engine's dialect, which differs from `re`'s where the refinements guide lists. A `re.Pattern` is accepted as metadata too, with its flags but for the few that guide refuses; a `bytes` pattern is refused.

Immutable, because it is hashable: a marker whose `pattern` can be rebound after it is written into an `Annotated` is one whose hash changes while a schema holds it. Written out rather than taken from `dataclasses`, and annotated without `typing`, because this module is on the import path of every program that imports the package and both cost it modules -- `tests/test_version.py` holds the count.

A pattern that is not a `str` is refused when the marker is made, which is where the mistake is written. The marker pickles and copies as the pattern it holds, so a schema carrying one can be sent where a validator cannot.

## Recursion

### recursive

```
recursive(
    builder: Callable[[Validator[Any]], object],
) -> Validator[object]
```

Build a recursive schema as a checked fixpoint.

`builder` receives a placeholder validator standing for the schema being defined and returns its body. The placeholder's self-reference is resolved to a back edge, and a non-contractive body — one whose recursive reference is not under a structural constructor — is rejected. Until the builder returns, the placeholder denotes no set yet: a question asked of it is answered only where the answer holds whatever set it comes to denote, and is `"undecided"` where the answer turns on that set; a walk that meets it stops with `unresolved_recursion`; and `open()` and `close()` refuse a schema holding it, since the definition they would rewrite is not built.

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `builder` | `Callable[[Validator[Any]], object]` | Called with a placeholder validator, and returns the body of the fixpoint. | *required* |

Returns:

| Type | Description |
| --- | --- |
| `Validator[object]` | A `Validator` for the fixpoint the body defines. |

Raises:

| Type | Description |
| --- | --- |
| `` `TypeError` `` | If `builder` is not callable. |
| `` `NotImplementedError` `` | If the body uses a form with no set. |
| `` `ValueError` `` | If the body is not contractive -- the recursive reference sits outside every structural constructor -- or the fixpoint crosses a size bound: depth, definitions, or nodes. |

## Operators on a validator

A compiled validator carries an operator surface as well as its methods. These are written here rather than generated, because CPython supplies its own text for the dunder behind a type slot and that is what introspection would show.

| Operator | Method | Meaning |
| --- | --- | --- |
| `obj in validator` | `__contains__` | Membership: the operator form of `is_valid`, so a check reads as the set test it is. Python spells membership `in` as it spells a union `\\|`, which is why both are operators and intersection and complement are not. |
| `a \\| b` | `__or__`, `__ror__` | The union of the two schemas. `\\|` is the operator typing already uses for a union; intersection and complement have no typing operator and stay named calls. The reflected form is what makes `None \\| validator` work. |
| `a == b` | `__eq__` | Equality of the **normal form**: the schema trees, recursive definitions, and pooled constants all match, after the lattice laws construction settles — so a difference of member order, of a repeat, or of an identity is not one, and neither is the order the `recursive` definitions were met in: a reference is read through to the definition it names ([the algebra page](<https://ppigazzini.github.io/valgebra/guides/algebra/index.md#subtyping-equivalence-and-emptiness>)). Ask `is_equivalent` for the semantic question — whether two schemas denote the same set, which needs a containment rather than a law. |
| `hash(validator)` | `__hash__` | Consistent with `==`, so a validator is a dict key or a set member. It digests the schema shape, each definition a reference names, and each pooled constant's own hash, so `Literal[1]` and `Literal[2]` hash apart; a constant with no hash contributes nothing, so an unhashable constant cannot break it. Computed once and kept, as a `frozenset` keeps its hash. |
| `repr(validator)` | `__repr__` | A rendering of the schema as an expression that builds it. |

`copy.copy` and `copy.deepcopy` both return the validator itself: it is immutable and cannot be subclassed, so its copy is the object, as the standard library's `copy` gives back a `tuple` or a `frozenset`.

`repr` is a **rendering**, not a serialization. What it gives back is an expression that builds the same schema — a recursive schema as the `recursive` call it is, its back edge bound to a name the rest of the render does not print, so a class named `X` in the body is not read back as the back edge; an open record as the catch-all entry it carries, the nullary product as `tuple[()]`, a union holding a record or a list display as the `union(...)` call, since `|` between two dicts is Python's merge, a record or a list display refined as the validator it builds, `Annotated[Validator({'a': int}), MinLen(1)]`, since Python 3.11's `typing` refuses a display as `Annotated`'s base, and a key and a constant by Python's own `repr`, whole — so it can be pasted into a session that holds the names it prints and read back. A refinement marker prints by its bare name, `Ge(0)` rather than `at.Ge(0)`, so that session imports each marker by name, as `from annotated_types import Ge` does, rather than through the `import annotated_types as at` these pages write. Six things it cannot render as an expression: a **class**, which is an object rather than syntax and appears as its name where its name builds what the schema holds there -- the class alone where it declares no fields, a dataclass or a named tuple met with the fields it declares -- and as `instance_of(Name)` where a dataclass's or a named tuple's class stands without them: `intersection(list[int], Plain)` prints as itself, and `instance_of(Pair)` met with `tuple[bool]` for a named tuple declaring an `int` prints as `intersection(tuple[bool], instance_of(Pair))`; a **predicate**, which is a function and appears as `Predicate(...)`, and which the frontend refuses where it is built; a **constant whose `repr` is not an expression of it**, which is a syntax error where it is parsed -- an enum member's own `<Color.RED: 1>`, an `int` past the interpreter's digit limit printed as `<unrepresentable>`, and a value of a subclass of `int`, `float`, `complex`, `str` or `bytes` whose `repr` is the builtin's spelling of it, which would read back as the builtin and prints as `<MyStr: 'a'>` instead -- as a literal's constant, and as a bound's or a step's operand whose class writes an order or a remainder of its own, which the walk reads ahead of the builtin's; a **meet of two classes that each declare attributes**, which flattens to the two classes alone, printed as `instance_of(...)`, and their two attribute records, and a record standing apart from its class prints as `object(x=int)`, a form no constructor spells -- the schema does not record which class each record came from, so the render cannot fold them back, and a `Protocol` prints the same way, as the record of its members, and so does a generic dataclass applied, `Box[int]` as `intersection(instance_of(Box), object(item=int))`, whose name alone reads back as its parameters' defaults or is refused where one has none; a **required key whose name ends in `?`**, which no dict display spells -- the dict literal reads every trailing `?` as optional -- and which prints marked, `<required: 'a?'>`, a syntax error where it is parsed: `TypedDict("TD", {"a?": int})` renders `{<required: 'a?'>: int, str: anything}` rather than the display of a record whose `a` is optional; and a **schema past the renderer's own depth bound**, which gives up and prints `<...>`. The bound is within reach: no *single* annotation can be written deep enough, since the frontend refuses past `MAX_SCHEMA_DEPTH` and the renderer's bound sits above it, but a chain of recursive definitions composes — the render descends into each in turn, so a hundred shallow links reach a depth one annotation cannot. The mark is deliberately not an ellipsis: `...` reads as a schema inside a subscript, so a truncated render would parse and hand back a *different* validator with nothing to say it had been cut. The bound is on depth, not on length: a render is as long as the schema unfolded, and a chain of definitions each naming the last twice prints the last once per path to it -- sixteen links of a hundred nodes print megabytes. A REPL, a debugger, `logging` with `%r` and pytest's assertion rewriting all ask for it. Do not parse a repr: it is for a person to read, and [inspection](<https://ppigazzini.github.io/valgebra/guides/inspection/index.md>) says how to ask a schema questions instead.

## Lattice bounds

`anything` and `nothing` are the two bounds of the lattice, and both are `Validator` instances rather than schema forms you construct.

- `anything` — the top: every Python value is a member, so `anything.is_valid(x)` is `True` for every `x`. It is the identity of `intersection` and the absorbing element of `union`.
- `nothing` — the bottom: no value is a member, and `nothing.is_empty()` is `True`. It is the identity of `union` and the absorbing element of `intersection`.

`nothing` is also where the third answer about emptiness is asked for: `is_empty` is a predicate and reports the proof, while `relation_to(nothing)` reports which of proof, refutation and decline the procedure reached ([the boundary](<https://ppigazzini.github.io/valgebra/explanation/decidability/index.md>)).

Both are ordinary validators: they compose with the combinators, compare with `is_subtype_of`, and are what the constructors fold to — `intersection(int, complement(int))` **is** `nothing` ([the algebra](<https://ppigazzini.github.io/valgebra/guides/algebra/index.md>)). `Any` is the same set and the same schema as `anything`, differing only in what `repr` gives back; see [`Any` versus `anything`](<https://ppigazzini.github.io/valgebra/guides/algebra/index.md#any-versus-anything>).

```
from valgebra import Validator, anything, complement, intersection, nothing, union

assert anything.is_valid(object())
assert nothing.is_empty()
assert Validator(int).is_subtype_of(anything)
assert nothing.is_subtype_of(int)
assert intersection(int, anything).is_equivalent(int)
assert union(int, nothing).is_equivalent(int)
assert complement(anything).is_equivalent(nothing)
assert Validator(int).relation_to(nothing) == "not_subset"  # a value says so
```

## What raises, and when

A failure at **build** time — when the schema is compiled — is a different kind of event from a failure at **validation** time, and it raises a different exception. `ValidationError` is only ever the second. Building refuses with one of three, and which one says what went wrong. A class whose annotation Python cannot evaluate raises what evaluating it raises, before any of them: a `NameError` for a name its module does not define when the validator is built, such as an import moved under `if TYPE_CHECKING:` ([static checking](<https://ppigazzini.github.io/valgebra/guides/static-checking/index.md>)).

| Raised | When | Example |
| --- | --- | --- |
| `NotImplementedError` | The spec names a form with no decidable runtime membership. | `Sequence[int]`, `Mapping[str, int]`, a `TypeVar`, `Final`, `ClassVar` |
| `NotImplementedError` | A callable that is not a class, or the annotation `Validator[T]`, stands where a schema goes. The message names the spelling that was meant: `Annotated[T, fn]` or `Literal[fn]` for a callable, the schema or a compiled validator for `Validator[T]`. | `Validator(fn)`, `intersection(Record, fn)`, `list[fn]`, `Validator(Validator[int])` |
| `NotImplementedError` | A class is reached again, under the type arguments it is applied to, while its own fields are being built, with no `type` alias opened since. | a self-referential dataclass, `TypedDict` or protocol, whose field type names the class with no alias between |
| `ValueError` | A schema crosses a size bound: depth, definitions, or nodes, whether a sequence of calls built it or an annotation spells it. | growing a schema in a loop with `\\|`, `union` or `intersection`; opening one near the node bound; `list[list[...]]` nested past `MAX_SCHEMA_DEPTH` |
| `ValueError` | A marker's value cannot denote a set. | `MultipleOf(0)` |
| `ValueError` | A `recursive` body is not contractive — its back edge is not under a structural constructor. | `recursive(lambda s: s)` |
| `TypeError` | An argument is the wrong Python type for the call. | `validate_json(123)`, `load(123)` |

The form row and the class row are **different refusals** that share a class. The first is about the *form* and no depth would help it; the second is a class whose field type names the class again with no `type` alias between, which never bottoms out and is refused where it is reached rather than at a depth; an alias between ties the cycle where the fields reach it again. The `ValueError` depth row is one bound, `MAX_SCHEMA_DEPTH`, on a schema a sequence of calls built and on one an annotation spells -- the frontend descends one level past it, so the message names the bound and the schema past it is refused rather than half-built -- and `MAX_SCHEMA_DEPTH` is importable so code that sizes a schema reads it rather than repeating it. The [resource limits](<https://ppigazzini.github.io/valgebra/guides/limits/index.md>) guide covers all three sizes.

```
from collections.abc import Sequence
from dataclasses import dataclass

from valgebra import Validator, recursive


@dataclass
class Node:
    next: "Node"


for spec in (Sequence[int], Node):
    try:
        Validator(spec)
        raise AssertionError("expected a rejection")
    except NotImplementedError:
        pass

try:
    Validator(recursive(lambda schema: schema))
    raise AssertionError("expected a rejection")
except ValueError:
    pass

try:
    Validator(int).validate_json(123)
    raise AssertionError("expected a rejection")
except TypeError:
    pass
```

Every one of these is raised before any value is checked, so a schema that compiles is a schema whose every membership question is answerable.

## Errors

### `ValidationError`

Raised by `validate`, `validate_json`, `load` and `ensure` when a value is not a member of the schema's set. It subclasses `Exception`, and carries a structured, machine-readable model as well as a message. The attributes are set on the instance, so they are written here rather than generated.

| Attribute | Type | Meaning |
| --- | --- | --- |
| `errors` | `tuple[dict[str, object], ...]` | One item per independent failure, each a JSON-serializable dict with the keys `code`, `path`, `message`, `expected` and `value`. `json.dumps(err.errors)` is the JSON form of the whole report. One call reports every failure unless `fail_fast=True` stops the walk at the first. |
| `code` | `str` | The first item's stable failure code, such as `int_type`, `missing_key` or `literal_error`. |
| `path` | `tuple[str \\| int, ...]` | The first item's location from the root, string keys and integer indices, empty at the root. |
| `message` | `str` | The first item's rendered one-line message. `str(err)` summarizes every failure rather than only this one. |
| `expected` | `str` | A short label of the set the first item expected, such as `int`. |
| `value` | `str` | A repr-style summary of the first item's offending value. |

The [error model](<https://ppigazzini.github.io/valgebra/guides/error-model/index.md>) guide gives the path format and the properties a code carries, and the files that declare the codes; `tests/test_error_matrix.py` drives every code a report can carry, because a list written out beside the walk drifts from it.

```
import json

from valgebra import ValidationError, Validator

raised = False
try:
    Validator({"a": int, "b": str}).validate({"a": "x", "b": 1})
except ValidationError as err:
    raised = True
    assert err.code == "int_type"
    assert err.path == ("a",)
    assert [item["path"] for item in err.errors] == [("a",), ("b",)]
    assert json.dumps(err.errors)  # the whole report is JSON-serializable
assert raised
```

## Construction limits

Three module constants give the bounds every schema-growing call is checked against, so a caller sizing a schema reads the number rather than repeating it. [Resource limits](<https://ppigazzini.github.io/valgebra/guides/limits/index.md>) says what each one bounds and why.

| name | value | bounds |
| --- | --- | --- |
| `MAX_SCHEMA_DEPTH` | 128 | levels of structural nesting |
| `MAX_DEFINITIONS` | 128 | recursive definitions in one schema |
| `MAX_SCHEMA_NODES` | 100,000 | total schema nodes |

```
from valgebra import MAX_SCHEMA_DEPTH, Validator, complement

schema: Validator = Validator(int)
for _ in range(MAX_SCHEMA_DEPTH - 1):
    schema = complement(schema)
# An odd number of complements is the complement of `int`, so `1` is outside.
assert schema.is_valid(1) is ((MAX_SCHEMA_DEPTH - 1) % 2 == 0)
```

## Package version

`valgebra.__version__` is the distribution version as a string. It comes from the Cargo workspace manifest, which is what maturin derives the wheel's metadata from — so it matches the built wheel and never drifts from a hand-maintained literal. Taken from the compiled extension rather than read back out of the installed metadata, because the metadata reader pulls modules of its own into `import valgebra` for a string the manifest already carries. `tests/test_version.py` bounds what the import pulls in, and holds the two versions to each other.

```
import valgebra

assert isinstance(valgebra.__version__, str)
assert valgebra.__version__
```

## What is public

Every name above is public and is reached from the top-level `valgebra` namespace. `valgebra.__all__` lists the schema surface — `Validator`, the combinators, `Regex`, `recursive`, the two lattice bounds, the three construction limits and `ValidationError` — and `__version__`, the one name in it that is metadata rather than part of the algebra.

The compiled extension underneath, `valgebra._valgebra`, is private: its layout, its module name, and which names it carries are free to change in any release. Import from `valgebra`.
