Secrets, Sandboxes, and Safe Execution › Worked Example: A Capability Budget in Practice
Language AI HandbookAll chapters Consider a synthetic catalog task with one authorized document view, a scratch allowance, and a separate result collector. The worker may open the catalogue's authorized input, record a temporary draft, or propose other operation labels. Admitting a proposal in this notebook changes only an integer counter. No label performs a read, a write, or a release. The collector separately decides whether an invented result could leave after a policy check. Both are in the same notebook to make the distinction observable.
We'll look at three kinds of admission failures: a label absent from the declared scope, a resource outside the permitted set for a listed operation, and a measured budget with no unit left. The distinction matters operationally. Repeated exhaustion can be a sign of a workload that needs fewer calls, more resources, or a tighter limit. An out-of-scope proposal raises a policy question. A denied resource may reflect a request bound to a stale or invalid document selection. The user-facing message can be short. Trusted telemetry can keep these outcomes separate without copying the proposed data into a log.
Setting up the manifest and the scorer
Represent both operation and resource with finite labels. Two of the operations are listed, each with its own resource and starting budget. A candidate request carries both fields. The fixture uses immutable rule records. The per-task count is separate mutable state, initialized before processing the first proposal. This separation lets us compare a declared rule with the remaining budget after a run and start a fresh deterministic replay without changing the declared limits.
In a production API, validation of incoming types, reference aliases, and resource identities would occur before evaluation. The operation and resource labels here are actual in-process enum values. Human-readable labels in an API cannot by themselves establish a trusted identity for a record. A workload policy can use opaque resource identifiers from its known registry. The service must independently check the binding to the workload, task, and current permissions.
PythonIn [7]Expand
from dataclasses import dataclass
from enum import Enum
class Operation(Enum):
READ_INPUT = "Read input"
SAVE_SCRATCH = "Save scratch"
RELEASE_RESULT = "Release result"
class Resource(Enum):
OWN_INPUT = "Task input"
OTHER_INPUT = "Other task input"
OWN_SCRATCH = "Task scratch"
OTHER_SCRATCH = "Other task scratch"
HELD_RESULT = "Held result"
class Decision(Enum):
ALLOWED = "Admitted"
OUTSIDE_SCOPE = "Outside operation scope"
RESOURCE_DENIED = "Resource denied"
EXHAUSTED = "Quota exhausted"
@dataclass(frozen=True)
class Rule:
resources: frozenset[Resource]
max_calls: int
@dataclass(frozen=True)
class Proposal:
operation: Operation
resource: Resource
read_rule = Rule(frozenset({Resource.OWN_INPUT}), 2)
scratch_rule = Rule(frozenset({Resource.OWN_SCRATCH}), 1)
rules = {
Operation.READ_INPUT: read_rule,
Operation.SAVE_SCRATCH: scratch_rule,
}A rule with an empty resource set grants no resource for its operation. A rule with a zero budget admits no call even to a resource it lists. These two situations are kept distinct in the scoring order. Read and scratch rules in this fixture have positive budgets and one resource each. Their numbers are declared demonstration inputs. They do not describe a recommended production ratio. Workload measurements, data ownership, and the behavior of the component that actually performs work determine an appropriate limit.
When preparing a production quota, decide whether retries consume a unit and what else counts as progress. A quota charged when a request is admitted cannot serve as a count of successful effects. A quota charged only after successful completion does not limit the total number of failed attempts without another guard. This distinction is why the printed output uses the word “admitted.” The local fixture has no effects, remote service, timeout, or completion record to inspect. In this fixture each admission charges one unit at the moment of the decision. The trace shows exactly what was charged.
The scorer
The check order first looks for a rule, then considers resource scope, then checks remaining quota. An absent operation cannot create a budget. A resource denied by an otherwise listed rule does not count as an admission and leaves the remaining amount alone. A request may be rejected at the resource check even if quota would also fail if reached. A recorded reason tells you which guard stopped the request in this decision procedure. It does not prove that no other control would also have refused the request. This distinction helps operators avoid drawing too much from one reported code.
PythonIn [8]Expand
def simulate_admission(
proposals: list[Proposal], policy: dict[Operation, Rule]
) -> tuple[list[tuple[Proposal, Decision]], dict[Operation, int]]:
remaining = {kind: rule.max_calls for kind, rule in policy.items()}
if any(
type(amount) is not int or amount < 0 for amount in remaining.values()
):
raise ValueError("Quotas must be nonnegative integers.")
events = []
for request in proposals:
rule = policy.get(request.operation)
if rule is None:
decision = Decision.OUTSIDE_SCOPE
elif request.resource not in rule.resources:
decision = Decision.RESOURCE_DENIED
elif remaining[request.operation] == 0:
decision = Decision.EXHAUSTED
else:
remaining[request.operation] -= 1
decision = Decision.ALLOWED
events.append((request, decision))
return events, remainingThe remaining counters are local to each call to the simulator. Sharing a quota across callers requires the component running admission to control the check and debit together. In a distributed system that might mean a transaction or another coordinator that provides the required semantics. Merely reading and updating an integer in two separate calls does not establish that two workers could not both obtain the last unit. In this simulator the loop has one thread of control, so processing the list in another order can change which eligible request gets a scarce unit, but it cannot make the simulator grant more units to that operation than the rule declared.
The rejection path consumes no allowed-call budget. There can still be operational costs to receiving and checking a refused proposal. A system may enforce limits on total requests and require a bounded response even when no operation is admitted. Keep these counters separately, especially when interpreting incident data. A chart of remaining quota does not answer how many people were affected or how much CPU the guard performed. An audit trail can carry aggregate counts of both refused and admitted requests without retaining raw proposals.
Running an invented action sequence
The eight requests below exercise both operation grants, two resource refusals, two exhausted cases, and a request for an operation missing from the worker's policy. The separate result gate can consider a release later. Its policy is neither called nor changed by this simulator. A test that tried only the allowed sequence would not tell us whether this distinction is implemented.
PythonIn [9]Expand
sample_requests = [
Proposal(Operation.READ_INPUT, Resource.OWN_INPUT),
Proposal(Operation.READ_INPUT, Resource.OTHER_INPUT),
Proposal(Operation.SAVE_SCRATCH, Resource.OWN_SCRATCH),
Proposal(Operation.READ_INPUT, Resource.OWN_INPUT),
Proposal(Operation.READ_INPUT, Resource.OWN_INPUT),
Proposal(Operation.SAVE_SCRATCH, Resource.OTHER_SCRATCH),
Proposal(Operation.SAVE_SCRATCH, Resource.OWN_SCRATCH),
Proposal(Operation.RELEASE_RESULT, Resource.HELD_RESULT),
]
sample_events, remaining = simulate_admission(sample_requests, rules)
expected = [
Decision.ALLOWED,
Decision.RESOURCE_DENIED,
Decision.ALLOWED,
Decision.ALLOWED,
Decision.EXHAUSTED,
Decision.RESOURCE_DENIED,
Decision.EXHAUSTED,
Decision.OUTSIDE_SCOPE,
]
assert [status for _, status in sample_events] == expected
assert remaining == {Operation.READ_INPUT: 0, Operation.SAVE_SCRATCH: 0}
assert rules[Operation.READ_INPUT].max_calls == 2ConsoleOut [10]Expand
1 Read input: Admitted
2 Read input: Resource denied
3 Save scratch: Admitted
4 Read input: Admitted
5 Read input: Quota exhausted
6 Save scratch: Resource denied
7 Save scratch: Quota exhausted
8 Release result: Outside operation scope
{'Admitted': 3, 'Outside operation scope': 1, 'Resource denied': 2, 'Quota exhausted': 2}The read budget is consumed in requests 1 and 4. Request 2 does not decrement it even though it comes between the two valid reads. The scratch unit is consumed by request 3. Request 6 is denied at the resource guard before checking the exhausted scratch quota, and request 7 fails at the quota guard. The release proposal never receives a worker grant. The aggregate counts are three admissions, two resource refusals, two exhaustion refusals and one operation-scope refusal. None of the requests releases data.
Change only the read quota to three and replay the same sequence. The fifth proposal can now be admitted. The resource refusal continues to have the same consequence, and the request carrying the release label remains outside the scope of the worker. The scratch outcomes remain identical. The change creates one additional admission under a preexisting resource grant; it does not make the other input reachable. These controls can change independently in a production policy, which is why a policy comparison should report effects by layer rather than simply saying that one configuration allows more work.
PythonIn [11]Expand
relaxed_read_rules = {
**rules,
Operation.READ_INPUT: Rule(read_rule.resources, 3),
}
relaxed_events, relaxed_remaining = simulate_admission(
sample_requests, relaxed_read_rules
)
changed_decisions = [
number
for number, (base, alternate) in enumerate(
zip(sample_events, relaxed_events, strict=True), 1
)
if base[1] is not alternate[1]
]
assert changed_decisions == [5]
assert relaxed_events[4][1] is Decision.ALLOWED
assert relaxed_remaining[Operation.READ_INPUT] == 0This replay illustrates one selected sensitivity, not a broad policy equivalence. An application with more operations or dynamic policy lookup has more cases to test. An empty resource grant refuses the record at the resource check. A listed resource with zero budget reaches the exhausted decision. Include both conditions in tests. Test repeated evaluation under a reused input list and verify the declaration was not mutated. Check whether the same short diagnostic appears for several codes when seen by an unauthorized caller. A separate evidence report can preserve the distinguishing codes for an operator. The goal is repeatable comparison under controlled inputs with minimal exposure of policy internals to general clients.
PythonIn [12]Expand
original_attempts = [event[1] is Decision.ALLOWED for event in sample_events]
relaxed_attempts = [event[1] is Decision.ALLOWED for event in relaxed_events]
def cumulative_admitted(flags: list[bool]) -> list[int]:
counts = [0]
for admitted in flags:
counts.append(counts[-1] + int(admitted))
return counts
base_curve = cumulative_admitted(original_attempts)
alternate_curve = cumulative_admitted(relaxed_attempts)
assert base_curve[-1] == 3
assert alternate_curve[-1] == 4VisualizationOut [13]Expand

The two step curves summarize admissions up to a position. They do not classify the refusal reasons separately. The gap begins at proposal 5, the only changed decision, and persists because the earlier additional admission remains in the cumulative sum. Both curves plateau, but a flat segment could reflect a resource or operation rule as well as exhaustion. Read the individual trace to distinguish those causes. A different order of the same proposals could leave the same final tally with a different admission position.
Reading the example back into the architecture
Now consider a separately stored candidate produced for one task. A collector receives its trusted metadata and independently checks both shape and recipient eligibility before delivery. This next fixture returns a disposition. It neither creates a file nor sends a message. The worker rule list is untouched. The collector's structure check simply represents the result of a prior, independently declared validation. In practice, the producer's proof of origin is carried through the trusted runtime. The collector should not accept caller-supplied strings as trusted metadata.
PythonIn [14]Expand
class ReleaseDecision(Enum):
HELD_FOR_FORMAT = "Invalid format"
HELD_FOR_ORIGIN = "Wrong task binding"
HELD_FOR_ACCESS = "Recipient not allowed"
ELIGIBLE = "Eligible for release"
@dataclass(frozen=True)
class HeldResult:
task_id: str
shape_valid: bool
def inspect_release(
result: HeldResult, *, expected_task: str, recipient_allowed: bool
) -> ReleaseDecision:
if not result.shape_valid:
return ReleaseDecision.HELD_FOR_FORMAT
if result.task_id != expected_task:
return ReleaseDecision.HELD_FOR_ORIGIN
if not recipient_allowed:
return ReleaseDecision.HELD_FOR_ACCESS
return ReleaseDecision.ELIGIBLE
safe_candidate = HeldResult("catalog-task-a", True)
release_rows = [
inspect_release(
HeldResult("catalog-task-a", False),
expected_task="catalog-task-a",
recipient_allowed=True,
),
inspect_release(
HeldResult("catalog-task-b", True),
expected_task="catalog-task-a",
recipient_allowed=True,
),
inspect_release(
safe_candidate, expected_task="catalog-task-a", recipient_allowed=False
),
inspect_release(
safe_candidate, expected_task="catalog-task-a", recipient_allowed=True
),
]
assert release_rows == list(ReleaseDecision)The first two guards return before the collector consults the supplied recipient verdict. Case 3 holds a valid, correctly bound result because the recipient is not eligible. Case 4 returns eligibility for the same candidate with a permitted recipient. A second delivery check at the actual boundary can observe a new revocation. The fixture does not implement a storage service, a time window, actual identity verification, a delivery event or the consumer's interpretation of the fields. These limitations let the experiment concentrate on the independence of admission and release. The code describes eligibility, which is distinct from successful delivery by a subsequent component.
In a real trace, a worker could finish and its output could be held while an access review completes. That is an ordinary operating condition. Expose a meaningful state to the appropriate user, such as “result under review,” and give the assigned owner a reference to the artifact rather than putting sensitive details in a notification. When review ends, check the audience again and record the final disposition and the policy version. An operator can use the retained trace to distinguish production latency from time spent awaiting a policy decision.
Test changes independently. Start with the eligible synthetic recipient and change only its eligibility. Verify the input-view permission and worker counts do not change. Then change the worker's operation limits while leaving the collector decision unchanged. This pair of tests can identify accidental coupling between the policies. It does not replace checking integration paths that handle end-to-end cancellation, timeout, or resource cleanup. Keep those separate cases and version the assumptions under which you ran them.
Comments
Add to the conversation
A question, a correction, or an example from your own work.
No comments yet. Be the first to share your thoughts!