Reference

KVStash Python client

The kvblockd package speaks the KVStash wire protocol from Python: a pooled, multi-stream client with batched reads, zero-copy reads into your own buffers, and checksums on by default.

Last updated

When to use it

Engines do not need this page: their adapters already use this client. Use it directly to build your own integration, to pre-load blocks, or to write tools and tests against a store.

Shell
# Python 3.10+; depends on blake3 and xxhash. Use a virtual environment: Debian/Ubuntu
# and Homebrew Pythons refuse a system-wide pip install (externally-managed-environment).
python3 -m venv .venv && . .venv/bin/activate
pip install kvblockd

PyPI packages, checked end to end on 8 November 2026 with the official engine images: kvblockd 0.2.0 with vllm-kvblockd 0.1.2 on vLLM 0.33.0, and sglang-kvblockd 0.2.1 on SGLang 0.5.23. Both store, reload into a restarted engine and give the answer the engine gives from its own cache. lmcache-kvblockd 0.2.1 is not recommended yet: in LMCache's own image (LMCache 0.5.6, vLLM 0.31.0) a prompt reloaded from LMCache's own cache answered wrongly, with or without KVStash. On vLLM, use the native vllm-kvblockd connector.

Connect

A Client holds a pool of connections to one namespace on one daemon and is safe to share between threads.

Python
from kvblockd.client import Client

c = Client(
    "10.0.0.5:9440",
    namespace="team-a",
    token=open("/run/kvb/team-a.token").read().strip(),
    streams=4,              # pooled TCP connections
    get_fanout=4,           # parallel read shards, at most streams
    connect_timeout=5.0,
    op_timeout=10.0,        # per operation; a stall becomes a miss
    verify=True,            # check each block's xxh3 checksum on read
)
print(c.limits.max_batch_keys)    # limits the daemon offered at connect
...
c.close()

Store and read

Python
import hashlib
from kvblockd.protocol import Status

key = lambda name: hashlib.sha256(name.encode()).digest()   # any 32 bytes

c.put(key("doc-1/block-0"), b"\x01" * 1_000_000)      # bytes, bytearray or memoryview
c.put(key("doc-1/block-1"), [b"head", b"tail"])        # or a list of buffers, sent as one block
c.put(key("doc-1/block-2"), data, ttl_ms=3_600_000)    # optional TTL

n, present = c.batch_exists([key("doc-1/block-0"), key("doc-1/block-1"), key("doc-1/block-9")])
# n == 2, present == [True, True, False]   n counts present keys from the first one on

values, statuses = c.batch_get_bytes([key("doc-1/block-0"), key("missing")])
# [b'\x01\x01...', None]   [<Status.OK: 0>, <Status.NOT_FOUND: 16>]

c.delete([key("doc-1/block-1")])                       # [<Status.OK: 0>]
# a block a read just returned is leased for 5 s (lease_default_ms): deleting it inside
# that window answers ERR_LEASED; pass force=True or release the lease first
c.stats()                                              # the daemon's stats JSON, as bytes

Zero-copy reads

batch_get_scatter reads blocks straight into memory you own, split across up to get_fanout connections in parallel. This is the path the engine adapters use to fill pinned host buffers before copying to the GPU.

Python
import time

BLOCK = 1 << 20
slab = bytearray(len(keys) * BLOCK)      # or pinned host memory you copy to the GPU from

def alloc(idx, prefix, body_len):
    """Called once per found block, possibly from several threads.
    Return a writable view for the block's bytes, or None to skip it."""
    off = idx * BLOCK
    return memoryview(slab)[off:off + body_len]

statuses = c.batch_get_scatter(keys, 0, alloc, deadline=time.monotonic() + 2.0)
# one Status per key, in key order; past the deadline, unread keys come back NOT_FOUND
  • alloc must be thread-safe for distinct idx values. A slab with one slot per index is.
  • Each block is verified before its status becomes OK.
  • A deadline bounds the whole call. Blocks already verified stay valid; the rest become misses.
  • prefix_len lets you read a small header first (for example a metadata prefix your format stores) and decide where the rest goes. Pass 0 if your blocks have none.

Leases and pins

Reads already grant a short lease automatically. Use these when you need blocks to stay longer, for example while a slow consumer is still copying them.

Python
from kvblockd.protocol import LEASE_GRANT, LEASE_RELEASE, TOUCH_RECENCY, PIN_SOFT, PIN_HARD, UNPIN

c.touch_lease(keys, LEASE_GRANT, ttl_ms=30_000)   # keep these from eviction for 30 s
c.touch_lease(keys, LEASE_RELEASE)                # give the lease back early
c.touch_lease(keys, TOUCH_RECENCY)                # mark as recently used
c.pin(keys[:1], PIN_HARD)                         # keep resident; counts against the pin quota
c.pin(keys[:1], UNPIN)

Errors and misses

The client is built so that a slow or failing store degrades to misses: reads that time out, connections that drop mid-read and blocks that fail verification come back as NOT_FOUND, and the reason is counted in counters. Exceptions are for problems you need to fix, such as a wrong token or namespace, or a daemon that cannot be reached when the client is created.

Python
from kvblockd.errors import KvblockdError, ConnectionLost, StatusError

try:
    c = Client("10.0.0.5:9440", namespace="team-a", token="wrong")
except KvblockdError as e:
    print(e)          # server fatal: status 0x21   (ERR_AUTH_FAILED, raised at connect)

print(c.counters.snapshot())
# {'evictions': 0, 'deadline_misses': 0, 'corrupt_blocks': 0, 'degraded_keys': 0,
#  'stale_drops': 0, 'put_retries': 0}
  • KvblockdError

    Base class of every error the client raises.

  • ConnectionLost

    The socket closed mid-exchange; that connection is discarded from the pool.

  • FatalProtocol

    The daemon ended the connection, for example after a failed login.

  • StatusError

    A request returned a non-OK status; the connection stays usable.

Keys

Keys are exactly 32 bytes. Any stable scheme works for your own data; what matters is that every writer and reader derives the same key for the same content. The adapters use a BLAKE3 chain over the model identity and the token prefix, and kvblockd.hashing.wire_key(fields) maps an ordered list of strings to a key the same way the Go client does.

If your keys depend on Python's built-in hash(), pin PYTHONHASHSEED=0 in every process; kvblockd.hashing.startup_determinism_check() raises DeterminismError when it is not pinned.

API summary

  • Client(addr, *, namespace, token, streams=4, get_fanout=None, connect_timeout=5.0, op_timeout=10.0, verify=True, so_rcvbuf=None)

    Opens a pool and authenticates one connection immediately, so a bad token fails here. so_rcvbuf overrides the kernel receive buffer (leave it unset to keep autotuning).

  • put(key, data, ttl_ms=0)

    Stores one block. data is a buffer or a list of buffers. Write-once: an existing key keeps its first block.

  • batch_exists(keys, deadline=None)

    Returns (n, present): the count of consecutive present keys from the first, and a per-key list of booleans.

  • batch_get_bytes(keys)

    Returns (values, statuses). Missing blocks are None.

  • batch_get_scatter(keys, prefix_len, alloc, deadline=None)

    Zero-copy read into your buffers through alloc(idx, prefix, body_len). Returns statuses in key order.

  • delete(keys, force=False)

    Deletes blocks. Without force, leased and hard-pinned blocks stay.

  • touch_lease(keys, sub, ttl_ms=0)

    TOUCH_RECENCY, LEASE_GRANT or LEASE_RELEASE.

  • pin(keys, sub)

    PIN_SOFT, PIN_HARD or UNPIN.

  • stats()

    The daemon stats document as JSON bytes.

  • counters.snapshot()

    Client-side miss causes: evicted connections, deadline misses, corrupt blocks, degraded keys, idle connections dropped before reuse (stale_drops) and PUT retries (only with put_retry=True).

  • close()

    Closes the pool.

Something missing or wrong on this page? Email rudray@kvstash.com and it gets fixed.