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:
- Tell the difference between a per-run limit and a shared resource budget.
- Design budgets per tenant, per rule set, and per time window.
- Capture and read resource usage snapshots before, during, and after a run.
- Write structured audit records that are complete, tamper-evident, and free of secrets.
- Use snapshots and audit data to tune limits and investigate incidents.
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.
| Concept | Scope | Typical response when exceeded |
|---|---|---|
| Limit | One run | Stop the run with a resource error |
| Budget | Many runs over a window | Reject or queue new runs, or degrade to a fallback |
| Quota | Contractual allowance per tenant | Bill, alert, or refuse further work |
| Snapshot | Point-in-time usage reading | No 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.
| Dimension | Measures | Good for |
|---|---|---|
| instructions | Executed VM instructions | CPU fairness, independent of machine speed |
| cpu_ms | Measured CPU time | Cost attribution |
| wall_ms | Elapsed time | Latency targets |
| peak_memory_bytes | Highest allocation | Capacity planning |
| http_calls / http_bytes | Network use | Partner rate limits and egress cost |
| output_bytes | Printed or returned output | Log and storage cost |
| runs | Number of executions | Simple 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
fn 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
fn 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 field | Meaning |
|---|---|
| instructions | Instructions executed so far |
| wall_ms | Elapsed time since run start |
| heap_bytes / peak_memory_bytes | Current and highest memory |
| stack_depth / max_stack_depth | Current and deepest call depth |
| output_bytes | Bytes written to output |
| http_calls | HTTP requests made |
| file_reads | File reads performed |
| limits | The 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.
fn 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.
fn 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.
| Question | Field |
|---|---|
| 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.
| Data | Treatment |
|---|---|
| API tokens, passwords, keys | Never logged |
| Order IDs, SKUs | Allowed if not personal |
| Customer names, emails | Hash or drop |
| Full input payload | Hash by default |
| Error messages | Allowed 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.
fn 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
- Find the failing requests by correlation_id or outcome.
- Compare package version and bytecode hash with a known-good run.
- Check whether the policy version changed.
- Compare usage snapshots: a jump in instructions with the same input size suggests a code change; a jump with larger inputs suggests a data change.
- Verify the hash chain for the time window before trusting the records.
3.14 Common mistakes
| Mistake | Consequence | Fix |
|---|---|---|
| Treating limits as budgets | One tenant can still exhaust shared capacity | Add windowed budgets per tenant |
| Logging raw inputs | Secrets and personal data leak into long-lived logs | Hash or redact inputs |
| No correlation ID | Cannot link script and host logs | Pass one ID end to end |
| Raising limits after every failure | Hides regressions | Check snapshots and versions first |
| Audit records without code version | Cannot reproduce behavior | Record package version and bytecode hash |
Guided practice
- Write a [budgets] section for two tenant tiers with a 60-second window.
- Add start and end snapshots to a batch function and log the difference.
- Write the headroom function and flag any dimension under 30 percent.
- Enable audit records with hashed inputs and inspect three records.
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
- How does a budget differ from a limit?
- Why check remaining budget against the per-run limit at admission?
- Which audit fields let you reproduce a run's behavior?
- What does a hash chain prove, and what does it not prove?
- Why is cooperative stopping not a replacement for hard limits?
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.