Part III — Advanced Systems · Chapter 15 · Lesson 6 of 7 · 18 min read
Lesson 6: Typed Embedding Contracts and Host-Specific Object Conversion
Lesson level: Advanced
Purpose: PeaLang exchanges only portable values with hosts: null, booleans, numbers, strings, lists, and string-keyed maps. Real hosts work with richer types such as decimals, timestamps, UUIDs, and enumerations. This lesson shows how to make the gap explicit with a typed embedding contract and a converter registry in each host, so that a value converted in Python, Java, or TypeScript means exactly the same thing when it reaches the script and when it comes back.
Release note: The [types] contract section, the pea contract check command, and the converter APIs shown here are illustrative of PeaLang v0.63 RC2 conventions. Confirm exact names in the release documentation.
Learning objectives
- Explain why portable values need logical types layered on top of them.
- Declare logical types in the embedding contract and mirror them with PeaLang annotations.
- Implement converter registries in Python, Java, and TypeScript that encode and decode the same logical types.
- Handle decimals, timestamps, dates, UUIDs, and enumerations without precision or time-zone loss.
- Prove converter correctness with round-trip and cross-language golden tests.
- Version converters so that contract changes roll out safely across hosts.
6.1 The problem: portable is not the same as precise
Consider the unit price 19.99. In Python it might be a Decimal, in Java a BigDecimal, and in TypeScript a string or a number. If each host sends whatever its JSON library produces, the script may receive 19.99 as a binary floating-point number in one host and as a string in another. Multiplying by a quantity of 3 then yields 59.97 in one case and 59.970000000000006 in the other. Neither host is wrong by its own rules; the contract simply never said what a price is.
The same kind of drift affects other types:
| Logical value | Typical drift | Visible symptom |
|---|---|---|
| Money / decimal | Float conversion, lost trailing zeros, different rounding | Totals that differ by a cent between hosts |
| Timestamp | Local versus UTC, millisecond versus microsecond precision | Rules that apply on the wrong day near midnight |
| Calendar date | Encoded as midnight in a host time zone | Dates shift by one day for some users |
| UUID / identifier | Upper versus lower case, braces, binary forms | Lookups miss; duplicates appear |
| Enumeration | Ordinal integers versus names; unknown values | A new value crashes an older host |
| Large integer | JavaScript numbers lose precision above 2^53 | Order IDs silently change in the browser |
The remedy is to separate two layers. The wire type is the portable value that actually crosses the boundary. The logical type is what that value means. The contract names the logical type and fixes its wire encoding; every host supplies a converter that implements that encoding exactly.
6.2 Declaring logical types in the contract
Version 2.4.0 of the pricing contract adds a [types] section. Each logical type names its wire type and the rules for its encoding. Fields then refer to logical types instead of raw wire types.
# contracts/pricing.contract.toml (excerpt, v2.4.0)
[contract]
name = "pricing"
version = "2.4.0"
converters = "pricing-conv/3" # converter set version, see 6.9
[types.Money]
wire = "string"
pattern = "^-?[0-9]{1,10}\\.[0-9]{2}$"
description = "Decimal amount, exactly two fraction digits, no exponent"
[types.Instant]
wire = "string"
format = "rfc3339-utc-millis" # e.g. 2026-10-31T07:54:00.000Z
[types.LocalDate]
wire = "string"
format = "iso-date" # e.g. 2026-10-31, no time, no zone
[types.CustomerId]
wire = "string"
pattern = "^C[0-9]{6}$"
[types.QuoteId]
wire = "string"
format = "uuid-lower"
[types.Reason]
wire = "string"
enum = ["NONE", "GOLD_100", "BULK_250"]
unknown = "reject" # or "fallback:NONE" for tolerant readers
[inputs]
customer_id = "CustomerId"
currency = { enum = ["EUR", "GBP", "USD"] }
priced_at = "Instant"
items = { list = "Item", max_items = 200 }
[outputs]
quote_id = "QuoteId"
subtotal = "Money"
discount_pct = { int = true, min = 0, max = 30 }
reason = "Reason"
valid_until = "LocalDate"
Money travels as a string, not a number. That choice is deliberate: strings carry exact decimal digits through every JSON library in every language, and the fixed pattern rules out exponents, thousands separators, and variable precision. Timestamps are always UTC with millisecond precision so that Java, Python, and JavaScript produce identical strings.
6.3 The script side: annotations that match the contract
Chapter 7 introduced optional typing. Embedding is where it pays off most, because the exported function’s annotations become a second, machine-checked statement of the contract. The script declares type aliases with the same names as the contract’s logical types and works with them through small helper functions.
// rules/pricing_types.pea
type Money = String // "123.45" — exact, two fraction digits
type Instant = String // RFC 3339 UTC, millisecond precision
type LocalDate = String // ISO date
type CustomerId = String
type Reason = String // "NONE" | "GOLD_100" | "BULK_250"
type Item = {
sku: String,
qty: Int,
unit_price: Money,
}
type Cart = {
customer_id: CustomerId,
currency: String,
priced_at: Instant,
items: List<Item>,
}
type Quote = {
subtotal: Money,
discount_pct: Int,
reason: Reason,
valid_until: LocalDate,
}
export { Money, Instant, LocalDate, CustomerId, Reason, Item, Cart, Quote }
// rules/pricing.pea (excerpt)
import std.decimal as dec
import std.datetime as dt
import pricing_types.{Cart, Quote, Money}
function line_total(price: Money, qty: Int) -> Money {
return dec.format(dec.mul(dec.parse(price), dec.from_int(qty)), 2)
}
export function quote(cart: Cart) -> Quote {
let total = dec.zero()
for item in cart.items {
total = dec.add(total, dec.parse(line_total(item.unit_price, item.qty)))
}
let priced = dt.parse_instant(cart.priced_at)
let valid_until = dt.format_date(dt.add_days(dt.to_date_utc(priced), 14))
let decision = discount_for(cart.customer_id, total)
return {
subtotal: dec.format(total, 2),
discount_pct: decision.pct,
reason: decision.reason,
valid_until: valid_until,
}
}
Two habits keep scripts precise. First, money stays a string at the boundary and becomes a decimal only inside arithmetic, through std.decimal. The script never converts money to a floating-point number. Second, dates are derived from the UTC instant supplied by the host, never from the script’s own clock, which keeps evaluation deterministic and testable.
Run pea check --types rules/ to verify the annotations, and pea contract check contracts/pricing.contract.toml rules/pricing.pea to verify that the exported signature matches the contract’s inputs and outputs field by field. Add both commands to CI.
6.4 A Python converter registry
A converter is a pair of functions: encode turns a host value into its wire form, and decode turns a wire value back into a host value. A registry maps logical type names to converters, so the facade can convert whole payloads by walking the contract instead of hand-coding each field.
# pricing/convert.py
from __future__ import annotations
import re
import uuid
from dataclasses import dataclass
from datetime import date, datetime, timezone
from decimal import Decimal, ROUND_HALF_EVEN
from enum import Enum
from typing import Any, Callable
class ConversionError(ValueError):
def __init__(self, logical: str, value: Any, why: str):
super().__init__(f"{logical}: {why} (got {value!r})")
self.logical = logical
@dataclass(frozen=True)
class Converter:
logical: str
encode: Callable[[Any], Any]
decode: Callable[[Any], Any]
_MONEY = re.compile(r"^-?[0-9]{1,10}\.[0-9]{2}$")
_CENT = Decimal("0.01")
def _enc_money(v: Decimal) -> str:
if not isinstance(v, Decimal):
raise ConversionError("Money", v, "expected Decimal, never float")
if not v.is_finite():
raise ConversionError("Money", v, "not finite")
q = v.quantize(_CENT, rounding=ROUND_HALF_EVEN)
if q != v:
raise ConversionError("Money", v, "more than two fraction digits")
return format(q, "f")
def _dec_money(s: str) -> Decimal:
if not isinstance(s, str) or not _MONEY.match(s):
raise ConversionError("Money", s, "bad wire format")
return Decimal(s)
def _enc_instant(v: datetime) -> str:
if v.tzinfo is None:
raise ConversionError("Instant", v, "naive datetime; attach a zone first")
u = v.astimezone(timezone.utc)
return u.strftime("%Y-%m-%dT%H:%M:%S.") + f"{u.microsecond // 1000:03d}Z"
def _dec_instant(s: str) -> datetime:
try:
if not s.endswith("Z"):
raise ValueError("must end with Z")
return datetime.strptime(s, "%Y-%m-%dT%H:%M:%S.%fZ").replace(tzinfo=timezone.utc)
except (ValueError, AttributeError) as e:
raise ConversionError("Instant", s, str(e)) from None
def _enc_date(v: date) -> str:
if isinstance(v, datetime):
raise ConversionError("LocalDate", v, "datetime given where date expected")
return v.isoformat()
def _dec_date(s: str) -> date:
try:
return date.fromisoformat(s)
except (TypeError, ValueError) as e:
raise ConversionError("LocalDate", s, str(e)) from None
def _enc_uuid(v: uuid.UUID) -> str:
return str(v) # canonical lower-case, hyphenated
def _dec_uuid(s: str) -> uuid.UUID:
u = uuid.UUID(s)
if str(u) != s:
raise ConversionError("QuoteId", s, "not canonical lower-case form")
return u
Enumerations need one more decision: what to do with a wire value the host does not know. The contract’s unknown setting answers it, and the converter factory reads that setting rather than hard-coding a policy.
def enum_converter(logical: str, py_enum: type[Enum], unknown: str) -> Converter:
known = {m.value for m in py_enum}
def enc(v: Enum) -> str:
if not isinstance(v, py_enum):
raise ConversionError(logical, v, f"expected {py_enum.__name__}")
return v.value
def dec(s: str) -> Enum:
if s in known:
return py_enum(s)
if unknown.startswith("fallback:"):
return py_enum(unknown.split(":", 1)[1])
raise ConversionError(logical, s, "unknown enumeration value")
return Converter(logical, enc, dec)
class Registry:
VERSION = "pricing-conv/3"
def __init__(self) -> None:
self._by_name: dict[str, Converter] = {}
def register(self, conv: Converter) -> None:
if conv.logical in self._by_name:
raise ValueError(f"duplicate converter for {conv.logical}")
self._by_name[conv.logical] = conv
def encode(self, logical: str, value: Any) -> Any:
return self._by_name[logical].encode(value)
def decode(self, logical: str, value: Any) -> Any:
return self._by_name[logical].decode(value)
def covers(self, contract) -> list[str]:
"""Return logical types named by the contract that have no converter."""
return sorted(set(contract.types) - set(self._by_name))
def default_registry(contract) -> Registry:
from pricing.domain import Reason
r = Registry()
r.register(Converter("Money", _enc_money, _dec_money))
r.register(Converter("Instant", _enc_instant, _dec_instant))
r.register(Converter("LocalDate", _enc_date, _dec_date))
r.register(Converter("CustomerId", str, str))
r.register(Converter("QuoteId", _enc_uuid, _dec_uuid))
r.register(enum_converter("Reason", Reason, contract.types["Reason"].unknown))
missing = r.covers(contract)
if missing:
raise RuntimeError(f"no converters for: {', '.join(missing)}")
if contract.converters != Registry.VERSION:
raise RuntimeError(f"contract wants {contract.converters}, host has {Registry.VERSION}")
return r
Startup fails if the contract names a logical type with no converter, or if the contract expects a different converter-set version. Both checks run in the FastAPI lifespan from Lesson 5, so a mismatched deployment never becomes ready.
6.5 Walking payloads by contract
With a registry in place, the facade converts a whole payload by walking the contract’s field declarations. Nested lists and records recurse; fields with plain wire types pass through after a type check.
# pricing/codec.py
def to_wire(spec, value, reg: Registry, path: str = "$"):
if spec.logical:
try:
return reg.encode(spec.logical, value)
except ConversionError as e:
raise ContractError("host", f"{path}: {e}") from None
if spec.list_of:
return [to_wire(spec.list_of, v, reg, f"{path}[{i}]") for i, v in enumerate(value)]
if spec.fields:
return {name: to_wire(fs, getattr(value, name), reg, f"{path}.{name}")
for name, fs in spec.fields.items()}
return value
def from_wire(spec, value, reg: Registry, path: str = "$"):
if spec.logical:
try:
return reg.decode(spec.logical, value)
except ConversionError as e:
raise ContractError("script", f"{path}: {e}") from None
if spec.list_of:
return [from_wire(spec.list_of, v, reg, f"{path}[{i}]") for i, v in enumerate(value)]
if spec.fields:
extra = set(value) - set(spec.fields)
if extra:
raise ContractError("script", f"{path}: unexpected fields {sorted(extra)}")
return {name: from_wire(fs, value[name], reg, f"{path}.{name}")
for name, fs in spec.fields.items()}
return value
The side on ContractError is the useful part. An encoding failure is the host’s fault: it handed the converter a value the contract does not allow. A decoding failure on output is the script’s fault: the rule returned something outside the contract. The error handlers from Lesson 5 log the side, so the right team is paged.
The FastAPI endpoint now replaces model_dump(mode="json") with to_wire(contract.input_spec, cart, registry), and builds its response from from_wire(contract.output_spec, raw, registry). Pydantic still validates HTTP shape; the registry owns meaning.
6.6 Java converters with Jackson
The Java client from Lesson 3 used Jackson defaults, which serialize BigDecimal as a JSON number and Instant according to whichever modules happen to be registered. Replace the defaults with explicit serializers registered in one module, so every mapper in the application uses the contract’s encodings.
// pricing/PricingWireModule.java
package pricing;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.module.SimpleModule;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.UUID;
import java.util.regex.Pattern;
public final class PricingWireModule extends SimpleModule {
public static final String VERSION = "pricing-conv/3";
private static final Pattern MONEY = Pattern.compile("^-?[0-9]{1,10}\\.[0-9]{2}$");
private static final DateTimeFormatter INSTANT =
DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(ZoneOffset.UTC);
public PricingWireModule() {
super("pricing-wire");
addSerializer(BigDecimal.class, new JsonSerializer<>() {
@Override public void serialize(BigDecimal v, JsonGenerator g, SerializerProvider p)
throws IOException {
BigDecimal q = v.setScale(2, RoundingMode.UNNECESSARY); // throws if lossy
g.writeString(q.toPlainString());
}
});
addDeserializer(BigDecimal.class, new JsonDeserializer<>() {
@Override public BigDecimal deserialize(JsonParser jp, DeserializationContext c)
throws IOException {
if (jp.currentToken() != JsonToken.VALUE_STRING)
throw c.weirdStringException(jp.getText(), BigDecimal.class, "Money must be a string");
String s = jp.getText();
if (!MONEY.matcher(s).matches())
throw c.weirdStringException(s, BigDecimal.class, "bad Money format");
return new BigDecimal(s);
}
});
addSerializer(Instant.class, new JsonSerializer<>() {
@Override public void serialize(Instant v, JsonGenerator g, SerializerProvider p)
throws IOException {
g.writeString(INSTANT.format(v.truncatedTo(ChronoUnit.MILLIS)));
}
});
addDeserializer(Instant.class, new JsonDeserializer<>() {
@Override public Instant deserialize(JsonParser jp, DeserializationContext c)
throws IOException {
return Instant.from(INSTANT.parse(jp.getText()));
}
});
addSerializer(LocalDate.class, new JsonSerializer<>() {
@Override public void serialize(LocalDate v, JsonGenerator g, SerializerProvider p)
throws IOException {
g.writeString(v.toString());
}
});
addSerializer(UUID.class, new JsonSerializer<>() {
@Override public void serialize(UUID v, JsonGenerator g, SerializerProvider p)
throws IOException {
g.writeString(v.toString()); // lower-case, hyphenated
}
});
}
public static ObjectMapper mapper() {
return new ObjectMapper()
.registerModule(new PricingWireModule())
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true)
.configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE, false);
}
}
RoundingMode.UNNECESSARY is the Java equivalent of the Python quantize check: it throws instead of silently rounding a value with too many fraction digits. For Reason, annotate the enum constant NONE with @JsonEnumDefaultValue and enable READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE only if the contract says unknown = "fallback:NONE". The PricingClient sends X-Pea-Converters: pricing-conv/3 on each request, and the sidecar rejects a mismatch with 409 CONVERTER_MISMATCH.
6.7 TypeScript: branded types and Zod codecs
JavaScript has no built-in decimal type, and its number cannot hold every 64-bit integer. The safest TypeScript strategy is to keep money as a branded string everywhere except inside arithmetic, and to do that arithmetic with a decimal library on the server only. Branding stops a plain string from being passed where Money is required.
// src/pricing/wire.ts
import { z } from "zod";
import Decimal from "decimal.js";
export const CONVERTERS = "pricing-conv/3";
declare const brand: unique symbol;
type Brand<T, B extends string> = T & { readonly [brand]: B };
export type Money = Brand<string, "Money">;
export type Instant = Brand<string, "Instant">;
export type LocalDate = Brand<string, "LocalDate">;
export type QuoteId = Brand<string, "QuoteId">;
const MONEY_RE = /^-?[0-9]{1,10}\.[0-9]{2}$/;
const INSTANT_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
export const MoneyZ = z.string().regex(MONEY_RE).transform((s) => s as Money);
export const InstantZ = z.string().regex(INSTANT_RE)
.refine((s) => !Number.isNaN(Date.parse(s)), "invalid instant")
.transform((s) => s as Instant);
export const LocalDateZ = z.string().regex(DATE_RE).transform((s) => s as LocalDate);
export const QuoteIdZ = z.string().regex(UUID_RE).transform((s) => s as QuoteId);
export const ReasonZ = z.enum(["NONE", "GOLD_100", "BULK_250"]);
export const money = {
fromDecimal(d: Decimal): Money {
if (!d.isFinite() || d.decimalPlaces() > 2) throw new RangeError("Money: lossy value");
return d.toFixed(2) as Money;
},
toDecimal(m: Money): Decimal {
return new Decimal(m);
},
};
export const instant = {
fromDate(d: Date): Instant {
return d.toISOString() as Instant; // always UTC, always 3 fraction digits
},
toDate(i: Instant): Date {
return new Date(i);
},
};
export const QuoteResponseZ = z.object({
quote_id: QuoteIdZ,
subtotal: MoneyZ,
discount_pct: z.number().int().min(0).max(30),
reason: ReasonZ,
valid_until: LocalDateZ,
module_version: z.string(),
}).strict();
export type QuoteResponse = z.infer<typeof QuoteResponseZ>;
Three properties make this safe. Date.prototype.toISOString() always produces the exact rfc3339-utc-millis form the contract requires. Money never becomes a number, so React components display subtotal directly, formatting it with Intl.NumberFormat only at render time. And .strict() rejects unexpected fields, matching extra="forbid" in Python and FAIL_ON_UNKNOWN_PROPERTIES in Java.
Do not format money for display by calling Number(subtotal) in business logic. Formatting for display is harmless; using the resulting number in further calculations reintroduces the float drift that the contract was written to remove.
6.8 Proving converters: round trips and golden vectors
Converters are small, but their bugs are expensive and silent. Two kinds of test catch nearly all of them.
Round-trip property tests generate many host values and assert that decode(encode(x)) == x and that encode(decode(w)) == w for every valid wire value. A property-testing library explores edge cases that hand-written examples miss: negative zero, the largest allowed amount, leap days, and the last millisecond of a year.
# tests/test_convert_properties.py
from datetime import datetime, timezone, timedelta
from decimal import Decimal
from hypothesis import given, strategies as st
from pricing.convert import default_registry
from pricing.contract import load_contract
reg = default_registry(load_contract("contracts/pricing.contract.toml"))
money = st.decimals(min_value=Decimal("-9999999999.99"), max_value=Decimal("9999999999.99"),
places=2, allow_nan=False, allow_infinity=False)
instants = st.datetimes(min_value=datetime(1970, 1, 1), max_value=datetime(2100, 1, 1),
timezones=st.just(timezone.utc)).map(
lambda d: d.replace(microsecond=(d.microsecond // 1000) * 1000))
@given(money)
def test_money_round_trip(x):
wire = reg.encode("Money", x)
assert reg.decode("Money", wire) == x
assert reg.encode("Money", reg.decode("Money", wire)) == wire
@given(instants, st.integers(min_value=-14, max_value=14))
def test_instant_is_zone_independent(x, offset_h):
shifted = x.astimezone(timezone(timedelta(hours=offset_h)))
assert reg.encode("Instant", shifted) == reg.encode("Instant", x)
assert reg.decode("Instant", reg.encode("Instant", x)) == x
@given(st.decimals(places=3, allow_nan=False, allow_infinity=False))
def test_money_rejects_lossy_values(x):
if x != x.quantize(Decimal("0.01")):
try:
reg.encode("Money", x)
raise AssertionError("lossy value accepted")
except ValueError:
pass
Golden vectors catch disagreement between languages. A shared file lists host-neutral inputs and the exact wire strings every converter must produce. Each host runs the same file in its own test suite, so a change in one host that breaks agreement fails immediately.
# contracts/vectors/pricing-conv-3.jsonl (excerpt)
{"type":"Money","value":"0","wire":"0.00"}
{"type":"Money","value":"-0.50","wire":"-0.50"}
{"type":"Money","value":"9999999999.99","wire":"9999999999.99"}
{"type":"Money","value":"1.005","error":"lossy"}
{"type":"Instant","value":"2024-02-29T23:59:59.999+05:30","wire":"2024-02-29T18:29:59.999Z"}
{"type":"Instant","value":"2026-12-31T23:59:59.9999Z","error":"precision"}
{"type":"LocalDate","value":"2028-02-29","wire":"2028-02-29"}
{"type":"QuoteId","value":"6F9619FF-8B86-D011-B42D-00C04FC964FF","wire":"6f9619ff-8b86-d011-b42d-00c04fc964ff"}
{"type":"Reason","wire":"PLATINUM_500","error":"unknown"}
Note the deliberate cases: a lossy decimal that must be rejected rather than rounded, an instant with a positive offset on a leap day that crosses into the previous calendar day in UTC, an instant with sub-millisecond precision that must be rejected, and an unknown enumeration value. Each language reads the value field into its native type with its own parser before calling the converter, which is exactly the path production code takes.
One subtlety: Python’s strptime with %f accepts one to six fraction digits, so the decoder shown in 6.4 would accept .9999Z. The golden vector exposes the gap. Fix it by matching the contract’s regular expression before parsing, and keep the vector so the bug cannot return.
6.9 Versioning converters
A converter set is part of the contract, so it is versioned like one. The converters = "pricing-conv/3" line names the exact set of encodings every host must implement. Changes fall into three classes:
| Change | Example | Version effect | Rollout |
|---|---|---|---|
| Stricter decode, same encode | Reject sub-millisecond instants that were wrongly accepted | Patch; same converter version | Ship hosts in any order |
| New logical type | Add Percent as a string with one decimal place | Minor; converter set 3 → 4, old types unchanged | Ship hosts first, then the contract that uses the type |
| Changed encoding | Money moves from two to four fraction digits | Major; new converter set and new contract major version | Run both versions side by side; migrate callers; retire the old one |
For a major change, the sidecar and the FastAPI service serve two module versions at once, selected by the X-Pea-Converters header or by a versioned path such as /v2/modules/pricing/.... Each version has its own golden-vector file. Retire the old version only when logs show no callers have used it for an agreed period.
Keep a short compatibility record next to the contract:
# contracts/CONVERTERS.md
pricing-conv/3 current Money=str(2dp) Instant=utc-millis LocalDate=iso QuoteId=uuid-lower
pricing-conv/2 retiring Money=str(2dp) Instant=utc-seconds (sunset 2027-03-31)
pricing-conv/1 retired Money=number (float drift; do not use)
6.10 Converting host objects, not just scalars
Scalars are the hard part, but hosts also hold structured objects: Python dataclasses, Java records, and TypeScript interfaces. Map these with the same discipline:
- Field names follow the contract, not the host. Java’s unitPrice becomes unit_price through an explicit naming strategy, never by relying on a library default.
- Absence is explicit. The contract states whether a field is optional. Optional fields map to PeaLang null, to Python None, to Java Optional or a nullable reference, and to TypeScript T | null. Do not use undefined on the wire; JSON drops it silently.
- No host identity crosses. Never pass ORM entities, Java objects with lazy-loaded fields, or class instances with methods. Convert to plain records first, at the boundary.
- Collections are bounded. Apply the contract’s max_items during conversion so that an oversized list is rejected before it is copied into the runtime.
# Python: domain dataclass to wire record
@dataclass(frozen=True)
class CartLine:
sku: str
qty: int
unit_price: Decimal
def line_to_wire(line: CartLine, reg: Registry) -> dict:
return {"sku": line.sku, "qty": line.qty,
"unit_price": reg.encode("Money", line.unit_price)}
// Java: record with explicit names
public record CartLine(
@JsonProperty("sku") String sku,
@JsonProperty("qty") int qty,
@JsonProperty("unit_price") BigDecimal unitPrice) {}
6.11 Common mistakes
| Mistake | Consequence | Fix |
|---|---|---|
| Sending money as a JSON number | Float drift; totals differ by a cent between hosts | Declare Money with a string wire type and exact pattern |
| Rounding silently during encode | Lost value goes unnoticed; audits disagree | Reject lossy values (quantize check, RoundingMode.UNNECESSARY) |
| Naive or local timestamps | Rules apply on the wrong day near midnight | Require zone-aware values; encode as UTC with millisecond precision |
| Encoding dates as midnight timestamps | Dates shift by a day for some users | Use a separate LocalDate type with ISO date encoding |
| Ad hoc enum handling per host | A new value crashes one host and is ignored by another | Set the unknown policy in the contract; converters read it |
| Converter tests only in one language | Hosts disagree without anyone noticing | Share golden vectors and run them in every host suite |
| Changing an encoding in place | Old and new hosts corrupt each other’s data | Version the converter set; run versions side by side |
Guided practice
- Encode Decimal("19.999") as Money in Python and new BigDecimal("19.999") in Java. Confirm both reject the value.
- Encode the same instant from three different time zones in Python and confirm the wire strings are identical.
- Run the golden-vector file against the TypeScript codecs and fix any failure you find.
- Add a Percent logical type to a copy of the contract and observe startup fail until every host registers a converter.
- Change the Reason unknown policy to fallback:NONE and confirm all three hosts now accept PLATINUM_500 as NONE.
Hands-on lab
Upgrade the pricing contract to v2.4.0 with the [types] section. Implement converter registries in Python, Java, and TypeScript; update the PeaLang script with matching type aliases; and replace every blunt conversion in the Lesson 2–5 hosts with contract-driven encoding and decoding. Create a golden-vector file with at least 30 entries, including at least eight error cases, and run it in all three test suites.
Deliverable: the updated contract and script, three converter implementations, the golden-vector file, passing property and vector tests in each language, and a one-paragraph note on any disagreement you found and how you resolved it.
Review questions
- What is the difference between a wire type and a logical type?
- Why is money encoded as a string rather than a number?
- Why must Instant and LocalDate be separate logical types?
- What does the side field on a contract error tell operators?
- What do round-trip property tests catch that golden vectors do not, and vice versa?
- Which converter changes require a new converter-set version, and why?
- Why should ORM entities never be passed into the runtime directly?
Applied challenge
Add multi-currency support. Introduce a MoneyAmount logical type encoded as a record with amount (Money) and currency (ISO 4217 code), where the number of fraction digits depends on the currency: two for EUR and USD, zero for JPY, three for KWD. Design the contract declaration, implement the converters in all three languages, extend the golden vectors, and decide which converter-set version change this requires. Justify the decision in writing.
Lesson summary
Portable values make embedding possible; logical types make it precise. A typed embedding contract names each logical type, fixes its wire encoding, and states its policy for unknown values. PeaLang annotations mirror the contract and are checked in CI. Each host implements a converter registry that rejects lossy or ambiguous values instead of guessing, and walks payloads by contract so that errors name the exact field and the responsible side. Round-trip properties prove each converter is consistent with itself; shared golden vectors prove every host agrees with every other. Versioned converter sets let encodings evolve without corrupting data in flight.
Transition to the Chapter 15 checkpoint
You now have every piece needed for a polyglot extension service: an embedding contract with logical types, a FastAPI host, a Java sidecar client, and a TypeScript and React front end. The checkpoint assembles them into one system and asks you to prove that all three hosts agree on every decision the rules make.
Lesson status: Ready for review.