多服务器协调#

当您运行多个 LMCache 多进程(MP)服务器时,MP 协调器是一个独立服务,各服务器向其注册,从而为您提供覆盖所有运行中服务器的单一全局视图。每个 MP 服务器独立缓存;协调器将它们整合为一个统一管理的集群。

运行协调器#

协调器是一个 FastAPI 服务。使用以下命令启动它:

lmcache coordinator

预期的日志输出:

LMCache INFO: MP coordinator listening on http://127.0.0.1:9300

By default, the coordinator is reachable only from the local machine. For MP servers on other hosts, bind it to a reachable interface explicitly, for example lmcache coordinator --host <COORDINATOR_IP>, and configure API-key authentication before exposing it to an untrusted network.

See lmcache coordinator for the full flag list. Equivalently, the coordinator can be launched as a module with python3 -m lmcache.v1.mp_coordinator, which accepts the same flags.

配置#

The coordinator is configured through CLI flags only; every flag left unset keeps the default below.

Flag

默认

描述

--host

127.0.0.1

HTTP服务器绑定的主机。

--port

9300

HTTP服务器绑定的端口。

--instance-timeout

30

超过此秒数未收到心跳后,服务器将从集群中移除。

--health-check-interval

10

Seconds between health-check sweeps that expire stale MP-server registrations. 0 disables the stale-instance eviction loop; it does not affect the /quota L2 eviction loop (see --eviction-check-interval below).

--eviction-check-interval

5

L2 逐出清扫之间的秒数。0 禁用循环。

--eviction-ratio

0.2

每个周期逐出的跟踪键的比例(按计数,范围为 0.0 到 1.0)。

--trigger-watermark

1.0

当使用量达到配额的该比例时触发逐出(取值范围为 (0.0, 1.0],不含 0.0)。

--chunk-size

256

每个 KV 块的令牌数:CacheBlend 匹配单元和用于将固定的 token_ids 解析为键的单元。必须等于 MP 服务器的 --chunk-size。

--hash-algorithm

blake3

用于 pin 密钥解析的令牌哈希算法。必须与 MP 服务器的 --hash-algorithm 相等。blake3 是自包含的;其他算法需要在协调器进程中可导入的 vLLM。

--enable-blend-lookup

off

Index stored chunk content so POST /directory/blend-lookup can serve fleet CacheBlend reuse. Off by default: hashing content costs CPU on every store. Also requires the MP servers' --coordinator-event-reporting.

--blend-probe-stride

1

Positions between CacheBlend match probes. 1 probes every offset for full recall. Ignored unless blend lookup is on.

--checkpoint-path

(empty)

File the coordinator's derived state is checkpointed to. Empty disables it and the coordinator starts cold after every restart.

--checkpoint-interval

60

Seconds between checkpoint writes; 0 writes only on a clean stop. Ignored without a path. Does not affect the metadata file, which is written whenever pins or quotas change.

--metadata-path

(empty)

File the operator-set state (L2 pins and per-cache_salt quotas) is stored in. Empty means that state is lost on restart.

--public-endpoint PATH

/healthz

Serve PATH without credentials when API-key authentication is on. Repeat the flag for several paths. The value replaces the default list, which is /healthz alone, rather than extending it. Matching is exact: no prefix or wildcard rules.

--no-public-endpoints

off

Require a valid API key for every HTTP path, including /healthz. Cannot be combined with --public-endpoint.

--extra-config

(empty)

JSON object of settings the core flags do not name, read by whichever view or controller looks for them. Two keys are read by the coordinator itself: controller_packages, a list of importable paths to load out-of-tree controllers from, and disabled_controllers, a list of class names to leave unbuilt -- which is how one of those takes a built-in controller's place instead of running beside it.

--timeout-keep-alive

10

HTTP 服务器在关闭空闲连接之前保持打开的秒数。必须大于 MP 服务器的心跳间隔(默认 5),否则心跳请求可能会遇到关闭的连接并失败,出现 服务器在未发送响应的情况下断开连接。

--disable-metrics

off

Skip OpenTelemetry metrics initialization. Metrics are on by default; pass this flag and the local /metrics endpoint returns 404.

--otlp-endpoint

unset

OTLP gRPC endpoint for metrics push mode. When unset, Prometheus pull mode exposes /metrics on the coordinator HTTP port. When set, the local /metrics endpoint returns 404.

--event-transport

http

Transport the fleet's cache events arrive on, exactly one. http serves POST /events; kafka consumes --kafka-topic instead (one CacheEventsRequest JSON envelope per record, the same body POST /events accepts) and POST /events answers 404. kafka needs the lmcache[kafka] extra (pip install 'lmcache[kafka]').

--kafka-bootstrap-servers

(empty)

Comma-separated Kafka bootstrap servers. Required with --event-transport kafka.

--kafka-topic

lmcache-cache-events

Topic to consume; must match the MP servers' --coordinator-kafka-topic. Ignored unless --event-transport kafka.

--kafka-group-id

lmcache-coordinator

Consumer group the coordinator joins, which decides how partitions are shared between members. Where a restart resumes comes from the checkpoint, not the group; with no checkpoint it reads the whole retained stream. Ignored unless --event-transport kafka.

Loading your own controllers#

A controller gives the coordinator behaviour of its own — fleet-wide L2 eviction is one, warm-prefetch dispatch is another. Add yours by putting it in any importable package and naming that package in --extra-config. The package imports from lmcache; nothing in lmcache imports it.

# acme_controllers/reaper.py
import asyncio
from contextlib import asynccontextmanager

from fastapi import APIRouter
from lmcache.v1.mp_coordinator.controllers.base import Controller
from lmcache.v1.mp_coordinator.views.instance_registry import InstanceRegistry


class ReaperController(Controller):
    @classmethod
    def from_config(cls, config, views):
        obj = cls()
        obj.registry = views.get(InstanceRegistry)                  # a shared view
        obj.interval = config.extra_config.get("acme.interval", 30.0)
        obj.last_seen = 0
        return obj

    @asynccontextmanager
    async def run(self, runtime):                    # background work
        task = asyncio.create_task(self._sweep())    # 1. start
        try:
            yield                                    # 2. serve
        finally:
            task.cancel()                            # 3. stop

    def get_routers(self):                           # your endpoints
        router = APIRouter()

        @router.get("/acme/reaper")
        async def status():
            return {"last_seen": self.last_seen}

        return (router,)

    async def _sweep(self):
        while True:
            await asyncio.sleep(self.interval)
            self.last_seen = len(self.registry.all_instances())

run is an async context manager and must do three things, in order:

  1. Start the background work.

  2. yield exactly once — the coordinator serves for the duration of that yield.

  3. Stop the work in a finally, so teardown runs whether shutdown was clean or an exception unwound the stack.

The same JSON names the package and carries the controller's own settings:

lmcache coordinator --extra-config '{
  "controller_packages": ["acme_controllers"],
  "acme.interval": 10
}'

curl -s http://localhost:9300/acme/reaper
# -> {"last_seen": 2}

Every hook is optional: write only run, only get_routers, or add consume to receive the cache-event stream and get_durable_components to have your state checkpointed. Name a package — scanned entire, so a controller that outgrows one file can be a directory — or a single module. A name that does not import raises at startup; a controller that raises while starting is logged and skipped. Views cannot be added this way: they are the coordinator's own shared state, which your controller reads.

Disabling a built-in controller. Name its class in disabled_controllers and it is not built, taking its endpoints with it — which is how a controller of your own replaces one rather than running beside it:

lmcache coordinator --extra-config '{
  "controller_packages": ["acme_controllers"],
  "disabled_controllers": ["FleetEvictionController"]
}'

A name matching no discovered controller raises at startup.

Coordinator metrics export#

Metrics are enabled by default. Without an OTLP endpoint, Prometheus scrapes the coordinator's existing FastAPI port; no separate metrics server or port is created:

curl -H "Authorization: Bearer $FLEET_KEY" http://localhost:9300/metrics

/metrics requires the fleet key: the gauges describe placement and reported-byte counts, so the coordinator does not publish them to an unauthenticated caller. The only path served without credentials is /healthz, the liveness probe.

--public-endpoint replaces that default rather than extending it, so a deployment that wants public metrics has to name the probe as well:

lmcache coordinator --api-key-file /run/secrets/fleet-key \
    --public-endpoint /healthz --public-endpoint /metrics

Passing only --public-endpoint /metrics makes /healthz require the key, and an orchestrator's probe would then get 401 and restart the pod. If that is what you want, Kubernetes httpGet probes can send a credential:

livenessProbe:
  httpGet:
    path: /healthz
    port: 9300
    httpHeaders:
      - name: Authorization
        value: Bearer <fleet-key>

--no-public-endpoints goes one step further and requires a key for every path, including the probe.

A scraper sends the credential through Prometheus' credentials_file:

scrape_configs:
  - job_name: lmcache-coordinator
    authorization:
      credentials_file: /etc/prometheus/lmcache-fleet-key
    static_configs:
      - targets: ["coordinator:9300"]

The file must contain the raw key, which is the same value the coordinator accepts through --api-key-file.

Set --otlp-endpoint http://collector:4317 to push metrics to an OpenTelemetry Collector instead. In OTLP push mode, and when --disable-metrics is set, GET /metrics returns 404. The Coordinator exports Key Directory placement and reported-logical-byte gauges for the l1 and l2 tiers, under the lmcache_coordinator. prefix. See 指标 for their exact names and semantics.

连接 MP 服务器#

当您通过 --coordinator-url 为 MP 服务器(lmcache server)指定协调器地址时,该服务器便会加入协调器。它在启动时注册、运行时持续发送心跳、关闭时注销——所有操作均在服务器自身的事件循环中完成。此功能为可选项:若未设置 URL,服务器的行为与之前完全相同。每个标志均可回退到对应的 LMCACHE_COORDINATOR_* 环境变量(在使用 Kubernetes Downward API 时非常便捷);显式标志优先于环境变量。

标志(在 MP 服务器上)

环境回退

描述

--coordinator-url

LMCACHE_COORDINATOR_URL

协调器基础 URL,例如 http://coordinator:9300。设置后启用注册。

--coordinator-advertise-ip

LMCACHE_COORDINATOR_ADVERTISE_IP

协调器应通过此服务器访问的 IP(默认为服务器的外部 IP)。

--coordinator-heartbeat-interval

LMCACHE_COORDINATOR_HEARTBEAT_INTERVAL

心跳之间的秒数(必须为 > 0,默认值为 5)。保持远低于协调器的 INSTANCE_TIMEOUT。

--coordinator-event-reporting

LMCACHE_COORDINATOR_EVENT_REPORTING

Stream cache store/access/delete events to the coordinator, feeding the key directory (fleet-wide placement tracking) and, for L2 events, usage/quota tracking and eviction.

--coordinator-event-flush-interval

LMCACHE_COORDINATOR_EVENT_FLUSH_INTERVAL

Seconds between cache-event batch flushes (must be > 0, default 1).

--coordinator-event-transport

(none)

Event delivery transport: http (default) or kafka.

--coordinator-kafka-bootstrap-servers

(none)

Comma-separated Kafka bootstrap servers. Required for the kafka event transport.

--coordinator-kafka-topic

(none)

Kafka event topic (default lmcache-cache-events).

--coordinator-kafka-delivery-timeout

(none)

Seconds the Kafka producer retries a record before dropping it (default 300).

With the Kafka transport, start the coordinator with --event-transport kafka and the same topic so it consumes the stream instead of serving POST /events; without that, the broker retains the records but nothing reads them. Both sides need the optional lmcache[kafka] extra (pip install 'lmcache[kafka]'), imported only when Kafka is selected. The lmcache/vllm-openai and lmcache/standalone images include it. A restarted coordinator resumes from its consumer group's committed offsets; coordinator-driven replay of a detected gap is a follow-up.

服务器在其稳定身份下注册(--instance-id / OTel service.instance.id);如果未传递该标志,服务器将在启动时生成一个随机的 UUID v4 并在该 UUID 下注册。

注册是尽力而为的:如果协调器无法访问,MP 服务器会记录警告,持续重试,并继续提供服务。启动时会拒绝格式错误的心跳间隔值。

HTTP 端点#

协调器的 HTTP 接口(基础 URL http://localhost:9300)分为:

  • Fleet membership and health -- registration, liveness, and a debugging snapshot (/instances, /healthz, /status).

  • 配额、使用情况和逐出 -- /quota 组:每个租户的字节预算、使用情况核算,以及驱动全队逐出的使用事件摄取。

  • 缓存控制 -- /cache 组:分派给命名服务器的缓存操作(热预取、固定/解固定和删除,更多功能即将推出)。

  • Fleet memory -- the /instances/usage endpoints: how full each server's memory compartments are, joining event-derived usage against the capacity each server declares on the same event stream. Read-only.

  • CacheBlend fragment lookup -- POST /directory/blend-lookup: finds cached chunk content anywhere inside a query sequence, using the blend index derived from the key directory's token bindings. Server-to-coordinator only; not usually called by hand.

每个端点的文档如下。成功状态为 200,除非另有说明,{cache_salt} 使用 _default 哨兵表示空盐。数据类型位于 lmcache/v1/mp_coordinator/schemas.py。

小技巧

The read-only endpoints below can be read without curl and jq. lmcache query coordinator --api NAME fetches one of them — usage, instances, health, directory, keys, quota, quota-config, prefetch, or metrics — and prints it as an aligned table with byte counts and ratios already formatted. See lmcache query.

车队成员资格和健康状态#

MP servers register, heartbeat, and deregister automatically (see Connecting MP servers); GET /instances, GET /healthz and GET /status are read-only operator views.

POST /instances#

注册(或重新注册)一个 MP 服务器。每个服务器在启动时会自动调用。

请求体:

字段

类型

描述

ip

字符串

Bare IPv4 address, IPv6 address, or resolver host name of the server's HTTP API. Do not include a scheme, port, path, query, fragment, or userinfo; http_port supplies the port separately. Resolver-specific names such as Docker service names containing underscores are accepted.

http_port

整数

服务器 HTTP API 的端口。

instance_id

字符串

可选。服务器标识符;如果省略(或留空),协调器将生成一个并返回。

metadata

对象

可选。自由格式的 string -> string 注册提示。

p2p_advertised_url

字符串

可选。服务器为点对点传输宣传的 URL;在不处于 P2P 时为空。

mq_port

整数

Optional (default 0). Port of the P2P gRPC listener (--p2p-rpc-port) that P2P peers send lookup/unlock RPCs to. The field name is retained for compatibility. 0 when P2P is disabled.

响应 (200 OK):

{"instance_id": "server-1", "re_registered": false}

instance_id 是注册的 ID(当请求省略时生成的 ID);re_registered 在替换现有注册时为 true。

HTTP 状态码:

  • 200: 已注册。

  • 422: request body fails field-level validation (e.g. blank or URL-shaped ip, or out-of-range http_port).

示例:

curl -s -X POST http://localhost:9300/instances \
    -H 'Content-Type: application/json' \
    -d '{"ip": "10.0.0.5", "http_port": 8080}'
# -> {"instance_id": "mp-3f2c9d...", "re_registered": false}

PUT /instances/{instance_id}/heartbeat#

记录存活心跳。在服务器运行时自动调用。

路径参数: instance_id — 记录心跳的实例。

响应 (200 OK):

{"instance_id": "server-1"}

HTTP 状态码:

  • 200: 心跳已记录。

  • 404: 未知实例 — 调用者应通过 POST /instances 重新注册。

示例:

curl -s -X PUT http://localhost:9300/instances/server-1/heartbeat
# -> {"instance_id": "server-1"}

DELETE /instances/{instance_id}#

注销一个 MP 服务器。在关闭时自动调用。

路径参数: instance_id — 要注销的服务器。

响应: 204 No Content,返回一个空主体,无论实例是否已注册(幂等)。

HTTP 状态码:

  • 204: 已注销(对于未知实例也会返回此状态)。

示例:

curl -s -X DELETE http://localhost:9300/instances/server-1 -o /dev/null -w '%{http_code}\n'
# -> 204

GET /instances#

列出每个注册的 MP 服务器。

响应 (200 OK):

{
  "instances": [
    {
      "instance_id": "server-1",
      "ip": "10.0.0.5",
      "http_port": 8080,
      "registration_time": 1719000000.0,
      "metadata": {},
      "p2p_advertised_url": "",
      "mq_port": 0
    }
  ]
}

每个条目报告服务器的 instance_id、协调器访问的 ip / http_port、墙钟 registration_time``(纪元秒)、注册时提供的任何 ``metadata,以及用于点对点传输的 p2p_advertised_url / mq_port``(当 P2P 被禁用时为空 / ``0)。

HTTP 状态码:

  • 200: 已列出舰队(空舰队返回 {\"instances\": []})。

示例:

curl -s http://localhost:9300/instances

GET /healthz#

协调器存活探测(用于 Kubernetes)。

响应 (200 OK):

{"status": "healthy"}

HTTP 状态码:

  • 200: 协调器正常运行。

示例:

curl -s http://localhost:9300/healthz
# -> {"status": "healthy"}

GET /status#

One JSON snapshot of the coordinator's state, for a person debugging it. Each section reads the same snapshot the corresponding metrics read, so the page and the dashboards never disagree. Use /healthz for probes; this endpoint is for people.

Response (200 OK, trimmed to one consumer):

{
  "event_source": {"source_name": "http", "replay_capability": "none"},
  "ingest": {
    "batches_applied": 1,
    "batches_duplicate": 0,
    "batches_stale": 0,
    "batches_missing": 0,
    "events_dropped": 0,
    "streams": {
      "mp-0": {
        "incarnation": 1,
        "last_seq": 1,
        "gap_detected": false,
        "missing_batches": 0,
        "events_dropped": 0,
        "seconds_since_last_event": 1.1,
        "event_delivery_delay_seconds": null
      }
    }
  },
  "consumers": {
    "KeyDirectory": {
      "batches_delivered": 1,
      "apply_seconds": 0.00001,
      "consume_failures": 0,
      "fence_failures": 0
    }
  },
  "registry": {"seconds_since_heartbeat": {"mp-0": 1.1}},
  "controllers": {"FleetEvictionController": true, "PrefetchManager": true},
  "background_loops": {
    "health": {
      "interval_seconds": 10.0,
      "last_success_timestamp": 1792441340.6,
      "passes_ok": 2,
      "passes_failed": 0,
      "last_error": null,
      "last_error_timestamp": null,
      "seconds_since_last_success": 0.1
    }
  },
  "event_loop": {"blocked_seconds": 0.003}
}
  • event_source: the source feeding the coordinator. With Kafka it also carries reads: records read by outcome, partitions_assigned, and per partition unread_records and next_offsets (the position the next checkpoint records).

  • ingest: fleet-wide batch counts, and each server's stream under streams. gap_detected: true means the coordinator knows it is missing part of that server's cache.

  • consumers: each view or controller fed by the event stream. A non-zero consume_failures or fence_failures means that consumer now disagrees with the others.

  • registry: seconds since each registered server's last heartbeat.

  • controllers: false means the controller failed to start (see the startup logs) and its work is not happening.

  • background_loops: each periodic loop (health, checkpoint, eviction). last_error is the latest failed pass; it stays after later successes, so compare last_error_timestamp with last_success_timestamp. The checkpoint loop is absent when periodic checkpoints are off.

  • event_loop: total seconds the coordinator's event loop was blocked.

HTTP 状态码:

  • 200: always, so the page is available exactly when something is wrong.

示例:

curl -s http://localhost:9300/status

配额、使用情况和逐出#

/quota 组拥有每个 cache_salt 字节预算、其背后的实时使用情况核算,以及驱动全队逐出的使用事件流。 (MP 服务器暴露了一个节点本地的 /quota,形状相同;这是其全队对应的版本。)使用 _default 作为路径参数以针对空字符串盐。

警告

请勿将 MP 服务器的节点本地 /quota API 与协调器的 API 一起使用。这两者是独立的、不同步的配额注册表,在 同一共享 L2 上强制执行逐出:服务器端的强制执行者(在服务器运行每个盐的逐出策略时处于活动状态)使用严格的白名单语义——任何缺失于 其自身 表中的盐都会被完全逐出——并且它永远无法看到在协调器上注册的配额,反之亦然。混合这两者会产生相互竞争的逐出决策:服务器可以删除协调器认为在配额内的数据(或在默认限制生效之前仍然豁免的数据)。每个部署选择一个所有者——在协调器管理的部署中,仅通过协调器的 /quota API 注册配额,并保持服务器的节点本地配额表不变。

没有显式配额的盐由注册表的 默认限制 (PUT /quota/config) 管控。启动时默认值未设置,未配额的盐 免于 逐出 — 配额存储在内存中,因此一个新启动的(重新)协调器在外部配额控制器重新同步之前有一个空的配额表,而免配额的默认值防止在这一窗口内大规模逐出未知租户。在重新注册每个盐的配额后,控制器将默认值设置为 0 — 这是启动严格允许列表强制执行的信号(所有未配额盐下的字节将在下一个周期变为可逐出):

# 1. re-register every tenant quota
curl -s -X PUT http://localhost:9300/quota/user-a \
    -H 'Content-Type: application/json' -d '{"limit_gb": 10.0}'
# ... one PUT per tenant ...

# 2. arm eviction of everything else
curl -s -X PUT http://localhost:9300/quota/config \
    -H 'Content-Type: application/json' -d '{"default_limit_gb": 0}'
# -> {"default_limit_gb": 0.0}

When MP servers enable --coordinator-event-reporting, they stream cache store, access, and delete events to the coordinator's POST /events. Applied l2 batches also feed the quota side: the coordinator aggregates per-cache_salt usage, enforces quotas, and selects LRU keys to evict. Each batch carries the server's instance_id, incarnation, and a monotonically increasing sequence number (seq) scoped to that instance, so replays are deduplicated and lost batches are detected.

Active eviction loop. Every --eviction-check-interval seconds, the coordinator inspects per-salt usage against the registered quotas and, for any salt over the trigger watermark, picks LRU victims and dispatches a single DELETE /cache/objects to a uniformly random registered MP server. Because all MP servers share the same backing L2 (e.g. one S3 bucket), one dispatch evicts the keys for the whole fleet. The MP server's L2 adapter fires on_l2_keys_deleted listeners after the delete completes; those listeners ship delete events back through POST /events, which is what updates the coordinator's LRU + per-salt totals. Dispatch failures or no-instances-registered fall through to the next cycle — at-least-once semantics, safe because the S3 delete is idempotent.

Cold start. The coordinator's trackers are in-memory and are built only from the cache-event stream, so after a restart per-salt usage starts at zero even though the bytes are still resident in L2. Quotas under-report until enough events accumulate. Unquota'd salts are exempt from eviction until the quota controller sets a default limit, so a cold coordinator cannot mass-evict — but it can under-evict, and an operator re-arming quotas right after a restart should expect the usage numbers to climb toward the true value rather than start at it.

PUT /quota/config / GET /quota/config#

设置/读取未明确配额条目的盐的默认限制。

请求体 (PUT):

字段

类型

描述

default_limit_gb

浮动或空值

null``(启动默认值)使未配额的盐免于逐出;``0 启用严格的白名单执行(所有未配额的字节在下一个周期变为可逐出);正值为每个未配额的盐提供该字节预算。

tier

字符串

可选(默认 l2)。目前仅支持 l2。

响应 (200 OK):

{"default_limit_gb": 0.0}

HTTP 状态码:

  • 200: applied.

  • 503: the metadata file (--metadata-path) could not be written; the change was undone, so retry once the storage is fixed.

示例:

curl -s http://localhost:9300/quota/config
# -> {"default_limit_gb": null}          (boot state: unquota'd exempt)

curl -s -X PUT http://localhost:9300/quota/config \
    -H 'Content-Type: application/json' -d '{"default_limit_gb": 0}'
# -> {"default_limit_gb": 0.0}           (allowlist enforcement armed)

PUT /quota/{cache_salt}#

创建或更新租户的字节预算。

路径参数: cache_salt — 租户标识符 (_default 表示空盐)。

请求体:

字段

类型

描述

limit_gb

浮点数

以 GiB 为单位的字节预算;必须为 >= 0``(``0 会在下一个逐出周期清除租户的数据)。

tier

字符串

可选(默认 l2)。配额适用的缓存层级;目前仅支持 l2。

响应 (200 OK):

{"cache_salt": "user-a", "limit_gb": 10.0, "status": "ok"}

HTTP 状态码:

  • 200: 已应用配额。

  • 400: 无效的限制(负值或非有限值)。

  • 422: 请求体未通过字段级验证。

  • 503: the metadata file (--metadata-path) could not be written; the change was undone, so retry once the storage is fixed.

示例:

curl -s -X PUT http://localhost:9300/quota/user-a \
    -H 'Content-Type: application/json' \
    -d '{"limit_gb": 10.0}'
# -> {"cache_salt": "user-a", "limit_gb": 10.0, "status": "ok"}

DELETE /quota/{cache_salt}#

删除盐的配额条目。任何仍然缓存的字节将在下一个逐出周期变为超出预算(有效限制降至 0)。

路径参数: cache_salt — 租户标识符 (_default 表示空盐)。

查询参数: tier — 可选(默认 l2);配额适用的缓存层级。

响应 (200 OK):

{"cache_salt": "user-a", "limit_gb": 0.0, "status": "removed"}

当未为盐注册配额时,status 为 "not_found"``(仍然是 ``200 OK)。

HTTP 状态码:

  • 200: 已移除,或 not_found 如果不存在配额。

  • 503: the metadata file (--metadata-path) could not be written; the change was undone, so retry once the storage is fixed.

示例:

curl -s -X DELETE http://localhost:9300/quota/user-a
# -> {"cache_salt": "user-a", "limit_gb": 0.0, "status": "removed"}

GET /quota/{cache_salt}#

读取单个盐的配额和实时使用情况。

路径参数: cache_salt — 租户标识符 (_default 表示空盐)。

Query parameters: tier — l1 or l2 (default l2). Every field describes the requested tier. Quotas are enforced on L2 only, so an l1 read reports L1 usage with quota_exists: false and quota_limit_gb: 0.0 -- never the L2 budget, which governs different bytes.

响应 (200 OK):

{"cache_salt": "user-a", "quota_limit_gb": 10.0, "quota_exists": true, "usage_gb": 0.001}

quota_limit_gb 是以 GiB 为单位的配置限制(当未设置配额时为 0.0),quota_exists 表示是否注册了显式配额,usage_gb 是当前的总使用量。此端点对于未知的 salt 永远不会返回 404。

HTTP 状态码:

  • 200: 报告配额和使用情况。

示例:

curl -s http://localhost:9300/quota/user-a
# -> {"cache_salt": "user-a", "quota_limit_gb": 10.0, "quota_exists": true, "usage_gb": 0.001}

GET /quota#

列出总使用量和每个 salt 的详细信息。

Query parameters: tier — l1 or l2 (default l2). Every field describes the requested tier, and rows come from that tier's usage plus the quotas that apply to it -- so an l1 listing holds only salts with L1 bytes, each with quota_exists: false. all is rejected with 400, because a key resident in both tiers holds bytes in both and a cross-tier total would count it twice.

响应 (200 OK):

{
  "total_gb": 0.005,
  "by_cache_salt": [
    {"cache_salt": "user-a", "quota_limit_gb": 10.0, "quota_exists": true, "usage_gb": 0.001}
  ]
}

total_gb 是所有 salt 的总使用量(以 GiB 为单位);每个 by_cache_salt 条目具有与 GET /quota/{cache_salt} 响应相同的字段。

HTTP 状态码:

  • 200: 报告的使用情况。

示例:

curl -s http://localhost:9300/quota
# -> {"total_gb": 0.005, "by_cache_salt": [...]}

Usage events arrive on the fleet cache-event stream (POST /events); there is no separate quota ingestion endpoint. See docs/design/v1/mp_coordinator/cache_events.md for the batch format and routing semantics.

Key directory#

The /directory group is a read-only operator view of the fleet-wide key directory: which keys are cached, where (instance / tier / backend), and what token ids each chunk holds. The directory is eventually consistent soft state built from the servers' cache-event stream -- every answer is a hint to be validated at the owning server, never a guarantee.

GET /directory/keys#

List cached keys and their placements, one page at a time.

Query parameters:

Parameter

默认

描述

tier

all

Keep placements on this tier (l1 / l2; all keeps every tier).

instance_id

(empty)

Keep placements reported by this MP server (empty keeps every instance).

backend

(empty)

Keep placements on this backend, e.g. dram / fs (empty keeps every backend).

offset

0

Matching keys to skip (pagination).

limit

1000

Maximum keys to return (1 to 10000).

响应 (200 OK):

{
  "total": 2,
  "keys": [
    {
      "key": {
        "chunk_hash_hex": "aa12...",
        "model_name": "meta-llama/Llama-3.1-8B-Instruct",
        "kv_rank": 0,
        "object_group_id": 0,
        "cache_salt": ""
      },
      "placements": [
        {
          "instance_id": "server-1",
          "incarnation": 1719000000,
          "tier": "l1",
          "backend": "dram",
          "size_bytes": 1048576,
          "shared": false
        }
      ],
      "num_tokens": 256,
      "access_count": 7
    }
  ]
}

total counts every key with at least one placement matching the filters; keys is the requested page of them, each with only its matching placements. num_tokens reports how many token ids the directory knows for the key's chunk (0 = unknown) -- fetch the actual tokens via POST /directory/lookup, which exists precisely so listing pages stay small. access_count is the number of access events applied to the key since the directory first saw it. Pages of a changing directory may skip or repeat keys (snapshot semantics).

HTTP 状态码:

  • 200: page returned (an empty directory returns {"total": 0, "keys": []}).

  • 422: invalid parameter (negative offset, limit out of range, unknown tier).

示例:

# Everything on server-1's L1:
curl -s "http://localhost:9300/directory/keys?tier=l1&instance_id=server-1&limit=100"

POST /directory/lookup#

Resolve cache content to its placements and token ids. One endpoint, two forms -- supply exactly one:

  • keys form -- {"keys": [...]}: resolve keys you already have (e.g. from GET /directory/keys).

  • tokens form -- {"token_ids": [...], "model_name": ..., "world_size": ..., "cache_salt": ..., "tags": ...}: resolve a request's tokens to the keys of its complete chunks (the same fan-out the pin APIs use).

重要

token_ids must be the request's whole token sequence from position 0, not one chunk's worth. Chunk hashes are prefix-chained -- each chunk's key depends on every token before it -- so a mid-request slice resolves to different (nonexistent) keys. Trailing tokens that do not fill a chunk are ignored.

Request body (tokens form):

{
  "token_ids": [15496, 11, 995, 314],
  "model_name": "meta-llama/Llama-3.1-8B-Instruct",
  "world_size": 1,
  "cache_salt": "",
  "tags": {"adapter_revision": "abc123"}
}

Request body (keys form):

{
  "keys": [
    {
      "chunk_hash_hex": "aa12...",
      "model_name": "meta-llama/Llama-3.1-8B-Instruct",
      "kv_rank": 0,
      "object_group_id": 0,
      "cache_salt": "",
      "tags": {"adapter_revision": "abc123"}
    }
  ]
}

响应 (200 OK):

{
  "chunks": 1,
  "results": [
    {
      "key": {"chunk_hash_hex": "aa12...", "model_name": "...", "kv_rank": 0,
              "object_group_id": 0, "cache_salt": "",
              "tags": {"adapter_revision": "abc123"}},
      "placements": [
        {"instance_id": "server-1", "incarnation": 1770000000, "tier": "l1",
         "backend": "dram", "size_bytes": 8388608, "shared": false}
      ],
      "token_ids": [15496, 11, 995],
      "access_count": 7
    }
  ]
}

chunks is the number of complete chunks the tokens resolved to (keys form: the number of keys requested); results has one entry per resolved key, in request order (tokens form: chunks x the per-rank fan-out). placements is empty for keys the directory does not know; token_ids is empty when the directory has no tokens for the key's chunk (never stored with token reporting on, or not yet re-reported after an event gap). access_count is the number of access events applied to the key, 0 for unknown keys.

tags is optional (default {}) in both forms. For token-addressed content, pass the exact lmcache.tag.* values used at store time with the prefix removed. Empty tags select only untagged content, not every tag namespace. Tag names must be nonempty strings and values must be strings.

HTTP 状态码:

  • 200: results returned.

  • 400: the token sequence exceeds the per-request cap, or a resolution parameter is invalid (e.g. model_name contains @).

  • 422: neither or both forms supplied, model_name missing with token_ids, or a key is malformed (e.g. chunk_hash_hex is not hex).

Examples:

# Tokens form -- where is this prompt cached, and what does each chunk hold?
curl -s -X POST http://localhost:9300/directory/lookup \
  -H 'Content-Type: application/json' \
  -d '{"token_ids": [15496, 11, 995], "model_name": "m", "world_size": 1}'

# Keys form -- keys taken from GET /directory/keys:
curl -s -X POST http://localhost:9300/directory/lookup \
  -H 'Content-Type: application/json' \
  -d '{"keys": [{"chunk_hash_hex": "aa12...", "model_name": "m", "kv_rank": 0}]}'

缓存控制#

/cache 组将缓存操作分派到命名的 MP 服务器。它涵盖 热预取、固定/解固定 和 删除;进一步的缓存控制操作将在此处作为端点记录。

热预取(从 L2 预加载 L1)。 在请求到达之前,用已知提示的 KV 预热一个 MP 服务器的 L1,以便第一个请求命中 L1,而不是支付 L2 内联获取的费用——当您知道工作负载即将路由到节点(流量转移、热共享系统提示)时,这非常有用。

You describe the content by token ids -- the unit the cache speaks -- or by keys you already hold (from GET /directory/keys or POST /directory/lookup). Token ids always cover every chunk from position 0, since chunk hashes are prefix-chained; keys reach a chunk in the middle of a prompt without its prefix chunks. The coordinator forwards the supplied form alone to the named server, which resolves it, expands each chunk across the node's object groups and ranks, loads the chunks from L2 into L1, and retains them so a later lookup hits. The submit returns a request_id; poll the status endpoint until completed. The warm acquires no lock -- the poll simply reports progress and clears the server-side job once the load finishes.

POST /cache/prefetches#

Submit a warm prefetch of keys, or a token sequence, on one named server. Supply exactly one of keys / token_ids.

请求体:

字段

类型

描述

instance_id

字符串

目标 MP 服务器;必须已注册。

keys

列表[对象]

Keys form. Each key, in the wire form GET /directory/keys returns, names its chunk; the server warms that chunk in every object group and rank, with no sliding window (see the note below). The keys must agree on model, world size, cache_salt and tags; at most 10,000 keys. The fields below are then ignored.

model_name

字符串

Tokens form, required. Model whose layout sizes the target's L1 buffers.

world_size

整数

Tokens form, required. World size (>= 1) selecting the KV layout and the per-rank fan-out (1 for a single-GPU, TP=1 deployment).

token_ids

列表[int]

Tokens form. Prompt tokens whose complete chunk_size chunks are warmed; must match what was stored (same tokenizer / special tokens). A sub-chunk sequence is a noop.

cache_salt

字符串

可选(默认 "")。应用于生成键的每个租户隔离盐。

tags

map[string, string]

Optional (default {}). Matching tags used when the content was stored, without the lmcache.tag. prefix.

响应 (200 OK):

{"instance_id": "server-1", "request_id": "abc123", "chunks": 12, "status": "submitted"}

当序列短于一个块时,什么都不会被提交,request_id 为空:

{"instance_id": "server-1", "request_id": "", "chunks": 0, "status": "noop"}

request_id is the id to poll; chunks is the number of whole chunks submitted to warm (keys form: the distinct chunks the keys name).

HTTP 状态码:

  • 200:已提交(或如上所述的 noop)。

  • 404: 未知 ``instance_id``(未注册)。

  • 502: 目标服务器无法访问或拒绝了提交。

  • 422: request body fails field-level validation, supplies both or neither of keys / token_ids, omits model_name or world_size in the tokens form, carries more than 10,000 keys, or has keys that disagree on model, world size, cache_salt or tags (or whose kv_rank packs no world size).

备注

Sliding-window models: the two forms load different chunks. The tokens form keeps each object group's window, and a warm prefetch loads nothing on a model with a sliding-window group. The keys form names chunks that need not be a contiguous prefix, so it ignores the windows and loads every named chunk in every group, and those chunks stay in L1 until evicted. Serving is unaffected: a lookup still applies each group's window.

备注

单节点范围: 一个 instance_id 仅对该节点的分片进行预热。对于跨多个节点的模型,每个节点的实例需提交一个请求。

示例:

curl -s -X POST http://localhost:9300/cache/prefetches \
    -H 'Content-Type: application/json' \
    -d '{
        "instance_id": "server-1",
        "model_name": "Qwen/Qwen3-8B",
        "world_size": 1,
        "token_ids": [101, 102, 103, "..."],
        "cache_salt": "user-a",
        "tags": {"adapter_revision": "abc123"}
    }'
# -> {"instance_id": "server-1", "request_id": "abc123", "chunks": 12, "status": "submitted"}

# Keys form: warm one mid-prompt chunk found via /directory/lookup.
curl -s -X POST http://localhost:9300/cache/prefetches \
    -H 'Content-Type: application/json' \
    -d '{
        "instance_id": "server-1",
        "keys": [{
            "chunk_hash_hex": "aa12...",
            "model_name": "Qwen/Qwen3-8B",
            "kv_rank": 16777472,
            "object_group_id": 0,
            "cache_salt": "user-a",
            "tags": {"adapter_revision": "abc123"}
        }]
    }'
# -> {"instance_id": "server-1", "request_id": "def456", "chunks": 1, "status": "submitted"}

GET /cache/prefetches/{instance_id}/{request_id}#

轮询已提交的预热预取;响应将拥有服务器的状态及其代码逐字传递。

路径参数:

字段

类型

描述

instance_id

字符串

提交预取的服务器。

request_id

字符串

由 POST /cache/prefetches 返回的 id。

响应 (200 OK) 在加载运行时:

{"status": "pending"}

…并且一旦完成:

{"status": "completed", "found_keys": 12, "total_keys": 12}

found_keys 的 total_keys 请求块是常驻的。

HTTP 状态码:

  • 200: 状态报告(pending 或 completed)。

  • 404: 未知的 instance_id,或来自服务器的未知 request_id。

  • 502: 目标服务器无法访问。

示例:

curl -s http://localhost:9300/cache/prefetches/server-1/abc123
# -> {"status": "completed", "found_keys": 12, "total_keys": 12}

Pin/unpin (protecting cache from eviction). Pin cache so it is not evicted from L2 until unpinned. The coordinator records the keys in its L2 eviction plan (POST) or releases them (DELETE), excluding pinned keys from quota-based eviction, with no MP-server round-trip. L2 pins are fleet-wide (per cache_salt), so no target instance is named. One endpoint, two forms -- supply exactly one:

  • tokens form -- {"token_ids": [...], "model_name": ..., "world_size": ..., "cache_salt": ..., "tags": ...}: the coordinator resolves the token sequence to the keys of its complete chunks locally. Chunk hashes are prefix-chained, so this always covers every chunk from position 0.

  • keys form -- {"keys": [...]}: pin the chunks these keys name, in the same wire form GET /directory/keys and POST /directory/lookup return. Use it to pin a chunk in the middle of a prompt without its prefix chunks.

Local resolution requires the coordinator's chunk_size and hash_algorithm (see Configuration) to match the MP servers' --chunk-size / --hash-algorithm; otherwise the resolved keys will not match what was stored and the pin protects nothing.

A pin is on a whole chunk. A chunk is stored once per kv rank and, with object-group separation (the default), once per object group; a pin taken through any one of its keys covers every group and every rank of that key's world size, including copies not stored yet. Otherwise eviction or a delete could remove one rank's share and leave the pinned chunk unusable. GET /cache/pins therefore lists one entry per chunk, under its rank-0 key in group 0. One request pins (or unpins) each chunk once, however many of its keys it names, so a tokens-form pin at TP=2 is released by one unpin in either form.

POST /cache/pins#

Pin keys in the L2 eviction plan.

请求体:

字段

类型

描述

keys

列表[对象]

Keys form. Keys naming the chunks to pin, each {"chunk_hash_hex", "model_name", "kv_rank", "object_group_id", "cache_salt", "tags"}; at most 10,000. The other fields below are ignored.

token_ids

列表[int]

Tokens form. Prompt tokens whose complete chunks are pinned; must match what was stored. A sub-chunk sequence pins nothing (affected 0).

model_name

字符串

Tokens form, required. Model whose rank fan-out to use when resolving keys.

world_size

整数

Tokens form, required. World size (>= 1) selecting the per-rank fan-out.

cache_salt

字符串

Tokens form. Optional (default ""). Per-tenant isolation salt.

tags

map[string, string]

Tokens form. Optional (default {}). Matching tags used when the content was stored, without the lmcache.tag. prefix.

响应 (200 OK):

{"requested": 12, "affected": 12, "status": "pinned"}

requested is the number of whole chunks resolved (keys form: the distinct chunks the keys name, so one chunk's keys on several ranks or groups count once); affected is the number of keys the request resolved to (tokens form: chunks times the per-rank fan-out), each covering its whole chunk. Unlike POST /directory/lookup, which reports one chunks per key given, pin, delete and prefetch count chunks.

HTTP 状态码:

  • 200: 已固定。

  • 400: token_ids 超过每个请求的上限,或者 cache_salt 违反了其不变性。

  • 422: request body fails field-level validation, supplies both or neither of keys / token_ids, omits model_name or world_size in the tokens form, carries more than 10,000 keys, or has an undecodable key.

  • 503: the metadata file (--metadata-path) could not be written; the change was undone, so retry once the storage is fixed.

示例:

curl -s -X POST http://localhost:9300/cache/pins \
    -H 'Content-Type: application/json' \
    -d '{
        "model_name": "Qwen/Qwen3-8B",
        "world_size": 1,
        "token_ids": [101, 102, 103, "..."],
        "cache_salt": "user-a",
        "tags": {"adapter_revision": "abc123"}
    }'
# -> {"requested": 12, "affected": 12, "status": "pinned"}

# Keys form: pin one mid-prompt chunk found via /directory/lookup.
curl -s -X POST http://localhost:9300/cache/pins \
    -H 'Content-Type: application/json' \
    -d '{
        "keys": [{
            "chunk_hash_hex": "aa12...",
            "model_name": "Qwen/Qwen3-8B",
            "kv_rank": 0,
            "object_group_id": 0,
            "cache_salt": "user-a",
            "tags": {"adapter_revision": "abc123"}
        }]
    }'
# -> {"requested": 1, "affected": 1, "status": "pinned"}

备注

Requires event reporting. The coordinator can only exclude keys from eviction for a salt it is tracking, which requires the MP servers started with --coordinator-event-reporting (see Connecting MP servers).

DELETE /cache/pins#

Unpin keys from the L2 eviction plan. Same request body (either form) as POST /cache/pins. The response mirrors the pin (affected is the number of keys unpinned), with status "unpinned". Pins are reference-counted: a chunk pinned N times needs N unpins before it can be evicted.

HTTP 状态码: 与 POST /cache/pins 相同。

示例:

curl -s -X DELETE http://localhost:9300/cache/pins \
    -H 'Content-Type: application/json' \
    -d '{
        "model_name": "Qwen/Qwen3-8B",
        "world_size": 1,
        "token_ids": [101, 102, 103, "..."],
        "cache_salt": "user-a",
        "tags": {"adapter_revision": "abc123"}
    }'
# -> {"requested": 12, "affected": 12, "status": "unpinned"}

GET /cache/pins#

List the chunks currently pinned in the L2 eviction plan, one entry per chunk under its rank-0 key in object group 0.

Query parameters (all optional):

Parameter

类型

描述

cache_salt

字符串

Only keys with this salt. Default: all salts.

model_name

字符串

Only keys for this model. Default: all models.

offset

整数

Matching keys to skip (>= 0). Default 0.

limit

整数

Maximum keys to return (1-10000). Default 1000.

响应 (200 OK):

{
  "total": 12,
  "pins": [
    {
      "key": {
        "chunk_hash_hex": "aa12...",
        "model_name": "Qwen/Qwen3-8B",
        "kv_rank": 0,
        "object_group_id": 0,
        "cache_salt": "user-a",
        "tags": {"adapter_revision": "abc123"}
      },
      "pin_count": 2
    }
  ]
}

total is the number of pinned keys matching the filters; pins is the requested page in first-pinned order, each with its current pin_count.

HTTP 状态码:

  • 200: listed.

  • 422: offset or limit out of range.

示例:

curl -s 'http://localhost:9300/cache/pins?cache_salt=user-a&limit=100'

POST /cache/delete#

Delete keys, or a token sequence's keys, on one named server.

Request body: instance_id, the content in either form as documented for POST /cache/pins (keys, or model_name, world_size, token_ids, cache_salt and optional matching tags), plus tier (l1 / l2 / all) and force (bool, default false). When force is true, locked keys are deleted anyway (L1 read/write locks on the node and the coordinator's L2 pin set).

响应 (200 OK):

{"instance_id": "server-1", "requested": 12, "affected": 24, "skipped": 0, "status": "deleted"}

requested is the number of whole chunks resolved (keys form: the distinct chunks the keys name). A key names its chunk: it is expanded to every copy the coordinator's directory holds of that chunk in the key's parallel setup -- every object group and every kv rank of the same world size -- so any one of the chunk's keys removes the whole chunk, not one rank's share. If any copy is pinned, a non-force delete holds back every copy. The expanded keys are sent to the server in batches of at most 10,000, the most it accepts per request. affected and skipped are totals across the tiers acted on: affected counts L1 keys removed by the node plus L2 keys removed by the coordinator, and skipped counts L1 keys the node refused plus L2 keys held back for an L2 pin (non-force only). A chunk resident in both tiers (tier=all) contributes to both counts, so affected may be up to 2 x requested x world_size. A sub-chunk sequence returns status "noop".

HTTP 状态码:

  • 200: 已删除(或为 noop)。

  • 404:没有服务器在 instance_id 下注册。

  • 422: request body fails field-level validation, supplies both or neither of keys / token_ids, omits model_name or world_size in the tokens form, or carries more than 10,000 keys.

  • 502: the target server was unreachable or rejected a batch. Earlier batches stay deleted, and detail says how many keys were removed.

  • 503: a forced delete removed the keys, but dropping their pins could not be written to the metadata file; the pins are kept.

示例:

curl -s -X POST http://localhost:9300/cache/delete \
    -H 'Content-Type: application/json' \
    -d '{
        "instance_id": "server-1",
        "model_name": "Qwen/Qwen3-8B",
        "world_size": 1,
        "token_ids": [101, 102, 103, "..."],
        "cache_salt": "user-a",
        "tags": {"adapter_revision": "abc123"},
        "tier": "all",
        "force": false
    }'
# -> {"instance_id": "server-1", "requested": 12, "affected": 24, "skipped": 0, "status": "deleted"}

Fleet memory#

The /instances/usage endpoints report how full each MP server's memory compartments are. A compartment is one thing that owns bytes: the L1 pool of a backing medium, or one L2 adapter. It is identified by (tier, backend) -- the same pair cache events tag placements with.

Two inputs are joined, and both ride the cache-event stream. Usage is derived from the events the servers already publish. Capacity arrives as a capacity report on the same stream -- after registration, when a Device-DAX L1 arena is added or starts draining, and whenever an L2 adapter is added, removed, or reconfigured. Both are automatic; there is nothing to configure beyond pointing servers at a coordinator and leaving event reporting enabled.

备注

Capacity travels on the event stream, so disabling event reporting disables both halves together: every usage_ratio reads null (unknown) rather than a ratio against a stale declaration.

These endpoints are read-only. The coordinator never evicts or throttles based on them.

备注

usage_ratio is null whenever the server declared no capacity for a compartment, and this is common: the fs, mooncake, p2p, and sagemaker adapters expose no capacity setting at all, and s3 / raw_block report one only when you set max_capacity_gb / capacity_bytes. A null means unknown, never empty -- do not treat it as 0.

Ratios above 1.0 are reported as-is rather than capped. They can expose an incorrect declaration, and are also expected while a draining Device-DAX arena still holds live bytes that no longer count as usable capacity.

GET /instances/usage#

The whole fleet: every server's compartments, plus the shared pools.

响应 (200 OK):

{
  "instances": [
    {
      "instance_id": "server-1",
      "registered": true,
      "declared_capacity": true,
      "modules": [
        {"tier": "l1", "backend": "dram", "shared": false,
         "used_bytes": 10737418240, "capacity_bytes": 42949672960,
         "usage_ratio": 0.25},
        {"tier": "l2", "backend": "fs", "shared": false,
         "used_bytes": 7516192768, "capacity_bytes": 0,
         "usage_ratio": null}
      ]
    }
  ],
  "shared_modules": [
    {"tier": "l2", "backend": "s3", "shared": true,
     "used_bytes": 4398046511104, "capacity_bytes": 17592186044416,
     "usage_ratio": 0.25}
  ]
}

shared_modules holds storage several servers mount -- one S3 bucket, one CXL region. These are counted once for the fleet and appear in no instance's modules. Summing them per mounting server would multiply both the bytes and the capacity by the number of mounts. A declared pool is listed even while it holds no bytes, with used_bytes: 0.

A server appears when it is registered, when it still holds bytes, or when it declared capacity. registered: false therefore means a departed server whose L2 data outlived it; its L1 bytes are dropped when it goes.

示例:

# Which servers are most heavily loaded?
curl -s http://localhost:9300/instances/usage | jq -r '
  .instances[] | .instance_id as $i | .modules[]
  | select(.usage_ratio != null)
  | "\($i) \(.tier)/\(.backend) \((.usage_ratio*100|floor))%"'
# -> server-1 l1/dram 25%
# -> server-2 l1/dram 81%

GET /instances/{instance_id}/usage#

One server's compartments, in the same shape as an entry of instances above.

HTTP 状态码:

  • 200: found.

  • 404: the coordinator knows nothing about this id -- it is not registered, holds no bytes, and declared no capacity.

示例:

curl -s http://localhost:9300/instances/server-1/usage

A server whose L1 pool uses the default lazy allocator grows its heap on demand. Capacity here is the configured size, not the grown heap, so a freshly started server correctly reads near 0% rather than near full. Device-DAX L1 capacity is the sum of active arenas; draining arenas are excluded.

CacheBlend fragment lookup#

POST /directory/blend-lookup is the fragment counterpart to /directory/lookup: the query need not be a prefix, and each match reports where the content sits in the query and where it sat when stored, so the caller can re-RoPE it.

It is served from the blend index, derived from the key directory's token bindings — the coordinator learns content from the cache-event stream, not from a separate publish call. Both feeds default to off and both are required: the coordinator needs --enable-blend-lookup, and every MP server whose chunks should be discoverable needs --coordinator-event-reporting (a server with a coordinator URL but no event reporting warns at startup and matches locally only). Matching is chunked at the coordinator's --chunk-size — which must equal the MP servers' --chunk-size — probing every --blend-probe-stride positions.

Request body — the query tokens plus the caller's identity, which names the namespace matches are scoped to. model_name is not optional: without it there is no namespace to scope to.

字段

类型

描述

tokens_b64

字符串

Query tokens packed as base64 little-endian uint32 (see encode_tokens / decode_tokens in schemas.py). Required.

model_name

字符串

Model the caller retrieves under. Required.

world_size

整数

The caller's world size (TP x PP), selecting its rank fan-out. Defaults to 1.

cache_salt

字符串

The caller's per-tenant isolation salt. Defaults to "".

model_name / world_size / cache_salt are the same three fields /directory/lookup's tokens form carries, but serve a different purpose here: prefix lookup uses them to build the keys it resolves, while a fragment match already names a stored chunk hash and uses them to stay in the namespace the caller can retrieve from. The token encodings differ between the two endpoints for now.

响应 (200 OK):

{
  "matches": [
    {"chunk_hash": "ab12...", "old_st": 0,   "cur_st": 512},
    {"chunk_hash": "cd34...", "old_st": 256, "cur_st": 768}
  ]
}

chunk_hash is the chunk's content hash, which the caller expands to per-rank object keys with its own model, salt, and world size; old_st is its position in the stored sequence (re-RoPE source) and cur_st its position in the query (re-RoPE target). Matches are sorted ascending by cur_st, at most one per chunk, and may overlap — a caller that scatters them resolves overlaps itself. A query shorter than one chunk, or a coordinator without --enable-blend-lookup, returns {"matches": []}.

Only chunks some instance stored under the request's model_name / cache_salt / world_size are returned. A chunk hash names content and prefix only, so an unscoped match could name KV under another model or tenant, which the caller's own key expansion could never retrieve. Content held solely by another namespace therefore returns no match rather than one that misses at prefetch.

HTTP 状态码:

  • 200: lookup completed (an empty match list is not an error).

  • 422: tokens_b64 is not valid base64 or not a whole number of uint32 tokens, or it is supplied without model_name.

Index counts are reported under the blend key of GET /directory/stats.

POST /directory/blend-lookup accepts an optional tags map. Supply the exact lmcache.tag.* values used when storing the content, without that prefix:

{"model_name": "model", "world_size": 1, "token_ids": [1, 2, 3, 4],
 "cache_salt": "", "tags": {"adapter_revision": "abc123"}}

The map defaults to {}, selecting untagged content. Names must be nonempty strings and values must be strings. Matches are limited to the caller's complete model_name / cache_salt / world_size / tags namespace.