Metadata-Version: 2.4
Name: redhare
Version: 0.7.0rc1
Summary: Stable, high-performance KVCache for LLM inference, with decentralized coordination, memory-pool storage, and multi-tier caching across hosts.
Author: Redhare contributors
License: Apache-2.0
Requires-Python: >=3.10
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM

# redhare (Python connector)

In-process Python binding around `RedhareClient`. Ships two API layers
that share the same embedded Rust client:

- **`KvStore`** — low-level SDK (this README).
- **`redhare.vllm_connector.RedhareConnector`** — vLLM v1 native KV
  connector. Full schema and mode-picking guide:
  [`docs/08-vllm-connector.md`](../../docs/08-vllm-connector.md).

The low-level SDK below exposes batch gather/scatter methods for custom
connector implementations:

```python
from redhare import KvStore

store = KvStore(
    redis_url="redis://127.0.0.1:6379",
    client_id="rank0",
    data_plane_addr="127.0.0.1:7000",
    capacity="64MB",              # int bytes also accepted
    transport="nixl",            # "nixl" (default) | "tcp" | "inmemory"
    local_disk_dirs=None,        # Linux directories, e.g. ["/mnt/nvme/redhare"]
    local_disk_capacity_bytes=None, # aggregate disk pool capacity (int or size string)
    shared_fs_root=None,          # optional cold-tier path
    shared_fs_backend="posix",    # "posix" (default) | "gds"
    block_size_bytes=None,        # optional fixed per-key block size
    hot_cache_fraction=0.20,
    hot_cache_min_shared_fs_reads=2,
    default_ttl_ms=30 * 60 * 1000,
    cache_node_rpc_addr=None,     # optional: enable cache-node mode
    enable_remote_dram=False,     # originator: place into discovered cache-nodes
)

# Pre-register the KV cache region once; later reads DMA straight into it
# without re-registering per call.
store.register_buffer(kv_cache.data_ptr(), kv_cache.numel() * kv_cache.element_size())

# Save: each key's payload is gathered from N (addr, size) pairs (one memcpy).
rc = store.batch_put_from_multi_buffers(keys, addrs_per_key, sizes_per_key)
# Load: NIXL scatters the payload across the same N (addr, size) pairs.
# True zero-copy when destinations live inside a register_buffer region.
rc = store.batch_get_into_multi_buffers(keys, addrs_per_key, sizes_per_key)

# Experimental local-only load: enqueue the scatter copy on Redhare's device
# copy stream (CUDA or Ascend NPU, whichever the process has) and poll or
# wait for completion. This raises if any key is not
# local, so callers should fall back to batch_get_into_multi_buffers.
handle = store.batch_get_into_multi_buffers_submit_local(
    keys, addrs_per_key, sizes_per_key
)
# Either poll handle.is_done() from your scheduler loop, or block explicitly.
handle.wait()

# Optional fixed-block size can also be set once after construction when the
# exact per-key KV block byte size is learned during runtime setup.
store.set_block_size_bytes(256 * 1024)

# Range scatter: read byte subranges from stored objects into destination
# buffers. This is mainly for advanced connector paths.
rc = store.batch_get_ranges_into_multi_buffers(keys, offsets, lengths, addrs, sizes)

# Existence check (1 = exists, 0 = missing, -1 = error per key)
rc = store.batch_is_exist(keys)

store.close()
```

Return convention uses per-key `int` lists where `0` is success and a negative
value indicates failure.

## Ephemeral local disk

On Linux, configure both `local_disk_dirs` (a nonempty list of existing
local directories) and `local_disk_capacity_bytes` (bytes or a size string).
For example, add `local_disk_dirs=["/mnt/nvme0/redhare", "/mnt/nvme1/redhare"]`
and `local_disk_capacity_bytes="64GB"` to the constructor above. The 64 GB
limit covers the entire pool across both disks and every Worker; `capacity`
continues to specify DRAM per Worker. Directory order does not change pool
identity. LocalDisk and SharedFs are mutually exclusive, and LocalDisk cannot
be combined with `cache_node_rpc_addr`.

Normal admission places objects in DRAM, demotes under pressure, and can
write directly to disk on admission bypass. There is no additional object-size
placement threshold. `hot_cache_fraction` and `hot_cache_min_shared_fs_reads`
also control LocalDisk read-through replicas. Leaving disk unconfigured keeps
the existing behavior. Workers must have distinct `client_id` values and must
initialize their stores after fork (or use spawn/exec).

Own and same-pool reads support full, gather/scatter and range operations.
Disk I/O uses owned aligned host buffers, with synchronous host/device copies.
Cross-pool TCP supports whole-object and range loads into CPU/GPU targets,
including requesters without local disk. Both peers must use TCP.
NIXL supports cold preparation, Rust owned-byte reads and direct CPU/GPU
scatter; cached payloads never fall back to TCP. Borrowed scatter operations
retain their worker, request and registrations until DMA completion, including
on cancellation. After a deadline or status error, completion drainage may use
an additional safety grace (`REDHARE_NIXL_DRAIN_TIMEOUT_MS`, default 1000 ms);
a failed drain or an uncertain partial post terminates the process before
caller memory can be reused. This grace submits no new reads. Full caller
registrations are reused by lazily initialized cold lanes. Direct scatter does
not populate a CPU hot replica. Peer-wide DMA quiescence is still unavailable,
so exposed NIXL cold arenas remain registered until process exit;
uncertain owned READs retain their target memory and quarantine the affected
lane until exit. Lease expiry reclaims source extents, not these allocations.
`batch_is_exist` checks logical expiry and holder liveness without opening data
files; a hit can still become a load miss.
Configure vLLM with `kv_load_failure_policy: "recompute"`.

The Connector accepts the same `local_disk_dirs` and
`local_disk_capacity_bytes` fields in `kv_connector_extra_config`; its DRAM
field remains `capacity_bytes`. TP keys and shard matching are unchanged.
LocalDisk statistics include `put_path_local_disk`, `put_bytes_local_disk`,
`get_hit_local_disk`, `get_bytes_local_disk`, `local_disk_demote_total`,
`local_disk_demote_failed`, and `get_latency_us_local_disk`.

The Worker reclaims expired entries, retries deferred file deletion and
continues bounded startup cleanup without Redis. Uncertain Redis publications
retain their files until absolute expiry or confirmation. External Cleaner
reconciliation and maintenance RPCs are a later integration: removing a
peer's Redis record does not immediately notify its owner to free disk quota.
`close()` stops local disk admission and releases its session before attempting
bounded Redis cleanup; restarting does not adopt old files as cache hits.
See [the design](../../docs/11-local-disk.md) for filesystem and lifecycle rules.

The Rust core feature `local-disk` is enabled by default; normal Cargo and
Maturin builds use blocking Direct I/O without extra feature flags. Runtime use
still requires the two explicit settings. Without LocalDisk configuration, no
disk pool or I/O executor is initialized. To select io_uring with Direct I/O,
build with `--features io-uring` (for example, `maturin develop --release
--features io-uring`). This optional executor requires Linux io_uring read/write
and probe support (upstream kernel 5.6+), allowed by the container policy;
configured LocalDisk initialization fails if unavailable, without switching
executors. The default blocking executor does not require io_uring. Bundled
daemon/CLI/cleaner commands do not gain LocalDisk flags in this SDK integration.

```bash
python crates/redhare-py/examples/smoke.py --transport tcp \
  --capacity 64 --local-disk-dir /mnt/nvme/redhare \
  --local-disk-capacity 1GB
```

## Build

For extension development, install directly into the active environment:

```bash
pip install maturin                          # once
cd crates/redhare-py
export CARGO_TARGET_DIR=/tmp/redhare-target   # NFS-safe (see project memory)
maturin develop --release                    # installs into the active env
```

For a distributable wheel, return to the repository root and use the
canonical wrapper, which also bundles `redhare-client`, `redhare-cli`, and
`redhare-cleaner`:

```bash
wheel_path="$(python3 crates/redhare-py/scripts/build_wheel.py)"
pip install "$wheel_path"
```

## Notes

- `transport="nixl"` is the only one with true zero-copy load. `tcp` and
  `inmemory` work but fall back to read-then-memcpy for scatters.
- On Ascend NPUs NIXL is not wired: pass `transport="tcp"` to `KvStore`. The
  vLLM connector picks `tcp` itself on an NPU when its config names no
  transport (and `nixl` on CUDA); a process without the NIXL runtime aborts
  instead of raising, so do not rely on the `nixl` default there.
- `redhare-bench` also leaves an omitted transport to the connector default;
  its cache-node uses the same backend-aware default. An explicit transport
  overrides both.
- Failed ACL async submissions drain queued DMA before returning. The drain
  budget is `REDHARE_DEVICE_COPY_DRAIN_TIMEOUT_MS` (default 30000), independent
  of `REDHARE_TRANSPORT_IO_TIMEOUT_MS` and the bench's `--io-timeout-ms`.
  Set it before importing `redhare`, above the workload's worst-case queued
  DMA time. A failed or timed-out drain terminates the process because the
  in-flight buffers cannot safely be reused.
- `batch_get_into_multi_buffers_submit_local()` is a local-only optimization
  for custom connectors. It does not read from remote peers or cold storage;
  use `batch_get_into_multi_buffers()` as the fallback path.
- `data_plane_addr` is what peers connect to (NIXL control channel or TCP).
  The vLLM connector also accepts a list, one entry per NIC, and gives each
  local rank one of them in turn.
  Must be reachable from other clients in the cluster.
- Remote DRAM uses `data_plane_addr` for payload movement and
  `cache_node_rpc_addr` only for control. With `transport="nixl"`, remote
  writes use NIXL Write into the cache-node arena after an RPC reservation.
- One connector `key` maps to one Redhare object: the per-key `(addrs, sizes)` lists
  are concatenated on save (one memcpy) and scattered on load (zero copy).
- With `block_size_bytes=...`, each key is forced to one fixed-size block:
  shorter saves are zero-padded, larger saves fail.

## Prefill/decode disaggregation

Use vLLM's own `NixlConnector` and swap the transport underneath it:

```bash
export REDHARE_NIXL_TRANSPORT=1      # enable on both peers
export REDHARE_NIXL_ARENA=8GB        # pinned host arena per rank

vllm serve "$MODEL" --tensor-parallel-size 2 --block-size 128 \
  --kv-transfer-config '{
      "kv_connector": "NixlConnector",
      "kv_role": "kv_producer",
      "kv_load_failure_policy": "recompute"
  }'
```

The same on the decoder with `"kv_role": "kv_consumer"`, and the router
protocol is NIXL's own — anything that already drives NIXL disaggregation
drives this. There is no connector of ours in the picture: a `.pth` shipped
with this package installs an import hook, which replaces `NixlWrapper` in
vLLM's NIXL worker the first time that module loads.

Before gathering device KV, the producer waits on an immutable CUDA/NPU event
recorded on the compute stream after the request's latest forward (including
continuing prefill chunks). Events are shared across readers and retained in a
bounded, expiring index. Missing events or unsupported runner versions fall
back to synchronizing the registered devices. Both V2 and legacy mixin forward
boundaries are hooked; Ascend event ordering still requires hardware validation.

### Ascend NPU

The vLLM 0.27 NIXL pull adapter registers Ascend's separate K/V tensors
as independent regions and requests NHD layout. Scheduling and the router
protocol still use vLLM's `NixlConnector`.

The supported NPU path is dense attention, TP1/PP1, NHD, block size 128,
and device KV buffers. MLA, Mamba, host buffers, and other parallel layouts
are rejected before KV registration. The CUDA registration path is unchanged.

Use `ASCEND_RT_VISIBLE_DEVICES` to select a separate device for each engine,
`--block-size 128`, and this transfer configuration on both peers:

```json
{"kv_connector":"NixlConnector","kv_role":"kv_both","kv_buffer_device":"npu","kv_load_failure_policy":"fail"}
```

Set `REDHARE_NIXL_TRANSPORT=1` on both peers. During validation, keep the
failure policy at `fail` so a transfer failure cannot be hidden by recomputation.
`install(force=True)` also applies the NPU worker and layout adapters when
installing explicitly.

Use [check_pd_npu.py](examples/check_pd_npu.py) to verify handoff bytes
and release accounting, and [bench_pd_npu.py](examples/bench_pd_npu.py)
to compare existing standalone and PD endpoints.

### Configuration

| variable | default | meaning |
| --- | --- | --- |
| `REDHARE_NIXL_TRANSPORT` | unset | `1` installs; `auto` installs only where RDMA hardware is absent; unset or `0` does nothing |
| `REDHARE_NIXL_ARENA` | `8GB` | pinned host arena per rank — the handoff buffer, which bounds requests in flight |
| `REDHARE_NIXL_CHUNK_BYTES` | `8388608` | target bytes per staged object |
| `REDHARE_NIXL_XFER_THREADS` | `8` | concurrent transfers (the data plane fans out within one) |
| `REDHARE_NIXL_TTL_MS` | `120000` | backstop lifetime of a staged request |
| `REDHARE_NIXL_EARLY_RELEASE` | `1` | let a producer free GPU blocks once its gather lands |
| `REDHARE_NIXL_ASSUME_RDMA` | unset | override the probe (`1`/`0`) |
| `REDHARE_NIXL_STATS_EVERY` | `0` | emit a stage-timing line every N transfers; `0` is off |

`REDHARE_NIXL_STATS_EVERY` splits a transfer into the control round trip
that asks the producer to gather and the pull itself. It logs at warning
level because vLLM reconfigures logging and info from this package does
not survive it.

`1` does not probe, deliberately. The probe answers *"does this host have
usable RDMA hardware"*, but the decision needs *"will these two peers
actually move bytes over it"*, and the two diverge in ordinary deployments:
two pods on one node never touch the NIC, an Ethernet fabric without RoCE
configured will not carry RDMA, and peers on different subnets may not
either.

`auto` uses the local hardware probe and logs at warning level when it
leaves NIXL on its own transport. "Usable hardware" means **both** an
openable `/dev/infiniband/uverbs*` device and an ACTIVE port in sysfs — a
container handed the PCI device but not the uverbs devices reports an ACTIVE
port and cannot do RDMA at all.

Both peers must run this transport. A stock NIXL peer is refused at
handshake with a message saying so, rather than quietly transferring
nothing.

Not supported: `NixlPushConnector` (the shim implements READ only), and
mixed RDMA/TCP fleets without `force` on the RDMA side.

