Certified plans
A learned guard gives estimates. Sometimes you need more: a proof, with high probability, that the risk of harm stays below a limit. You can get one when your environment can be reset and sampled, such as a simulator or a sandbox. The tools for this are in causalrepair.certify.
The idea in plain words
- A plan is a first action plus a rule for what to do next. For example: “check the payment status; then retry with a key only if no charge is found”.
- The risk of a plan is the chance of harm if the guard makes that first action now and the agent then follows the plan.
- You reset the environment many times, force each action, and record what happens next. These records are the evidence.
- From the evidence, the library computes a lower and an upper bound on the risk of every plan. With probability at least
1 - beta(betais 0.05 by default, so 0.95), all bounds are right at the same time. So they stay right after the guard has used them to pick a plan.
Each plan gets a verdict:
| verdict | meaning |
|---|---|
certified | the upper bound is within the limit: the plan is proven safe enough |
exceeds_limit | the lower bound is above the limit: the plan is proven too risky |
unresolved | the data cannot tell yet; more draws may help |
policy_rejected | the policy does not allow the plan |
The guard picks the closest certified plan: the certified plan with the smallest distance from what the agent asked for.
A full example
A payment timed out. The first attempt went through with chance 0.3. A retry with an idempotency key (a key that lets the gateway spot a repeat) is honoured with chance 0.6, and a status check is right with chance 0.8. Harm means a double charge. The limit is 0.05.
1. Describe the environment. List the states and actions, the horizon (the number of steps), the possible next states of each step, and which final states are harmful. The guard does not know the chances. step holds them only so that sample can draw from them, as a real simulator would.
import numpy as np
from causalrepair.certify import BudgetPlanner, Evidence, FiniteModel, Plan, certify
P_APPLIED, P_KEY, P_CHECK = 0.3, 0.6, 0.8
states = ["timed_out", "check_says_charged", "check_says_clear", "done", "charged_twice"]
actions = ["retry", "keyed_retry", "check_status", "stop"]
def step(t, s, a):
"""The true chances of each next state (hidden from the guard; it only sees draws)."""
if s == "timed_out" and a == "retry":
return {"charged_twice": P_APPLIED, "done": 1 - P_APPLIED}
if s == "timed_out" and a == "keyed_retry":
p = P_APPLIED * (1 - P_KEY)
return {"charged_twice": p, "done": 1 - p}
if s == "timed_out" and a == "check_status":
return {"check_says_charged": P_APPLIED * P_CHECK, "check_says_clear": 1 - P_APPLIED * P_CHECK}
if s == "check_says_clear" and a == "keyed_retry":
miss = P_APPLIED * (1 - P_CHECK) / (1 - P_APPLIED * P_CHECK) # the check said "clear" by mistake
return {"charged_twice": miss * (1 - P_KEY), "done": 1 - miss * (1 - P_KEY)}
return {s: 1.0} if s in ("done", "charged_twice") else {"done": 1.0}
def sample(t, s, a, rng):
"""One draw: reset the simulator to state s, force action a, and return the next state."""
d = step(t, s, a)
return list(d)[rng.choice(len(d), p=list(d.values()))]
model = FiniteModel(states, actions, horizon=2, successors=lambda t, s, a: list(step(t, s, a)),
harm=lambda s: float(s == "charged_twice"))
2. List the plans. Each plan has a name, a first action, a rule then(t, state) for later steps, a distance, and whether the policy allows it (eligible).
plans = [
Plan("retry", "retry", lambda t, s: "stop", distance=0.0, eligible=False), # the policy forbids a retry with no key
Plan("keyed retry", "keyed_retry", lambda t, s: "stop", distance=0.5),
Plan("check, then keyed retry if clear", "check_status",
lambda t, s: "keyed_retry" if s == "check_says_clear" else "stop", distance=1.0),
Plan("escalate", "stop", lambda t, s: "stop", distance=2.0),
]
3. Collect evidence and certify. We try three amounts of data:
for n in (300, 3000, 30000):
ev = Evidence.collect(model, sample, n=n, rng=np.random.default_rng(n), beta=0.05)
cert = certify(ev, plans, t=0, state="timed_out", limit=0.05)
print(f"\n{n} draws per input (beta = {ev.beta}):")
for name in cert.order:
b = cert.bounds[name]
print(f" {name:34s} risk in [{b.lower:.3f}, {b.upper:.3f}] {cert.statuses[name].value}")
print(f" -> selected: {cert.selected} proven closest within the limit: {cert.true_minimum}")
It prints:
300 draws per input (beta = 0.05):
retry risk in [0.212, 0.386] policy_rejected
keyed retry risk in [0.095, 0.235] exceeds_limit
check, then keyed retry if clear risk in [0.007, 0.073] unresolved
escalate risk in [0.000, 0.000] certified
-> selected: escalate proven closest within the limit: False
3000 draws per input (beta = 0.05):
retry risk in [0.263, 0.318] policy_rejected
keyed retry risk in [0.102, 0.142] exceeds_limit
check, then keyed retry if clear risk in [0.017, 0.036] certified
escalate risk in [0.000, 0.000] certified
-> selected: check, then keyed retry if clear proven closest within the limit: True
30000 draws per input (beta = 0.05):
retry risk in [0.288, 0.306] policy_rejected
keyed retry risk in [0.112, 0.124] exceeds_limit
check, then keyed retry if clear risk in [0.021, 0.027] certified
escalate risk in [0.000, 0.000] certified
-> selected: check, then keyed retry if clear proven closest within the limit: True
How to read it:
- The keyed retry is the nearest allowed fix, but it is proven too risky at every data size (its true risk is 0.12).
- With 300 draws, the check-first plan is not yet proven safe, so the guard escalates. This is the safe choice.
- With 3,000 draws, the check-first plan is certified (its true risk is 0.024) and it is picked.
true_minimumisTruewhen every closer plan is proven too risky or not allowed. Then no closer plan could have been within the limit.
The result is a Certificate. Its fields: selected (the plan’s name, or None), statuses, bounds (each with lower, upper and supported), true_minimum, limit, beta, reason, and order (the plans by distance).
If no plan is certified, selected is None. This does not mean that doing nothing is safe. Decide in advance what your system does then, for example hand over to a person.
Keep the promise while the agent runs
A plan is only safe if it is followed. There are two ways to make sure:
- Commit to the plan. Once the guard picks a plan, enforce its later steps too, not just the first one.
- Pass a risk budget down.
BudgetPlannerlets the agent choose its next actions freely, as long as each one keeps the risk within a budget.
ev = Evidence.collect(model, sample, n=3000, rng=np.random.default_rng(3000), beta=0.05)
planner = BudgetPlanner(ev, allowed=lambda t, s, a: a != "retry") # the policy's hard check
print(planner.admissible(0, "timed_out", budget=0.05)) # actions that fit a budget of 0.05
print(planner.admissible(0, "timed_out", budget=0.15))
budgets = planner.split(0, "timed_out", "check_status", budget=0.05) # budgets for the next states
print({state: round(b, 3) for state, b in budgets.items()})
It prints:
['check_status', 'stop']
['keyed_retry', 'check_status', 'stop']
{'check_says_charged': 0.05, 'check_says_clear': 0.05}
At each step, take only an action from admissible(t, state, budget). After it, call split(...) before you see the next state, and carry that state’s budget forward. When the evidence holds, an episode that starts with budget r has a chance of harm of at most r. min_budget(t, state) is the smallest budget that can work in a state.
What you must check yourself
The proofs hold only if these are true. The code cannot check them for you:
- each draw is independent, and comes from forcing that action in that state;
- the state holds everything that matters for what happens next;
- the environment at deployment behaves like the one you sampled;
- every call goes through the guard.
More tools
| function | what it does |
|---|---|
Evidence.from_draws(model, draws) | build evidence from draws you already have: draws[(t, state, action)] is a list of next states |
Evidence.collect(..., method="hoeffding") | use Hoeffding bounds in place of the default Clopper-Pearson bounds |
ev.interval(t, state, action) | the bounds on each next state’s chance |
plan_bounds(ev, plan, t, state) | the risk bounds of one plan |
policy_ok(model, plan, t, state, allowed) | True if every action the plan can take, on every branch, passes allowed |