lmcache-cli 0.5.9rc2.dev0__py3-none-any.whl → 0.5.9rc3.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 (47) hide show
  1. lmcache/_version.py +3 -3
  2. lmcache/cli/commands/describe.py +140 -14
  3. lmcache/integration/atom/multi_process_adapter.py +24 -6
  4. lmcache/integration/sglang/unified_lmcache_mp_connector.py +25 -1
  5. lmcache/integration/tensorrt_llm/tensorrt_mp_adapter.py +23 -4
  6. lmcache/integration/vllm/mp_server_launcher.py +16 -1
  7. lmcache/lmcache_frontend/static/js/app.js +15 -10
  8. lmcache/tools/cache_simulator/trace_analyze.py +5 -4
  9. lmcache/usage_telemetry/metric_specs.py +3 -8
  10. lmcache/usage_telemetry/mp_continuous.py +2 -18
  11. lmcache/v1/distributed/internal_api.py +4 -0
  12. lmcache/v1/distributed/l1_manager/base.py +6 -0
  13. lmcache/v1/distributed/l2_adapters/raw_block/core.py +21 -1
  14. lmcache/v1/distributed/serde/fp8.py +12 -2
  15. lmcache/v1/distributed/storage_controllers/prefetch_controller.py +50 -2
  16. lmcache/v1/mp_coordinator/config.py +3 -5
  17. lmcache/v1/mp_coordinator/http_apis/dependencies.py +19 -41
  18. lmcache/v1/mp_coordinator/http_apis/instances_api.py +1 -1
  19. lmcache/v1/mp_coordinator/registrar.py +6 -41
  20. lmcache/v1/mp_coordinator/schemas.py +2 -13
  21. lmcache/v1/mp_coordinator/views/key_directory.py +0 -30
  22. lmcache/v1/multiprocess/config.py +4 -4
  23. lmcache/v1/multiprocess/engine_context.py +16 -140
  24. lmcache/v1/multiprocess/http_server.py +1 -1
  25. lmcache/v1/multiprocess/modules/blend/lookup.py +6 -6
  26. lmcache/v1/multiprocess/modules/blend/module.py +10 -13
  27. lmcache/v1/multiprocess/modules/blend/retrieve.py +1 -1
  28. lmcache/v1/multiprocess/modules/blend/store.py +2 -2
  29. lmcache/v1/multiprocess/modules/lmcache_driven_transfer.py +1 -1
  30. lmcache/v1/multiprocess/modules/lookup.py +3 -1
  31. lmcache/v1/multiprocess/modules/management.py +3 -20
  32. lmcache/v1/multiprocess/plugin_modules/qstore.py +1 -1
  33. lmcache/v1/multiprocess/server.py +2 -15
  34. lmcache/v1/multiprocess/session.py +3 -3
  35. lmcache/v1/platform/base/ipc_wrapper.py +36 -1
  36. lmcache/v1/platform/devices/musa/__init__.py +0 -5
  37. lmcache/v1/platform/devices/npu/event_ipc.py +30 -1
  38. lmcache/v1/transport/auth.py +1 -1
  39. lmcache/v1/transport/grpc/protos/management_service.proto +0 -10
  40. lmcache/v1/transport/request_client.py +0 -5
  41. {lmcache_cli-0.5.9rc2.dev0.dist-info → lmcache_cli-0.5.9rc3.dev0.dist-info}/METADATA +1 -1
  42. {lmcache_cli-0.5.9rc2.dev0.dist-info → lmcache_cli-0.5.9rc3.dev0.dist-info}/RECORD +46 -47
  43. lmcache/v1/mp_coordinator/http_apis/config_api.py +0 -26
  44. {lmcache_cli-0.5.9rc2.dev0.dist-info → lmcache_cli-0.5.9rc3.dev0.dist-info}/WHEEL +0 -0
  45. {lmcache_cli-0.5.9rc2.dev0.dist-info → lmcache_cli-0.5.9rc3.dev0.dist-info}/entry_points.txt +0 -0
  46. {lmcache_cli-0.5.9rc2.dev0.dist-info → lmcache_cli-0.5.9rc3.dev0.dist-info}/licenses/LICENSE +0 -0
  47. {lmcache_cli-0.5.9rc2.dev0.dist-info → lmcache_cli-0.5.9rc3.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.9rc2.dev0'
22
- __version_tuple__ = version_tuple = (0, 5, 9, 'rc2', 'dev0')
21
+ __version__ = version = '0.5.9rc3.dev0'
22
+ __version_tuple__ = version_tuple = (0, 5, 9, 'rc3', 'dev0')
23
23
 
24
- __commit_id__ = commit_id = 'g51428bcc2'
24
+ __commit_id__ = commit_id = 'gce19803d6'
@@ -7,8 +7,10 @@ Usage::
7
7
  """
8
8
 
9
9
  # Standard
10
- from typing import TYPE_CHECKING
10
+ from http.client import IncompleteRead
11
+ from typing import TYPE_CHECKING, Iterable
11
12
  import argparse
13
+ import math
12
14
  import sys
13
15
  import urllib.error
14
16
  import urllib.request
@@ -40,6 +42,28 @@ class DescribeError(Exception):
40
42
  """Raised when the describe command cannot fetch or parse status data."""
41
43
 
42
44
 
45
+ _RUNNING_REQUESTS = "vllm:num_requests_running"
46
+
47
+
48
+ # Lookup counters exported by the MP server's metrics subscriber
49
+ # (``lmcache/v1/mp_observability/subscribers/metrics/lookup.py``), named by
50
+ # Prometheus family as they appear on ``GET /metrics``.
51
+ LOOKUP_REQUESTED_TOKENS = "lmcache_mp_lookup_requested_tokens"
52
+ LOOKUP_HIT_TOKENS = "lmcache_mp_lookup_hit_tokens"
53
+ LOOKUP_HIT_L1_TOKENS = "lmcache_mp_lookup_hit_l1_tokens"
54
+ LOOKUP_HIT_L2_TOKENS = "lmcache_mp_lookup_hit_l2_tokens"
55
+ LOOKUP_PROMPT_TOKENS = "lmcache_mp_lookup_prompt_tokens"
56
+ LOOKUP_REQUEST_HIT_TOKENS = "lmcache_mp_lookup_request_hit_tokens"
57
+ HIT_COUNTER_NAMES: tuple[str, ...] = (
58
+ LOOKUP_REQUESTED_TOKENS,
59
+ LOOKUP_HIT_TOKENS,
60
+ LOOKUP_HIT_L1_TOKENS,
61
+ LOOKUP_HIT_L2_TOKENS,
62
+ LOOKUP_PROMPT_TOKENS,
63
+ LOOKUP_REQUEST_HIT_TOKENS,
64
+ )
65
+
66
+
43
67
  def fetch_json(url: str, timeout: int = 10) -> dict:
44
68
  """GET *url* and return the parsed JSON body.
45
69
 
@@ -93,27 +117,61 @@ def fetch_running_requests(url: str, timeout: int = 10) -> int | None:
93
117
  unreachable or the metric is absent (e.g. metrics disabled or an
94
118
  unsupported engine version).
95
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
+ def fetch_metric_totals(
126
+ url: str, names: Iterable[str], timeout: int = 10
127
+ ) -> dict[str, float]:
128
+ """Sum Prometheus metric families from a ``/metrics`` page.
129
+
130
+ Each requested family is summed across all its label series (e.g. one
131
+ per model or cache salt). Counters are named by family, without the
132
+ ``_total`` suffix (``lmcache_mp_lookup_hit_tokens`` reads
133
+ ``lmcache_mp_lookup_hit_tokens_total``); their ``_created`` timestamps
134
+ are not counted. This is best effort, for informational rows.
135
+
136
+ Args:
137
+ url: Full ``/metrics`` URL to GET.
138
+ names: Metric family names to read.
139
+ timeout: Socket timeout in seconds.
140
+
141
+ Returns:
142
+ A mapping from each requested family found on the page to its sum.
143
+ Families absent from the page or with a non-finite sum (``NaN`` or
144
+ ``Inf``) are omitted, and an unreachable, truncated or unparsable
145
+ page yields an empty mapping.
146
+ """
147
+ wanted = set(names)
96
148
  try:
97
149
  with urllib.request.urlopen(
98
150
  urllib.request.Request(url), timeout=timeout
99
151
  ) as resp:
100
152
  text = resp.read().decode()
101
- except (urllib.error.URLError, OSError):
102
- return None
153
+ except (urllib.error.URLError, OSError, IncompleteRead, UnicodeDecodeError):
154
+ return {}
103
155
 
104
- total = 0.0
105
- found = False
156
+ totals: dict[str, float] = {}
106
157
  try:
107
158
  for family in text_string_to_metric_families(text):
108
- if family.name != "vllm:num_requests_running":
159
+ if family.name not in wanted:
109
160
  continue
110
- for sample in family.samples:
111
- total += sample.value
112
- found = True
161
+ # A counter's value is its ``_total`` sample; a gauge's sample
162
+ # carries the family name itself.
163
+ values = [
164
+ sample.value
165
+ for sample in family.samples
166
+ if sample.name in (family.name, f"{family.name}_total")
167
+ ]
168
+ if values:
169
+ totals[family.name] = totals.get(family.name, 0.0) + sum(values)
113
170
  except ValueError:
114
- # Malformed exposition text; treat as unavailable.
115
- return None
116
- return int(total) if found else None
171
+ # Malformed exposition text; treat the whole page as unavailable.
172
+ return {}
173
+ # The exposition format allows NaN and +/-Inf, which no count can hold.
174
+ return {name: total for name, total in totals.items() if math.isfinite(total)}
117
175
 
118
176
 
119
177
  def fmt_bytes(n: int) -> str:
@@ -133,6 +191,22 @@ def fmt_l1_used(used_bytes: int, total_bytes: int) -> str:
133
191
  return f"{used_bytes / 1024**3:.2f} ({pct:.1f}%)"
134
192
 
135
193
 
194
+ def fmt_hit_rate(hits: int | None, total: int | None) -> float | None:
195
+ """Return *hits* / *total* as a percentage rounded to one decimal.
196
+
197
+ Args:
198
+ hits: Tokens that hit, or ``None`` if unknown.
199
+ total: Tokens looked up, or ``None`` if unknown.
200
+
201
+ Returns:
202
+ The percentage, or ``None`` if either count is unknown or *total*
203
+ is 0 (no lookups yet), so the row renders as ``N/A``.
204
+ """
205
+ if hits is None or not total:
206
+ return None
207
+ return round(hits / total * 100, 1)
208
+
209
+
136
210
  def fmt_health(is_healthy: object) -> str | None:
137
211
  """Format a boolean health flag as ``'OK'`` / ``'UNHEALTHY'``."""
138
212
  if is_healthy is None:
@@ -166,15 +240,33 @@ class KVCacheDescriber:
166
240
  about it.
167
241
  """
168
242
 
169
- def __init__(self, metrics: "Metrics", data: dict, base_url: str) -> None:
243
+ def __init__(
244
+ self,
245
+ metrics: "Metrics",
246
+ data: dict,
247
+ base_url: str,
248
+ hit_totals: dict[str, float],
249
+ ) -> None:
250
+ """Bind the inputs for one ``describe kvcache`` report.
251
+
252
+ Args:
253
+ metrics: The output collector to populate.
254
+ data: The server's ``/status`` response.
255
+ base_url: The normalized server URL, shown in the overview.
256
+ hit_totals: Lookup counter sums from the server's ``/metrics``, as
257
+ returned by :func:`fetch_metric_totals` for
258
+ :data:`HIT_COUNTER_NAMES`; missing names render as ``N/A``.
259
+ """
170
260
  self.metrics = metrics
171
261
  self.data = data
172
262
  self.base_url = base_url
263
+ self.hit_totals = hit_totals
173
264
 
174
265
  def describe(self) -> None:
175
266
  """Run all section builders and emit."""
176
267
  self.add_overview()
177
268
  self.add_l1_storage()
269
+ self.add_cache_hits()
178
270
  self.add_models()
179
271
  self.add_l2_adapters()
180
272
  self.metrics.emit()
@@ -226,6 +318,34 @@ class KVCacheDescriber:
226
318
  for tag, manager in managers.items():
227
319
  self._add_l1_section(tag, manager, evictions[tag])
228
320
 
321
+ def add_cache_hits(self) -> None:
322
+ """Lookup hit counts and rates since the server started.
323
+
324
+ Adds the ``cache_hits`` section from :attr:`hit_totals`. Token counts
325
+ missing from ``/metrics`` are ``None`` (``N/A``); a rate is ``None``
326
+ when either operand is missing or its denominator is 0.
327
+ """
328
+ requested = self._hit_tokens(LOOKUP_REQUESTED_TOKENS)
329
+ hit = self._hit_tokens(LOOKUP_HIT_TOKENS)
330
+ sec = self.metrics.add_section("cache_hits", "Cache hits (since server start)")
331
+ sec.add("lookup_requested_tokens", "Lookup requested (tokens)", requested)
332
+ sec.add("lookup_hit_tokens", "Lookup hits (tokens)", hit)
333
+ sec.add("lookup_hit_rate", "Lookup hit rate (%)", fmt_hit_rate(hit, requested))
334
+ sec.add(
335
+ "l1_hit_tokens", "L1 hits (tokens)", self._hit_tokens(LOOKUP_HIT_L1_TOKENS)
336
+ )
337
+ sec.add(
338
+ "l2_hit_tokens", "L2 hits (tokens)", self._hit_tokens(LOOKUP_HIT_L2_TOKENS)
339
+ )
340
+ sec.add(
341
+ "request_hit_rate",
342
+ "Request hit rate (%)",
343
+ fmt_hit_rate(
344
+ self._hit_tokens(LOOKUP_REQUEST_HIT_TOKENS),
345
+ self._hit_tokens(LOOKUP_PROMPT_TOKENS),
346
+ ),
347
+ )
348
+
229
349
  def add_models(self) -> None:
230
350
  """Per-model KV cache layout sections.
231
351
 
@@ -378,6 +498,11 @@ class KVCacheDescriber:
378
498
  sec.add("cached_objects", "Cached objects", manager["total_object_count"])
379
499
  sec.add("eviction_policy", "Eviction policy", eviction["eviction_policy"])
380
500
 
501
+ def _hit_tokens(self, name: str) -> int | None:
502
+ """Return the summed counter *name* as a token count, or ``None``."""
503
+ value = self.hit_totals.get(name)
504
+ return int(value) if value is not None else None
505
+
381
506
 
382
507
  # -------------------------------------------------------------------
383
508
  # Engine describer
@@ -474,8 +599,9 @@ class DescribeCommand(BaseCommand):
474
599
  print(str(exc), file=sys.stderr)
475
600
  sys.exit(1)
476
601
 
602
+ hit_totals = fetch_metric_totals(f"{base_url}/metrics", HIT_COUNTER_NAMES)
477
603
  metrics = self.create_metrics("LMCache KV Cache Service", args, width=50)
478
- KVCacheDescriber(metrics, data, base_url).describe()
604
+ KVCacheDescriber(metrics, data, base_url, hit_totals).describe()
479
605
 
480
606
  def _describe_engine(self, args: argparse.Namespace) -> None:
481
607
  base_url = normalize_url(args.url)
@@ -50,9 +50,23 @@ class _IpcEvent(Protocol):
50
50
  def wait(self, stream: object | None = None) -> None: ...
51
51
 
52
52
 
53
- def _get_chunk_size(client: RequestClient, timeout: float) -> int:
54
- """Read the server's configured token chunk size."""
55
- return int(client.get_chunk_size().result(timeout))
53
+ def _get_chunk_size(
54
+ client: RequestClient, timeout: float, required_alignment: int
55
+ ) -> int:
56
+ """Resolve the server minimum to the ATOM block alignment.
57
+
58
+ Args:
59
+ client: MP request client used to read the server minimum.
60
+ timeout: Maximum seconds to wait for the response.
61
+ required_alignment: ATOM block size in tokens.
62
+
63
+ Returns:
64
+ The server minimum rounded up to ``required_alignment``.
65
+ """
66
+ server_minimum = client.get_chunk_size().result(timeout)
67
+ return (
68
+ (server_minimum + required_alignment - 1) // required_alignment
69
+ ) * required_alignment
56
70
 
57
71
 
58
72
  def _caller_chunk_hashes(
@@ -64,7 +78,7 @@ def _caller_chunk_hashes(
64
78
  chunk_hashes: ``lmcache_chunk_hashes`` of the prompt's complete
65
79
  chunks in ``[0, end)``, concatenated.
66
80
  end: End token index of the key being built.
67
- chunk_size: The server's chunk size.
81
+ chunk_size: The adapter's effective chunk size.
68
82
  enabled: Whether the adapter was built with ``client_chunk_hashes``.
69
83
 
70
84
  Returns:
@@ -141,7 +155,9 @@ class AtomMPSchedulerAdapter:
141
155
  self._parallel = parallel_config
142
156
  self._mq_timeout = mq_timeout
143
157
  try:
144
- self.lmcache_tokens_per_chunk = _get_chunk_size(client, mq_timeout)
158
+ self.lmcache_tokens_per_chunk = _get_chunk_size(
159
+ client, mq_timeout, block_size
160
+ )
145
161
  if self.lmcache_tokens_per_chunk % block_size:
146
162
  raise ValueError(
147
163
  "LMCache chunk size must be divisible by ATOM block size, got "
@@ -360,7 +376,9 @@ class AtomMPWorkerAdapter:
360
376
  self._transfer_mode = transfer_mode
361
377
  self.instance_id = uuid.uuid4().int & ((1 << 63) - 1)
362
378
  try:
363
- self.lmcache_tokens_per_chunk = _get_chunk_size(client, mq_timeout)
379
+ self.lmcache_tokens_per_chunk = _get_chunk_size(
380
+ client, mq_timeout, block_size
381
+ )
364
382
  if self.lmcache_tokens_per_chunk % block_size:
365
383
  raise ValueError(
366
384
  "LMCache chunk size must be divisible by ATOM block size, got "
@@ -11,6 +11,7 @@ by SGLang; the selected transfer context moves their KV data.
11
11
  from __future__ import annotations
12
12
 
13
13
  # Standard
14
+ from math import lcm
14
15
  from typing import TYPE_CHECKING, Any, Optional, Sequence
15
16
  import hashlib
16
17
  import logging
@@ -241,6 +242,9 @@ class UnifiedLMCacheMPConnector:
241
242
  self._mp_transfer_mode = config.get_extra_config_value(
242
243
  "lmcache.mp.mp_transfer_mode", None
243
244
  )
245
+ self._client_minimum_chunk_size: int | None = config.get_extra_config_value(
246
+ "lmcache.mp.chunk_size", None
247
+ )
244
248
 
245
249
  self.model_name = model_config.model_path
246
250
  (
@@ -389,7 +393,27 @@ class UnifiedLMCacheMPConnector:
389
393
  return specs, tuple(spec["engine_group_id"] for spec in specs)
390
394
 
391
395
  def _get_chunk_size(self) -> int:
392
- return int(self._req_client.get_chunk_size().result(timeout=self._mq_timeout))
396
+ server_minimum = self._req_client.get_chunk_size().result(
397
+ timeout=self._mq_timeout
398
+ )
399
+ if server_minimum <= 0:
400
+ raise ValueError(
401
+ "LMCache server minimum chunk size must be positive, got "
402
+ f"{server_minimum}"
403
+ )
404
+ client_minimum = self._client_minimum_chunk_size
405
+ if client_minimum is not None and client_minimum <= 0:
406
+ raise ValueError(
407
+ "LMCache client minimum chunk size must be positive, got "
408
+ f"{client_minimum}"
409
+ )
410
+ alignment = lcm(*(group.tokens_per_block for group in self._kv_groups))
411
+ base = (
412
+ server_minimum
413
+ if client_minimum is None
414
+ else max(server_minimum, client_minimum)
415
+ )
416
+ return ((base + alignment - 1) // alignment) * alignment
393
417
 
394
418
  @property
395
419
  def is_lookup_leader(self) -> bool:
@@ -59,6 +59,23 @@ def _get_server_url(llm_args: "TorchLlmArgs") -> str:
59
59
  return os.environ.get("LMCACHE_SERVER_URL", DEFAULT_SERVER_URL)
60
60
 
61
61
 
62
+ def _resolve_chunk_size(
63
+ req_client: RequestClient, timeout: float, block_size: int
64
+ ) -> int:
65
+ """Round the server minimum up to the TensorRT-LLM block size.
66
+
67
+ Args:
68
+ req_client: MP request client used to read the server minimum.
69
+ timeout: Maximum seconds to wait for the response.
70
+ block_size: TensorRT-LLM paged block size in tokens.
71
+
72
+ Returns:
73
+ The aligned effective chunk size.
74
+ """
75
+ server_minimum = req_client.get_chunk_size().result(timeout=timeout)
76
+ return ((server_minimum + block_size - 1) // block_size) * block_size
77
+
78
+
62
79
  @dataclass
63
80
  class _BlockSpec:
64
81
  tokens: List[int]
@@ -89,8 +106,9 @@ class LMCacheMPKvConnectorScheduler(KvCacheConnectorScheduler):
89
106
  os.environ.get("LMCACHE_MQ_TIMEOUT", DEFAULT_MQ_TIMEOUT)
90
107
  )
91
108
 
92
- future = self._req_client.get_chunk_size()
93
- self._chunk_size = future.result(timeout=self._mq_timeout)
109
+ self._chunk_size = _resolve_chunk_size(
110
+ self._req_client, self._mq_timeout, self._block_size
111
+ )
94
112
  logger.info(
95
113
  "LMCache MP scheduler: connected to server at %s (chunk_size=%d)",
96
114
  _get_server_url(self._llm_args),
@@ -295,8 +313,9 @@ class LMCacheMPKvConnectorWorker(KvCacheConnectorWorker):
295
313
  self._world_size = tp_size * pp_size
296
314
  self._model_name = str(getattr(llm_args, "model", "unknown_model"))
297
315
 
298
- future = self._req_client.get_chunk_size()
299
- self._chunk_size = future.result(timeout=self._mq_timeout)
316
+ self._chunk_size = _resolve_chunk_size(
317
+ self._req_client, self._mq_timeout, self._block_size
318
+ )
300
319
 
301
320
  def _create_key(
302
321
  self,
@@ -9,6 +9,7 @@ from collections.abc import Mapping
9
9
  from dataclasses import dataclass
10
10
  from typing import Protocol, cast
11
11
  from urllib.parse import urlparse
12
+ import importlib.util
12
13
  import math
13
14
  import shlex
14
15
  import subprocess
@@ -27,6 +28,7 @@ _AUTOSTART_KEY = "lmcache.mp.autostart"
27
28
  _SERVER_ARGS_KEY = "lmcache.mp.autostart.server_args"
28
29
  _WAIT_TIMEOUT_KEY = "lmcache.mp.autostart.wait_timeout"
29
30
 
31
+ _SERVER_PACKAGE = "lmcache.v1.multiprocess"
30
32
  _DEFAULT_WAIT_TIMEOUT = 90.0
31
33
  _LOCAL_HOSTS = {"localhost", "127.0.0.1"}
32
34
  # The URL scheme picks the server transport, so server_args cannot override it.
@@ -337,7 +339,7 @@ class MPServerAutostartConfig:
337
339
  return [
338
340
  sys.executable,
339
341
  "-m",
340
- "lmcache.v1.multiprocess.http_server",
342
+ f"{_SERVER_PACKAGE}.http_server",
341
343
  "--host",
342
344
  self.host,
343
345
  "--port",
@@ -378,6 +380,8 @@ class MPServerLauncher:
378
380
  None.
379
381
 
380
382
  Raises:
383
+ RuntimeError: If no server is reachable and this environment has no
384
+ server to start, as with only ``lmcache-client`` installed.
381
385
  ConnectionError: If the server process exits early or does not become
382
386
  healthy before the configured timeout.
383
387
  """
@@ -391,6 +395,15 @@ class MPServerLauncher:
391
395
  )
392
396
  return
393
397
 
398
+ if importlib.util.find_spec(_SERVER_PACKAGE) is None:
399
+ raise RuntimeError(
400
+ f"No LMCache MP server is reachable at {server_url}, and "
401
+ "lmcache.mp.autostart cannot start one here: starting a server "
402
+ f"needs the full lmcache distribution, and {_SERVER_PACKAGE} is "
403
+ "not installed (lmcache-client has no server). Install lmcache, "
404
+ "or start the server separately and connect to it."
405
+ )
406
+
394
407
  command = self.config.command()
395
408
  logger.info("Auto-starting LMCache MP server with command: %s", command)
396
409
  self._process = subprocess.Popen(command)
@@ -572,6 +585,8 @@ def maybe_start_mp_server_from_url(
572
585
  Raises:
573
586
  ValueError: If an auto-start configuration value or server URL is
574
587
  invalid.
588
+ RuntimeError: If no server is reachable and this environment has no
589
+ server to start, as with only ``lmcache-client`` installed.
575
590
  ConnectionError: If auto-start is enabled and the server does not
576
591
  become reachable before the configured timeout.
577
592
  """
@@ -847,6 +847,19 @@ async function setLogLevel() {
847
847
  }
848
848
  }
849
849
 
850
+ // Read a top-level section from the MP configuration endpoint.
851
+ async function readConfig(configKey = '') {
852
+ const response = await fetch(transformPath('config'));
853
+ if (!response.ok) {
854
+ throw new Error(`HTTP ${response.status}: ${await response.text()}`);
855
+ }
856
+ if (configKey) {
857
+ const data = await response.json();
858
+ return JSON.stringify(Object.hasOwn(data, configKey) ? {[configKey]: data[configKey]} : {}, null, 2);
859
+ }
860
+ return response.text();
861
+ }
862
+
850
863
  // Load configuration
851
864
  async function loadConfig() {
852
865
  if (!currentNode) return;
@@ -860,9 +873,7 @@ async function loadConfig() {
860
873
  configValueInput.value = '';
861
874
 
862
875
  try {
863
- const response = await fetch(transformPath('conf'));
864
- const text = await response.text();
865
- contentDiv.textContent = text;
876
+ contentDiv.textContent = await readConfig();
866
877
  } catch (error) {
867
878
  contentDiv.textContent = `Failed to load configuration: ${error.message}`;
868
879
  }
@@ -876,13 +887,7 @@ async function getConfig() {
876
887
  const configKey = configKeyInput.value.trim();
877
888
 
878
889
  try {
879
- let url = transformPath('conf');
880
- if (configKey) {
881
- url += `?key=${encodeURIComponent(configKey)}`;
882
- }
883
- const response = await fetch(url);
884
- const text = await response.text();
885
- alert(text);
890
+ alert(await readConfig(configKey));
886
891
  } catch (error) {
887
892
  alert(`Failed to get configuration: ${error.message}`);
888
893
  }
@@ -450,14 +450,15 @@ def replay(
450
450
  records: Requests in replay order.
451
451
  hashes: Chunk hashes per request, as from :func:`hash_records`.
452
452
  chunk_size: Tokens per chunk the hashes were computed with.
453
- capacity_tokens: Cache capacity in tokens.
453
+ capacity_tokens: Cache capacity in tokens. Only whole chunks fit;
454
+ smaller budgets yield zero prefix and non-prefix hits.
454
455
 
455
456
  Returns:
456
457
  Aggregate and per-request hit accounting.
457
458
  """
458
- capacity_chunks = max(1, capacity_tokens // chunk_size)
459
+ capacity_chunks = capacity_tokens // chunk_size
459
460
  cache = LRUCacheFast(capacity_chunks)
460
- matcher = BlendTokenRangeMatcher(chunk_size)
461
+ matcher = BlendTokenRangeMatcher(chunk_size) if capacity_chunks else None
461
462
 
462
463
  total_tokens = 0
463
464
  prefix_total = 0
@@ -474,7 +475,7 @@ def replay(
474
475
  prefix_tokens = hit_prefix * chunk_size
475
476
 
476
477
  non_prefix_tokens = 0
477
- if chunk_hashes:
478
+ if matcher is not None and chunk_hashes:
478
479
  segments = select_non_prefix_segments(
479
480
  matcher.match_sub_sequence(record.input_ids), prefix_tokens
480
481
  )
@@ -46,14 +46,9 @@ class MetricSpec:
46
46
  reduce: Callable[[Sequence[int | float]], int | float]
47
47
 
48
48
 
49
- def default_metric_specs(get_chunk_size: Callable[[], int]) -> list[MetricSpec]:
49
+ def default_metric_specs() -> list[MetricSpec]:
50
50
  """Build the parity metrics matching the single-process reporter.
51
51
 
52
- Args:
53
- get_chunk_size: Returns the current server chunk size in tokens;
54
- converts the chunk counts carried by store/retrieve events to
55
- tokens.
56
-
57
52
  Returns:
58
53
  Specs covering every metric field of ``ContinuousContextMessage``.
59
54
  """
@@ -61,13 +56,13 @@ def default_metric_specs(get_chunk_size: Callable[[], int]) -> list[MetricSpec]:
61
56
  MetricSpec(
62
57
  event_type=EventType.MP_RETRIEVE_END,
63
58
  field="interval_num_hit_tokens",
64
- extract=lambda e: int(e.metadata["retrieved_count"]) * get_chunk_size(),
59
+ extract=lambda e: int(e.metadata["num_tokens"]),
65
60
  reduce=sum,
66
61
  ),
67
62
  MetricSpec(
68
63
  event_type=EventType.MP_STORE_END,
69
64
  field="interval_num_stored_tokens",
70
- extract=lambda e: int(e.metadata["stored_count"]) * get_chunk_size(),
65
+ extract=lambda e: int(e.metadata["num_tokens"]),
71
66
  reduce=sum,
72
67
  ),
73
68
  MetricSpec(
@@ -69,7 +69,6 @@ class MPContinuousUsageReporter(EventSubscriber):
69
69
 
70
70
  def __init__(
71
71
  self,
72
- chunk_size: int,
73
72
  sender: UsageMessageSender | None = None,
74
73
  specs: list[MetricSpec] | None = None,
75
74
  max_buffered_samples: int = 65536,
@@ -77,8 +76,6 @@ class MPContinuousUsageReporter(EventSubscriber):
77
76
  """Initialize the reporter and start its flush thread.
78
77
 
79
78
  Args:
80
- chunk_size: The server chunk size in tokens, used by the
81
- default metric specs.
82
79
  sender: Message transport; ``None`` selects the default HTTP
83
80
  sender.
84
81
  specs: Metric definitions; ``None`` selects the defaults.
@@ -96,12 +93,7 @@ class MPContinuousUsageReporter(EventSubscriber):
96
93
  raise ValueError(
97
94
  f"max_buffered_samples must be positive, got {max_buffered_samples}"
98
95
  )
99
- self._chunk_size = chunk_size
100
- self._specs = (
101
- specs
102
- if specs is not None
103
- else default_metric_specs(lambda: self._chunk_size)
104
- )
96
+ self._specs = specs if specs is not None else default_metric_specs()
105
97
  spec_fields = [spec.field for spec in self._specs]
106
98
  message_fields = {
107
99
  f.name for f in fields(ContinuousContextMessage)
@@ -144,12 +136,6 @@ class MPContinuousUsageReporter(EventSubscriber):
144
136
  self._flush_thread.stop()
145
137
  self.flush()
146
138
 
147
- def update_chunk_size(self, chunk_size: int) -> None:
148
- """Update token-count metric conversion after chunk-size negotiation."""
149
- with self._lock:
150
- self._chunk_size = chunk_size
151
- self._buffers = {spec.field: [] for spec in self._specs}
152
-
153
139
  @swallow_telemetry_errors
154
140
  def flush(self) -> None:
155
141
  """Reduce the buffered samples, send them, and reset the buffers.
@@ -206,7 +192,6 @@ class MPContinuousUsageReporter(EventSubscriber):
206
192
  @swallow_telemetry_errors
207
193
  def InitializeMPContinuousUsage(
208
194
  event_bus: EventBus,
209
- chunk_size: int,
210
195
  sender: UsageMessageSender | None = None,
211
196
  ) -> MPContinuousUsageReporter | None:
212
197
  """Start continuous usage reporting for a multiprocess cache server.
@@ -216,7 +201,6 @@ def InitializeMPContinuousUsage(
216
201
 
217
202
  Args:
218
203
  event_bus: The server's started EventBus.
219
- chunk_size: The server chunk size in tokens.
220
204
  sender: Message transport; ``None`` selects the default HTTP sender.
221
205
 
222
206
  Returns:
@@ -226,6 +210,6 @@ def InitializeMPContinuousUsage(
226
210
  if not is_usage_tracking_enabled():
227
211
  return None
228
212
  logger.info("Initializing MP continuous usage reporting.")
229
- reporter = MPContinuousUsageReporter(chunk_size, sender)
213
+ reporter = MPContinuousUsageReporter(sender=sender)
230
214
  event_bus.register_subscriber(reporter)
231
215
  return reporter
@@ -280,6 +280,10 @@ class L1ManagerInterface(Protocol):
280
280
  """Register a listener for this L1's lifecycle notifications."""
281
281
  ...
282
282
 
283
+ def unregister_listener(self, listener: L1ManagerListener) -> None:
284
+ """Remove a listener before its resources are closed."""
285
+ ...
286
+
283
287
  def reserve_read(
284
288
  self, keys: list[ObjectKey], read_locks: int = 1
285
289
  ) -> dict[ObjectKey, L1OperationResult]:
@@ -295,6 +295,12 @@ class BaseL1Manager(L1ManagerInterface):
295
295
  with self._lock:
296
296
  self._registered_listeners.append(listener)
297
297
 
298
+ def unregister_listener(self, listener: L1ManagerListener) -> None:
299
+ """Wait for any active callback and remove the listener if registered."""
300
+ with self._lock:
301
+ if listener in self._registered_listeners:
302
+ self._registered_listeners.remove(listener)
303
+
298
304
  @l1_mgr_synchronized
299
305
  def reserve_read(
300
306
  self,