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

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

Lesson 2: Python Host Integration and Boundary Validation

Lesson level: Advanced

Purpose: Build a production-shaped Python host for the pricing contract, with conversion, validation, caching, error mapping, and tests on both sides of the boundary.

Learning objectives

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

2.1 Host architecture

Keep the PeaLang runtime behind one facade class. The rest of the application calls the facade with ordinary Python objects and receives ordinary Python objects back. Only the facade knows about PeaLang, portable values, or runtime exceptions.

app/
  domain/models.py         # Cart, LineItem, Quote (host types)
  pricing/contract.py      # validators generated from the contract file
  pricing/convert.py       # host types <-> portable values
  pricing/engine.py        # PricingEngine facade
  pricing/errors.py        # domain exceptions
  rules/pricing-2.3.0.peac # admitted artifact
tests/
  test_convert.py
  test_contract.py
  test_engine.py

2.2 Host domain types

# app/domain/models.py
from dataclasses import dataclass
from decimal import Decimal
from enum import Enum

class Currency(str, Enum):
    EUR = "EUR"
    GBP = "GBP"
    USD = "USD"

@dataclass(frozen=True)
class LineItem:
    sku: str
    qty: int
    price: Decimal

@dataclass(frozen=True)
class Cart:
    customer_id: str
    currency: Currency
    items: tuple[LineItem, ...]

@dataclass(frozen=True)
class Quote:
    subtotal: Decimal
    discount_pct: Decimal
    reason: str

These types use Decimal for money and an Enum for currency. Neither is a portable value, so the facade must convert both before the call and convert results back afterwards.

2.3 Converting host values to portable values

Conversion is a small, pure module. It never calls the runtime and never touches I/O, so it is easy to test exhaustively.

# app/pricing/convert.py
from decimal import Decimal, ROUND_HALF_EVEN
from app.domain.models import Cart, Quote

MONEY = Decimal("0.01")

def cart_to_portable(cart: Cart) -> dict:
    return {
        "customer_id": cart.customer_id,
        "currency": cart.currency.value,
        "items": [
            {"sku": i.sku, "qty": int(i.qty), "price": float(i.price)}
            for i in cart.items
        ],
    }

def quote_from_portable(raw: dict) -> Quote:
    return Quote(
        subtotal=Decimal(str(raw["subtotal"])).quantize(MONEY, ROUND_HALF_EVEN),
        discount_pct=Decimal(str(raw["discount_pct"])).quantize(MONEY),
        reason=raw["reason"],
    )

Money and floats. Converting Decimal to float for the call is acceptable here because the rule computes a percentage and the host re-derives the final price in Decimal. If a rule must return exact money amounts, pass prices as integer minor units (cents) or as strings, and say so in the contract.

Converting back through str() avoids importing binary floating-point noise into Decimal: Decimal(0.1) is 0.1000000000000000055…, while Decimal(str(0.1)) is exactly 0.1.

2.4 Contract validators

Validators mirror the contract file. In a mature project they are generated; here they are written by hand so each rule is visible.

# app/pricing/contract.py
import re
CUSTOMER = re.compile(r"C[0-9]{6}")
CURRENCIES = {"EUR", "GBP", "USD"}
REASONS = {"NONE", "GOLD_100", "BULK_250"}

class ContractError(ValueError):
    def __init__(self, side: str, field: str, problem: str):
        super().__init__(f"{side}.{field}: {problem}")
        self.side, self.field, self.problem = side, field, problem

def check_input(p: dict) -> None:
    if not CUSTOMER.fullmatch(str(p.get("customer_id", ""))):
        raise ContractError("input", "customer_id", "pattern")
    if p.get("currency") not in CURRENCIES:
        raise ContractError("input", "currency", "enum")
    items = p.get("items")
    if not isinstance(items, list) or not 1 <= len(items) <= 200:
        raise ContractError("input", "items", "length")
    for n, it in enumerate(items):
        if not isinstance(it.get("qty"), int) or not 1 <= it["qty"] <= 999:
            raise ContractError("input", f"items[{n}].qty", "range")
        if not isinstance(it.get("price"), float) or it["price"] < 0:
            raise ContractError("input", f"items[{n}].price", "range")

def check_output(o) -> None:
    if not isinstance(o, dict):
        raise ContractError("output", "*", "not a map")
    if not isinstance(o.get("subtotal"), (int, float)) or o["subtotal"] < 0:
        raise ContractError("output", "subtotal", "range")
    pct = o.get("discount_pct")
    if isinstance(pct, bool) or not isinstance(pct, (int, float)) or not 0 <= pct <= 30:
        raise ContractError("output", "discount_pct", "range")
    if o.get("reason") not in REASONS:
        raise ContractError("output", "reason", "enum")

The side attribute separates two very different failures. An input error is the caller’s problem and maps to a 400-class response. An output error means the rule broke its promise; it is the platform’s problem and must alert the rule owner.

2.5 The engine facade

# app/pricing/engine.py
import hashlib, threading
from pathlib import Path
from pealang import (PeaRuntime, RuntimeOptions, PeaPermissionError,
                     PeaResourceLimitError, PeaRuntimeError)
from app.pricing import contract, convert
from app.pricing.errors import PricingUnavailable, InvalidCart, RuleDefect

OPTIONS = RuntimeOptions(
    permissions=frozenset({"tier.read"}),
    max_execution_ms=50, max_instructions=200_000,
    max_http_requests=0, max_file_read_bytes=0, allow_process=False,
)

class PricingEngine:
    def __init__(self, artifact: Path, tier_lookup):
        self._artifact = artifact
        self._tier_lookup = tier_lookup
        self._lock = threading.Lock()
        self._module, self._digest = None, None

    def _current_module(self):
        data = self._artifact.read_bytes()
        digest = hashlib.sha256(data).hexdigest()
        with self._lock:
            if digest != self._digest:
                rt = PeaRuntime(OPTIONS)
                rt.register_function("host.lookup_tier", self._tier_lookup, "tier.read")
                self._module = rt.load_bytecode(data, source_name=self._artifact.name)
                self._digest = digest
            return self._module

    def quote(self, cart):
        portable = convert.cart_to_portable(cart)
        try:
            contract.check_input(portable)
        except contract.ContractError as e:
            raise InvalidCart(e.field) from None
        module = self._current_module()
        try:
            raw = module.call("quote", portable)
        except PeaResourceLimitError:
            raise PricingUnavailable("RESOURCE_LIMIT") from None
        except PeaPermissionError:
            raise RuleDefect("PERMISSION") from None
        except PeaRuntimeError as e:
            raise RuleDefect(getattr(e, "kind", "SCRIPT_ERROR")) from None
        try:
            contract.check_output(raw)
        except contract.ContractError as e:
            raise RuleDefect(f"OUTPUT:{e.field}") from None
        return convert.quote_from_portable(raw)

Key decisions in this facade:

Note: load_bytecode and the kind attribute follow the illustrative API used in this chapter. Reading the file on every call is acceptable for a lesson; in production, check a modification time or a deployment signal instead.

2.6 Writing safe host functions

Host functions are the second boundary: the script calls into the host. Treat their arguments exactly like external input, and return only portable values.

# app/pricing/tiers.py
import re, time
CUSTOMER = re.compile(r"C[0-9]{6}")

def make_tier_lookup(repo, cache_seconds=60):
    cache: dict[str, tuple[float, str]] = {}

    def lookup_tier(customer_id) -> str:
        if not isinstance(customer_id, str) or not CUSTOMER.fullmatch(customer_id):
            raise ValueError("INVALID_CUSTOMER_ID")
        hit = cache.get(customer_id)
        now = time.monotonic()
        if hit and now - hit[0] < cache_seconds:
            return hit[1]
        tier = repo.tier_for(customer_id) or "STANDARD"
        cache[customer_id] = (now, tier)
        return tier

    return lookup_tier

The cache keeps the rule’s latency predictable even when the repository is slow, and the fallback to STANDARD is a business decision written in the host, not hidden in the rule. If the repository fails, raise a specific error so the rule’s contract can map it to TIER_UNAVAILABLE.

2.7 Testing the boundary

Test each layer separately, then together.

# tests/test_convert.py
from decimal import Decimal
from app.domain.models import Cart, LineItem, Currency
from app.pricing.convert import cart_to_portable, quote_from_portable

def test_cart_converts_to_portable_types():
    cart = Cart("C000123", Currency.EUR, (LineItem("A1", 2, Decimal("9.99")),))
    p = cart_to_portable(cart)
    assert p == {"customer_id": "C000123", "currency": "EUR",
                 "items": [{"sku": "A1", "qty": 2, "price": 9.99}]}

def test_quote_round_trips_money_exactly():
    q = quote_from_portable({"subtotal": 19.98, "discount_pct": 15, "reason": "GOLD_100"})
    assert q.subtotal == Decimal("19.98")

# tests/test_engine.py
import pytest
from app.pricing.errors import InvalidCart, RuleDefect

def test_rejects_bad_customer_before_calling_rule(engine, cart_factory, spy_runtime):
    with pytest.raises(InvalidCart):
        engine.quote(cart_factory(customer_id="X1"))
    assert spy_runtime.calls == 0

def test_out_of_contract_output_is_rule_defect(engine_with_rule, cart):
    engine = engine_with_rule("fixtures/returns_discount_45.pea")
    with pytest.raises(RuleDefect, match="OUTPUT:discount_pct"):
        engine.quote(cart)

Add a property-based test that generates random valid carts and asserts that the engine never raises RuleDefect for the approved rule. It is the fastest way to find inputs the rule author never considered.

2.8 Common mistakes

MistakeConsequenceFix
Calling the runtime from many placesBoundary rules scattered and inconsistentOne facade owns every call
Passing Decimal or Enum directlyType errors or silent coercionConvert in a pure conversion module
Decimal(float) on the way backFloating-point noise in moneyConvert through str() and quantize
Validating only inputsBroken rule output reaches customersValidate outputs and fail closed
Reloading without a lockRequests see half-loaded modulesSwap the module reference under a lock
Chaining runtime tracebacksInternal details leak to API callersRaise domain errors with from None
Host function trusts its argumentsInjection or cross-tenant readsValidate every argument in the host

Guided practice

Hands-on lab

Build the complete Python host for the pricing contract. Include the domain types, conversion, validators, facade, tier lookup, and tests. Add a FastAPI-free command-line entry point that reads a cart from JSON, prints the quote, and exits with a non-zero status for each domain error. Then deploy a new rule version while a load script calls the engine 1,000 times, and show that no call fails.

Deliverable: the source tree, test results, and a short reload report showing the version used by each call and zero failures.

Review questions

Applied challenge

Generate check_input and check_output automatically from the contract file. Show that changing the contract regenerates the validators, and that a breaking change fails a test without any hand edits.

Lesson summary

A well-built Python host hides PeaLang behind one facade, converts host types to portable values in a pure module, validates both directions against the contract, reloads artifacts atomically by content hash, and maps runtime failures to a small set of domain errors. Host functions get the same validation as external input, and tests cover each layer separately.

Transition to Lesson 3

Lesson 3 serves the same contract to a Java 17 application through the PeaLang sidecar and its client.

Lesson status: Ready for review.

← Previous Next →