lmcache-cli 0.5.9rc3.dev0__py3-none-any.whl → 0.5.10.dev0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. lmcache/_version.py +3 -3
  2. lmcache/cli/commands/base.py +47 -0
  3. lmcache/cli/commands/bench/server_bench/allocator.py +29 -3
  4. lmcache/cli/commands/bench/server_bench/arguments.py +13 -1
  5. lmcache/cli/commands/bench/server_bench/cases/baseline.py +87 -1
  6. lmcache/cli/commands/bench/server_bench/client.py +6 -5
  7. lmcache/cli/commands/bench/server_bench/config.py +5 -0
  8. lmcache/cli/commands/describe.py +81 -33
  9. lmcache/cli/commands/memory.py +13 -11
  10. lmcache/cli/commands/query/_request.py +8 -0
  11. lmcache/cli/commands/query/engine_command.py +8 -0
  12. lmcache/cli/commands/server.py +13 -12
  13. lmcache/integration/vllm/lmcache_mp_connector.py +85 -42
  14. lmcache/integration/vllm/vllm_multi_process_adapter.py +64 -17
  15. lmcache/lmcache_frontend/app.py +110 -7
  16. lmcache/lmcache_frontend/static/js/app.js +113 -92
  17. lmcache/lmcache_native.pyi +0 -3
  18. lmcache/tools/cache_simulator/trace_analyze.py +16 -4
  19. lmcache/v1/client/heartbeat.py +32 -15
  20. lmcache/v1/common/kv_format/specs/base.py +2 -1
  21. lmcache/v1/common/utils.py +2 -2
  22. lmcache/v1/distributed/api.py +4 -0
  23. lmcache/v1/distributed/key_codec.py +29 -2
  24. lmcache/v1/distributed/l2_adapters/base.py +8 -0
  25. lmcache/v1/distributed/l2_adapters/dax_l2_adapter.py +100 -40
  26. lmcache/v1/distributed/l2_adapters/fs_l2_adapter.py +3 -18
  27. lmcache/v1/distributed/l2_adapters/gdr_peer_l2_adapter.py +284 -0
  28. lmcache/v1/distributed/l2_adapters/native_connector_l2_adapter.py +10 -5
  29. lmcache/v1/distributed/l2_adapters/nixl_store_dynamic_l2_adapter.py +35 -2
  30. lmcache/v1/distributed/l2_adapters/nixl_store_l2_adapter.py +74 -29
  31. lmcache/v1/distributed/l2_adapters/p2p_l2_adapter.py +333 -3
  32. lmcache/v1/distributed/l2_adapters/raw_block/core.py +34 -23
  33. lmcache/v1/distributed/storage_controllers/prefetch_controller.py +50 -5
  34. lmcache/v1/distributed/storage_manager.py +28 -0
  35. lmcache/v1/distributed/transfer_channel/abstract.py +19 -0
  36. lmcache/v1/distributed/transfer_channel/impl/nixl_impl.py +28 -0
  37. lmcache/v1/memory_management.py +51 -34
  38. lmcache/v1/memory_orchestrator/_proto_gen/__init__.py +1 -1
  39. lmcache/v1/multiprocess/engine_module.py +8 -2
  40. lmcache/v1/multiprocess/modules/blend/lookup.py +38 -6
  41. lmcache/v1/multiprocess/modules/engine_driven_transfer.py +10 -2
  42. lmcache/v1/multiprocess/modules/lmcache_driven_transfer.py +8 -2
  43. lmcache/v1/multiprocess/modules/lookup.py +89 -8
  44. lmcache/v1/multiprocess/modules/management.py +25 -2
  45. lmcache/v1/multiprocess/transport/grpc_impl/aio_server.py +2 -2
  46. lmcache/v1/platform/devices/musa/format_capabilities.py +4 -6
  47. lmcache/v1/platform/torch_ops/mp_mem_kernels.py +7 -11
  48. lmcache/v1/transport/grpc/_proto_gen/__init__.py +1 -1
  49. lmcache/v1/transport/grpc/_proto_gen/_generate.py +4 -1
  50. lmcache/v1/transport/grpc/descriptors.py +2 -2
  51. lmcache/v1/transport/grpc/protos/management_service.proto +10 -0
  52. lmcache/v1/transport/request_client.py +7 -0
  53. {lmcache_cli-0.5.9rc3.dev0.dist-info → lmcache_cli-0.5.10.dev0.dist-info}/METADATA +1 -1
  54. {lmcache_cli-0.5.9rc3.dev0.dist-info → lmcache_cli-0.5.10.dev0.dist-info}/RECORD +58 -60
  55. lmcache/v1/common/kv_format/specs/nl_x_nbbs_one_hs.py +0 -68
  56. lmcache/v1/common/kv_format/specs/two_x_nl_x_nb_bs_nh_hs.py +0 -65
  57. lmcache/v1/common/kv_format/specs/two_x_nl_x_nbbs_nh_hs.py +0 -70
  58. {lmcache_cli-0.5.9rc3.dev0.dist-info → lmcache_cli-0.5.10.dev0.dist-info}/WHEEL +0 -0
  59. {lmcache_cli-0.5.9rc3.dev0.dist-info → lmcache_cli-0.5.10.dev0.dist-info}/entry_points.txt +0 -0
  60. {lmcache_cli-0.5.9rc3.dev0.dist-info → lmcache_cli-0.5.10.dev0.dist-info}/licenses/LICENSE +0 -0
  61. {lmcache_cli-0.5.9rc3.dev0.dist-info → lmcache_cli-0.5.10.dev0.dist-info}/top_level.txt +0 -0
lmcache/_version.py CHANGED
@@ -18,7 +18,7 @@ version_tuple: tuple[int | str, ...]
18
18
  commit_id: str | None
19
19
  __commit_id__: str | None
20
20
 
21
- __version__ = version = '0.5.9rc3.dev0'
22
- __version_tuple__ = version_tuple = (0, 5, 9, 'rc3', 'dev0')
21
+ __version__ = version = '0.5.10.dev0'
22
+ __version_tuple__ = version_tuple = (0, 5, 10, 'dev0')
23
23
 
24
- __commit_id__ = commit_id = 'gce19803d6'
24
+ __commit_id__ = commit_id = 'g1f3b3a473'
@@ -6,6 +6,7 @@ from __future__ import annotations
6
6
 
7
7
  # Standard
8
8
  from collections.abc import Sequence
9
+ from pathlib import Path
9
10
  import abc
10
11
  import argparse
11
12
  import sys
@@ -60,6 +61,52 @@ def nonnegative_int(value: str) -> int:
60
61
  return count
61
62
 
62
63
 
64
+ def missing_grpc_bindings_hint(error: ImportError) -> str | None:
65
+ """Return how to produce the binding *error* shows as missing, or ``None``.
66
+
67
+ An editable ``pip install -e .`` runs the generator from ``build_py``, but
68
+ setuptools downgrades a failing custom ``build_py`` to a warning, so a
69
+ missing ``grpcio-tools`` leaves a package that imports without the
70
+ bindings and the commands that need them fail with an import error that
71
+ hides the cause. The failing import itself names what is missing, so the
72
+ remedy is tied to it and offered for nothing else. It runs the generator
73
+ from the repository, so it is only offered for a package installed from a
74
+ source checkout, where ``requirements/proto.txt`` sits next to it; the
75
+ ``lmcache-cli`` wheel ships without the bindings too, and its users get
76
+ ``None`` so that the caller's reinstall advice stands.
77
+
78
+ Args:
79
+ error: The ``ImportError`` raised while loading the command's runtime.
80
+
81
+ Returns:
82
+ The remedy, or ``None`` when *error* does not report a missing binding
83
+ or the package is not installed from a source checkout.
84
+ """
85
+ # <repository>/lmcache/cli/commands/base.py
86
+ repository_root = Path(__file__).resolve().parents[3]
87
+ if not (repository_root / "requirements" / "proto.txt").is_file():
88
+ return None
89
+ name = error.name
90
+ if name is None:
91
+ return None
92
+ if error.path is None:
93
+ # "No module named <package>.<binding>": the binding is the leaf.
94
+ package, _, binding = name.rpartition(".")
95
+ if not binding.endswith(("_pb2", "_pb2_grpc")):
96
+ return None
97
+ else:
98
+ # "cannot import name <binding> from <package>": the name is the package.
99
+ package = name
100
+ if not package.endswith("._proto_gen"):
101
+ return None
102
+ return (
103
+ "This installation is missing LMCache's generated gRPC bindings. "
104
+ "From the repository root, regenerate them with:\n"
105
+ " pip install -r requirements/proto.txt\n"
106
+ " python lmcache/v1/transport/grpc/_proto_gen/_generate.py"
107
+ )
108
+
109
+
63
110
  def _route_head(tokens: Sequence[str]) -> tuple[str | None, list[str]]:
64
111
  """Split the current level's route head off the remaining tokens.
65
112
 
@@ -27,22 +27,48 @@ class RequestBlocks:
27
27
 
28
28
 
29
29
  class BlockAllocator:
30
- """Single-threaded, request-exclusive allocation without prefix sharing."""
30
+ """Single-threaded, request-exclusive allocation without prefix sharing.
31
+
32
+ The server's null block (``--null-block-id``, default ``0``) is never
33
+ handed out: the MP server drops every chunk whose block ids are all
34
+ null, so allocating it would silently lose data (issue #6741).
35
+ An id outside the pool (e.g. the server's ``-1`` marker) reserves
36
+ nothing, as on the server: ids are non-negative, so the marker never
37
+ collides with a real block.
38
+ """
31
39
 
32
40
  def __init__(
33
41
  self,
34
42
  groups: int,
35
43
  capacity: int,
36
44
  *,
45
+ null_block_id: int = 0,
37
46
  allocation_order: Literal["sequential", "random"] = "sequential",
38
47
  seed: int = 0,
39
48
  ) -> None:
40
- """Create one free pool per group with a reproducible allocation order."""
49
+ """Create one free pool per group with a reproducible allocation order.
50
+
51
+ Args:
52
+ groups: Number of engine groups, each with its own pool.
53
+ capacity: Block id space size per group (ids ``0..capacity-1``);
54
+ the null block is excluded, leaving ``capacity - 1``
55
+ allocatable blocks when it is in range.
56
+ null_block_id: The server's null block marker. An id inside
57
+ the pool is reserved away; an id outside it (e.g. ``-1``)
58
+ reserves nothing, mirroring the server, whose block ids are
59
+ non-negative and never equal such a marker.
60
+ allocation_order: Hand out the lowest free ids or sample randomly.
61
+ seed: Seed for the random allocation order.
62
+
63
+ Raises:
64
+ ValueError: If groups or capacity is negative or the allocation
65
+ order is unsupported.
66
+ """
41
67
  if groups < 0 or capacity < 0:
42
68
  raise ValueError("groups and capacity must be non-negative")
43
69
  if allocation_order not in ("sequential", "random"):
44
70
  raise ValueError(f"unsupported allocation order: {allocation_order}")
45
- self._free = [set(range(capacity)) for _ in range(groups)]
71
+ self._free = [set(range(capacity)) - {null_block_id} for _ in range(groups)]
46
72
  self._allocation_order = allocation_order
47
73
  self._random = random.Random(seed)
48
74
 
@@ -143,7 +143,10 @@ def add_server_arguments(parser: argparse.ArgumentParser) -> None:
143
143
  "--num-blocks",
144
144
  type=int,
145
145
  default=1024,
146
- help="Paged blocks (default: 1024)",
146
+ help=(
147
+ "Fallback block count per group, including any reserved null block "
148
+ "(default: 1024)"
149
+ ),
147
150
  )
148
151
  kv.add_argument(
149
152
  "--block-size",
@@ -151,6 +154,15 @@ def add_server_arguments(parser: argparse.ArgumentParser) -> None:
151
154
  default=16,
152
155
  help="Tokens per block (default: 16)",
153
156
  )
157
+ kv.add_argument(
158
+ "--null-block-id",
159
+ type=int,
160
+ default=0,
161
+ help=(
162
+ "Match the server's --null-block-id (default: 0). "
163
+ "An ID in [0, NB) reserves one block per group."
164
+ ),
165
+ )
154
166
 
155
167
  parser.add_argument(
156
168
  "--start",
@@ -16,10 +16,18 @@ import time
16
16
  from lmcache.cli.commands.bench.server_bench.cases.base import BenchResult
17
17
  from lmcache.cli.commands.bench.server_bench.client import (
18
18
  LookupResult,
19
+ RequestContext,
19
20
  ServerBenchClient,
20
21
  TransferResult,
21
22
  )
22
23
 
24
+ # A STORE reply can arrive before the stored objects are visible to lookups
25
+ # (lmcache_driven mode commits them with a later stream callback). A warm
26
+ # LOOKUP that fully misses, or hits only a prefix, right after a successful cold
27
+ # STORE is retried for at most this long before it is accepted as a real one.
28
+ _VISIBILITY_RETRY_INTERVAL_S = 0.01
29
+ _VISIBILITY_RETRY_BUDGET_S = 0.5
30
+
23
31
 
24
32
  def _lookup_succeeded(outcome: _RequestOutcome | None) -> bool:
25
33
  return outcome is not None and outcome.lookup.succeeded
@@ -33,6 +41,21 @@ def _transfer_succeeded(transfer: TransferResult | None) -> bool:
33
41
  )
34
42
 
35
43
 
44
+ def _not_yet_visible(lookup: LookupResult) -> bool:
45
+ """Whether a warm LOOKUP may still be racing the cold STORE: nothing found,
46
+ or only a prefix found."""
47
+ return lookup.is_full_miss or lookup.is_partial_hit
48
+
49
+
50
+ def _stored_new_chunks(outcome: _RequestOutcome | None) -> bool:
51
+ """Return whether a cold request stored chunks the warm one must find."""
52
+ return (
53
+ outcome is not None
54
+ and outcome.store is not None
55
+ and _transfer_succeeded(outcome.store)
56
+ )
57
+
58
+
36
59
  @dataclass(frozen=True)
37
60
  class _RequestOutcome:
38
61
  """Outcome of one cold or warm request."""
@@ -122,7 +145,13 @@ class BaselineBenchCase:
122
145
 
123
146
  time.sleep(self.interval_seconds)
124
147
 
125
- warm_outcome = self._execute_request(client, sequence_id, "warm")
148
+ warm_outcome = self._execute_request(
149
+ client,
150
+ sequence_id,
151
+ "warm",
152
+ expect_visible=_stored_new_chunks(cold_outcome),
153
+ log=log,
154
+ )
126
155
  self._record_request_latencies(result, "warm", warm_outcome)
127
156
 
128
157
  result.completed_runs += 1
@@ -218,6 +247,8 @@ class BaselineBenchCase:
218
247
  client: ServerBenchClient,
219
248
  sequence_id: int,
220
249
  request_kind: Literal["cold", "warm"],
250
+ expect_visible: bool = False,
251
+ log: Callable[[str], None] | None = None,
221
252
  ) -> _RequestOutcome | None:
222
253
  # First Party
223
254
  from lmcache.cli.commands.bench.server_bench.helpers import _build_token_ids
@@ -233,6 +264,8 @@ class BaselineBenchCase:
233
264
 
234
265
  try:
235
266
  lookup = client.lookup(request)
267
+ if expect_visible:
268
+ lookup = self._retry_until_visible(client, request, lookup, log)
236
269
  if not lookup.succeeded:
237
270
  return _RequestOutcome(lookup=lookup)
238
271
 
@@ -290,3 +323,56 @@ class BaselineBenchCase:
290
323
  )
291
324
  finally:
292
325
  client.release_request(request)
326
+
327
+ @staticmethod
328
+ def _retry_until_visible(
329
+ client: ServerBenchClient,
330
+ request: RequestContext,
331
+ lookup: LookupResult,
332
+ log: Callable[[str], None] | None,
333
+ ) -> LookupResult:
334
+ """Re-run a warm LOOKUP that missed, or only partly hit, a just-completed STORE.
335
+
336
+ The STORE reply does not mean the objects are readable yet: the warm
337
+ LOOKUP can miss everything, or see just a cached prefix while the newly
338
+ stored chunks are still write-locked. The retry is bounded, so a store
339
+ the server really dropped still shows as a miss or a partial hit.
340
+ """
341
+ deadline = time.monotonic() + _VISIBILITY_RETRY_BUDGET_S
342
+ retries = 0
343
+ while _not_yet_visible(lookup) and time.monotonic() < deadline:
344
+ time.sleep(_VISIBILITY_RETRY_INTERVAL_S)
345
+ # The sleep may cross the deadline; do not start a LOOKUP after it.
346
+ if time.monotonic() >= deadline:
347
+ break
348
+ lookup = client.lookup(request)
349
+ retries += 1
350
+ if retries and log is not None:
351
+ if not lookup.succeeded:
352
+ log(
353
+ " [seq %d/warm] LOOKUP retried %d time(s); the last retry "
354
+ "failed: %s" % (request.sequence_id, retries, lookup.error)
355
+ )
356
+ elif lookup.is_full_miss:
357
+ log(
358
+ " [seq %d/warm] LOOKUP retried %d time(s); cold STORE "
359
+ "still not visible after retry budget"
360
+ % (request.sequence_id, retries)
361
+ )
362
+ elif lookup.is_partial_hit:
363
+ log(
364
+ " [seq %d/warm] LOOKUP retried %d time(s); cold STORE "
365
+ "still not fully visible after retry budget (%d of %d chunks)"
366
+ % (
367
+ request.sequence_id,
368
+ retries,
369
+ lookup.hit_chunks,
370
+ lookup.total_chunks,
371
+ )
372
+ )
373
+ else:
374
+ log(
375
+ " [seq %d/warm] LOOKUP retried %d time(s) until the cold "
376
+ "STORE was visible" % (request.sequence_id, retries)
377
+ )
378
+ return lookup
@@ -250,15 +250,16 @@ class ServerBenchClient:
250
250
  ready.set()
251
251
  for future in warmup:
252
252
  future.result(timeout=self._config.transfer_timeout_s)
253
+ self._allocator = BlockAllocator(
254
+ self._num_engine_group_infos,
255
+ self._num_blocks,
256
+ null_block_id=self._config.null_block_id,
257
+ allocation_order=self._config.block_allocation,
258
+ )
253
259
  except BaseException:
254
260
  self.close()
255
261
  raise
256
262
 
257
- self._allocator = BlockAllocator(
258
- self._num_engine_group_infos,
259
- self._num_blocks,
260
- allocation_order=self._config.block_allocation,
261
- )
262
263
  self._started = True
263
264
 
264
265
  def create_request(
@@ -36,6 +36,9 @@ class BenchConfig:
36
36
  concurrency: Number of clients sending requests at the same time.
37
37
  isolated_ipc: Whether clients use the isolated IPC policy.
38
38
  block_allocation: Allocate the lowest free IDs or sample free IDs randomly.
39
+ null_block_id: Server null block id; an id inside the block pool
40
+ is excluded from allocation, an id outside it (e.g. ``-1``)
41
+ reserves nothing, mirroring the server.
39
42
  transfer_timeout_s: Positive, finite shared wait budget per transfer call.
40
43
  """
41
44
 
@@ -53,6 +56,7 @@ class BenchConfig:
53
56
  isolated_ipc: bool = False
54
57
  block_allocation: Literal["sequential", "random"] = "sequential"
55
58
  transfer_timeout_s: float = 10.0
59
+ null_block_id: int = 0
56
60
 
57
61
  def __post_init__(self) -> None:
58
62
  if self.mode not in ("cpu", "gpu"):
@@ -157,5 +161,6 @@ def parse_args_to_config(args: argparse.Namespace) -> BenchConfig:
157
161
  concurrency=int(getattr(args, "concurrency", 1)),
158
162
  isolated_ipc=args.isolated_ipc,
159
163
  block_allocation=getattr(args, "block_allocation", "sequential"),
164
+ null_block_id=int(getattr(args, "null_block_id", 0)),
160
165
  transfer_timeout_s=float(getattr(args, "transfer_timeout", 10.0)),
161
166
  )
@@ -31,7 +31,7 @@ from lmcache.cli.http import (
31
31
 
32
32
  if TYPE_CHECKING:
33
33
  # First Party
34
- from lmcache.v1.common.metrics import Metrics
34
+ from lmcache.v1.common.metrics import Metrics, Section
35
35
 
36
36
  # -------------------------------------------------------------------
37
37
  # Shared helpers
@@ -42,7 +42,28 @@ class DescribeError(Exception):
42
42
  """Raised when the describe command cannot fetch or parse status data."""
43
43
 
44
44
 
45
+ # ``/metrics`` is optional for every target, so it gets a short timeout, while
46
+ # the required ``/status`` and ``/v1/models`` fetches keep their 10 s. It is a
47
+ # socket timeout: it bounds inactivity, so an endpoint that hangs delays the
48
+ # report by about this many seconds, but it does not cap the total time of a
49
+ # response that keeps arriving slowly.
50
+ METRICS_TIMEOUT = 2
51
+
52
+ # vLLM engine metrics (``vllm/v1/metrics/loggers.py``), named by Prometheus
53
+ # family. Without a KV connector the external counters stay at 0.
45
54
  _RUNNING_REQUESTS = "vllm:num_requests_running"
55
+ PREFIX_CACHE_QUERIES = "vllm:prefix_cache_queries"
56
+ PREFIX_CACHE_HITS = "vllm:prefix_cache_hits"
57
+ EXTERNAL_CACHE_QUERIES = "vllm:external_prefix_cache_queries"
58
+ EXTERNAL_CACHE_HITS = "vllm:external_prefix_cache_hits"
59
+
60
+ ENGINE_METRIC_NAMES: tuple[str, ...] = (
61
+ _RUNNING_REQUESTS,
62
+ PREFIX_CACHE_QUERIES,
63
+ PREFIX_CACHE_HITS,
64
+ EXTERNAL_CACHE_QUERIES,
65
+ EXTERNAL_CACHE_HITS,
66
+ )
46
67
 
47
68
 
48
69
  # Lookup counters exported by the MP server's metrics subscriber
@@ -100,30 +121,8 @@ def fetch_health(url: str, timeout: int = 10) -> bool:
100
121
  return False
101
122
 
102
123
 
103
- def fetch_running_requests(url: str, timeout: int = 10) -> int | None:
104
- """Return the number of in-flight requests from a vLLM ``/metrics`` page.
105
-
106
- Parses the Prometheus ``vllm:num_requests_running`` gauge, summing the
107
- value across all reported series (e.g. one per model). This is best
108
- effort: the metric is informational, so any failure to fetch or parse
109
- degrades to ``None`` (rendered as ``N/A``) rather than raising.
110
-
111
- Args:
112
- url: Full ``/metrics`` URL to GET.
113
- timeout: Socket timeout in seconds.
114
-
115
- Returns:
116
- The total running-request count, or ``None`` if the endpoint is
117
- unreachable or the metric is absent (e.g. metrics disabled or an
118
- unsupported engine version).
119
- """
120
- totals = fetch_metric_totals(url, [_RUNNING_REQUESTS], timeout=timeout)
121
- running = totals.get(_RUNNING_REQUESTS)
122
- return int(running) if running is not None else None
123
-
124
-
125
124
  def fetch_metric_totals(
126
- url: str, names: Iterable[str], timeout: int = 10
125
+ url: str, names: Iterable[str], timeout: int = METRICS_TIMEOUT
127
126
  ) -> dict[str, float]:
128
127
  """Sum Prometheus metric families from a ``/metrics`` page.
129
128
 
@@ -136,7 +135,8 @@ def fetch_metric_totals(
136
135
  Args:
137
136
  url: Full ``/metrics`` URL to GET.
138
137
  names: Metric family names to read.
139
- timeout: Socket timeout in seconds.
138
+ timeout: Socket timeout in seconds. It bounds inactivity (connecting
139
+ and each read), not the total time of the fetch.
140
140
 
141
141
  Returns:
142
142
  A mapping from each requested family found on the page to its sum.
@@ -514,7 +514,8 @@ class EngineDescriber:
514
514
 
515
515
  Reads model identity and context window from the engine's
516
516
  ``/v1/models`` response and combines them with a ``/health`` liveness
517
- result to render a concise status view.
517
+ result and the engine's ``/metrics`` totals to render a concise status
518
+ view.
518
519
  """
519
520
 
520
521
  def __init__(
@@ -522,18 +523,30 @@ class EngineDescriber:
522
523
  metrics: "Metrics",
523
524
  models_data: dict,
524
525
  is_healthy: bool,
525
- running_requests: int | None,
526
+ metric_totals: dict[str, float],
526
527
  base_url: str,
527
528
  ) -> None:
529
+ """Bind the inputs for one ``describe engine`` report.
530
+
531
+ Args:
532
+ metrics: The output collector to populate.
533
+ models_data: The engine's ``/v1/models`` response.
534
+ is_healthy: Whether ``/health`` answered HTTP 200.
535
+ metric_totals: Metric sums from the engine's ``/metrics``, as
536
+ returned by :func:`fetch_metric_totals` for
537
+ :data:`ENGINE_METRIC_NAMES`; missing names render as ``N/A``.
538
+ base_url: The normalized engine URL.
539
+ """
528
540
  self.metrics = metrics
529
541
  self.models_data = models_data
530
542
  self.is_healthy = is_healthy
531
- self.running_requests = running_requests
543
+ self.metric_totals = metric_totals
532
544
  self.base_url = base_url
533
545
 
534
546
  def describe(self) -> None:
535
547
  """Run all section builders and emit."""
536
548
  self.add_overview()
549
+ self.add_cache_hits()
537
550
  self.metrics.emit()
538
551
 
539
552
  def add_overview(self) -> None:
@@ -546,7 +559,44 @@ class EngineDescriber:
546
559
  model.get("max_model_len") if model else None,
547
560
  )
548
561
  self.metrics.add("status", "Status", fmt_health(self.is_healthy))
549
- self.metrics.add("running_requests", "Running requests", self.running_requests)
562
+ self.metrics.add(
563
+ "running_requests", "Running requests", self._count(_RUNNING_REQUESTS)
564
+ )
565
+
566
+ def add_cache_hits(self) -> None:
567
+ """Prefix and external cache hit counts and rates since engine start.
568
+
569
+ Adds the ``cache_hits`` section from :attr:`metric_totals`. Token
570
+ counts missing from ``/metrics`` are ``None`` (``N/A``); a rate is
571
+ ``None`` when either operand is missing or its denominator is 0, as
572
+ the external rate is without a KV connector.
573
+ """
574
+ sec = self.metrics.add_section("cache_hits", "Cache hits (since engine start)")
575
+ self._add_hit_rows(
576
+ sec, "prefix_cache", "Prefix cache", PREFIX_CACHE_QUERIES, PREFIX_CACHE_HITS
577
+ )
578
+ self._add_hit_rows(
579
+ sec,
580
+ "external_cache",
581
+ "External cache",
582
+ EXTERNAL_CACHE_QUERIES,
583
+ EXTERNAL_CACHE_HITS,
584
+ )
585
+
586
+ def _add_hit_rows(
587
+ self, sec: "Section", key: str, label: str, queries_name: str, hits_name: str
588
+ ) -> None:
589
+ """Add the query, hit and hit-rate rows for one cache to *sec*."""
590
+ queries = self._count(queries_name)
591
+ hits = self._count(hits_name)
592
+ sec.add(f"{key}_query_tokens", f"{label} queries (tokens)", queries)
593
+ sec.add(f"{key}_hit_tokens", f"{label} hits (tokens)", hits)
594
+ sec.add(f"{key}_hit_rate", f"{label} hit rate (%)", fmt_hit_rate(hits, queries))
595
+
596
+ def _count(self, name: str) -> int | None:
597
+ """Return the summed metric *name* as an integer, or ``None``."""
598
+ value = self.metric_totals.get(name)
599
+ return int(value) if value is not None else None
550
600
 
551
601
  def _first_model(self) -> dict | None:
552
602
  """Return the first model entry from a ``/v1/models`` response."""
@@ -612,8 +662,6 @@ class DescribeCommand(BaseCommand):
612
662
  sys.exit(1)
613
663
 
614
664
  is_healthy = fetch_health(f"{base_url}/health")
615
- running_requests = fetch_running_requests(f"{base_url}/metrics")
665
+ metric_totals = fetch_metric_totals(f"{base_url}/metrics", ENGINE_METRIC_NAMES)
616
666
  metrics = self.create_metrics("Inference Engine", args, width=50)
617
- EngineDescriber(
618
- metrics, models, is_healthy, running_requests, base_url
619
- ).describe()
667
+ EngineDescriber(metrics, models, is_healthy, metric_totals, base_url).describe()
@@ -6,7 +6,7 @@ import argparse
6
6
  import sys
7
7
 
8
8
  # First Party
9
- from lmcache.cli.commands.base import BaseCommand
9
+ from lmcache.cli.commands.base import BaseCommand, missing_grpc_bindings_hint
10
10
  from lmcache.v1.common.logging import init_logger
11
11
 
12
12
  logger = init_logger(__name__)
@@ -30,9 +30,10 @@ class MemoryCommand(BaseCommand):
30
30
  """Add the orchestrator flags, shared with
31
31
  ``python -m lmcache.v1.memory_orchestrator``.
32
32
 
33
- Skips registration when the orchestrator dependencies (gRPC and its
34
- generated bindings) are not installed; ``execute`` then prints an
35
- actionable error.
33
+ When the orchestrator runtime cannot be imported, logs the remedy and
34
+ skips registration; ``execute`` then prints the same remedy: an
35
+ editable build that skipped the gRPC generator is pointed at it, a
36
+ lightweight ``lmcache-cli`` install at ``pip install lmcache``.
36
37
 
37
38
  Args:
38
39
  parser: The ``ArgumentParser`` for this subcommand.
@@ -41,11 +42,10 @@ class MemoryCommand(BaseCommand):
41
42
  # First Party
42
43
  from lmcache.v1.memory_orchestrator.server import add_orchestrator_args
43
44
  except ImportError as e:
44
- logger.warning(
45
- "Memory orchestrator dependencies are missing (%s); install the "
46
- "full lmcache package to use 'memory'.",
47
- e,
45
+ advice = missing_grpc_bindings_hint(e) or (
46
+ "install the full lmcache package to use 'memory'."
48
47
  )
48
+ logger.warning("Cannot load the memory orchestrator (%s); %s", e, advice)
49
49
  return
50
50
  add_orchestrator_args(parser)
51
51
 
@@ -67,10 +67,12 @@ class MemoryCommand(BaseCommand):
67
67
  parse_args_to_orchestrator_config,
68
68
  serve,
69
69
  )
70
- except ImportError:
70
+ except ImportError as e:
71
71
  print(
72
- "The 'lmcache memory' command requires the full lmcache "
73
- "installation.\nInstall with: pip install lmcache",
72
+ f"The 'lmcache memory' command cannot load its runtime: {e}",
73
+ missing_grpc_bindings_hint(e)
74
+ or "Install the full lmcache package with: pip install lmcache",
75
+ sep="\n",
74
76
  file=sys.stderr,
75
77
  )
76
78
  sys.exit(1)
@@ -15,6 +15,7 @@ MetricMap = dict[str, MetricValue]
15
15
  _METRIC_NAMES = {
16
16
  "prompt_tokens": "Input tokens",
17
17
  "output_tokens": "Output tokens",
18
+ "cached_tokens": "Cached tokens",
18
19
  "ttft_ms": "TTFT (ms)",
19
20
  "tpot_ms_per_token": "TPOT (ms/token)",
20
21
  "total_latency_ms": "Total latency (ms)",
@@ -278,6 +279,12 @@ def _stream(
278
279
 
279
280
  u = usage or {}
280
281
  prompt_tokens = int(u.get("prompt_tokens") or 0)
282
+ details = u.get("prompt_tokens_details")
283
+ cached_tokens: Optional[int] = None
284
+ if isinstance(details, dict):
285
+ reported = details.get("cached_tokens")
286
+ if reported is not None:
287
+ cached_tokens = int(reported)
281
288
  num_completion = u.get("completion_tokens")
282
289
  num_generated = int(num_completion) if num_completion is not None else max_tokens
283
290
  if first_token_t is None:
@@ -296,6 +303,7 @@ def _stream(
296
303
  "answer": joined,
297
304
  "prompt_tokens": prompt_tokens,
298
305
  "output_tokens": num_generated,
306
+ "cached_tokens": cached_tokens,
299
307
  "ttft_ms": ttft_s * 1000.0,
300
308
  "tpot_ms_per_token": tpot_s * 1000.0,
301
309
  "total_latency_ms": dt * 1000.0,
@@ -96,6 +96,14 @@ class EngineCommand(BaseCommand):
96
96
  metrics.add("prompt_tokens", prompt_name, int(prompt_value))
97
97
  output_name, output_value = engine_stats["output_tokens"]
98
98
  metrics.add("output_tokens", output_name, int(output_value))
99
+ cached = engine_stats.pop("cached_tokens", None)
100
+ if cached is not None:
101
+ cached_name, cached_value = cached
102
+ if cached_value is None:
103
+ cached_name = (
104
+ "Cached tokens (n/a; enable --enable-prompt-tokens-details)"
105
+ )
106
+ metrics.add("cached_tokens", cached_name, cached_value)
99
107
 
100
108
  latency = metrics.add_section("latency", "Latency Metrics")
101
109
  for key, (name, value) in engine_stats.items():
@@ -5,7 +5,7 @@
5
5
  import argparse
6
6
 
7
7
  # First Party
8
- from lmcache.cli.commands.base import BaseCommand
8
+ from lmcache.cli.commands.base import BaseCommand, missing_grpc_bindings_hint
9
9
  from lmcache.v1.common.logging import init_logger
10
10
 
11
11
  logger = init_logger(__name__)
@@ -35,9 +35,10 @@ class ServerCommand(BaseCommand):
35
35
 
36
36
  Composes argument groups from the multiprocess, storage manager,
37
37
  HTTP frontend, Prometheus, and telemetry config modules.
38
- Silently skips argument registration when server dependencies
39
- (e.g. CUDA extensions) are not installed; ``execute`` will then
40
- print an actionable error.
38
+ When the server runtime cannot be imported, logs the remedy and skips
39
+ argument registration; ``execute`` then prints the same remedy: an
40
+ editable build that skipped the gRPC generator is pointed at it, a
41
+ lightweight ``lmcache-cli`` install at ``pip install lmcache``.
41
42
 
42
43
  Args:
43
44
  parser: The ``ArgumentParser`` for this subcommand.
@@ -60,11 +61,10 @@ class ServerCommand(BaseCommand):
60
61
  add_observability_args(parser)
61
62
  add_coordinator_args(parser)
62
63
  except ImportError as e:
63
- logger.warning(
64
- "lmcache-cli (lightweight) detected (%s); install the full "
65
- "lmcache package to use 'server' and 'bench'.",
66
- e,
64
+ advice = missing_grpc_bindings_hint(e) or (
65
+ "install the full lmcache package to use 'server' and 'bench'."
67
66
  )
67
+ logger.warning("Cannot load the 'server' runtime (%s); %s", e, advice)
68
68
  return
69
69
 
70
70
  def execute(self, args: argparse.Namespace) -> None:
@@ -92,11 +92,12 @@ class ServerCommand(BaseCommand):
92
92
  )
93
93
  from lmcache.v1.multiprocess.http_auth import HTTPAuthenticationConfig
94
94
  from lmcache.v1.multiprocess.http_server import run_http_server
95
- except ImportError:
95
+ except ImportError as e:
96
96
  print(
97
- "The 'lmcache server' command requires the full lmcache "
98
- "installation with CUDA extensions.\n"
99
- "Install with: pip install lmcache",
97
+ f"The 'lmcache server' command cannot load its runtime: {e}",
98
+ missing_grpc_bindings_hint(e)
99
+ or "Install the full lmcache package with: pip install lmcache",
100
+ sep="\n",
100
101
  file=sys.stderr,
101
102
  )
102
103
  sys.exit(1)