Kavach Invariants
ASecurityFind the rules a stateful service must always obey (sink delivery semantics, causal effect ordering, Kafka offset safety, at-least-once payload consistency, scoped at-most-once side effects on retry, no silent output drops, balances never negative, money neither created nor destroyed), declare them in `.kavach/invariants.yaml` (zero boilerplate) or in code (`kv.Invariant` / `kv.invariant`), and mutation-test each invariant in milliseconds so it provably catches corrupted state. Use when the u...
- 3 stars
- 0 votes
- 0 copies
- 2 views
- Added November 15, 2026
Works with
Security analysis
100/100Pro scans all 2 files and shows the line behind each finding
npx -y skills add kavachlabs/kavach --skill kavach-invariants --agent claude-codeAre you the author of Kavach Invariants?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/kavachlabs-kavach-invariants)---
name: kavach-invariants
description: >
Find the rules a stateful service must always obey (sink delivery semantics,
causal effect ordering, Kafka offset safety, at-least-once payload consistency,
scoped at-most-once side effects on retry, no silent output drops, balances
never negative, money neither created nor destroyed), declare them in
`.kavach/invariants.yaml` (zero boilerplate) or in code (`kv.Invariant` /
`kv.invariant`), and mutation-test each invariant in milliseconds so it
provably catches corrupted state. Use when the user asks what could go wrong
in a ledger, payment flow, billing pipeline, queue consumer, or state machine,
wants invariants or property checks, or is about to write a Kavach contract.
Reads `.kavach/invariants.yaml` and `.kavach/plan/state-map.md` from
`kavach-setup` when they exist.
compatibility: Requires the `kavach` CLI on PATH.
metadata:
version: "0.6.0"
---
# Discover, Declare, and Mutation-Test Invariants (`kavach-invariants`)
The hardest part of deterministic verification is staring at a service and asking: *"What invariants must hold?"* And even after writing one, seeing it pass on a happy-path trace only proves nothing crashed—not that the invariant catches real bugs.
Kavach solves both problems:
1. **Declarative `.kavach/invariants.yaml` (Zero-Boilerplate Default):** Declare downstream `sinks:` delivery semantics and enforce production guarantees (`causal_order`, `offset_safety`, `at_least_once_emit`, `at_most_once_emit`, `anti_lobotomy`, `non_negative`, `conservation`) purely in YAML—zero handler code changes, evaluated automatically by `kavach replay`, `kavach diff`, `kavach explore`, `kavach-go`, and `@kavachlabs/core`.
2. **Code Invariants (When Needed):** Register custom Go (`kv.Invariant`), TypeScript (`kv.invariant`), or Mode-2 handler invariants for internal state-structure checks not visible in emitted payloads.
3. **Millisecond Mutation Sweep:** Falsify every invariant with `kavach rules check --mutate` and against 1-line mutants using `kavach diff`, recording the verified kill table in `.kavach/plan/invariants.md`.
---
## Mandatory 4-Question Check Before Writing `at_most_once_emit` (or `on_error_emit_count: 0`)
Before adding `at_most_once_emit` — and **especially** before setting `on_error_emit_count: 0` — answer all four questions against the target pipeline and downstream consumers. Blanket `at_most_once_emit` on an idempotent at-least-once sink causes false alarms on valid checkpointed sagas (like `getlago/lago#893`/`#894`) while missing real cross-service reordering and silent offset-skip data loss:
1. **Does the downstream store deduplicate (`ReplacingMergeTree`, unique constraint, idempotency table)?**
- **If yes:** Declare top-level `sinks:` metadata (`delivery: at_least_once`, `idempotent: true`, `dedup_key`) plus `at_least_once_emit` (`consistent_payload_on_retry: true`) — or scope `at_most_once_emit` with `retry_scope: in_process` — instead of blanket `at_most_once_emit`.
2. **Does this pipeline intentionally checkpoint and keep earlier emits across downstream step retries (`pipeline.Progress` / saga)?**
- **If yes:** Do **not** set `on_error_emit_count: 0` on the early step (a checkpointed saga legitimately emits step 1 before step 3 fails on a transient Redis/Postgres outage). Guard `before -> after` with `causal_order` and guard in-process duplicate suppression with `retry_scope: in_process`.
3. **Must effect `A` be visible downstream before trigger `B` fires?**
- **If yes:** Add a `causal_order` rule locking `before: A` and `after: [B]` so no patch or AI-generated fix can satisfy local invariants by reordering `A` after `B`.
4. **If a Kafka/queue handler leaves a record uncommitted, does it rewind the cursor or pause & retry in-place?**
- **Always for manual-commit consumers:** Add an `offset_safety` rule (`forbid_commit_past_failed: true`, `retry_containment: rewind_or_pause`) targeting the commit loop (`kavachkgo.WrapCommitLoop` / `WrapPollClient`).
> **Retry Fault Domains & Consistency Lints:** Distributed consumers distinguish three retry domains: `in_process_retry` (same batch/progress kept across transient faults -> zero duplicate emits expected), `rebalance_redelivery` (partition revoked or pod restarted -> fresh progress, safe iff sink is `idempotent: true` with identical canonical payload on `dedup_key`), and `broker_duplicate` (upstream redelivery -> safe iff `idempotent: true`). `kavach rules check` automatically flags `sink_semantics_conflict` (blanket `at_most_once_emit` on an `at_least_once` + `idempotent: true` sink) and `saga_early_emit_conflict` (`on_error_emit_count: 0` on a `causal_order.before` sink with a retryable `after` step).
---
## Declarative `.kavach/invariants.yaml` (Default — Zero Boilerplate)
`kavach init` scaffolds `.kavach/invariants.yaml` automatically. `kavach replay`, `kavach diff`, `kavach explore`, and `kavach rules check` auto-detect `.kavach/invariants.yaml` (override with `--invariants FILE`, or disable with `--invariants none`), and both `kavach-go` (`Config.InvariantsPath`) and `@kavachlabs/core` (`config.invariantsPath`) load it automatically when present.
### Top-Level `sinks:` Metadata
Declare the real delivery and deduplication contract of each downstream sink at the top of `.kavach/invariants.yaml`:
```yaml
sinks:
kafka:events_enriched:
delivery: at_least_once # "at_least_once" | "at_most_once" | "exactly_once"
idempotent: true # true if downstream deduplicates retries
dedup_key: $.transaction_id # JSONPath key used by downstream deduplication
downstream: "ClickHouse ReplacingMergeTree(transaction_id)"
kafka:events_charged_in_advance:
delivery: at_least_once
idempotent: true
dedup_key: $.transaction_id
downstream: "lago-api skips existing pay_in_advance_event_transaction_id"
```
When a sink is declared `idempotent: true`, `kavach explore` downgrades identical-payload retries during `rebalance_redelivery` / `broker_duplicate` to informational stats, while still failing hard (`non_idempotent_duplicate`) if a retry emits a **different** payload for the same `dedup_key`.
### Supported Declarative Rule Kinds
| `kind` | Required / Key Fields | What It Enforces |
| --- | --- | --- |
| `causal_order` | `before` (target), `after` (list of targets), optional `key` (JSONPath), `scope` (`step` default \| `trace`), `require_before_present` (bool, default `true`) | Enforces happens-before ordering across both `Output` emits (`kafka:*`) and mutating `Gateway` effects (`redis:zadd`, `pg:insert`). Fails if any `after` target succeeds before `before` (or without `before` when `require_before_present: true`). |
| `offset_safety` | `source` (e.g. `kafka:events`; matches `kafka:<topic>` and `kafka-batch:<topic>`), `commit_sink` (e.g. `kafka:commit`), optional `seek_sink` (default `kafka:seek`), optional `dlq_sink`, `forbid_commit_past_failed` (bool, default `true`), `retry_containment` (`rewind` \| `pause` \| `rewind_or_pause`, default `rewind_or_pause`) | Prevents silent data loss in manual-commit consumers. Fails (`committed_past_failed`) if `commit_sink` advances `committed_offset` past an unresolved failed offset, or if a failing step finishes without satisfying `retry_containment` (`SetOffsets`/`Seek` rewind, or `PauseFetchPartitions` + in-place retry loop, or either). |
| `at_least_once_emit` | `sink`, `key` (JSONPath), optional `dlq_sink`, `consistent_payload_on_retry` (bool), `ignore_fields` (list of JSONPaths) | Replaces misuse of `at_most_once_emit` on idempotent at-least-once pipelines. Guarantees every resolved/committed input emits `>= 1` output on `sink` (or `dlq_sink`), and when `consistent_payload_on_retry: true`, fails if a redelivery for the same `key` mutates canonical payload bytes (excluding `ignore_fields`). |
| `at_most_once_emit` | `sink`, `key` (JSONPath), optional `retry_scope` (`in_process` \| `rebalance` \| `all`, default `all`), optional `on_error_emit_count` (int, e.g. `0`) | No key may be emitted to `sink` more than once within the chosen `retry_scope`. Set `retry_scope: in_process` on checkpointed sagas with idempotent sinks so in-process retries enforce zero duplicates without false-failing on rebalance redeliveries. Only use `on_error_emit_count: 0` when emitting before a later fallible call is genuinely forbidden (see 4-question check above). |
| `anti_lobotomy` | `sinks` (list) or `sink`, optional `min_ratio_vs_baseline` (float, default `1.0`) | Blocks "fix by swallowing errors / returning early / dropping work." Fails if a step or session emits fewer outputs to any listed sink than `baseline * min_ratio_vs_baseline`. |
| `non_negative` | `sink`, `field` (JSONPath; `key` accepted as alias) | Every numeric value extracted from `field` (supports nested paths and wildcards like `$.accounts[*].balance`) on matching outputs must be `>= 0`. |
| `conservation` | `sink`, `field` (JSONPath; `key` accepted as alias) | Sum of all numeric values extracted from `field` across matching outputs in a step must equal `0` (tolerance `1e-9`)—catches unbalanced double-entry transfers or money creation/destruction. |
*Sink matching rule:* Exact match (e.g. `kafka:events_charged_in_advance`, `pg:exec`, `redis:zadd`, `http:response`), bare suffix without prefix (e.g. `events_charged_in_advance` matches `kafka:events_charged_in_advance`), or `*` for all sinks.
### Example `.kavach/invariants.yaml`
```yaml
service: events-processor
sinks:
kafka:events_enriched:
delivery: at_least_once
idempotent: true
dedup_key: $.transaction_id
downstream: "ClickHouse ReplacingMergeTree(transaction_id)"
kafka:events_charged_in_advance:
delivery: at_least_once
idempotent: true
dedup_key: $.transaction_id
downstream: "lago-api deduplicates on pay_in_advance_event_transaction_id"
invariants:
- name: enriched_before_api_triggers
kind: causal_order
before: kafka:events_enriched
after:
- kafka:events_charged_in_advance
- redis:zadd
scope: step
require_before_present: true
- name: no_skipped_uncommitted_offset
kind: offset_safety
source: kafka:events
commit_sink: kafka:commit
seek_sink: kafka:seek
dlq_sink: kafka:events_dead_letter
forbid_commit_past_failed: true
retry_containment: rewind_or_pause
- name: enriched_delivered_or_dlq
kind: at_least_once_emit
sink: kafka:events_enriched
dlq_sink: kafka:events_dead_letter
key: $.transaction_id
consistent_payload_on_retry: true
ignore_fields: [$.ingested_at, $.traced_at]
- name: no_duplicate_in_process_retry_emit
kind: at_most_once_emit
sink: kafka:events_charged_in_advance
key: $.transaction_id
retry_scope: in_process
- name: no_silent_billing_drop
kind: anti_lobotomy
sinks: [kafka:events_enriched, kafka:events_charged_in_advance]
min_ratio_vs_baseline: 1.0
- name: balances_non_negative
kind: non_negative
sink: pg:exec
field: $.balance_cents
- name: ledger_money_conserved
kind: conservation
sink: ledger.entries
field: $.delta_cents
```
---
## Code Invariants (When Internal State Must Be Inspected)
Add code invariants only when a rule inspects in-memory structures (secondary indices, caches, state-machine monotonicity across fields not emitted on a sink) or custom cross-field predicates:
- **Go (`github.com/kavachlabs/kavach-go`):**
```go
kv.Invariant("single_advance_bill_per_tx", func(s kavach.Step) error {
return s.AssertAtMostOnceEmit("kafka:events_charged_in_advance", "$.transaction_id")
})
```
- **TypeScript (`@kavachlabs/core`):**
```ts
kv.invariant("single_advance_bill_per_tx", (step) =>
step.assertAtMostOnceEmit("kafka:events_charged_in_advance", "$.transaction_id")
);
```
- **Mode 2 (`sdk/*`):** Register invariant callbacks directly on the handler with a diagnostic error message showing the offending values.
*Anti-patterns to avoid:*
- Never write tautological invariants that just re-compute the exact line of code the handler just ran.
- Never perform external I/O or advance the clock/RNG inside an invariant check.
---
## Step-by-Step Invariant Discovery & Falsification Workflow
### Step 1: Write `.kavach/plan/invariants.md` (Before Touching Code)
1. Read `.kavach/invariants.yaml` and `.kavach/plan/state-map.md` (if present); otherwise inspect the service's handlers, drivers, and output sinks first (run `kavach rules scan --dir .` to discover `schema`, `state`, `api`, `writes`, `docs`, `tests`, `clock`, and `transport` invariant candidates, or `kavach doctor` for Mode 1 services / [`../kavach-setup/references/state-map-template.md`](../kavach-setup/references/state-map-template.md) for Mode 2).
2. Run the **Mandatory 4-Question Check** above and identify concrete domain properties that must always hold:
- **Sink semantics & delivery (`sinks:` + `at_least_once_emit` or `at_most_once_emit` with `retry_scope`):** Record whether each downstream sink deduplicates (`idempotent: true`, `dedup_key`), enforce payload determinism across retries (`consistent_payload_on_retry: true`), and scope duplicate prohibition (`retry_scope: in_process`) for checkpointed sagas.
- **Cross-service causal ordering (`causal_order`):** Lock `before -> after` across `Output` emits and mutating `Gateway` calls (e.g., `kafka:events_enriched` before `kafka:events_charged_in_advance` and `redis:zadd`).
- **Consumer offset safety (`offset_safety`):** Forbid committing past unresolved failed offsets and require `retry_containment: rewind_or_pause` (`SetOffsets`/`Seek` or `PauseFetchPartitions` + in-place retry loop).
- **Liveness / anti-lobotomy (`anti_lobotomy`):** Valid inputs keep producing expected downstream messages, HTTP responses, or DB writes instead of being silently swallowed.
- **Bounds & non-negativity (`non_negative`):** Balances, quantities, capacities, reference counts, and TTLs never go negative.
- **Conservation laws (`conservation`):** Debits and credits sum to zero; reserved + available inventory equals total stock.
- **Structural & monotonicity laws (code invariants):** Secondary indices match primary state; terminal states (`cancelled`, `settled`, `dead_lettered`) never regress; sequence numbers never move backward.
3. Write **`.kavach/plan/invariants.md`** following [`references/mutation-sweep.md`](./references/mutation-sweep.md) (see [`examples/ledger/.kavach/plan/invariants.md`](../../examples/ledger/.kavach/plan/invariants.md) for a complete example), pairing each invariant with its **planned 1-line falsification mutant** (`file:line` change that must trigger `invariant_violated`).
### Step 2: Declare the Invariants & Verify Baseline
1. Add all output-observable rules to **`.kavach/invariants.yaml`** first.
2. Add code invariants (`kv.Invariant` / `kv.invariant` / Mode-2 handler invariants) only for properties requiring internal state inspection.
3. Confirm the unmutated build passes all declared invariants and that every rule is non-vacuous and catches synthetic mutations using `kavach rules check`:
```bash
kavach rules check <capsule.kavach> --bin "/tmp/baseline" --mutate --strict-vacuous
kavach replay <capsule.kavach> --bin "/tmp/baseline"
```
Expect `passed: true` (`0` vacuous, `0` blind) and `ok` (or `fixed` on a fixed incident fixture).
### Step 3: Falsify Each Invariant (Millisecond Mutation Sweep)
Follow [`references/mutation-sweep.md`](./references/mutation-sweep.md):
For each declared invariant `X` in `.kavach/plan/invariants.md`:
1. Inject the planned **one-line mutant** in the service that violates `X` (e.g., emitting before a failing cache/DB call without rollback, swallowing a retry error and returning early, skipping a debit on transfer, or removing a sufficient-funds check).
2. Build or stage the mutant host command (`/tmp/mutant-X`, or an isolated git worktree for TS/Python) and **immediately revert the working tree** so the repository never stays dirty.
3. Run `kavach diff` (which evaluates `.kavach/invariants.yaml`, code invariants, and mutated gateway-fault/retry variants):
```bash
kavach diff <capsule.kavach> --old "/tmp/baseline" --new "/tmp/mutant-X" --variants 25 --json
```
4. **Evaluate the mutant:**
- **Killed (`invariant_violated(X)@N` or `variant_failed(K)@N` naming `X`):** The invariant and capsule/variants actively catch the bug class.
- **Survived (`ok` or `fixed`):** Either (a) the invariant rule/JSONPath/sink does not match the actual emitted payload, or (b) the recorded capsule and its variants never exercise the mutated branch. Fix the sink/JSONPath or record a capsule step reaching that branch, then re-test until killed.
### Step 4: Record the Verified Kill Table in `.kavach/plan/invariants.md`
Update the **Falsification Results** table in `.kavach/plan/invariants.md` and present it to the user:
- Invariant name, declaration layer (`.kavach/invariants.yaml` vs code), and domain property
- 1-line mutant injected (`file:line`)
- Verdict & step (`invariant_violated(X)@N` or `variant_failed(K)@N`)
- Replay / diff verification time
### Step 5: Refresh the Interactive Flow Map
For Mode 1 repos, regenerate and open the topology map with all declarative invariants attached:
```bash
kavach map --auto
kavach map --open
```
For Mode 2 custom specs, author `.kavach/plan/map.json` (following [`../kavach-setup/references/map-template.md`](../kavach-setup/references/map-template.md)) and render:
```bash
kavach map .kavach/plan/map.json <fixtures> --bin <host> -o .kavach/plan/map.html
```
Files in this skill
- SKILL.md
- references/mutation-sweep.md
Attribution
Related skills
View all in development →Comments
Loading comments…
Newsletter
Get the weekly list of safe new skills, and the ones we pulled.