# Python SDK

> Record and replay synchronous Python handlers. Python 3.10 or later, standard library only.

```bash
pip install ./sdk/python    # from a checkout of the Kavach repository
```

```python
import kavach
```

Python 3.10 or later. No dependencies outside the standard library. Handlers are synchronous and called from one thread at a time; asyncio handlers are planned.

## Handler

```python
import kavach
from kavach import Input, Invariant

class Wallet:
    def __init__(self):
        self.balance = 0

    def handle(self, env: kavach.Env, input: Input) -> None:
        now = env.now()                              # aware UTC datetime; env.now_ns() for nanoseconds
        txn = env.random(8)                          # never os.urandom / random
        rate = env.query("fx-rates", b"EURUSD")      # raises kavach.GatewayError on failure
        limit = env.config("MAX_TRANSFER")           # bytes | None
        env.emit("postgres:balances", b"...")        # delivered after the step succeeds

    # optional
    def snapshot(self) -> bytes: ...
    def restore(self, data: bytes) -> None: ...
    def invariants(self) -> list[Invariant]:
        return [Invariant("non_negative", lambda: self.balance >= 0)]
```

| `Env` method | Records |
| --- | --- |
| `now() -> datetime`, `now_ns() -> int` | `clock` |
| `random(n) -> bytes` | `rand` |
| `query(gateway, request) -> bytes` | `gateway` |
| `config(key) -> bytes \| None` | `config` |
| `emit(sink, data, local=False)` | `output` |

An `Invariant(name, check)` holds when `check()` returns normally and fails when it raises or returns `False`.

## Failures

| The handler | Marker | Message |
| --- | --- | --- |
| raises any exception `e` | `panic` | `f"{type(e).__name__}: {e}"`, for example `KeyError: 'amount'`; the traceback is marker data |
| raises `kavach.Panic(msg)` | `panic` | exactly `msg` |
| raises `kavach.HandlerError(msg)` | `error` | exactly `msg` |
| ends ok but an invariant fails | `invariant` | the invariant's name |

A `KeyboardInterrupt` or `SystemExit` in a step is recorded as a panic and re-raised.

## Recording

```python
rec = kavach.Recorder(
    Wallet(),
    service="wallet",
    dir="kavach",                                     # fixtures go in kavach/fixtures/
    gateways={"fx-rates": (fx_connection, "remote")}, # name -> (connection(request) -> bytes, scope)
    config=lambda key: flags.get(key),                # default: os.environ.get
    flags=lambda: {"flag.ledger-v2": "on"},           # facts for the environment record
    deliver=lambda outputs: [send(o.sink, o.data) for o in outputs],
    required=False,                                   # True: raise if the recorder cannot start
    on_fixture=lambda msg: alert(msg["file"]),        # {"file", "seq", "failure", ...}
)

result = rec.step(kavach.Input("kafka:wallet-events", "3:1042", payload))
if not result.ok:                                     # result.kind: panic | error | invariant
    log.warning("step failed: %s", result.message)

rec.flush(durable=True)
rec.close()
```

`step()` never raises for handler failures; it returns a `StepResult` (call `result.raise_for_failure()` to raise). Outputs are delivered only after a successful step. Pass `start="snapshot"` to start the journal from `handler.snapshot()`. If the recorder cannot start or stops, the SDK logs on the `kavach` logger and keeps stepping.

Other journal settings are keyword arguments: `compression`, `level`, `block_bytes`, `flush_ms`, `segment_bytes`, `segment_seconds`, `retain_segments`, `secret_keys`, `recorder_command`.

## Replay host

```python
def main():
    kavach.maybe_host(lambda: Wallet(), gateways={"fx-rates": (fx_connection, "remote")})
    ...  # normal startup
```

Call `maybe_host` first. When the last argument is `kavach-host` it serves the CLI and exits; otherwise it returns. It points `sys.stdout` at stderr, so `print` in a handler is safe.

```bash
kavach replay incident.kavach --bin "python -m wallet"
kavach diff incident.kavach --old "python -m wallet" --new "python -m wallet --fix"
```

For an interpreted service, the old build must be a separate copy of the code (`git worktree add /tmp/old HEAD`), or a flag that selects old behaviour. Never select builds with an environment variable.

## Example

`sdk/python/examples/ledger` is the quickstart ledger:

```bash
cd sdk/python/examples/ledger
PYTHONPATH=../.. python -m ledger          # buggy: TypeError on evt-008
PYTHONPATH=../.. python -m ledger --fix    # fixed: rejects it
```

Source: https://www.thekavachlabs.com/docs/sdks/python
