Write invariants
Declare the rules your service's state must always obey, check them after every step live and in replay, and prove each one catches a real bug.
An invariant is a named check of the handler's state that must hold after every step that succeeds. Kavach runs invariants live, while recording, and again during replay. A step that leaves state broken is recorded as a failure, and a fixture is written, even if nothing crashed.
Invariants turn silent corruption (a balance off by one, a job in two states) into an incident you can replay.
What makes a good invariant#
Look for properties of the domain, not of the code:
| Kind | Example |
|---|---|
| Conservation | The sum of balances equals deposits minus withdrawals. Reserved plus available stock equals total stock. |
| Bounds | Balances, capacities, reference counts and TTLs never go negative or past a ceiling. |
| Consistency | Every entry in a secondary index exists in the primary store with matching fields. Expired keys are never returned as live. |
| Monotonicity | Terminal states (cancelled, settled) never become active again. Sequence numbers and epochs never go backwards. |
| Idempotency | Redelivering a processed message never applies it twice. |
Avoid:
- Tautologies that recompute the line the handler just ran. They pass whenever the code runs, right or wrong.
- Side effects. An invariant must not do I/O or read the clock or randomness.
Declare them#
func (l *Ledger) Invariants() []kavach.Invariant {
return []kavach.Invariant{
{Name: "balances_non_negative", Check: func() error {
for a, b := range l.Balances {
if b < 0 {
return fmt.Errorf("account %s has balance %d", a, b)
}
}
return nil
}},
{Name: "money_conserved", Check: func() error {
var sum int64
for _, b := range l.Balances {
sum += b
}
if sum != l.Net {
return fmt.Errorf("balances sum to %d, net is %d", sum, l.Net)
}
return nil
}},
}
}from kavach import Invariant
class Wallet:
def invariants(self) -> list[Invariant]:
return [
Invariant("balances_non_negative",
lambda: all(b >= 0 for b in self.balances.values())),
Invariant("money_conserved",
lambda: sum(self.balances.values()) == self.net),
]const handler: Handler = {
async handle(env, input) { /* ... */ },
invariants() {
return [
{ name: "balances_non_negative", check() {
for (const [a, b] of balances) if (b < 0) throw new Error(`account ${a} has balance ${b}`);
} },
{ name: "money_conserved", check() {
const sum = [...balances.values()].reduce((x, y) => x + y, 0);
if (sum !== net) throw new Error(`balances sum to ${sum}, net is ${net}`);
} },
];
},
};Make failure messages print the offending values: they appear in the fixture and in the verdict. Invariants run in declaration order; the first that fails fails the step, as invariant_violated(name)@N.
Prove each one catches a bug#
An invariant that passes on a happy trace proves only that nothing crashed. To know it would notice broken state, falsify it: inject a one-line bug it should catch, and check that Kavach reports it.
For each invariant:
-
Plan a one-line mutant that breaks the property: skip the sufficient-funds check on
withdraw, skip the sender debit ontransfer. -
Build the mutant to
/tmp/mutant-X, then revert the working tree. -
Replay a recorded journal against it:
kavach diff journal.kavach --old /tmp/baseline --new /tmp/mutant-X --json -
Killed (
invariant_violated(X)@N, orvariant_failed(K)@NnamingX): the invariant works. Survived (okorfixed): the check is too weak, or the journal never reaches that transition. Strengthen the check or record an input that reaches it, and try again.
On the demo ledger, both invariants are killed by their mutants: skipping the overdraft guard gives invariant_violated(balances_non_negative)@19, and skipping the transfer debit gives invariant_violated(money_conserved)@9. Each replay takes microseconds, so a full sweep runs in well under a second.
Let an agent do it#
The /kavach-invariants skill proposes invariants and their planned mutants in .kavach/plan/invariants.md for you to review before it changes code, then declares them and runs the mutation sweep, recording which mutant each invariant killed.
Something wrong or missing on this page? Report it on GitHub, or write to hello@thekavachlabs.com.