Metadata-Version: 2.4
Name: redhare
Version: 0.8.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)
# Optional: also block until Redis confirms each key's metadata is published;
# then 0 means every client can already see the object.
rc = store.batch_put_from_multi_buffers(keys, addrs, sizes, wait_for_metadata=True)
# 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)

# Publication probe, straight to Redis — bypasses local caches and locally
# staged-but-unpublished puts, so unlike batch_is_exist it never reports a
# pending object as present. Per key: (1, size) published, (0, 0) not
# published, (-1, 0) probe error.
rc = store.batch_probe_published(keys)

store.close()
```

The existing KV APIs return per-key `int` lists: `0` is success and `-1`
is failure. Their return conventions and connector behavior are unchanged.
EC uses the separate `ec_get_checked` receive API: `0` is success,
`1` is a safe miss, and unknown completion raises `UnknownCompletionError`.
Its `unknown_indices` list identifies all destinations requiring retention for
process life by zero-based batch index; completed siblings may be released.
Callers using an older native wheel without that attribute must retain every
submitted destination. The EC worker quarantines
that buffer/store, disables further shared reads on that worker for a bounded
window (`REDHARE_EC_SHARED_READS_DISABLE_MS`, default 60s; `0` restores
disabled-until-restart), and reports recompute; an existing local
encoder-cache hit still works.

## 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 reads use `data_plane_addr`. A remote write is reserved and
  fenced over `cache_node_rpc_addr`; with `transport="nixl"` the cache-node
  then pulls the payload over the data plane from the originator's registered
  buffers (`register_buffer`); unregistered sources and other transports send
  the payload on the RPC connection.
- 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.

## Multimodal encoder cache (ECRedhareConnector)

Experimental. A best-effort shared multimodal encoder cache over redhare
objects for vLLM's EC transfer path (recompute adjustment,
[docs/12-mm-cache-recompute-adjustment.md](../../docs/12-mm-cache-recompute-adjustment.md)):
an encoder-only producer (E, TP1) gather-PUTs each encoder output as one
ordinary shared object — 48-byte header + payload, write-once, best-effort;
a PD consumer (TP4, full encoder) reads and validates shared objects against
the identity both sides derive from the deployment generation and media.
NIXL reads only inputs admitted by vLLM's normal encoder cache and compute
budgets, directly into their final GPU tensors. The inputs remain on the
normal encoder schedule: the runner skips encoding when the tensor is
present, or encodes in the same step after a safe miss. Every TP rank
participates in a CPU-group success reduction before any tensor is committed;
any rank's miss makes all ranks encode. TCP keeps deferred host staging.

`ECRedhareConnector` inherits the existing `REDHARE_NIXL_READ_LANES`
setting (default **1** when unset); it does not set a separate EC lane count.
For example, `REDHARE_NIXL_READ_LANES=8 vllm serve ...` uses eight read
lanes for all NIXL stores in that process, including co-resident KV stores.
The default of one lane can serialize concurrent EC object reads on that
lane's mutex; multiple lanes can enable concurrent transfers, but an EC
throughput or TTFT improvement from eight lanes has not been independently
established. EC stores pass
`nixl_lazy_read_lanes=True`: read-lane agents are created in the
background on first use, so an idle EC store keeps a single agent
(and UCX progress thread), and reads arriving before a lane is ready
fall back to the control agent. Other `KvStore` callers keep the
main-equivalent eager policy, including their existing registration
failure contract. The EC connector never mutates the process environment.

NIXL receives the whole object into a GPU byte tensor and commits its
payload view without a second payload allocation or H2D copy. One step's
items share a single publication probe, a single checked batch GET and
one TP consensus collective over the ready flags. The native batch
submits item reads concurrently, but transfer-level parallelism depends
on lane availability: with the default one lane, reads can serialize on
its mutex; with `REDHARE_NIXL_READ_LANES=8`, up to eight ready read lanes
may serve independent reads in parallel. This is a capability, not a
guarantee that step latency equals the slowest item, nor an EC-specific
performance result. Only the 48-byte header is copied to the CPU for
validation. There is no GPU payload
prefetch before formal allocation, no receive pool, and no additional GPU
staging quota. `staging_capacity_bytes` applies only to TCP. NIXL retains
normal encoder compute reservations even when the GET hits; it does not
spend those reservations on extra work in this step.

NIXL requires original media (`--no-rewrite`). Metadata-only `ec_items`
requests are rejected before scheduling because they cannot safely fall
back to encoding. TCP retains their existing deferred delivery contract.
An unknown-completion receive is the memory-safety exception: its destination
and store remain quarantined until verified settlement, or for process life
if the operation is permanently stuck or a legacy wheel supplies no receipt.
Recomputation uses independent memory. Shared reads are temporarily disabled
(`REDHARE_EC_SHARED_READS_DISABLE_MS`, default 60s; `0` explicitly
means disabled until restart). Two *different* limits apply per worker:

- `REDHARE_EC_MAX_QUARANTINE_BYTES` (default **2 GiB**) is a
  **live hard bound** on retained destination bytes. Reaching it disables
  shared GETs until verified settlement restores capacity and backoff permits
  new reads; stuck or legacy holds cannot restore their retained capacity.
  A batch that cannot fit its worst-case retained bytes is rejected before
  DMA, though a smaller batch may fit.
- `REDHARE_EC_MAX_QUARANTINE_EVENTS` (default **4 events per rolling hour**)
  is a **rate limit**, not a lifetime shutdown threshold. On the fourth
  event within an hour, the disable window extends until the oldest event
  expires; isolated events across days/weeks do not accumulate toward
  a permanent event-count stop. `0` explicitly disables shared GETs.

Neither re-arming nor aging out events frees quarantined memory or
NIXL registrations. Native `unknown_indices` limits retention to actually
unconfirmed destinations; old native wheels conservatively retain the batch.
Unknown holders back off for at least the ordinary disable window (minimum
60s); safe misses do not back holders off. `shared_read_disables` counts
unknown-completion events, `quarantine_event_rate_limits` counts rate
suppressions, and `quarantined_bytes`/`quarantined_buffers` track
cumulative retention events. `quarantine_budget_disables` counts budget
disable events. A continuing hard-disable state emits a recurring error
warning every **5 minutes** while the worker is active. See
[EC receive ownership and settlement](#ec-receive-ownership-and-settlement)
for the receipt contract, live gauges and recovery conditions.

Discarding a read frees only connector-owned receive references. A tensor already
in vLLM's encoder cache remains owned by vLLM; rank-local tensors are cleared
for recomputation only in the step that actually schedules the encoder, so
one request's miss or cancellation cannot remove another request's input.

TCP host-staging buffers are pooled per object size and registered with the
store once on first reuse (`register_buffer`): a repeat fetch of the same
size reuses a pre-registered buffer instead of registering the same host allocation repeatedly. Pooled buffers are never freed
while the store lives (native registrations are permanent), so two
invariants bound the pool, both counted over ALL registered buffers —
free and borrowed alike, so borrowing cannot hide bytes from admission:
total registered memory stays within a quarter of the staging budget
(capped at 512MB) with at most 8 buffers per object size, and in-flight
staging plus free-pool bytes stay within `staging_capacity_bytes`. A
buffer whose one-time registration attempt fails is retained for the
store's lifetime (nixl registers per state with no rollback, so a failure
may be partial), and the first failure also stops further registration
attempts — later buffers were never offered for registration and drop
normally, so a persistent registration failure retains one buffer instead
of one per fetch; a fetch that cannot reuse or admit a pooled buffer takes
the fresh-buffer path unchanged.

**The cache is a losable optimization.** A failed publish, an evicted
object, a Redis outage or a dead holder can never fail an original-media
request: the PD recomputes in the current request through its own vision
encoder. No ticket, delivery hold or cross-stage retry protocol exists; a
duplicate publish (two E's, same content) is an idempotent write-once
discard — the first writer's object serves everyone. EC's dedicated
receive path reuses content-fingerprint validation (arena-slot reuse detection);
a transfer whose completion state is unknown quarantines its destination
and store until verified settlement. Permanently stuck receives and legacy
unknowns without receipts remain retained for process life. The worker
disables further shared reads according to the byte budget, event limit and
configured backoff, and recomputes using independent memory. No unconfirmed
destination is read, reused, committed, or returned to the staging pool.
Verified settlement permits disposal or fresh reuse, not trusting the failed
receive's contents. See [EC receive ownership and settlement](#ec-receive-ownership-and-settlement).
The EC read deadlines and completion classification do not change the
existing KV GET/range APIs, Attention KV connector, or Remote DRAM PUT path.
Metadata-only inputs (no pixels to encode) fail the request on a miss
instead of scheduling an impossible encode. Stock mode does not promise
cross-E zero-encode: every E encodes, and the shared object makes the
bytes reusable, not the computation skippable.

No vLLM patches are required: the connector runs on stock vLLM, and the
stock EPD proxy runs with `--no-rewrite` so the raw media (and processor /
media kwargs) reach P; both sides derive the same shared key from the
media content, so nothing redhare-specific rides the request.

**The consumer requires the V2 model runner** (leave
`VLLM_USE_V2_MODEL_RUNNER` unset, or set it to `1`): the connector defers
a request until its read resolves, and the read outcomes only flow back
through the V2 runner's EC hooks. Startup refuses a consumer configured
for the legacy runner, which would defer the first multimodal request
forever.

**EC reads require content fingerprints.** The checked read
(`ec_get_checked`) serves only objects whose metadata carries a content
fingerprint and refuses fingerprint-less objects as a plain miss, because
the reuse guard cannot validate their bytes. Sampling is on by default
(`REDHARE_FINGERPRINT_SAMPLE_BYTES=48`); with sampling disabled the EC
cache is inert (every read recomputes) but still correct.

A consistent E TP1 / PD TP4 pair (the two commands share one config
template):

```bash
# E: encoder-only producer, TP1
vllm serve "$MODEL" --mm-encoder-only --tensor-parallel-size 1 \
  --ec-transfer-config '{
      "ec_connector": "ECRedhareConnector",
      "ec_connector_module_path": "redhare.ec_connector.connector",
      "ec_role": "ec_producer",
      "ec_connector_extra_config": {
          "redis_url": "redis://10.0.0.1:6379",
          "embedding_cache_prefix": "gen-2026-11-09",
          "transport": "nixl",
          "capacity_bytes": "8GB"
      }
  }'

# PD: consumer, TP4 — full model (the vision encoder must be present)
vllm serve "$MODEL" --tensor-parallel-size 4 \
  --ec-transfer-config '{
      "ec_connector": "ECRedhareConnector",
      "ec_connector_module_path": "redhare.ec_connector.connector",
      "ec_role": "ec_consumer",
      "ec_connector_extra_config": {
          "redis_url": "redis://10.0.0.1:6379",
          "embedding_cache_prefix": "gen-2026-11-09",
          "transport": "nixl"
      }
  }'

# EPD proxy (stock script, raw media forwarded unchanged)
python3 examples/disaggregated/disaggregated_encoder/disagg_epd_proxy.py \
  --host 0.0.0.0 --port 8130 --no-rewrite \
  --encode-servers-urls http://e:8001 --decode-servers-urls http://pd:8002
```

Both sides must share the same `--model` identity and
`embedding_cache_prefix` (the namespace digest covers model + generation +
encoder output dtype).

**E/PD read-timeout configuration:** Set each producer E's `read_timeout_ms`
to **at least the largest `read_timeout_ms` of any consumer PD** that can
read from it (both default to 5000 ms). These settings are independent:
PD uses its value as the whole-object GET deadline, while E derives its
pinned-DRAM arena reuse quarantine from **E's** value plus 1000 ms. If a
PD's timeout increases, update the corresponding E instances too. This
time-based reuse delay is a mitigation, **not a DMA completion guarantee**:
an unconfirmed NIXL/RDMA receive may continue after its timeout, and a
sampled fingerprint is not a full payload checksum.

Connector keys (`ec_connector`, `ec_connector_module_path`, `ec_role`) sit at
the top level of `--ec-transfer-config`; vLLM reads every other key from
`ec_connector_extra_config` only (`get_from_extra_config` has no flat-key
fallback):

| key | default | meaning |
| --- | --- | --- |
| `redis_url` | required | `redis://`, `rediss://`, or `redis+sentinel://` metadata URL |
| `embedding_cache_prefix` | required | deployment generation; E and PD must match |
| `transport` | `nixl` | data-plane transport: `nixl` or `tcp` |
| `capacity_bytes` | `"8GB"` | producer: local DRAM capacity holding its published objects. A consumer never PUTs — its store is built with a 1MB arena, and its only host memory is the TCP staging pool |
| (producer store) | E's `read_timeout_ms + 1000` | producer pinned-arena reuse-quarantine delay; reduces the 30s default's interaction with the put reclaim loop. Match E's timeout to the longest consuming PD timeout as described above. This delay does not prove completion of unknown DMA; the core reclaim-loop fix is separate, pre-existing-on-main work |
| `cluster` | `redhare-ec` | Redis key namespace; keep deployments disjoint |
| `client_id` | `ec-<uuid>` | unique client id |
| `data_plane_addr` | `0.0.0.0:0` | peer data-plane address |
| `ttl_ms` | `1800000` | object TTL |
| `read_timeout_ms` | `5000` | consumer: whole-object GET deadline; producer: input to its reuse-quarantine delay. E must be configured at least as high as any corresponding PD |
| `staging_capacity_bytes` | `"8GB"` | TCP-only per-rank host staging bound; NIXL uses normal vLLM encoder admission |
| `max_object_bytes` | `134217728` | publish/read size cap |
| `device` | `cuda` | device for committed tensors |

Constraints: producers require `tensor_parallel_size=1` (plus
`pipeline_parallel_size=1` and `data_parallel_size=1`), and the encoder
output dtype must be float16 / bfloat16 / float32. A consumer may run TP>1:
every rank runs its own whole-object GET into its own receive memory, the
item commits only when every rank staged a validated copy, and any rank's
miss turns the whole group to a per-rank recompute. Cost: one data-plane
egress and one staging copy per rank.

Semantics worth knowing before operating it:

- TCP defers while reads are in flight. NIXL performs its reads only at the
  scheduled load hook, with normal compute/cache capacity already admitted.
  Both paths recompute original-media misses in the current request.
- TCP claims external presence only after every rank staged a validated copy.
  NIXL keeps `has_cache_item=False` so the normal encoder fallback remains
  scheduled and budgeted; successful GETs populate the cache before encoding.
- Only a fully validated read may enter the encoder cache; a header that
  does not match the request's derived identity is a miss (recompute), and
  an unknown-completion transfer quarantines the buffer/store and disables
  further shared reads on that worker for a bounded window
  (`REDHARE_EC_SHARED_READS_DISABLE_MS`, default 60s). A rolling
  4-events/hour threshold extends the temporary block. Exhausting the live
  retained-byte cap blocks reads until verified releases restore capacity
  and backoff expires; permanently stuck buffers do not restore capacity.
  Explicit zero-disable settings still require restart.
  Original-media requests recompute locally; existing local encoder-cache
  hits remain available.
- Metadata-only requests (no pixels) fail on a miss — the proxy's bounded
  retry re-encodes on E.


### EC receive ownership and settlement

`KvStore.ec_get_checked_owned(keys, addrs, sizes, owners, timeout_ms=5000)`
retains an actual Python owner for each destination and the store through every
receive. Each owner must keep its corresponding writable range alive; do not
resize, modify or reuse that range while a receive is unresolved. The EC worker
uses this method automatically, including registered host-buffer ownership.

Like `ec_get_checked`, it returns `0` for a checked hit and `1` for a safe miss.
`UnknownCompletionError.unknown_indices` identifies uncertain destinations;
`error.receive_handles[index]` is an `EcReceiveHandle`. These details are
best-effort: missing indices mean quarantine the entire batch; missing receipts
mean retain those destinations for process life. Its `is_settled()` synchronizes
with completed writer leases and permits releasing or reusing the allocation,
**not using its unvalidated contents**. `is_stuck()`
means the transport can no longer prove settlement and retains its resources for
process life. Timeout or caller cancellation alone never establishes settlement.

NIXL parks the request, both descriptor lists, ad hoc and applicable
pre-registered memory handles, and destination.
One EC watcher per lane polls pending receives. Only verified successful
completion permits reclamation. Every post/status error stays permanently
quarantined, even for a single descriptor: a failed UCX Flush does not prove
that its Read stopped. TCP retains host staging through detached task completion.
Local copy/fingerprint fence failures remain conservative process-lifetime
holds. Existing KV and remote-DRAM completion policies are unchanged.

Settlement permits safe release; actual Python owner destruction can happen
asynchronously after the last receipt is dropped.

The worker reports cumulative `verified_releases` / `verified_release_bytes`
and worker snapshots of `unsettled_bytes`, `unsettled_objects`,
`peak_unsettled_bytes`, `stuck_bytes`, and `shared_reads_disabled_ranks`.
Snapshots replace the previous value for the same worker (not TP rank), never
sum over steps. Live observations and recovery transitions are emitted; unchanged
idle snapshots are omitted. The historical peak is reported with active or
changed snapshots; the optional stats file still records the full per-worker
series. Verified releases restore the byte budget, but do not shorten the
backoff deadline recorded at the fault. Event limits, holder backoff and the
explicit zero-window restart policy remain in effect. Older native wheels use
the original process-lifetime quarantine.

