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:
- compare in-process, sidecar, worker-process, and browser embedding models;
- choose a model from latency, isolation, language, and operational requirements;
- describe the lifecycle of an embedded module from load to unload;
- write an exported-function contract covering inputs, outputs, errors, limits, and version;
- apply compatibility rules when a contract changes; and
- keep the same contract usable from several host languages.
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
| Model | How it works | Strengths | Costs |
|---|---|---|---|
| In-process | Host loads the runtime as a library and calls functions directly | Lowest latency; simplest deployment | Shares the host process; host language must be supported |
| Sidecar | A separate PeaLang service runs beside the host; calls travel over local HTTP or gRPC | Any host language; independent scaling and restarts | Network hop; serialisation; another process to operate |
| Worker process | Host starts dedicated workers and sends jobs through a queue or pipe | Strong isolation; crash containment | Higher latency; worker lifecycle management |
| Browser | PeaLang runs as a WebAssembly artifact in the user’s browser | Offline use; no server cost per call | Preview 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.
- Who wrote the code? Untrusted or anonymous authors push you toward worker processes or containers (Chapter 14).
- Which language is the host? If the host cannot load the runtime directly, use a sidecar.
- What latency budget applies? Sub-millisecond paths favour in-process calls; tens of milliseconds tolerate a sidecar.
- How independently must it scale? If rule evaluation dominates load, a sidecar or worker pool scales separately from the host.
- Must it work offline or on the client? Only the browser model satisfies that, with preview caveats.
| Situation | Recommended model |
|---|---|
| Python service running reviewed pricing rules | In-process |
| Java 17 order service using shared rules | Sidecar |
| Partner-uploaded rules in a multi-tenant SaaS | Worker process or container |
| Instant form validation in a web app, re-checked on the server | Browser plus server re-evaluation |
| Batch scoring of millions of records | Worker 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.
| Stage | Host responsibility | Typical failure |
|---|---|---|
| Resolve | Find the approved artifact by name and version or hash | Wrong version selected |
| Load | Parse or decode, run top-level code, collect exports | Syntax error; missing export |
| Configure | Grant capabilities, register host functions, set limits | Over-broad permissions |
| Invoke | Convert inputs, call the export, convert outputs | Type mismatch; limit exceeded |
| Observe | Record usage, errors, and audit data | Silent failure; secrets in logs |
| Reload | Swap to a new version safely | Mixed versions serving one request |
| Unload | Release resources and caches | Leaked 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:
- Name and version of the module and each export;
- Inputs: field names, portable types, ranges, and whether each is required;
- Outputs: fields, types, ranges, and allowed codes;
- Errors: the error kinds the export may raise and what each means;
- Capabilities: host functions and permissions the export needs;
- Limits: expected and maximum instructions, time, and memory;
- Determinism: whether the same input always gives the same output; and
- Compatibility promise: what may change in minor versus major versions.
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.
| PeaLang | Python | Java 17 | TypeScript |
|---|---|---|---|
| null | None | null | null |
| boolean | bool | Boolean | boolean |
| integer | int | Long | number (safe integer range) |
| float | float | Double | number |
| string | str | String | string |
| list | list | List<Object> | unknown[] |
| map | dict[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.
| Change | Compatible? | Version bump |
|---|---|---|
| Add an optional input field | Yes | Minor |
| Add a new output field that callers may ignore | Yes, if hosts ignore unknown fields | Minor |
| Add a new reason code | No for strict host validators | Major, or ship with a host update first |
| Widen an input range | Yes | Minor |
| Narrow an input range | No | Major |
| Rename or remove a field | No | Major |
| Change a field’s type | No | Major |
| Change behaviour for the same input | Depends on the promise | Major if the documented meaning changes |
| Raise the maximum instructions limit | Operationally significant | Minor, 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
| Mistake | Consequence | Fix |
|---|---|---|
| Choosing a model by habit | Unneeded latency or weak isolation | Work through the questions in 1.3 |
| Side effects in module top level | Slow or non-deterministic loads | Keep top level to constants and functions |
| Undocumented exports | Hosts guess at types and meanings | Write a contract file for every export |
| Passing host objects across the boundary | Hidden coupling; failures in other hosts | Convert to portable values first |
| Large integers in TypeScript hosts | Silent precision loss | Type identifiers as strings |
| Shipping a new reason code before hosts accept it | Production calls fail closed | Release host validators first |
| Contract and code drift apart | Runtime surprises in one host only | Check the contract in CI |
Guided practice
- Choose an embedding model for a Go service that needs shared shipping rules, and justify it with the questions in 1.3.
- List the lifecycle stage where each of these fails: a missing export, an over-broad permission, and stale tenant state.
- Write the input section of a contract for an eligibility rule with employee ID, grade, and tenure in months.
- Classify these changes: add optional region input; rename tier to level; add reason code LOYALTY.
- Explain why a customer number of 9,007,199,254,740,993 should be a string in the contract.
- Describe the release order for adding a new output reason code.
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
- What are the four embedding models, and what does each trade off?
- Which question most often forces a sidecar?
- Why should module top-level code avoid side effects?
- Name six things a complete exported-function contract states.
- Why are new output codes risky even though they look additive?
- How does one contract file keep several hosts consistent?
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.