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

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

Chapter 15 Checkpoint: Polyglot Extension Service

Checkpoint level: Advanced

Purpose: Build one PeaLang extension and serve it to three different hosts — a Python FastAPI service, a Java 17 application through the sidecar, and a TypeScript and React front end — under a single typed embedding contract. Prove that every host makes the same decision for the same input, that every boundary rejects what the contract forbids, and that a contract change rolls out without breaking any host.

Release note: contract keys, sidecar endpoints, converter-set names, and client classes follow the illustrative APIs used in Lessons 1–6 of this chapter. Verify exact names against the PeaLang v0.63 RC2 release documentation.

Checkpoint outcomes

By completing this checkpoint, you will demonstrate that you can:

Scenario

A subscription business sells software plans to companies in several countries. When a customer changes plan mid-cycle, the business must calculate a proration credit: the unused value of the old plan, the cost of the new plan for the rest of the cycle, any promotional adjustment, and the amount to charge or credit today.

Three systems need this calculation. The billing API (Python, FastAPI) charges customers. The finance ledger (Java 17) books revenue and must match billing to the cent. The self-service portal (TypeScript, Next.js and React) shows the customer a preview before they confirm. Today each system has its own implementation, and support tickets show that the portal preview, the actual charge, and the ledger entry sometimes differ by a cent or by a day.

Your task is to replace all three implementations with one PeaLang extension, proration.pea, exposed through one contract, proration.contract.toml.

Input contract. Every host passes this record to the exported function prorate(change):

FieldLogical typeConstraint
subscription_idSubscriptionIdMatches S followed by 10 digits
old_plan_priceMoney0.00 to 100000.00 per cycle
new_plan_priceMoney0.00 to 100000.00 per cycle
currencyCurrencyEUR, GBP, or USD
cycle_startLocalDateStart of the current billing cycle
cycle_endLocalDateExclusive end; after cycle_start; at most 366 days later
changed_atInstantUTC; on or after cycle_start and before cycle_end
promo_codePromoCode or nullOptional; matches [A-Z0-9]{4,12}

Output contract. The function returns:

FieldLogical typeMeaning
unused_creditMoneyValue of the old plan for the remaining days
new_chargeMoneyCost of the new plan for the remaining days
promo_adjustmentMoneyZero or negative
amount_dueMoneynew_charge − unused_credit + promo_adjustment; negative means a credit
remaining_daysIntWhole days from the change date to cycle_end
cycle_daysIntWhole days in the cycle
ruleProrationRuleDAILY, NO_PRICE_CHANGE, or PROMO_CAPPED
explanationStringPlain-language summary, at most 280 characters

Business rules. Proration is daily. The change date is the UTC calendar date of changed_at. Remaining days count from the change date to cycle_end. Each amount is computed as price × remaining_days ÷ cycle_days and rounded half-to-even to two decimal places, rounding each amount separately before combining them. A change on the first day of the cycle is charged as a full cycle under rule DAILY. A promo code may reduce amount_due by at most 20% of new_charge and never below zero; when the cap applies, the rule is PROMO_CAPPED. A change where old and new prices are equal yields zero amounts and rule NO_PRICE_CHANGE.

15C.1 Requirements

Functional requirements

IDRequirement
FR1One PeaLang module, proration.pea, implements every business rule. No host re-implements any calculation.
FR2The FastAPI billing API exposes POST /v1/proration/preview and POST /v1/proration/charge. Both call the extension in-process.
FR3The Java ledger calls the extension through the PeaLang sidecar and books the returned amounts without recalculation.
FR4The portal calls its own server route, which calls the billing API preview endpoint; the browser never calls the sidecar or the billing API directly.
FR5Every response includes module_version and contract_version so that a preview, a charge, and a ledger entry can be matched to the same rule build.
FR6The charge endpoint records an audit entry with input hash, output, module_version, and request ID.

Non-functional requirements

IDRequirement
NFR1Agreement: for every golden vector and for 10,000 generated inputs, all three hosts return byte-identical wire outputs.
NFR2Precision: no host converts Money to a binary floating-point number at any point on the decision path.
NFR3Latency: p95 under 40 ms for the billing API and under 60 ms for the Java client through the sidecar, at 50 requests per second.
NFR4Least privilege: the extension has no capabilities. It needs no host functions, files, network, or clock.
NFR5Limits: max_execution_ms 50, max_instructions 500,000, max_memory_bytes 16 MiB per evaluation.
NFR6Compatibility: a minor contract change (adding an optional output field) is deployed with zero failed requests.

15C.2 Architecture

                 contracts/proration.contract.toml  (v1.0.0, conv proration-conv/1)
                 contracts/vectors/proration-conv-1.jsonl
                                  |
             +--------------------+--------------------+
             |                    |                    |
   rules/proration.pea   build: pea check --types, pea contract check,
             |                  pea compile -> proration.peac (signed)
             |
   +---------+----------------------------+
   |                                      |
 billing-api (Python/FastAPI)       pea sidecar serve (127.0.0.1:7071)
  - lifespan loads .peac                  |
  - converter registry (Py)          ledger (Java 17)
  - /v1/proration/preview              - PricingWireModule-style converters
  - /v1/proration/charge               - ProrationClient + CircuitBreaker
             ^
             |  server-to-server, bearer token
 portal (Next.js server route, Zod codecs)
             ^
             |  same-origin fetch, session cookie
 browser (React useProrationPreview hook)

The design has one rule source, one compiled artifact, two execution paths (in-process and sidecar), and three converter implementations bound to one converter-set version. The browser is a display surface only: it never computes or submits amounts.

Trust boundaries. The browser is untrusted. The portal server route is trusted to authenticate the user and look up the subscription from its own records; it must never accept prices from the browser. The billing API trusts the portal only through a service token and still validates every field. The sidecar listens on loopback only and requires a bearer token.

15C.3 The contract

# contracts/proration.contract.toml
[contract]
name = "proration"
version = "1.0.0"
converters = "proration-conv/1"
export = "prorate"
capabilities = []

[types.Money]
wire = "string"
pattern = "^-?[0-9]{1,10}\\.[0-9]{2}$"

[types.LocalDate]
wire = "string"
format = "iso-date"

[types.Instant]
wire = "string"
format = "rfc3339-utc-millis"

[types.SubscriptionId]
wire = "string"
pattern = "^S[0-9]{10}$"

[types.PromoCode]
wire = "string"
pattern = "^[A-Z0-9]{4,12}$"

[types.Currency]
wire = "string"
enum = ["EUR", "GBP", "USD"]
unknown = "reject"

[types.ProrationRule]
wire = "string"
enum = ["DAILY", "NO_PRICE_CHANGE", "PROMO_CAPPED"]
unknown = "reject"

[inputs]
subscription_id = "SubscriptionId"
old_plan_price  = { type = "Money", min = "0.00", max = "100000.00" }
new_plan_price  = { type = "Money", min = "0.00", max = "100000.00" }
currency        = "Currency"
cycle_start     = "LocalDate"
cycle_end       = "LocalDate"
changed_at      = "Instant"
promo_code      = { type = "PromoCode", optional = true }

[outputs]
unused_credit    = "Money"
new_charge       = "Money"
promo_adjustment = { type = "Money", max = "0.00" }
amount_due       = "Money"
remaining_days   = { int = true, min = 0, max = 366 }
cycle_days       = { int = true, min = 1, max = 366 }
rule             = "ProrationRule"
explanation      = { type = "string", max_length = 280 }

[limits]
max_execution_ms = 50
max_instructions = 500000
max_memory_bytes = 16777216

Cross-field constraints such as cycle_end > cycle_start cannot be expressed in the field table. They belong in the extension’s own validation, which raises a typed error that every host maps to INVALID_CHANGE with status 400.

15C.4 Reference extension

The reference solution below shows the expected shape. Promotional codes are a small table inside the module, because the extension has no capabilities and cannot look them up. In a later version, a host function with a promo.read capability would replace the table.

// rules/proration.pea
import std.decimal as dec
import std.datetime as dt
import std.string as str

type Money = String
type LocalDate = String
type Instant = String

type Change = {
    subscription_id: String,
    old_plan_price: Money,
    new_plan_price: Money,
    currency: String,
    cycle_start: LocalDate,
    cycle_end: LocalDate,
    changed_at: Instant,
    promo_code: String?,
}

type Proration = {
    unused_credit: Money,
    new_charge: Money,
    promo_adjustment: Money,
    amount_due: Money,
    remaining_days: Int,
    cycle_days: Int,
    rule: String,
    explanation: String,
}

const PROMO_PCT = { "SWITCH10": "0.10", "UPGRADE20": "0.20", "LOYAL25": "0.25" }
const PROMO_CAP = dec.parse("0.20")

export error InvalidChange(message: String)

function money(x) -> Money {
    return dec.format(dec.round_half_even(x, 2), 2)
}

function portion(price: Money, remaining: Int, total: Int) {
    let p = dec.parse(price)
    return dec.round_half_even(
        dec.div(dec.mul(p, dec.from_int(remaining)), dec.from_int(total), 12), 2)
}

export function prorate(change: Change) -> Proration {
    let start = dt.parse_date(change.cycle_start)
    let end = dt.parse_date(change.cycle_end)
    let changed = dt.to_date_utc(dt.parse_instant(change.changed_at))

    let cycle_days = dt.days_between(start, end)
    if cycle_days < 1 or cycle_days > 366 {
        throw InvalidChange("cycle must be 1 to 366 days")
    }
    if changed < start or changed >= end {
        throw InvalidChange("change date must fall inside the current cycle")
    }
    let remaining = dt.days_between(changed, end)

    if change.old_plan_price == change.new_plan_price {
        return {
            unused_credit: "0.00", new_charge: "0.00", promo_adjustment: "0.00",
            amount_due: "0.00", remaining_days: remaining, cycle_days: cycle_days,
            rule: "NO_PRICE_CHANGE",
            explanation: "Price unchanged; nothing to charge or credit.",
        }
    }

    let credit = portion(change.old_plan_price, remaining, cycle_days)
    let charge = portion(change.new_plan_price, remaining, cycle_days)
    let due = dec.sub(charge, credit)

    let rule = "DAILY"
    let adj = dec.zero()
    if change.promo_code != null and PROMO_PCT.has(change.promo_code) {
        let wanted = dec.round_half_even(
            dec.mul(charge, dec.parse(PROMO_PCT[change.promo_code])), 2)
        let cap = dec.round_half_even(dec.mul(charge, PROMO_CAP), 2)
        let applied = dec.min(wanted, cap)
        if dec.gt(wanted, cap) { rule = "PROMO_CAPPED" }
        if dec.gt(due, dec.zero()) {
            applied = dec.min(applied, due)      // never push a charge below zero
        } else {
            applied = dec.zero()                 // promos do not enlarge credits
        }
        adj = dec.neg(applied)
        due = dec.add(due, adj)
    }

    let text = str.format("{} of {} days remain. Credit {} {}, charge {} {}, due {} {}.",
        remaining, cycle_days, money(credit), change.currency,
        money(charge), change.currency, money(due), change.currency)

    return {
        unused_credit: money(credit),
        new_charge: money(charge),
        promo_adjustment: money(adj),
        amount_due: money(due),
        remaining_days: remaining,
        cycle_days: cycle_days,
        rule: rule,
        explanation: str.truncate(text, 280),
    }
}

Points to check in your own solution: amounts are rounded separately before they are combined, so amount_due always equals new_charge − unused_credit + promo_adjustment exactly; division uses twelve working digits before rounding; the change date is the UTC date of the instant; and promo_adjustment is never positive, which the output contract enforces with max = "0.00".

Note that dec.format(..., 2) of a negative zero must produce "0.00", not "-0.00". Add a golden vector for it; this is a classic place for hosts to disagree.

15C.5 Host wiring

Each host is thin. It authenticates, loads trusted data, converts through its registry, calls the extension, converts back, and maps errors. None of them contains a proration formula.

Billing API (Python, FastAPI). Reuse the Lesson 5 structure. The lifespan loads the signed proration.peac into a runtime with an empty permission set and the contract’s limits, builds the converter registry, and runs the golden vectors as a startup self-test.

# billing/routes/proration.py
@router.post("/v1/proration/preview", response_model=ProrationOut)
async def preview(body: ProrationIn, svc: ServiceDep, budget: BudgetDep) -> ProrationOut:
    sub = await svc.subscriptions.get(body.subscription_id)     # trusted prices and cycle
    change = ChangeModel(
        subscription_id=sub.id, old_plan_price=sub.plan.price,
        new_plan_price=(await svc.plans.get(body.new_plan_id)).price,
        currency=sub.currency, cycle_start=sub.cycle_start, cycle_end=sub.cycle_end,
        changed_at=svc.clock.now_utc(), promo_code=body.promo_code,
    )
    wire_in = to_wire(svc.contract.input_spec, change, svc.registry)
    raw = await run_extension(svc.engine, "prorate", wire_in, budget)
    out = from_wire(svc.contract.output_spec, raw.value, svc.registry)
    return ProrationOut(**out, module_version=raw.module_version,
                        contract_version=svc.contract.version)

The request body carries only subscription_id, new_plan_id, and an optional promo_code. Prices, cycle dates, and the change time come from the billing system’s own records and clock. The charge endpoint is identical except that it also writes the audit record and submits amount_due to the payment provider.

Ledger (Java 17). The ledger receives a confirmed change event from billing and asks the sidecar to recompute the proration with the same inputs. It books the result only if it matches the amounts and module version carried in the event; a mismatch raises an alert and parks the event for review.

// ledger/ProrationBooking.java
public void onChangeConfirmed(ChangeConfirmed event) {
    Proration p = client.prorate(event.change());           // sidecar, proration-conv/1
    if (!p.moduleVersion().equals(event.moduleVersion())
            || p.amountDue().compareTo(event.amountDue()) != 0) {
        alerts.raise("PRORATION_MISMATCH", event.subscriptionId());
        parking.park(event, p);
        return;
    }
    journal.post(Entries.forProration(event.subscriptionId(), p));
}

Use compareTo, not equals, for BigDecimal amounts: new BigDecimal("1.0").equals(new BigDecimal("1.00")) is false. Because the converter fixes the scale at two, both work here, but compareTo remains the safer habit.

Portal (TypeScript). The Next.js server route authenticates the user, confirms the user owns the subscription, and calls the billing preview endpoint with a service token. It parses the response with the Zod codecs from Lesson 6 and passes branded values to the client. The React hook only displays them.

// portal/app/api/proration/preview/route.ts
export async function POST(req: Request) {
  const session = await requireSession(req);
  const input = PreviewRequestZ.parse(await req.json());   // { subscriptionId, newPlanId, promoCode? }
  await assertOwnsSubscription(session.userId, input.subscriptionId);
  const res = await billing.post("/v1/proration/preview", {
    subscription_id: input.subscriptionId,
    new_plan_id: input.newPlanId,
    promo_code: input.promoCode ?? null,
  }, { headers: { "X-Pea-Converters": CONVERTERS } });
  return Response.json(ProrationOutZ.parse(res));
}

15C.6 Worked examples

Use these cases to check your extension by hand before writing automated tests. All amounts are in EUR; credit and charge are each rounded half-to-even to two decimal places before they are combined.

#Cyclechanged_at (wire)Old → newPromoDaysCreditChargeAdj.DueRule
W12026-11-01 to 2026-12-012026-11-10T22:30:00.000Z30.00 → 90.00—21 / 3021.0063.000.0042.00DAILY
W2samesame30.00 → 90.00UPGRADE2021 / 3021.0063.00-12.6029.40DAILY
W3samesame30.00 → 90.00LOYAL2521 / 3021.0063.00-12.6029.40PROMO_CAPPED
W4same2026-11-11T01:30:00.000Z30.00 → 90.00—20 / 3020.0060.000.0040.00DAILY
W52026-12-01 to 2027-01-012026-12-20T09:00:00.000Z49.99 → 99.99—12 / 3119.3538.710.0019.36DAILY
W6samesame99.99 → 49.99SWITCH1012 / 3138.7119.350.00-19.36DAILY
W72026-11-01 to 2026-12-012026-11-30T12:00:00.000Z10.00 → 12.00LOYAL251 / 300.330.40-0.070.00PROMO_CAPPED
W8same2026-11-05T08:00:00.000Z45.00 → 45.00—26 / 300.000.000.000.00NO_PRICE_CHANGE

W4 is the time-zone trap from the support tickets. A customer in UTC−2 changes plan at 23:30 local time on 10 November. The instant is 01:30 UTC on 11 November, so the change date is 11 November and 20 days remain, not 21. The portal used to compute 21 from the browser’s local date; the ledger computed 20. With the contract, every host sends the same UTC instant and the extension alone derives the date.

W5 and W6 show that rounding each amount separately makes an upgrade and the reverse downgrade exact mirror images. W7 shows two limits interacting: the 25% promo is capped at 20% of the charge (0.08), and then capped again so the amount due does not go below zero.

15C.7 Golden vectors and differential agreement

Two vector files are required. The converter vectors (proration-conv-1.jsonl) test each logical type in isolation, as in Lesson 6. The decision vectors (proration-decisions.jsonl) hold complete wire inputs and the exact expected wire outputs, starting with W1–W8.

{"id":"W4","input":{"subscription_id":"S0000000042","old_plan_price":"30.00",
  "new_plan_price":"90.00","currency":"EUR","cycle_start":"2026-11-01",
  "cycle_end":"2026-12-01","changed_at":"2026-11-11T01:30:00.000Z","promo_code":null},
 "output":{"unused_credit":"20.00","new_charge":"60.00","promo_adjustment":"0.00",
  "amount_due":"40.00","remaining_days":20,"cycle_days":30,"rule":"DAILY"}}

The explanation field is excluded from byte comparison because it is free text, but its length limit is still checked.

Differential agreement. A harness generates 10,000 random valid changes with a fixed seed and sends each one through three paths: the FastAPI preview endpoint, the Java client through the sidecar, and the portal server route. It canonicalizes each wire output (sorted keys, no whitespace, explanation removed) and compares the three strings. Any difference fails the build and writes the input to disagreements.jsonl so it can become a new golden vector.

# harness/agree.py  (outline)
rng = random.Random(1563)
for i in range(10_000):
    change = random_change(rng)                 # valid by construction, edge-biased
    py = canon(billing.preview(change))
    jv = canon(java_cli.prorate(change))        # small CLI wrapping ProrationClient
    ts = canon(portal.preview(change))
    if not (py == jv == ts):
        record_disagreement(i, change, py, jv, ts)

Bias the generator toward edges: changes on the first and last day of a cycle, instants within one minute of UTC midnight, cycles of 28, 29, 30, 31, and 366 days, prices that produce exact half-cent results before rounding, and the maximum price.

15C.8 Test matrix

Boundary and security tests. Run each against every host that exposes the boundary.

IDTestExpected result
B1Money sent as a JSON number (90 instead of "90.00")422 or 400 at the first host boundary; extension never called
B2Money with three fraction digits ("90.005")Rejected by the converter; error names the field
B3changed_at without Z or with a local offset on the wireRejected; hosts must convert to UTC before encoding
B4cycle_end before cycle_start400 INVALID_CHANGE raised by the extension
B5changed_at outside the cycle400 INVALID_CHANGE
B6Unknown currency "JPY"Rejected by the converter (unknown = reject)
B7Browser sends old_plan_price to the portal routeField rejected by the strict request schema; prices never accepted from the browser
B8User previews a subscription they do not own403 from the portal route; billing API not called
B9Extension modified to return promo_adjustment "1.00"500 CONTRACT_VIOLATION, side = script, in every host
B10Extension modified to loop forever429 PEA_RESOURCE_LIMIT within the 50 ms limit plus overhead
B11Sidecar called without bearer token or from a non-loopback address401 or connection refused
B12Client sends X-Pea-Converters: proration-conv/0409 CONVERTER_MISMATCH

Agreement and operations tests.

IDTestExpected result
A1Decision vectors W1–W8 and at least 22 more in each hostAll pass byte-for-byte
A2Differential harness, 10,000 seeded casesZero disagreements
A3Ledger receives an event whose amount differs from its recomputationPRORATION_MISMATCH alert; event parked; nothing booked
A4Readiness before the startup self-test completes503 from billing; sidecar /readyz not ready
A5Load test at 50 requests per second for five minutesNFR3 latency targets met; no 5xx
A6Rolling deployment of contract 1.1.0 (see 15C.9) under loadZero failed requests; versions visible in responses

15C.9 Rolling out a contract change

Finance asks for a new output field, daily_rate_new: the new plan’s daily price, as Money. Adding an output field is a minor change (1.0.0 → 1.1.0); no new logical type is needed, so the converter set stays at proration-conv/1. Roll it out in this order and record evidence for each step:

Reversing steps 1 and 3 is the classic failure: a strict reader with FAIL_ON_UNKNOWN_PROPERTIES or Zod .strict() rejects responses that contain the new field. Test A6 must prove the order works under load.

15C.10 Acceptance criteria

15C.11 Submission package

polyglot-proration/
  contracts/   proration.contract.toml, CONVERTERS.md, vectors/*.jsonl
  rules/       proration.pea, proration.peac, signature
  billing/     FastAPI service and tests
  ledger/      Java 17 client, booking logic, and tests
  portal/      Next.js route, Zod codecs, React hook, and tests
  harness/     differential agreement harness and seed
  evidence/    test reports, load-test results, rollout log, disagreement log
  README.md    architecture, trust boundaries, and how to run everything

15C.12 Rubric

CriterionWeightExcellentAcceptableNeeds work
Contract design15%Logical types, limits, and unknown policies fully specified; cross-field rules documentedTypes specified; some policies implicitRaw wire types; money as numbers
Extension correctness20%All worked examples and vectors pass; rounding and date rules exactMinor edge-case gaps found and fixed by vectorsIncorrect rounding or local-date logic
Host integration20%Hosts are thin, trusted data loaded server-side, consistent error mappingHosts thin but error mapping inconsistentFormulas duplicated in a host
Cross-host agreement20%Zero disagreements; generator edge-biased; disagreements turned into vectorsZero disagreements on uniform random inputs onlyDisagreements remain
Security boundaries15%B1–B12 pass; browser cannot influence amountsMost pass; gaps documentedPrices accepted from the browser
Operations and rollout10%Versions visible end to end; 1.1.0 rollout with zero failuresRollout succeeds with brief errorsNo version evidence

15C.13 Reflection questions

Chapter 15 summary

Chapter 15 treated PeaLang as an extension engine that serves many hosts. Lesson 1 defined exported-function contracts as the stable boundary. Lesson 2 embedded the runtime in Python behind a facade that validates on both sides. Lesson 3 reached Java through a hardened sidecar with a resilient client. Lesson 4 brought decisions to TypeScript and React while keeping authority on the server. Lesson 5 turned the Python host into a production FastAPI service with lifespan-managed engines, request budgets, and one error mapping. Lesson 6 added logical types and converter registries so that values keep their meaning across languages. The checkpoint combined all of it: one rule, one contract, three hosts, and evidence that they agree.

Transition to Chapter 16

So far, PeaLang has evaluated one record at a time: a cart, a shipment, a subscription change. Many real workloads operate on whole tables instead — thousands or millions of rows to filter, join, aggregate, and reshape. Chapter 16 introduces the PeaLang data foundation: typed schemas, the DataFrame for eager work, and the LazyFrame for planned, optimized execution.

Checkpoint status: Ready for review.

← Previous Next →