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

Part III — Advanced Systems · Chapter 13 · Lesson 2 of 5 · 4 min read

Lesson 2: Host Awaitables and Asynchronous Boundaries

Lesson level: Advanced

Purpose: Understand how PeaLang async code awaits work performed by the host, how values and errors cross that boundary, and how to keep the boundary safe and testable.

Release note: host API names and registration patterns in this lesson are illustrative. Verify them against your installed v0.63 release and the embedding guide for your host.

Learning objectives

By the end of this lesson, you should be able to:

2.1 What a host awaitable is

A host awaitable is a Future whose work happens outside PeaLang: an HTTP request in the host language, a database query, or a timer. The script awaits it like any other Future; the host decides how the work actually runs.

2.2 The boundary contract

ConcernRule
ArgumentsPortable values only, validated by the host
ResultPortable values only, validated before resuming the script
ErrorsMapped to PeaLang errors with safe messages
CancellationHost stops the work when the script cancels
CapabilitiesThe call is denied unless granted
BudgetsWaiting time counts against time limits

2.3 Exposing an async host function

In the host, an async function is registered under a name the script can call. The illustrative Python host below exposes a tier lookup:

# Python host (illustrative)
async def lookup_tier(customer_id: str) -> str:
    row = await db.fetch_one("SELECT tier FROM customers WHERE id = ?", customer_id)
    return row["tier"] if row else "standard"

runtime.register_async("host.lookup_tier", lookup_tier, capability="db.read")
# PeaLang script
async function tier_for(order) {
  return await host.lookup_tier(order["customer_id"])
}

2.4 Value conversion

The host converts its results into portable values before resuming the script: strings, numbers, booleans, null, lists, and string-keyed maps. Database rows, response objects, and timestamps are converted explicitly. This is the same rule as Chapter 5, applied at every await.

2.5 Error mapping

When host work fails, the host should raise a PeaLang error with a clear category and a message that does not leak secrets, stack traces, or connection strings. The script sees the error at its await.

Host failureSuggested PeaLang error
TimeoutTimeout error with the operation name
Not foundDomain result such as null, or a not-found error
Permission or credential problemPermission error without credential details
Unexpected exceptionHost error with a correlation identifier

2.6 Async or sync host functions

Expose as async whenExpose as sync when
The work waits on I/OThe work is fast and CPU-only
Many calls may overlapOrdering must be strictly sequential
The host has a native async clientThe host library is blocking and cannot be wrapped safely

A blocking host call made from async code holds the scheduler (Lesson 1). If only a blocking library exists, the host should run it on a worker and expose the result as an awaitable.

2.7 Capabilities at the boundary

Registering a host function with a capability name means the call fails with a permission error unless the runtime policy grants that capability. This keeps async I/O inside the same least-privilege model as Chapter 8 and Chapter 14.

2.8 Budgets while waiting

Waiting does not consume instructions, but it does consume wall-clock time. Time limits therefore still apply to awaited work. Set per-call timeouts in the host and an overall deadline for the script; Lesson 3 shows how deadlines propagate.

2.9 Simulated hosts for testing

# test host (illustrative)
fake_tiers = {"C-1": "gold", "C-2": "standard"}
async def fake_lookup(customer_id):
    await sleep(0.01)
    return fake_tiers.get(customer_id, "standard")
runtime.register_async("host.lookup_tier", fake_lookup, capability="db.read")

A fake host with fixed data and small fixed delays makes async tests deterministic. Add variants that raise timeouts, return malformed values, or deny permission to cover failure paths.

2.10 Worked example

The order_rules service now calls host.lookup_tier for each order. In production the host queries a database; in tests a fake returns fixed tiers. When the database is slow, the host raises a timeout after 2 seconds, and the script falls back to "standard", which produces BULK or NONE instead of a GOLD reason. The fallback is logged so operators can see how often it happens.

2.11 Common mistakes

MistakeConsequenceFix
Returning host objects to the scriptNon-portable values, hidden couplingConvert to portable values
Leaking exception textSecrets in logs or outputMap to safe error messages
No host-side timeoutScript waits indefinitelySet per-call timeouts
Registering without a capabilityBypasses policyAlways name the capability

2.12 Guided practice

2.13 Hands-on lab

Expose a host tier lookup to the order_rules script, first with a fake host and then with a deliberately slow one. Confirm that the timeout produces the documented fallback and that denying the capability produces a permission error.

Deliverable: the host registration, the script, and test output for success, timeout, malformed value, and denied permission.

2.14 Review questions

2.15 Applied challenge

Design the async boundary for a host that offers HTTP, database, and timer functions. For each, state the capability name, timeout, error mapping, and how you will test it.

Lesson summary

Transition to Lesson 3

Waiting work must sometimes be stopped. Lesson 3 covers cancellation tokens, scopes, deadlines, and how cancellation propagates.

Lesson status: Ready for review.

← Previous Next →