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:
- Explain what a host awaitable is.
- Describe how values, errors, and cancellation cross the async boundary.
- Choose between exposing async and sync host functions.
- Apply capability and budget rules to async host calls.
- Test async boundaries with simulated hosts.
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
| Concern | Rule |
|---|---|
| Arguments | Portable values only, validated by the host |
| Result | Portable values only, validated before resuming the script |
| Errors | Mapped to PeaLang errors with safe messages |
| Cancellation | Host stops the work when the script cancels |
| Capabilities | The call is denied unless granted |
| Budgets | Waiting 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 failure | Suggested PeaLang error |
|---|---|
| Timeout | Timeout error with the operation name |
| Not found | Domain result such as null, or a not-found error |
| Permission or credential problem | Permission error without credential details |
| Unexpected exception | Host error with a correlation identifier |
2.6 Async or sync host functions
| Expose as async when | Expose as sync when |
|---|---|
| The work waits on I/O | The work is fast and CPU-only |
| Many calls may overlap | Ordering must be strictly sequential |
| The host has a native async client | The 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
| Mistake | Consequence | Fix |
|---|---|---|
| Returning host objects to the script | Non-portable values, hidden coupling | Convert to portable values |
| Leaking exception text | Secrets in logs or output | Map to safe error messages |
| No host-side timeout | Script waits indefinitely | Set per-call timeouts |
| Registering without a capability | Bypasses policy | Always name the capability |
2.12 Guided practice
- Design the argument and result shape for a host price lookup.
- Write an error-mapping table for three host failures.
- Decide whether a currency conversion function should be async or sync.
- Write a fake host that returns a malformed value and observe validation.
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
- What is a host awaitable?
- Which values may cross the async boundary?
- How should host errors appear to the script?
- Why should blocking host libraries be wrapped?
- How do capabilities apply to async host calls?
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
- Host awaitables let scripts wait on host-side I/O.
- The boundary carries only portable values and safe errors.
- Capabilities and time budgets apply to every async host call.
- Fake hosts make async behaviour testable and repeatable.
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.