PeaBox Lab › PeaLang › Learn › Chapter 6 › Lesson 3

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:

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

QuestionValidationAssertion
Can the condition fail during correct use?YesNo
Primary sourceExternal or untrusted dataInternal assumptions
Typical responseStructured invalid result or documented errorStop and expose a defect safely
Exampleimpact is outside 0–10valid 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.

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:

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:

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

ContractMeaning
Required, non-nullThe key must exist and contain an approved value.
Required, nullableThe key must exist; null is one allowed state.
OptionalThe key may be absent; default behavior is documented.
Optional, nullableAbsence 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:

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

LayerResponsibility
Transport or hostAuthenticate, bound payload size, parse transport, and convert portable values
PeaLang boundaryValidate shape, fields, categories, ranges, and domain relationships
Core logicOperate on validated values and assert internal assumptions
Output boundaryValidate returned shape, portability, and consistency
Host enforcementRecheck 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:

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

3.26 Common mistakes

3.27 Worked example: Validated transfer request

A transfer request contains source account, destination account, amount, currency, and available balance.

Validation rules:

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

3.29 Guided practice

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:

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

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.

← Previous Next →