What this is
What is safe deployment?
Safe deployment is how an AI agent, a program that lets an AI language model take real actions, is let onto real work one earned step at a time. First it runs in shadow, recording what it would have done while people keep doing the job. Then it proposes and a person approves. Then it acts alone, on low-risk actions only, and loses that trust on a single incident. Around those steps, each new version reaches a few users first, any action can be stopped, and every action goes into a log that shows any later edit.
Why it matters: You need it the day an agent's output stops being a draft and becomes a refund, an email or a changed record. Tests before release cover only the cases they hold, and real traffic brings cases they did not.
At a glance
Key takeaways
- Earn autonomy in steps: shadow mode, then a person approves each action, then autonomy for low-risk actions only; demote on any incident or drift.
- Treat prompts as code: name each version by a hash of its text, review and evaluate it before release, and keep the previous version one step away.
- Send a new version to a small canary share of users first, grow the share only while its success rate keeps up with the current version's, and roll back automatically when it doesn't.
- Bound the blast radius with kill switches, per tenant and global, and rate limits on actions.
- Keep a tamper-evident audit log (a hash chain) linking every action to its user and its trace.
How it works, from scratch
An agent that takes real actions (refunds, emails, changes to a company's records) does real damage when it gets one wrong. So before anything happens, every action it proposes passes the same gates, in the same order.
Figure 1 · Diagram
flowchart LR
P[Proposed action] --> K{Kill switch<br/>on?}
K -->|yes| X[Blocked]
K -->|no| R{Rate limit<br/>allows it?}
R -->|no| X
R -->|yes| A{Autonomy level<br/>and risk allow<br/>acting alone?}
A -->|no| H[Queue for<br/>human approval]
A -->|yes| E[Execute]
H -->|approved| E
E --> L[Append to<br/>audit log]
In code: the gates are KillSwitch.allowed, TokenBucket.allow and
AutonomyController.may_act_alone, and AuditLog.append records what runs. View source
Chapter 1
Graduated autonomy: from shadow mode to acting alone
The third gate is the one that takes judgement, and the agent earns its setting. A new pilot does not start in the captain's seat. First they sit beside the captain and call out every move they would make. Then they fly with the captain's hands near the controls. Then they fly routine legs alone while the captain still takes the storms, and after any incident the captain takes over again. Letting an agent onto real work in steps like these is called graduated autonomy.
In shadow mode the agent runs on real inputs and records what it would do, but takes no action. People keep doing the work, and you compare its decisions with theirs. When it agrees with them often enough, it proposes actions and a person approves each one. When nearly every proposal is approved, it may act alone on low-risk actions, while high-risk ones, such as large refunds or deletions, still go to a person. Any incident or drop in quality sends it back a level.
The shadow comparison says most when you break it down by action. Here are ten support tickets:
| Agent proposed | Human did | Agree? |
|---|---|---|
| refund | refund | yes |
| refund | escalate | no |
| reply ×5 | reply ×5 | yes ×5 |
| refund | refund | yes |
| refund | escalate | no |
| refund | refund | yes |
Overall agreement is 8/10 = 80%. Broken down by what the agent proposed, replies agree 5/5 = 100% but refunds only 3/5 = 60%. So the agent should be trusted with replies first, and refunds later.
The formula and its symbols
Symbols
| Symbol | Meaning here | Worked example |
|---|---|---|
| number of shadow decisions compared | 10 | |
| what the agent proposed for case | refund | |
| what the human actually did for case | escalate | |
| 1 if the condition is true, 0 if not (an indicator) | 0 for case 2 | |
| add up over all cases |
In words: agreement is the share of cases where the agent proposed what the human did.
On the worked example: eight of the ten indicators are 1, so agreement = 8/10 = 0.8.
In Python
a = ["refund", "refund"] + ["reply"] * 5 + ["refund", "refund", "refund"]
h = ["refund", "escalate"] + ["reply"] * 5 + ["refund", "escalate", "refund"]
# 𝟙[a_i = h_i]
indicators = [1 if a_i == h_i else 0 for a_i, h_i in zip(a, h)]
indicators # → [1, 0, 1, 1, 1, 1, 1, 1, 0, 1]
# (1/N) Σ over i
sum(indicators) / len(indicators) # → 0.8
New to Σ, ∂ or ‖x‖? The symbols reference decodes each one as a few lines of Python.
Figure 2 · Diagram
stateDiagram-v2 state "Shadow mode: record, don't act" as Shadow state "Human approves each action" as Approve state "Autonomous for low-risk actions" as Auto [*] --> Shadow Shadow --> Approve: agreement ≥ 95% over the last 50 decisions Approve --> Auto: ≥ 98% of the last 50 approved, no incidents Auto --> Approve: incident or quality drift Approve --> Shadow: incident
Figure 3 · Chart
Rolling agreement with humans must first clear the 95% bar over a full 50-decision window, and only then is the agent promoted
In code: shadow_agreement computes agreement overall and per action,
and AutonomyController is the state diagram. View source
Chapter 2
Versioned prompts
Once an agent has earned its autonomy, it keeps changing: someone edits its prompt, or the language model under it is replaced. A change to a prompt can break behaviour as badly as a change to code, so it gets the same treatment. It is versioned, reviewed and run through the evals before release (Evaluation), and the previous version stays one step away.
The version's name can come from the prompt itself. A hash (here
SHA-256) is a fixed-length fingerprint of a text: the same text always
gives the same fingerprint, and any change, even one character, gives a
completely different one. A prompt named by a hash of its own text is
content-addressed. "Be concise." hashes to ab018bdb…, so its version
is support@ab018bdb. Registering the same text again returns the same
version, and "Be concise and friendly." gets a new one. Every trace
records which version produced each model call (Observability),
so a change in behaviour can be tied to the prompt edit that caused it.
In code: PromptRegistry.register turns a prompt into a version and
makes it active, and PromptRegistry.rollback steps back one version. View source
Chapter 3
Canary releases
A new version that passes the evals has passed a fixed set of cases, and real users bring inputs that set never held. A canary release sends a small share of traffic to the new version, compares its success rate with the current version's (the control), and grows the share only while the new version keeps up. The name comes from the canaries miners once carried underground: when the air turned bad, the bird showed it before the miners were harmed.
Take a rollout that grows from 1% of traffic to 5%, 25%, 50% and 100%. The canary may fall at most 2 points below the control, and it is not judged until it has handled 100 tasks:
| Control success | Canary success | Canary tasks | Decision |
|---|---|---|---|
| 95% | 95% | 100 | advance from 1% to 5% |
| 95% | 90% | 100 | 90 < 95 − 2: roll back to 0% |
| 95% | 90% | 10 | too few samples: stay at 1% |
The formula and its symbols
Symbols
| Symbol | Meaning here | Worked example |
|---|---|---|
| measured success rate on canary traffic (the hat means "measured from samples") | 0.90 | |
| measured success rate on the current version | 0.95 | |
| the largest drop you'll tolerate (Greek delta) | 0.02 |
In words: roll back when the new version's success rate falls more than the allowed margin below the current version's.
On the worked example: 0.90 < 0.95 − 0.02 = 0.93, so roll back.
In Python
p_canary, p_control, delta = 0.90, 0.95, 0.02
round(p_control - delta, 2) # → 0.93
# roll back?
p_canary < p_control - delta # → True
Users are assigned to the canary by hashing their id into one of 100 buckets. A user always lands in the same bucket, so no one switches versions in the middle of a conversation, and growing from 5% to 25% only adds users. A feature flag works the same way for a single capability: a switch in configuration that turns it on for chosen customers or users without redeploying, and off again as fast.
Figure 4 · Diagram
sequenceDiagram participant D as Deploy system participant R as Router participant M as Metrics D->>R: send 1% of users to v2 R->>M: success rates, v1 vs v2 M-->>D: v2 95%, v1 95%: healthy D->>R: grow to 5% R->>M: success rates, v1 vs v2 M-->>D: v2 91%, v1 95%: worse by 4 points D->>R: roll back: 0% to v2 D-->>D: alert the owner with traces
Figure 5 · Chart
The good version tracks the control through 1, 5, 25, 50 and 100%; the bad one passes the 1% step by luck and is rolled back at 5%
In code: in_canary assigns users to buckets, CanaryController.step
applies the rollback rule, and simulate_rollout runs the two rollouts in
the chart. View source
Chapter 4
Kill switches and rate limits
A canary judges a new version by its average over many tasks. Once a version is live, something else has to stop it when it goes wrong all at once, say by sending the same email again and again. A kill switch stops the agent at once, for one tenant (one customer organisation) or for everyone. A rate limit caps actions per unit of time, so even a malfunctioning agent can send only so many emails, or change only so many records, per minute. Together they bound the blast radius: how much damage a failure can do before someone notices.
One way to build a rate limit is a token bucket. Picture a jar that holds at most 5 tokens and gains 1 token a second. Each action takes a token, and an action that finds the jar empty is refused. Starting full, a burst of 5 actions succeeds and the 6th is refused. After 2 seconds the jar holds 2 tokens again, so 2 more succeed and the next is refused.
The formula and its symbols
Symbols
| Symbol | Meaning here | Worked example |
|---|---|---|
| tokens in the bucket at time | 2 at t = 2 s | |
| when the bucket was last updated | 0 s | |
| tokens left then | 0 after the burst | |
| refill rate, tokens per second | 1 | |
| capacity: the largest burst allowed | 5 | |
| the smaller of the two: the jar can't overflow |
In words: the tokens now are what was left plus what has dripped in since, but never more than the jar holds.
On the worked example: min(5, 0 + 1 × (2 − 0)) = 2 tokens, so two more actions are allowed.
In Python
# capacity, tokens per second
C, r = 5, 1
def b(t, t_0, b_t0):
# what was left plus the drip, capped at C
return min(C, b_t0 + r * (t - t_0))
# 2 s after the burst emptied the jar
b(2, 0, 0) # → 2
# a long wait refills only to capacity
b(60, 0, 0) # → 5
Figure 6 · Chart
A burst of 8 requests gets 5 through before the bucket empties, then requests pass one per second at the refill rate
In code: KillSwitch holds the global and per-tenant switches, and
TokenBucket.allow spends a token or refuses. View source
Chapter 5
A tamper-evident audit log
Once the kill switch has been pulled, someone has to find out what the agent did. An audit log records which agent took which action, for which user, with what inputs. For regulated work it must be tamper-evident, so that no alteration goes unnoticed. A hash chain does this with the fingerprints that named the prompt versions: each entry stores the hash of the entry before it, and its own hash covers its contents together with that previous hash.
The formula and its symbols
(Entries are numbered from 1 here, but verification reports positions counted from 0, as Python lists are, so entry 2 is position 1.)
Symbols
| Symbol | Meaning here |
|---|---|
| the fingerprint (hash) stored with entry | |
| the previous entry's fingerprint | |
| the hash function: any input to a 64-hex-digit fingerprint | |
| "joined together with" (concatenation) | |
| a fixed starting value for the first entry |
In words: each entry's fingerprint is the fingerprint of the previous fingerprint joined to this entry's contents.
On the worked example: take three entries: refund A200 for 40, refund A201 for 15, escalate A300. Change entry 2's amount from 15 to 1,500, and recomputing its fingerprint no longer gives the stored , so verification reports position 1. Delete entry 2 instead, and entry 3 moves up to position 1. The previous fingerprint it stores is , the deleted entry's, which doesn't match , so the break is again reported at position 1.
In Python:
import hashlib
def seal(prev, entry):
# SHA256(h_{i-1} ‖ entry_i)
return hashlib.sha256((prev + entry).encode()).hexdigest()
# h_0
log, prev = [], "0" * 64
for entry in ["refund A200 40", "refund A201 15", "escalate A300"]:
prev = seal(prev, entry)
# each entry is stored with its h_i
log.append((entry, prev))
def verify(log):
prev = "0" * 64
for position, (entry, h_i) in enumerate(log):
if seal(prev, entry) != h_i:
# the first broken link
return position
prev = h_i
verify(log) is None # → True
# entry 2's amount changed
verify([log[0], ("refund A201 1500", log[1][1]), log[2]]) # → 1
# entry 2 deleted
verify([log[0], log[2]]) # → 1
Figure 7 · Diagram
flowchart LR G["h0 = 000…"] --> E1["entry 1: refund A200, 40<br/>prev = h0<br/>h1 = SHA256(h0 ‖ entry 1)"] E1 --> E2["entry 2: refund A201, 15<br/>prev = h1<br/>h2 = SHA256(h1 ‖ entry 2)"] E2 --> E3["entry 3: escalate A300<br/>prev = h2<br/>h3 = SHA256(h2 ‖ entry 3)"]
In production, the log also goes to storage that can't be modified afterwards (write-once storage), and each entry links to its full trace.
In code: AuditLog.append seals each new entry with the previous
entry's hash, and AuditLog.verify returns the position of the first
broken link, or None. View source
Chapter 6
Change management
Every control so far keeps a working agent safe. The agent still fails if the people whose work it touches don't trust it or don't use it. Involve them from shadow mode on, since their corrections are your best eval data. Design around the way they already work, show sources and confidence so they can check an answer, and make handing a case to a person one click.
Test yourself
4 questions
Answer each one out loud or on paper before you open it.
Question 1How would you roll out an agent that takes real actions in a company's ERP system (its finance and operations system of record)?Think it through, then reveal
Start read-only in shadow mode on real transactions, comparing proposals with what staff actually did, broken down by action type. Give the agent a dedicated service identity with the narrowest permissions, a sandbox or dry-run mode for writes, and idempotency keys so retries can't double-post. Move to proposing actions that a person approves in their existing workflow, starting with the low-value, reversible action types that scored best in shadow. Grant autonomy only for those, with value thresholds that still require approval, per-tenant kill switches, rate limits on writes, a canary rollout for every prompt or model change, eval gates in CI, and a tamper-evident audit log tied to traces. Demote automatically on incidents or drift, and keep the finance team involved throughout.
Question 2Why start in shadow mode instead of with human approval?Think it through, then reveal
Shadow mode costs the humans nothing extra and produces a clean comparison against what they actually did, at full volume, before the agent can influence anything. Approval mode adds review load and can bias reviewers toward accepting the agent's suggestion.
Question 3What does a canary protect against that offline evals don't?Think it through, then reveal
Real traffic: inputs, integrations and user behaviour the golden set didn't anticipate. Evals gate the release; the canary limits the damage from whatever the evals missed.
Question 4Why a hash chain rather than an ordinary log table?Think it through, then reveal
Anyone with write access can quietly edit an ordinary row. With a hash chain, any edit or deletion breaks every later link, so tampering is detectable, and anchoring the latest hash somewhere separate (or using write-once storage) makes it provable.
Primary sources
The papers behind this lesson
Haber & Stornetta, How to Time-Stamp a Digital Document (Journal of Cryptology, 1991), Introduced chaining each record to the hash of the one before, the idea behind tamper-evident logs (and, later, blockchains).
The paperResearcher's shelf
Further reading
- Google SRE workbook, canarying releases: https://sre.google/workbook/canarying-releases/
- Martin Fowler, feature toggles: https://martinfowler.com/articles/feature-toggles.html
- Token bucket algorithm: https://en.wikipedia.org/wiki/Token_bucket
- NIST AI Risk Management Framework: https://www.nist.gov/itl/ai-risk-management-framework
About this lesson. This lesson is built from the open-source AI Primer ↗. Its text, figures and numbers are generated from the Primer's source at commit f8b43d1, so the two always agree: the explanation, the code that builds it and the tests that prove it. Its hand-built interactive figures are still to come: the status page shows which lessons have them.