Heuristic:1ay1 Agentty Unrepresentable Invalid State
| Knowledge Sources | |
|---|---|
| Domains | Type_Safety, Architecture |
| Last Updated | 2026-10-28 14:00 GMT |
Overview
Design types so that invalid states cannot be represented in the first place, making compile-time enforcement replace runtime validation.
Description
The Unrepresentable_Invalid_State heuristic (also known as "parse, don't validate" or "make illegal states unrepresentable") means choosing type shapes that structurally exclude invalid combinations. Instead of a runtime check that rejects bad data after the fact, the type system prevents bad data from being constructed at all. Sum types, refinement types, strong newtype IDs, and typestate patterns are all tools for this.
In agentty this appears in: strong newtype IDs (`id.hpp`) that prevent mixing a `ThreadId` with a `ToolCallId`; refinement types (`refined.hpp`) that make an invalid `Positive<int>` unconstructible; the entitlement registry (`entitlement.hpp`) that scopes facts to an account at the type level; and the typestate IO lifecycle (`fsm.hpp`) that makes "use IO after close" a compile error.
Usage
Apply this heuristic when designing domain types, state machines, or identifiers. If a runtime check is guarding against a state that "shouldn't happen," ask whether the type can be reshaped to make that state unrepresentable instead. The cost is more type machinery; the benefit is that an entire class of bugs moves from runtime to compile time.
The Insight (Rule of Thumb)
- Action: Replace runtime validation with type-level constraints that make invalid states unconstructible.
- Value: Sum types, newtypes, refinement types, typestate — the invalid data never exists as a value.
- Trade-off: More complex type definitions; but bugs are caught at compile time, not production.
- Compatibility: Requires a type system with sum types or equivalent; C++ achieves this via `std::variant`, strong typedefs, and concepts.
Reasoning
Runtime validation is a running cost: every call site must remember to validate, and forgetting once is a bug. Type-level constraints are a one-time cost: the type is defined once, and every use site is automatically checked by the compiler. The compiler never forgets, never skips, and never fatigues. Moving the constraint from runtime to compile time eliminates the human error of forgetting to validate, and makes the valid/invalid distinction visible in every function signature.
Related Pages
- Implementation:1ay1_Agentty_Provider_Picker_Rows
- Implementation:1ay1_Agentty_Strong_Newtype_IDs
- Implementation:1ay1_Agentty_Refinement_Types
- Implementation:1ay1_Agentty_Capability_Key_Normalization
- Implementation:1ay1_Agentty_Scope_Resolution_Algebra
- Implementation:1ay1_Agentty_Fused_Model_Picker_Ranking
- Implementation:1ay1_Agentty_Entitlement_Registry
- Implementation:1ay1_Agentty_Typestate_IO_Lifecycle
- Implementation:1ay1_Agentty_Capped_File_Read
- Implementation:1ay1_Agentty_Login_State_Machine