Part II — Intermediate Development · Chapter 6 · Lesson 3 of 5 · 10 min read
Lesson 3: Assertions, Invariants, and Boundary Validation
Lesson level: Intermediate
Purpose: State assumptions explicitly, protect program invariants, and validate untrusted boundary data before deeper logic relies on it.
Learning objectives
By the end of this lesson, you should be able to:
- distinguish validation, assertions, and invariants;
- write assert statements with useful messages;
- choose which conditions belong at input, internal, and output boundaries;
- validate required keys before property or index access;
- validate types, ranges, categories, sizes, and cross-field relationships;
- state and verify loop, state, and accounting invariants;
- avoid using assertions as a substitute for expected input handling;
- design portable validation results and safe failures; and
- test boundary and invariant logic systematically.
3.1 Three related ideas
Validation checks data that may legitimately be wrong because it came from a user, file, network, provider, or host boundary. Assertions state conditions the programmer believes must hold if the implementation is correct. Invariants describe relationships that must remain true across a defined region of execution.
The three ideas reinforce each other but serve different audiences. Validation protects the program from external uncertainty. Assertions expose implementation defects. Invariants support reasoning about state transitions and completeness.
3.2 The assert statement
Assert evaluates a condition for truthiness. If it is false-like, execution stops with an assertion failure. An optional message explains the violated assumption.
assert inspected_count == valid_count + invalid_count
assert selected_count <= valid_count, "selected count exceeds valid count"
Use a message when the condition alone does not explain the intended relationship. Keep it concise and free of secrets.
3.3 What an assertion means
An assertion says: reaching this point with a false condition indicates a defect or broken internal contract. It should not describe ordinary, expected user mistakes.
For example, a negative quantity from an external record should produce a validation result. A negative quantity after the record has already passed validation may justify an assertion because internal logic broke its promise.
3.4 Validation versus assertion
| Question | Validation | Assertion |
|---|---|---|
| Can the condition fail during correct use? | Yes | No |
| Primary source | External or untrusted data | Internal assumptions |
| Typical response | Structured invalid result or documented error | Stop and expose a defect safely |
| Example | impact is outside 0–10 | valid plus invalid does not equal inspected |
3.5 Preconditions
A precondition must be true before an operation starts. Public or boundary-facing preconditions should normally be validated explicitly because callers can violate them.
if quantity < 0 {
return {"valid": false, "reason_code": "INVALID_QUANTITY"}
}
Inside a trusted helper that is called only after validation, an assertion can document the established precondition:
assert quantity >= 0, "validated quantity became negative"
3.6 Postconditions
A postcondition must be true when an operation completes successfully. It protects the function or pipeline’s output contract.
assert result.priority == "low" or result.priority == "medium" or result.priority == "high"
At a host boundary, validate the returned value as well. An internal assertion helps developers; host-side output validation protects the caller even when extension code is defective.
3.7 State invariants
A state invariant describes a relationship that remains true whenever an object, record set, or workflow is in a valid observable state.
- balance is never negative;
- a completed result has a non-null completion time;
- a high priority always has its documented response target;
- every selected inventory record is valid and active; and
- an approved request never carries a denial reason.
3.8 Loop invariants revisited
A loop invariant must hold before the first iteration, after every completed iteration, and when the loop exits. Assertions can test the invariant during development.
while index < len(items) {
assert inspected == index
# Process items[index].
inspected += 1
index += 1
assert inspected == index
}
Assertions supplement the proof; they do not replace reasoning about initialization, preservation, and termination.
3.9 Accounting invariants
Pipelines often maintain related counters and totals. Write their relationships before coding:
- inspected = valid + invalid;
- attempted = succeeded + failed;
- selected <= valid;
- global totals equal the sum of grouped totals; and
- one result exists for every accepted input.
These invariants reveal missed updates, double counting, early exits, and inconsistent recovery paths.
3.10 Boundary validation order
Validate from least dependent to most dependent:
- Confirm the outer value has the expected broad shape.
- Check required keys before accessing them.
- Check each field’s value category.
- Check ranges and approved categories.
- Check collection sizes.
- Check cross-field relationships.
- Normalize only when the contract explicitly permits it.
- Construct a validated internal representation.
3.11 Validate shape before access
Accessing a missing key before validation converts a manageable data problem into a KeyError. Inspect available keys first or use a validation pattern that does not require unsafe access.
Validation should report which required field is missing without dumping the complete input record.
3.12 Required, optional, and nullable
| Contract | Meaning |
|---|---|
| Required, non-null | The key must exist and contain an approved value. |
| Required, nullable | The key must exist; null is one allowed state. |
| Optional | The key may be absent; default behavior is documented. |
| Optional, nullable | Absence and explicit null may have different meanings. |
Do not treat missing, null, empty string, zero, and empty list as interchangeable unless the contract explicitly defines them that way.
3.13 Type and value-category validation
Check the expected value category before applying operators. A field intended to be numeric should not rely on an implicit conversion from arbitrary text. A boolean field should not accept the string "false" as though it were the value false.
Optional typing can add static guarantees later, but boundary data still requires runtime validation.
3.14 Range validation
Define inclusive and exclusive endpoints precisely. For an impact score from 0 through 10:
let impact_valid = impact >= 0 and impact <= 10
Test one value below, the lower boundary, ordinary interior values, the upper boundary, and one value above.
3.15 Category validation
When a string represents a closed category, compare it with the approved set. Do not allow unknown categories to fall silently into a default business result.
let tier_valid = tier == "standard" or tier == "gold" or tier == "platinum"
Normalization such as trimming or case conversion must be documented. Otherwise, reject the value and preserve the original contract.
3.16 Collection-size validation
Portable lists and maps can still consume excessive time, memory, and output. Validate domain-specific sizes before expensive traversal, and rely on runtime collection and memory budgets as a second line of defense.
A request that permits at most 100 category codes should be rejected or bounded before nested processing begins.
3.17 Cross-field relationships
Fields can be individually valid but mutually inconsistent:
- end time precedes start time;
- minimum exceeds maximum;
- inactive item claims an active-only status;
- approved decision includes a denial reason;
- selected count exceeds valid count; or
- currency and amount use incompatible contracts.
Validate relationships after the required individual fields are known to be safe.
3.18 Validation results
A useful structured validation result can contain:
{
"valid": false,
"reason_code": "INVALID_IMPACT",
"field": "service_impact",
"message": "service_impact must be between 0 and 10"
}
Keep field names and codes stable. Include the received value only when it is safe and genuinely useful.
3.19 Fail fast versus collect errors
Fail fast when later checks depend on the failed condition or when continuing could be unsafe. Collect multiple errors when checks are independent and the user benefits from correcting them together.
If collecting errors, preserve deterministic order and avoid evaluating dependent checks after a required field is missing.
3.20 Validation layers
| Layer | Responsibility |
|---|---|
| Transport or host | Authenticate, bound payload size, parse transport, and convert portable values |
| PeaLang boundary | Validate shape, fields, categories, ranges, and domain relationships |
| Core logic | Operate on validated values and assert internal assumptions |
| Output boundary | Validate returned shape, portability, and consistency |
| Host enforcement | Recheck sensitive constraints before side effects |
3.21 Assertions and production behavior
Treat an assertion failure as evidence that a supposedly impossible state occurred. Record safe diagnostic context and stop the affected operation. Do not catch an assertion merely to continue with uncertain state.
Assertions are not a replacement for permissions, runtime budgets, host isolation, or explicit boundary validation.
3.22 Assertions in exception handling
A catch block may restore a documented state, then assert its recovery invariant:
catch err {
status = "failed"
result = null
assert status == "failed" and result == null
}
Do not assert the content of an untrusted error message. Assert properties your own recovery logic controls.
3.23 Derived-value validation
Validate or assert calculated values when downstream code depends on strict limits:
- a discount never exceeds the subtotal;
- a probability remains between zero and one;
- a shortfall is never negative after selection;
- a percentage denominator is nonzero; and
- a generated collection remains within its documented bound.
3.24 Portable-boundary validation
Before returning to a host, confirm that every nested value belongs to the portable set: null, boolean, integer, float, string, list, or string-keyed map. Reject or convert host-specific objects before they cross the boundary.
Also validate semantic shape. A portable map can still contain missing fields, unknown keys, inconsistent values, or excessive collections.
3.25 Validation and sensitive data
- Do not echo secrets in validation messages.
- Mask identifiers when full values are unnecessary.
- Do not serialize an entire rejected record into logs.
- Use stable field names and reason codes.
- Apply output-size limits to aggregated validation errors.
3.26 Common mistakes
- Using assert for user input: expected invalid data needs a validation response.
- Accessing before checking: validate required keys first.
- Checking type but not range: a number can still be invalid.
- Checking fields but not relationships: individually valid values can conflict.
- Silently defaulting unknown categories: reject unsupported values explicitly.
- Assuming optional means nullable: absence and null are separate states.
- Setting invariants_ok directly: calculate it from actual relationships.
- Logging full rejected inputs: minimize diagnostic data.
- Continuing after an assertion failure: internal consistency is no longer established.
3.27 Worked example: Validated transfer request
A transfer request contains source account, destination account, amount, currency, and available balance.
Validation rules:
- all fields are required;
- source and destination are nonempty strings and must differ;
- amount must be greater than zero;
- currency must belong to the approved set;
- available balance must be nonnegative; and
- amount must not exceed available balance.
After validation, core logic can assert:
assert source_account != destination_account
assert amount > 0
assert amount <= available_balance
After calculation, assert that the projected balance is nonnegative. The authorized host still performs identity checks, concurrency controls, persistence, and final enforcement.
3.28 Validation-design workflow
- Define the portable input shape.
- Classify fields as required, optional, and nullable.
- Define value categories.
- Define ranges and approved categories.
- Define collection-size limits.
- Define cross-field relationships.
- Choose fail-fast or error collection.
- Define stable reason codes and safe messages.
- Construct validated internal values.
- State internal and output invariants.
- Test boundaries, malformed shapes, and inconsistent combinations.
3.29 Guided practice
- Classify ten conditions as validation rules or assertions.
- Write an assert with a useful message for an accounting invariant.
- Design required, optional, and nullable rules for an assigned-agent field.
- Create boundary tests for a score from 0 through 10.
- Validate an approved category without silently defaulting.
- Identify three cross-field inconsistencies in a date-range request.
- Choose fail-fast or error collection for a batch-upload form.
- Define a portable validation result with stable reason codes.
3.30 Hands-on lab: Build a boundary validator
Scenario: Validate source-defined support-case request maps before priority scoring.
Required fields: case_id, customer_tier, service_impact, affected_users, security_relevant, tags, and optional assigned_agent.
Requirements:
- validate outer shape and required keys before access;
- distinguish missing assigned_agent from explicit null;
- validate approved tiers and impact range 0–10;
- reject negative affected_users;
- bound the tag list and validate every tag as a nonempty string;
- validate that security-relevant cases contain a required security tag;
- return stable reason codes and safe field messages;
- construct a normalized portable map only after validation;
- assert internal relationships before scoring; and
- validate the final priority result before returning it.
Required cases: valid ordinary request, exact boundaries, missing key, null required field, unknown tier, negative users, oversized tag list, invalid tag, inconsistent security flag and tags, and a valid optional null.
Deliverable: Validator source, contract table, test matrix, normalized outputs, assertion list, expected and actual diagnostics, and a note dividing host, boundary, core, and enforcement responsibilities.
3.31 Review questions
- How does validation differ from assertion?
- What does an assertion failure imply?
- Why should required keys be checked before access?
- How do missing, null, empty, and zero differ?
- Why do range tests need exact boundaries?
- What is a cross-field relationship?
- When should validation fail fast?
- Why should outputs be validated as well as inputs?
- Why is a portable value not automatically semantically valid?
- Why should execution stop after an internal invariant fails?
3.32 Applied challenge
Add a complete validation and assertion layer to the resilient import simulator from Lesson 2. Separate expected invalid records from exceptional provider failures, state every accounting invariant, calculate an overall invariant result, validate returned portability, and prove that neither invalid nor exceptional records contribute to successful totals.
Lesson summary
Validation handles data that can be wrong during correct use; assertions expose supposedly impossible internal states; invariants describe relationships that must remain true across execution. Safe systems validate shape before access, check types, ranges, categories, sizes, and cross-field relationships, then operate on validated values and verify outputs before host enforcement.
Next lesson: Debugging with the CLI, Debugger, and Debug Adapter Protocol
The next lesson combines diagnostics, assertions, focused reproduction, breakpoints, stack and variable inspection, expression evaluation, and editor integration into a disciplined debugging workflow.
Lesson status: Ready for review.