Invariants
Rules over the whole conversation, such as one charge per booking or no text without consent, enforced before each side effect.
Code blocks on this page are excerpts of tested programs; each block's title names its file in examples/, where the complete program runs.
A rule looks at one call. An invariant looks at what already ran: "at most one charge per booking", "no text
message before the customer consented", "never refund after the order was cancelled". Invariants live in the same
policy file, under invariants:, and use the invariant/v1 document that Viewport Evals asserts after a run, so a
rule you test in Evals is a rule the gate enforces in production.
# A booking agent may charge cards, record consent, send texts and refund. Three invariants hold across the whole
# conversation, whatever order the model calls tools in.
rules:
booking-tools: { allow: [charge_card, record_consent, send_sms, refund_booking] }
invariants:
- name: one charge per booking
each: { tool: charge_card }
limit: { max: 1, by: $.args.booking_id }
- name: no sms without consent
each: { tool: send_sms }
after: { tool: record_consent }
same: { $.args.customer_id: $.args.customer_id }
- name: every refund approved by a person
each: { tool: refund_booking }
after: { approval: { tool: refund_booking, status: approved } }
same: $.call_id # the approval must be for this very call
effect: ask # not yet approved: ask the default approver
The tools are ordinary gated tools. Adapters pass the framework's call id and thread; invariants are scoped to the thread by default.
gate = hitl.Gate(POLICY, channels=[desk], clock=FakeClock("2026-11-25T10:00:00Z"))
@gate
async def charge_card(booking_id: str, amount: float) -> str:
return f"Charged ${amount:g} for {booking_id}"
@gate
async def record_consent(customer_id: str) -> str:
return f"Consent recorded for {customer_id}"
@gate
async def send_sms(customer_id: str, text: str) -> str:
return f"Texted {customer_id}"
# Adapters pass the framework's call id and thread; invariants are scoped to the thread by default.
calls = count(1)
def turn() -> ToolContext:
thread = {"hitl": {"context": {"thread_id": "booking-chat-42"}}}
return ToolContext(call_id=f"call_{next(calls)}", attributes=thread)const gate = new Gate(POLICY, { channels: [desk], clock: new FakeClock("2026-11-25T10:00:00Z") });
const chargeCard = gate.tool({
name: "charge_card",
input_schema: {
type: "object",
properties: { booking_id: { type: "string" }, amount: { type: "number" } },
required: ["booking_id", "amount"],
},
execute: async ({ booking_id, amount }) => `Charged $${amount} for ${booking_id}`,
});
const recordConsent = gate.tool({
name: "record_consent",
input_schema: { type: "object", properties: { customer_id: { type: "string" } }, required: ["customer_id"] },
execute: async ({ customer_id }) => `Consent recorded for ${customer_id}`,
});
const sendSms = gate.tool({
name: "send_sms",
input_schema: {
type: "object",
properties: { customer_id: { type: "string" }, text: { type: "string" } },
required: ["customer_id", "text"],
},
execute: async ({ customer_id }) => `Texted ${customer_id}`,
});
// Adapters pass the framework's call id and thread; invariants are scoped to the thread by default.
let n = 0;
const turn = () => ({ callId: `call_${++n}`, attributes: { hitl: { context: { thread_id: "booking-chat-42" } } } });A text before consent is refused; after consent for that customer it runs; consent for one customer does not cover another:
early = await refusal(send_sms.tool.execute({"customer_id": "C-1", "text": "Your table is booked"}, turn()))
print(f"text before consent: {early.message}")
# text before consent: Invariant "no sms without consent" would be violated: no matching earlier event
await record_consent.tool.execute({"customer_id": "C-1"}, turn())
await send_sms.tool.execute({"customer_id": "C-1", "text": "Your table is booked"}, turn()) # now it runs
other = await refusal(send_sms.tool.execute({"customer_id": "C-2", "text": "Hi"}, turn())) # consent was for C-1const early = await refusal(sendSms({ customer_id: "C-1", text: "Your table is booked" }, turn()));
console.log(`text before consent: ${early.message}`);
// text before consent: Invariant "no sms without consent" would be violated: no matching earlier event
await recordConsent({ customer_id: "C-1" }, turn());
await sendSms({ customer_id: "C-1", text: "Your table is booked" }, turn()); // now it runs
const other = await refusal(sendSms({ customer_id: "C-2", text: "Hi" }, turn())); // consent was for C-1 onlyA second charge for the same booking is refused, even with a new call id:
await charge_card.tool.execute({"booking_id": "B-9", "amount": 120}, turn())
twice = await refusal(charge_card.tool.execute({"booking_id": "B-9", "amount": 120}, turn())) # a retry
await charge_card.tool.execute({"booking_id": "B-10", "amount": 80}, turn()) # another booking is fineawait chargeCard({ booking_id: "B-9", amount: 120 }, turn());
const twice = await refusal(chargeCard({ booking_id: "B-9", amount: 120 }, turn())); // a retry, a new call id
await chargeCard({ booking_id: "B-10", amount: 80 }, turn()); // another booking is fineDecisions name the invariant as invariant:<name>, in decision.rules, in explain() and on receipts.
Operators
| Key | Meaning |
|---|---|
each | Which actions the invariant applies to (a selector: tool, args, ...) |
never | Such an action is never allowed |
after | Allowed only after a matching earlier event |
not_after | Refused after a matching earlier event |
limit | { max, by?, per?, sum? }: at most max matching events (or a sum of a field) per by key, optionally within a per window |
same | Fields that must be equal between the action and the earlier event: a path, a list, or a map of action path to event path |
scope | thread (default), session, actor or tenant |
effect | deny (default) or ask: a person may let it through |
followed_by (something must happen afterwards) cannot be enforced before the fact: it is a load error in a gate
policy and an after-the-run assertion in Viewport Evals.
Correlating with approvals
An invariant can require an approval for the same call: after: { approval: { tool: send, status: approved } } with
same: $.call_id. Approval events are matched to the call by call_id, then by tool_call_id (the recorded tool
call the approval belongs to), then, for a call with no id, by order: the nearest earlier unmatched approval without
an id for that tool. An approval with an id never matches an id-less call by order. not_after uses the same rule.
The gate's own outcome for the call counts, so a policy allow or a consumed approval satisfies it. The third invariant in the policy above asks a person for every refund call; one
approval covers one call, and the next refund call is asked again:
# `same: $.call_id`: an approval covers exactly the call it was given for.
def refund(call_id: str) -> dict[str, Any]:
return {
"tool": "refund_booking",
"args": {"booking_id": "B-9"},
"call_id": call_id,
"context": {"thread_id": "booking-chat-42"},
}
first = await gate.authorize(refund("call_r1"), wait=False) # "pending": no approval for call_r1 yet
assert first.approval is not None
await gate.respond(first.approval.id, hitl.approve(by="desk:dana"))
ran = await gate.authorize(refund("call_r1"), wait=False) # "approved": the approval is for this call
await ran.succeeded()
second = await gate.authorize(refund("call_r2"), wait=False) # a second refund call
print(f"refund call_r1: {first.status}, then {ran.status}; refund call_r2: {second.status}")
# refund call_r1: pending, then approved; refund call_r2: pending// `same: $.call_id`: an approval covers exactly the call it was given for.
const refund = (callId: string) => ({
tool: "refund_booking",
args: { booking_id: "B-9" },
call_id: callId,
context: { thread_id: "booking-chat-42" },
});
const first = await gate.authorize(refund("call_r1"), { wait: false }); // "pending": no approval for call_r1 yet
await gate.respond(first.approval?.id as string, approve({ by: "desk:dana" }));
const ran = await gate.authorize(refund("call_r1"), { wait: false }); // "approved": the approval is for this call
await ran.succeeded();
const second = await gate.authorize(refund("call_r2"), { wait: false }); // a second refund call
console.log(`refund call_r1: ${first.status}, then ${ran.status}; refund call_r2: ${second.status}`);
// refund call_r1: pending, then approved; refund call_r2: pendingFails closed
An invariant denies when its scope key is missing (no thread id), when a same or by path resolves to nothing,
when a sum is not a number, or when history cannot be read. Limit invariants count through the same atomic
reservations as rule limits, so concurrent calls cannot overshoot.
History
after and not_after read a per-scope history the gate keeps in its store. It records only the argument paths
some invariant references, and is bounded: 10,000 events per scope by default, with optional retention. Set this
with the gate's invariants option (InvariantOptions(max_entries=..., retention="30d") in Python,
{ maxEntries, retention } in TypeScript). The gate's own allowed calls and consumed approvals count as events, so
an invariant over approvals sees the same facts Evals sees in a trajectory.
When a call is consumed, the gate first writes its history entry as pending (write-ahead), and settling finalizes
it in place. A pending entry counts for not_after (the effect may have happened) and never satisfies after (it
may not have), so an outage between the effect and its settle stays on the safe side without any repair. A pending
entry stays until its execution settles. If one never will (the process died for good, or the execution record was
never written), an operator who knows the effect did not happen can call
clear_pending_history(execution_key, by=...) / clearPendingHistory(executionKey, { by }) (pass scopes for an
orphan): it finalizes the entries as ok: false, abandoned: true and records an operator_action receipt.
Recording history never changes an outcome that already happened, so a failed write is retried in the background.
If it still fails, the gate reports hitl.history_lost and marks the scope tainted (in the process at once, and in the
store when it supports it, retrying until the store accepts it): after, not_after and limit invariants in that scope then deny with
hitl.history_unavailable, because the missing event could have been the one they look for. An operator clears it
with clear_history_taint(scope, by=...) / clearHistoryTaint(scope, { by }), which is recorded as an
operator_action receipt.