PeaBox Lab › PeaLang › Learn › Chapter 5 › Lesson 4

Part I — Foundations · Chapter 5 · Lesson 4 of 5 · 8 min read

Lesson 4: Portable-Value Boundaries Between PeaLang and Hosts

Lesson level: Foundation

Purpose: Design explicit, validated data contracts between PeaLang code and the applications that invoke it.

Learning objectives

By the end of this lesson, you should be able to:

4.1 Why a boundary contract matters

A PeaLang module often runs inside, beside, or behind another application. Data must cross that boundary in a form that both sides understand. The contract determines which values may enter, which values may leave, which operations are callable, and which failures the host must handle.

A narrow contract improves portability and security. It keeps rules independent from a host language’s internal object model and prevents a script from receiving authority merely because the host possesses it.

4.2 The portable value set

The portable boundary values are:

Lists and maps may be nested as long as every contained value remains portable. A boundary value can therefore represent records, collections of records, optional values, and structured results without exposing host implementation details.

4.3 Portable does not mean automatically valid

A value can be portable yet still violate the business contract. The map {"impact": -4} uses portable values, but the impact is outside a documented range. Portability answers whether a value can cross the boundary; validation answers whether the value is acceptable for this operation.

Validate required keys, allowed types, ranges, categories, collection sizes, and relationships between fields. Reject malformed data before policy logic trusts it.

4.4 Host-specific values stay outside

Database connections, file handles, sockets, framework request objects, arbitrary class instances, and unrestricted runtime objects are not portable boundary values. The host should extract the required data and convert it into explicit portable structures.

For example, instead of passing an employee object, pass a map containing approved fields such as employee identifier, region, grade, and policy inputs. Instead of passing a database connection, register one narrow host operation if database access is genuinely required.

4.5 Designing an input record

Suppose a support system invokes a priority rule. A clear input contract can use this shape:

{
    "case_id": "CASE-1042",
    "customer_tier": "gold",
    "service_impact": 6,
    "affected_users": 25,
    "security_relevant": false
}

Every key is a string and every value belongs to the portable set. The contract should additionally specify required keys, allowed tier values, numeric ranges, and whether unknown keys are ignored or rejected.

4.6 Designing an output record

Return a complete result rather than several loosely related values:

{
    "valid": true,
    "priority": "medium",
    "response_minutes": 240,
    "reason_code": "GOLD_IMPACT"
}

The host can validate the result as one decision. Related fields should remain internally consistent: a priority must agree with its response target and reason code.

4.7 Conversion responsibilities

StageResponsibility
Host extractionSelect only approved fields from host objects or external requests.
Host conversionConvert values into null, booleans, numbers, strings, lists, and string-keyed maps.
Boundary validationCheck shape, types, ranges, sizes, categories, and required relationships.
PeaLang policyApply domain rules without depending on host internals.
Return validationVerify the returned portable result before trusting or persisting it.
Host enforcementPerform authorized side effects such as persistence, notification, or payment.

4.8 Exported functions are entry points

An exported PeaLang function forms a host-call boundary. The host loads a module, selects an exported function, converts arguments, invokes it under runtime limits, and validates the result.

Only intentional exports should be callable. A missing export, an export that is not callable, or an invalid argument should produce a controlled failure rather than implicit access to internal module state.

4.9 Registered host capabilities are different

An exported function lets the host call PeaLang. A registered host capability lets PeaLang call an operation supplied by the host. These are opposite directions and should not be confused.

Host operations must be registered explicitly. If a capability requires permission, invocation should fail when that permission is absent. Do not expose unrestricted reflection, arbitrary imports, or a powerful service object as a shortcut.

4.10 Keep pure rules pure where possible

A rule that receives portable data and returns portable data is easier to test, move, cache, and compare across runtimes. Keep database access, network calls, identity, secrets, and final enforcement in the host unless the design has a specific reason to expose a narrow capability.

Pure boundaries also make differential testing practical: the same input and expected output can be checked through direct interpretation, VM execution, a sidecar, or a browser-safe runtime.

4.11 Numeric and structural care

Different hosts may represent numbers differently. Preserve the intended integer or floating-point meaning and avoid relying on host-specific numeric classes. When transporting values through JSON-oriented clients, document acceptable ranges and precision expectations.

Maps must use string keys at the portable boundary. Convert host maps with non-string keys deliberately rather than allowing ambiguous or lossy conversion. Preserve list order when order is part of the contract.

4.12 Null and optional fields

Use null only when the contract explicitly permits absence. Distinguish among a missing key, a key whose value is null, and an empty value such as an empty string or list. They can represent different business states.

For example, an absent assigned_agent key may mean the producer violated the schema, while "assigned_agent": null may mean the case is intentionally unassigned.

4.13 Boundary errors

FailureSafe response
Unsupported host valueReject it and convert explicitly; do not expose the raw object.
Missing or wrong-shaped inputReturn or raise a stable validation failure before policy evaluation.
Missing exportReport that the requested module entry point is unavailable.
Non-callable exportReject invocation rather than guessing how to use the value.
Permission deniedDo not execute the host capability; return a controlled permission error.
Resource limit exceededStop execution and report the bounded failure without partial trust.
Invalid returned valueReject it before persistence or side effects.

4.14 Security and resource governance

Boundary design must cover authority as well as data. Embedded execution should deny process access and unregistered host operations by default. Apply execution time, instruction, call-depth, stack, memory, collection, output, HTTP, and file-read limits appropriate to the workload.

In-process limits reduce accidental or bounded misuse but do not replace operating-system isolation for hostile code. Choose isolation according to the threat model.

4.15 Cross-host portability

Python, Java-sidecar, TypeScript-client, and browser-oriented integrations should preserve the same conceptual portable-value semantics. Transport details may differ, but PeaLang logic should not require a Python class, Java object, or browser framework object.

For user-interface scenarios, return validated data or a bounded UI schema. Do not return arbitrary executable interface code.

4.16 Worked example: Inventory reorder decision

A host selects approved inventory fields and passes this map:

{
    "sku": "NB-100",
    "on_hand": 8,
    "reorder_point": 12,
    "discontinued": false
}

PeaLang validates the required keys and calculates a recommendation. It returns:

{
    "valid": true,
    "reorder": true,
    "recommended_quantity": 4,
    "reason_code": "BELOW_REORDER_POINT"
}

The host validates the result, checks current inventory again if necessary, and decides whether to create a purchase request. PeaLang recommends; the authorized host enforces.

4.17 Boundary review checklist

4.18 Common mistakes

4.19 Guided practice

4.20 Hands-on lab: Design and test a portable contract

Scenario: A host application needs PeaLang to recommend whether a shipment requires manual review.

Input requirements:

Output requirements:

Create the PeaLang function and a source-defined test harness. Validate required keys and ranges before applying rules. Test ordinary approval, high value, hazardous material, multiple reasons, null where permitted, missing key, wrong type, oversized category list, and an attempted nonportable host value described in the boundary note.

Deliverable: Input and output schemas, the PeaLang source, a conversion table, validation tests, expected and actual outputs, error mappings, limits, and a short statement of which actions remain exclusively under host control.

4.21 Review questions

4.22 Applied challenge

Refactor the inventory analytics pipeline from the previous lesson into a boundary-oriented design. Define a portable request containing records and approved options, and a portable response containing selected records, invalid reason codes, group summaries, totals, and accounting fields. Document conversions for a Python host, a Java-sidecar client, and a TypeScript client without changing the PeaLang contract.

Lesson summary

PeaLang host boundaries use null, booleans, integers, floats, strings, lists, and string-keyed maps. Hosts convert their own objects into this contract, validate inputs, invoke intentional exports under permissions and resource limits, validate returned values, and retain authority for sensitive side effects. Narrow portable contracts improve security, testing, and portability across host implementations.

Next lesson: Chapter 5 Checkpoint — Inventory Analyzer

The checkpoint will combine core values, indexing, slicing, mutation, copying, equality, traversal, transformation, filtering, aggregation, and portable boundary design in one inventory-analysis project.

Lesson status: Ready for review.

← Previous Next →