# openmeterio/openmeter — Kavach Visual Invariant Atlas

> Cloud-native usage metering and credit entitlement engine. Zero-memrepo replay across 8 Ent Postgres repos and ClickHouse HTTP.

- **Repository:** https://github.com/openmeterio/openmeter
- **Commit:** `f2da409` (branch `main`)
- **Proof Tier:** `gold_showcase`
- **Stateful Backend Supported:** `true`
- **Scan:** 2766 ms · 2709 files · $0.00 LLM tokens

## Detected Stateful Drivers & Gateways

| Driver | Language | Category | Kavach Adapter |
| :--- | :--- | :--- | :--- |
| `entgo.io/ent/dialect/sql` | go | database | `kavachpgx` |
| `github.com/ClickHouse/clickhouse-go/v2` | go | database | `kavachhttp` |

## Extracted System Invariants (3)

| Invariant | Proof State | Category | Rule Kind | Evidence |
| :--- | :--- | :--- | :--- | :--- |
| `non_negative_credit_balance` | `verified` | schema | `non_negative` | `.kavach/invariants.yaml` |
| `credit_conservation_and_snapshot_invariance` | `verified` | conservation | `conservation` | `harness/internal/host/worker.go`, `.kavach/invariants.yaml` |
| `window_history_overage_consistency` | `verified` | schema | `non_negative` | `harness/internal/host/worker.go` |

### `non_negative_credit_balance`
- **Summary:** Declarative YAML invariant (.kavach/invariants.yaml): credit balance and overage must never be negative.
- **Proof State:** `verified`
- **Code:** `.kavach/invariants.yaml`

### `credit_conservation_and_snapshot_invariance`
- **Summary:** Snapshot-resumed GetEntitlementBalance must match full-period ground truth.
- **Proof State:** `verified`
- **Code:** `harness/internal/host/worker.go`, `.kavach/invariants.yaml`

### `window_history_overage_consistency`
- **Summary:** History window OverageAtStart and BalanceAtStart must match point-in-time GetBalanceAt.
- **Proof State:** `verified`
- **Code:** `harness/internal/host/worker.go`

## Guided Causal Flows

### O1: Recurring grant snapshot double-credit
Resuming from a reset-boundary Ent Postgres balance_snapshot at idx==0 re-applies grantsRecurredAtStart and erases 120 preserved overage.

1. **`in_reset_usage`**: At 2026-01-02T00:00:00Z reset_usage calls ResetUsageForOwner with 120 preserved overage.
2. **`fn_reset_owner`**: Terminal [Until, Until] phase recurs grant-0001 to 150, burns 120 overage -> persists Ent balance_snapshots Balance=30.
3. **`in_verify_balance`**: At 02:00Z after 10 more ClickHouse usage, verify_balance resumes Engine.Run from StartingSnapshot.At=00:00Z (idx=0).
4. **`fn_get_phases`**: getPhases (burnphase.go:55-59) puts grant-0001 into grantsRecurredAtStart because recurrenceTime == period.From.
5. **`bug_o1`**: runBetweenResets (run.go:170-174) re-applies recurrence at idx==0 (30 -> 150), yielding Balance=140 instead of 20.
6. **`inv_conservation`**: credit_conservation_and_snapshot_invariance fails (detected on openmeter_credit output & error).

### O2: Windowed balance history 2x overage
GetEntitlementBalanceHistory seeds tsBalance.overage with end-of-segment Overage and re-accumulates every ClickHouse window's overage.

1. **`in_ingest_usage`**: 245 GPU-seconds ingested via ClickHouse HTTP across a 100-credit Ent grant leaves 145 true overage.
2. **`in_verify_history`**: verify_history calls GetEntitlementBalanceHistory.
3. **`fn_hist`**: metered/balance.go:286 sets overage: segment.Overage (145) instead of segment.OverageAtStart (0).
4. **`bug_o2`**: Window loop re-adds 145 uncovered usage on top of 145 -> OverageAtStart=290 (exact 2x).
5. **`inv_history`**: window_history_overage_consistency fails.

### O3: Multi-reset scheduled future grant failure
filterRelevantGrants omits a future grant in Period 0, then passes it to Period 1 without initializing its snapshot balance.

1. **`in_multi_reset`**: Loads owner from Ent Postgres & usage from ClickHouse HTTP, then runs Engine.Run across a reset boundary when g2 activates in Period 1.
2. **`fn_engine_run`**: Period 0 filters out g2; e.reset produces a snapshot with only {g1}.
3. **`fn_run_between`**: Period 1 passes Grants=[g1, g2] with Balances={g1} into runBetweenResets.
4. **`bug_o3`**: run.go:125 fails ExactlyForGrants ('provided grants and balances don't pair up').

## Replay-Verified Proofs (132/132 variants, 126/126 regressions)

- **O1: Recurring Grant Snapshot Resume Double-Credit** (`openmeter/credit/engine/run.go:170-174`) — Resuming from a reset-boundary snapshot re-applies recurring grants, minting +120 phantom credits. [37/37 variants · verdict `fixed`]
- **O2: Entitlement Balance History 2x Overage Inflation** (`openmeter/entitlement/metered/balance.go:285-288`) — Seeds anchor with end-of-segment overage instead of OverageAtStart, doubling reported overage. [43/43 variants · verdict `fixed`]
- **O3: Multi-Reset Scheduled Grant Pairing Failure** (`openmeter/credit/engine/run.go:56-64`) — Period 1 crashes in ExactlyForGrants when a future scheduled grant activates post-reset. [52/52 variants · verdict `fixed`]

## Starter `.kavach/invariants.yaml`

```yaml
# Declarative Kavach invariants for OpenMeter — checked on every replay & variant.
service: openmeter
invariants:
  - name: non_negative_credit_balance
    kind: non_negative
    sink: openmeter_credit
    field: $.balance

  - name: non_negative_credit_overage
    kind: non_negative
    sink: openmeter_credit
    field: $.overage

  - name: no_silent_credit_drop
    kind: anti_lobotomy
    sinks: [openmeter_credit]
    min_ratio_vs_baseline: 1.0
```

## Driver Wrap Snippet

```text
import (
  "github.com/kavachlabs/kavach-go/kavachpgx"
  "github.com/kavachlabs/kavach-go/kavachhttp"
)

drv := kavachpgx.WrapEntDriver(entSqlDriver)
ch := kavachhttp.WrapClient(clickhouseHTTPClient)
```

## Run Locally (Zero Upload)

```bash
brew install kavachlabs/tap/kavach && kavach map --auto --open
```
