PeaBox Lab › PeaLang › Learn › Chapter 14 › Lesson 3

Part III — Advanced Systems · Chapter 14 · Lesson 3 of 5 · 8 min read

Lesson 3: Resource Budgets, Snapshots, and Auditability

Lesson level: Advanced

Purpose: Lesson 2 set hard limits that stop a run. This lesson shows how to budget resources across many runs, read the runtime's usage snapshots, and produce audit records that let operators explain what happened and why.

Release note: The configuration keys, API names, and record fields in this lesson are illustrative. Verify exact names and syntax against the PeaLang v0.63 reference before you publish or teach from this material.

Learning objectives

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

3.1 Limits versus budgets

A limit caps one execution: if a single run uses more than 2,000,000 instructions, it stops. A budget caps total use across many executions: a tenant may spend 500 CPU-milliseconds per minute across all its rule calls. Limits protect the host from one runaway script. Budgets protect fairness and cost across a fleet.

ConceptScopeTypical response when exceeded
LimitOne runStop the run with a resource error
BudgetMany runs over a windowReject or queue new runs, or degrade to a fallback
QuotaContractual allowance per tenantBill, alert, or refuse further work
SnapshotPoint-in-time usage readingNo action; it is evidence

3.2 Budget dimensions

Choose budget dimensions that match real costs. Budgeting on instructions alone ignores slow HTTP calls; budgeting on wall time alone punishes scripts waiting on a slow host.

DimensionMeasuresGood for
instructionsExecuted VM instructionsCPU fairness, independent of machine speed
cpu_msMeasured CPU timeCost attribution
wall_msElapsed timeLatency targets
peak_memory_bytesHighest allocationCapacity planning
http_calls / http_bytesNetwork usePartner rate limits and egress cost
output_bytesPrinted or returned outputLog and storage cost
runsNumber of executionsSimple rate limiting

3.3 Declaring budgets

Budgets live beside limits in project or host configuration. Keep the window explicit so readers do not have to guess.

[budgets.tenant_default]
window = "60s"
instructions = 50_000_000
http_calls = 120
output_bytes = 1_048_576
runs = 600
on_exhausted = "reject"   # reject | queue | fallback

[budgets.tenant_premium]
window = "60s"
instructions = 200_000_000
http_calls = 600
runs = 3000
on_exhausted = "queue"

A host assigns each run to a budget key, such as the tenant ID. The runtime charges the run's final usage against that key when the run ends.

3.4 Charging and admission

Budget enforcement has two moments. Admission happens before a run starts: if the budget is already exhausted, the host refuses or queues the request. Charging happens after the run: the host records what was actually used. Admission is cheap; charging is accurate.

import std.runtime

function admit(tenant: String) -> Result[Null, String] {
    let b = runtime.budget(tenant)
    if b.remaining("runs") <= 0 {
        return Err("BUDGET_EXHAUSTED: runs")
    }
    if b.remaining("instructions") < 2_000_000 {
        return Err("BUDGET_EXHAUSTED: instructions")
    }
    return Ok(null)
}

Note the second check: the host refuses a run if the remaining instruction budget is smaller than the per-run limit. This prevents a run from starting when it could not finish.

3.5 Usage snapshots

A snapshot is a read-only record of resource use at one moment. The runtime can take one at the start of a run, at chosen checkpoints, and at the end.

import std.runtime

function evaluate_batch(orders: List[Map]) -> List[Map] {
    let start = runtime.snapshot()
    let results = []
    for o in orders {
        results.push(order_rules.evaluate(o))
    }
    let end = runtime.snapshot()
    let used = end.diff(start)
    log.info("batch used {used.instructions} instructions, peak {used.peak_memory_bytes} bytes")
    return results
}
Snapshot fieldMeaning
instructionsInstructions executed so far
wall_msElapsed time since run start
heap_bytes / peak_memory_bytesCurrent and highest memory
stack_depth / max_stack_depthCurrent and deepest call depth
output_bytesBytes written to output
http_callsHTTP requests made
file_readsFile reads performed
limitsThe configured limits, for comparison

3.6 Reading headroom

Headroom is the gap between what a run used and what its limit allows. Low headroom means a small change in input could push the run over the limit.

function headroom(s: Snapshot) -> Map {
    return {
        "instructions": 1.0 - s.instructions / s.limits.instructions,
        "memory": 1.0 - s.peak_memory_bytes / s.limits.memory_bytes,
        "stack": 1.0 - s.max_stack_depth / s.limits.max_stack_depth,
    }
}

A practical rule: if the 99th-percentile run keeps less than 30 percent headroom in any dimension, investigate before raising the limit. The cause is often an input-size assumption that no longer holds.

3.7 Snapshots inside long runs

For long batch jobs, take snapshots at regular checkpoints. A script can then stop cleanly before a hard limit hits, returning partial results instead of failing with nothing.

function evaluate_until_low(orders: List[Map]) -> Map {
    let done = []
    for o in orders {
        let s = runtime.snapshot()
        if s.instructions > s.limits.instructions * 0.9 {
            return {"status": "PARTIAL", "processed": done.len(), "results": done}
        }
        done.push(order_rules.evaluate(o))
    }
    return {"status": "COMPLETE", "processed": done.len(), "results": done}
}

Cooperative stopping is a courtesy, not a guarantee. The hard limit still applies; the script simply avoids reaching it.

3.8 What an audit record must answer

An audit record exists so someone can later answer: who ran what, with which permissions, against which code version, what did it use, and how did it end? If a record cannot answer one of these, it is incomplete.

QuestionField
Who?caller_id, tenant
What code?module, function, package version, bytecode hash
With what authority?granted capabilities, policy version
When?start and end timestamps (UTC)
What did it use?final usage snapshot
How did it end?outcome: OK, ERROR, LIMIT_EXCEEDED, DENIED, CANCELLED
Why did it end that way?error code and the limit or capability involved
Which request?correlation_id linking host logs and script logs

3.9 Emitting audit records

[audit]
enabled = true
sink = "jsonl"
path = "audit/runs.jsonl"
include_snapshot = true
include_inputs = "hash"   # none | hash | redacted
hash_chain = true

A typical record, one JSON object per line:

{"ts_start":"2026-10-29T10:15:02.114Z","ts_end":"2026-10-29T10:15:02.131Z",
 "correlation_id":"req-7f3a","tenant":"acme","caller_id":"orders-api",
 "module":"order_rules","function":"evaluate","package":"order_rules@1.4.2",
 "bytecode_sha256":"9c1e...","policy_version":"cap-2026-10",
 "capabilities":["log"],"input_sha256":"41ab...",
 "outcome":"LIMIT_EXCEEDED","limit":"instructions",
 "usage":{"instructions":2000000,"peak_memory_bytes":812044,"wall_ms":17},
 "prev_hash":"d02f...","hash":"77be..."}

3.10 Keeping secrets and personal data out

Audit logs are often kept longer and shared more widely than application data. Never write raw inputs, tokens, or personal data to them. Prefer hashes, which prove what was processed without revealing it, or redacted copies built from an allow-list of safe fields.

DataTreatment
API tokens, passwords, keysNever logged
Order IDs, SKUsAllowed if not personal
Customer names, emailsHash or drop
Full input payloadHash by default
Error messagesAllowed after scrubbing interpolated values

3.11 Tamper evidence

With hash_chain = true, each record includes the hash of the previous record. Removing or editing a line breaks the chain, so a verifier can detect it. This does not prevent tampering; it makes tampering visible. For stronger guarantees, ship records to append-only storage outside the host's control.

function verify_chain(lines: List[String]) -> Result[Int, String] {
    let prev = ""
    for i, line in lines.enumerate() {
        let r = json.parse(line)
        if r["prev_hash"] != prev {
            return Err("chain broken at line {i + 1}")
        }
        prev = r["hash"]
    }
    return Ok(lines.len())
}

3.12 Using audit data to tune limits

Once records accumulate, compute usage percentiles per function and set limits from evidence rather than guesswork.

let df = data.read_jsonl("audit/runs.jsonl")
let stats = df.filter(col("outcome") == "OK")
    .group_by(["module", "function"])
    .agg([col("usage.instructions").quantile(0.5).alias("p50"),
          col("usage.instructions").quantile(0.99).alias("p99"),
          col("usage.instructions").max().alias("max")])
print stats

A reasonable starting rule is to set the limit at two to four times the observed p99, then review monthly. Chapter 16 covers the DataFrame operations used here in depth.

3.13 Investigating an incident

3.14 Common mistakes

MistakeConsequenceFix
Treating limits as budgetsOne tenant can still exhaust shared capacityAdd windowed budgets per tenant
Logging raw inputsSecrets and personal data leak into long-lived logsHash or redact inputs
No correlation IDCannot link script and host logsPass one ID end to end
Raising limits after every failureHides regressionsCheck snapshots and versions first
Audit records without code versionCannot reproduce behaviorRecord package version and bytecode hash

Guided practice

Hands-on lab

Run order_rules.evaluate 1,000 times with synthetic orders of varying sizes, with audit records enabled. Compute p50, p99, and max instruction usage, propose new limits, then deliberately edit one audit line and show that verify_chain detects it.

Deliverable: the budget configuration, the audit file, a short usage table, and the chain-verification output before and after tampering.

Review questions

Applied challenge

Design a "fallback" budget policy: when a tenant's instruction budget runs out, requests are served by a precomputed default decision (reason NONE) and flagged in the audit log. Explain how you would stop this fallback from hiding real failures.

Lesson summary

Limits stop single runs; budgets share capacity fairly over time. Snapshots turn resource use into evidence, and audit records make each run explainable: who, what code, which authority, how much, and how it ended. Keep secrets out, chain records for tamper evidence, and tune limits from measured percentiles.

Transition to Lesson 4

You now have limits, budgets, and audit trails. Lesson 4 combines them with capabilities into a complete approach for running scripts you did not write and do not trust.

Lesson status: Ready for review.

← Previous Next →