PeaBox Lab › PeaLang › Learn › Chapter 15 › Lesson 1

Part III — Advanced Systems · Chapter 15 · Lesson 1 of 7 · 9 min read

Lesson 1: Embedding Architecture and Exported-Function Contracts

Lesson level: Advanced

Purpose: Choose an embedding architecture deliberately and define exported-function contracts that remain stable across hosts, versions, and teams.

Release note: class names, sidecar endpoints, and contract-file fields in this chapter are illustrative. Verify them against the v0.63 embedding reference before publishing or teaching from this material.

Learning objectives

By the end of this lesson you will be able to:

1.1 What embedding means

An application embeds PeaLang when it loads PeaLang code and calls it as part of its own work. The application is the host; the PeaLang code is the extension. The host decides when code runs, what it may touch, and what happens to its results. Chapter 14 treated that boundary as a security perimeter. This chapter treats it as an interface: a contract that host and extension authors can rely on as both sides evolve.

Good embedding keeps business logic in PeaLang where it can change quickly, while identity, persistence, payment, and other durable responsibilities stay in the host. The contract is what lets those two worlds change at different speeds.

1.2 Four embedding models

ModelHow it worksStrengthsCosts
In-processHost loads the runtime as a library and calls functions directlyLowest latency; simplest deploymentShares the host process; host language must be supported
SidecarA separate PeaLang service runs beside the host; calls travel over local HTTP or gRPCAny host language; independent scaling and restartsNetwork hop; serialisation; another process to operate
Worker processHost starts dedicated workers and sends jobs through a queue or pipeStrong isolation; crash containmentHigher latency; worker lifecycle management
BrowserPeaLang runs as a WebAssembly artifact in the user’s browserOffline use; no server cost per callPreview status; browser-only capabilities; results cannot be trusted by the server

The models are not mutually exclusive. A platform might run reviewed internal rules in-process, partner rules in a worker pool, and a preview of the same rule in the browser for instant feedback, all sharing one contract.

1.3 Choosing a model

Answer these questions in order. The first answer that forces a choice usually decides the model.

SituationRecommended model
Python service running reviewed pricing rulesIn-process
Java 17 order service using shared rulesSidecar
Partner-uploaded rules in a multi-tenant SaaSWorker process or container
Instant form validation in a web app, re-checked on the serverBrowser plus server re-evaluation
Batch scoring of millions of recordsWorker pool

1.4 The embedded-module lifecycle

Whatever the model, an embedded module passes through the same stages. Naming them makes failures easier to locate.

StageHost responsibilityTypical failure
ResolveFind the approved artifact by name and version or hashWrong version selected
LoadParse or decode, run top-level code, collect exportsSyntax error; missing export
ConfigureGrant capabilities, register host functions, set limitsOver-broad permissions
InvokeConvert inputs, call the export, convert outputsType mismatch; limit exceeded
ObserveRecord usage, errors, and audit dataSilent failure; secrets in logs
ReloadSwap to a new version safelyMixed versions serving one request
UnloadRelease resources and cachesLeaked state between tenants

Top-level code runs during Load, not during Invoke. Keep module top level to constants and function definitions so loading stays fast, deterministic, and free of side effects.

1.5 What an exported-function contract contains

An export is only usable across teams if its behaviour is written down. A complete contract states:

1.6 A contract file

Keep the contract beside the module as a machine-readable file. Hosts can generate validators from it, reviewers can diff it, and CI can fail when code and contract disagree.

# contracts/pricing.contract.toml
[module]
name = "pricing"
version = "2.3.0"
artifact = "pricing-2.3.0.peac"

[exports.quote]
summary = "Price one cart line set for one customer"
deterministic = true
capabilities = ["tier.read"]

[exports.quote.input]
customer_id = { type = "string", pattern = "C[0-9]{6}", required = true }
currency    = { type = "string", enum = ["EUR", "GBP", "USD"], required = true }
items       = { type = "list", max_items = 200, required = true }

[exports.quote.input.items.item]
sku   = { type = "string", max_len = 32 }
qty   = { type = "int", min = 1, max = 999 }
price = { type = "float", min = 0 }

[exports.quote.output]
subtotal     = { type = "float", min = 0 }
discount_pct = { type = "float", min = 0, max = 30 }
reason       = { type = "string", enum = ["NONE", "GOLD_100", "BULK_250"] }

[exports.quote.errors]
INVALID_ITEM = "An item failed validation inside the rule"
TIER_UNAVAILABLE = "Tier lookup failed; caller may retry"

[exports.quote.limits]
instructions_typical = 4_000
instructions_max = 200_000
time_ms_max = 50

Notice what the contract does not say: how the discount is calculated. The contract is the promise; the implementation is free to change as long as the promise holds.

1.7 Portable values at the boundary

Contracts use only portable types: null, boolean, integer, float, string, list, and string-keyed map. Every host language maps these to its own types, as shown below. Anything else, such as dates, decimals, enums, or objects, must be converted to one of these forms by the host before the call.

PeaLangPythonJava 17TypeScript
nullNonenullnull
booleanboolBooleanboolean
integerintLongnumber (safe integer range)
floatfloatDoublenumber
stringstrStringstring
listlistList<Object>unknown[]
mapdict[str, ...]Map<String,Object>Record<string, unknown>

Watch the integer edge. TypeScript numbers lose precision above 253−1. Contracts that may carry large identifiers should type them as strings, not integers.

1.8 Changing a contract safely

Apply semantic versioning to the contract, not to the code. A change is compatible if every existing caller and every existing host validator keeps working without modification.

ChangeCompatible?Version bump
Add an optional input fieldYesMinor
Add a new output field that callers may ignoreYes, if hosts ignore unknown fieldsMinor
Add a new reason codeNo for strict host validatorsMajor, or ship with a host update first
Widen an input rangeYesMinor
Narrow an input rangeNoMajor
Rename or remove a fieldNoMajor
Change a field’s typeNoMajor
Change behaviour for the same inputDepends on the promiseMajor if the documented meaning changes
Raise the maximum instructions limitOperationally significantMinor, with capacity review

New reason codes catch many teams out. Chapter 14’s hosts fail closed on unknown codes, which is correct for security but means the host’s allow-list must ship before the rule that emits the new code. Order releases accordingly: host first, rule second.

1.9 Enforcing the contract in CI

A contract that is not checked will drift. Add two automated gates:

# 1. Exports and signatures match the contract
pea contract check contracts/pricing.contract.toml src/pricing.pea

# 2. Contract change is classified against the last release
pea contract diff contracts/pricing.contract.toml \
    --against release/pricing-2.2.0.contract.toml --fail-on major

The first gate catches an export that was renamed in code but not in the contract. The second turns an accidental breaking change into a failed build unless the version was deliberately raised to a new major.

Note: pea contract stands for whichever contract-tooling commands your release provides. If none exist, a short script that loads the module, lists exports, and compares them with the TOML file achieves the same result.

1.10 One contract, many hosts

The same contract file can drive validators in every host. In Python, generate a function that checks the input map. In Java, generate a record type and a validator. In TypeScript, generate an interface and a runtime check. Because all three come from one file, they cannot silently disagree. Lessons 2 to 6 build each of these hosts against the pricing contract above.

1.11 Common mistakes

MistakeConsequenceFix
Choosing a model by habitUnneeded latency or weak isolationWork through the questions in 1.3
Side effects in module top levelSlow or non-deterministic loadsKeep top level to constants and functions
Undocumented exportsHosts guess at types and meaningsWrite a contract file for every export
Passing host objects across the boundaryHidden coupling; failures in other hostsConvert to portable values first
Large integers in TypeScript hostsSilent precision lossType identifiers as strings
Shipping a new reason code before hosts accept itProduction calls fail closedRelease host validators first
Contract and code drift apartRuntime surprises in one host onlyCheck the contract in CI

Guided practice

Hands-on lab

Take the merchant discount rule from Chapter 14, Lesson 4 and write a complete contract file for it. Write a small Python script that loads the module, lists its exports, and fails if they differ from the contract. Then make three changes to the rule, one compatible, one requiring a minor bump, and one breaking, and show that your check classifies each correctly.

Deliverable: the contract file, the checking script, and a table of the three changes with their classification and version bump.

Review questions

Applied challenge

Design an embedding plan for a company with a Python billing service, a Java 17 order service, and a React checkout page that all need the same pricing rule. Specify the model for each host, the shared contract, how a contract change is released across all three, and how you prevent the browser’s result from being trusted by the server.

Lesson summary

Embedding places PeaLang inside or beside a host. In-process, sidecar, worker, and browser models trade latency, isolation, language reach, and operational cost. Every model shares the same lifecycle, and every export needs a written contract covering inputs, outputs, errors, capabilities, limits, and compatibility. Version the contract, check it in CI, release host validators before new codes, and generate validators for every host from one file.

Transition to Lesson 2

Lesson 2 builds the first real host against the pricing contract: a Python service with full boundary validation in both directions.

Lesson status: Ready for review.

← Previous Next →