main
py 950 lines 40.6 KB
Raw
1 # SPDX-License-Identifier: Apache-2.0
2 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3 """P2PSecondaryTierManager: Secondary tier for P2P KV cache sharing.
4
5 Owns transports and a single bidirectional P2PSession per remote peer.
6 """
7
8 from __future__ import annotations
9
10 import time
11 import uuid
12 from collections.abc import Iterable, Sequence
13 from dataclasses import dataclass, field
14 from typing import TYPE_CHECKING, Any
15
16 from typing_extensions import override
17
18 import vllm.envs as envs
19 from vllm.logger import init_logger
20 from vllm.v1.core.kv_cache_utils import get_none_hash_seed
21 from vllm.v1.kv_offload.base import (
22 LookupResult,
23 OffloadKey,
24 OffloadPolicy,
25 ReqContext,
26 RequestOffloadingContext,
27 ScheduleEndContext,
28 )
29 from vllm.v1.kv_offload.file_mapper import FileMapper
30 from vllm.v1.kv_offload.tiering.base import (
31 JobResult,
32 SecondaryTierManager,
33 TransferJob,
34 )
35 from vllm.v1.kv_offload.tiering.p2p.control import ControlTransport, ZmqTransport
36 from vllm.v1.kv_offload.tiering.p2p.data import DataTransport, NixlTransport
37 from vllm.v1.kv_offload.tiering.p2p.session import P2PSession
38
39 if TYPE_CHECKING:
40 from vllm.v1.kv_offload.base import OffloadingSpec
41 from vllm.v1.kv_offload.tiering.base import ParentManager
42 from vllm.v1.kv_offload.tiering.p2p.control.base import ControlConnection
43
44 logger = init_logger(__name__)
45
46 # Reap unbound store batches that have been parked without a FetchMsg
47 # binding them to a session for longer than this. Protects against the
48 # prefiller buffering blocks for a decoder that never asks (decoder died,
49 # network partition, lost kv_request_id). Applies only while a batch is
50 # unbound: binding hands it to the session, which times the job out under
51 # _STORE_TIMEOUT_S instead.
52 # Overridable per tier via the ``unbound_store_timeout_s`` config key.
53 _UNBOUND_STORE_TIMEOUT_S = 60.0
54
55 # How long a reaped kv_request_id is remembered so a fetch that arrives
56 # after the reap can be rejected immediately. Must exceed the consumer's
57 # load timeout (session.client._LOAD_TIMEOUT_S): past that the consumer has
58 # already given up on its own, so there is nobody left to reject.
59 _REAPED_ID_RETENTION_S = 60.0
60
61 # Time we wait during shutdown for inflight transfers to drain via
62 # cancel(mode="wait") before falling back to mode="immediate". Bounded
63 # so a wedged peer can't hang shutdown.
64 _SHUTDOWN_DRAIN_TIMEOUT_S = 3.0
65
66 # Sleep between iterations of the bounded drain loops in drain_jobs() and
67 # _drain_inflight_for_shutdown(). Short enough to keep latency low, long
68 # enough to avoid busy-spinning the scheduler thread.
69 _DRAIN_SLEEP_S = 0.001
70
71
72 def _remote_prefiller_params(kv_params: dict | None) -> dict | None:
73 """Return the ``remote_prefiller`` sub-dict, or None if absent.
74
75 Set on decoder requests to name the remote prefiller they pull from;
76 carries kv_request_id, remote_host, remote_port.
77 """
78 if not kv_params:
79 return None
80 return kv_params.get("remote_prefiller")
81
82
83 def _remote_decoder_params(kv_params: dict | None) -> dict | None:
84 """Return the ``remote_decoder`` sub-dict, or None if absent.
85
86 Set on prefiller requests to name the remote decoder they serve;
87 carries kv_request_id.
88 """
89 if not kv_params:
90 return None
91 return kv_params.get("remote_decoder")
92
93
94 def _remote_kv_source_params(kv_params: dict | None) -> dict | None:
95 """Return the ``remote_kv_source`` sub-dict, or None if absent.
96
97 Set on symmetric-P2P consumer requests to name the remote source they
98 pull from; carries kv_request_id, remote_host, remote_port.
99 """
100 if not kv_params:
101 return None
102 return kv_params.get("remote_kv_source")
103
104
105 def _peer_id_from_params(role_params: dict) -> str | None:
106 """Build ``host:port`` peer_id from a role-scoped sub-dict, or None."""
107 host = role_params.get("remote_host")
108 port = role_params.get("remote_port")
109 if host and port:
110 return f"{host}:{port}"
111 return None
112
113
114 @dataclass(slots=True)
115 class P2PSourceInfo:
116 """Consumer side: this request fetches from a remote (prefiller or peer)."""
117
118 kv_request_id: str
119 peer_id: str
120 do_probe: bool # False for remote_prefiller (PD), True for remote_kv_source
121
122
123 @dataclass(slots=True)
124 class P2PDestInfo:
125 """Producer side: a remote fetches this request's blocks from us.
126
127 ``kv_request_id`` is None when the ``remote_decoder`` block is present
128 but malformed (no id); the block's presence still marks the request as
129 remote-decode, so submit_store must fail rather than store locally.
130 """
131
132 kv_request_id: str | None
133
134
135 def _parse_source(kv_params: dict | None) -> P2PSourceInfo | None:
136 """Parse the consumer sub-dict (PD ``remote_prefiller`` or symmetric
137 ``remote_kv_source``) into a ``P2PSourceInfo``, or None if absent/incomplete."""
138 role = _remote_prefiller_params(kv_params)
139 do_probe = False
140 if role is None:
141 role = _remote_kv_source_params(kv_params)
142 do_probe = True
143 if not role:
144 return None
145 peer_id = _peer_id_from_params(role)
146 kv_request_id = role.get("kv_request_id")
147 if peer_id is None or not kv_request_id:
148 return None
149 return P2PSourceInfo(
150 kv_request_id=kv_request_id,
151 peer_id=peer_id,
152 do_probe=do_probe,
153 )
154
155
156 def _parse_dest(kv_params: dict | None) -> P2PDestInfo | None:
157 """Parse the producer ``remote_decoder`` sub-dict into a ``P2PDestInfo``,
158 or None if the block is absent (not a remote-decode request)."""
159 role = _remote_decoder_params(kv_params)
160 if role is None:
161 return None
162 return P2PDestInfo(kv_request_id=role.get("kv_request_id") or None)
163
164
165 def _annotate_req_context(req_context: ReqContext) -> None:
166 """Parse kv_transfer_params once and cache the P2P routing state.
167
168 Called from ``on_new_request``; later calls for the same request read
169 the cached ``P2PSourceInfo``/``P2PDestInfo`` via ``get_state`` instead
170 of re-parsing.
171 """
172 source = _parse_source(req_context.kv_transfer_params)
173 if source is not None:
174 req_context.set_state(source)
175 dest = _parse_dest(req_context.kv_transfer_params)
176 if dest is not None:
177 req_context.set_state(dest)
178
179
180 @dataclass
181 class _UnboundStoreBatch:
182 """A submit_store batch parked at the manager before any peer has fetched.
183
184 Indexed by kv_request_id only — the prefiller no longer learns the peer
185 identity at store time. When a FetchMsg(kv_request_id) arrives on some
186 session, the manager binds the kv_request_id to that session and replays
187 every parked batch into ServerRole via session.add_stored_blocks.
188 """
189
190 job_id: int
191 keys: list[OffloadKey]
192 block_ids: Sequence[int]
193 submitted_at: float = field(default_factory=time.monotonic)
194
195
196 class P2PSecondaryTierManager(SecondaryTierManager):
197 """Secondary tier for P2P KV cache sharing.
198
199 A single P2PSession per remote peer handles both client-role (loading
200 blocks from the peer) and server-role (serving blocks to the peer)
201 over the same control connection.
202
203 Single-threaded: every public method runs on the scheduler thread, and
204 the engine drives polling via ``get_finished_jobs()`` once per step.
205 ``has_pending_work()`` keeps the engine ticking so the control transport
206 and existing sessions are polled even when no requests are scheduled.
207 """
208
209 def __init__(
210 self,
211 offloading_spec: OffloadingSpec,
212 primary_kv_view: memoryview,
213 tier_type: str = "p2p",
214 host: str | None = None,
215 port: int | None = None,
216 backends: list[str] | None = None,
217 num_threads: int = 4,
218 unbound_store_timeout_s: float = _UNBOUND_STORE_TIMEOUT_S,
219 **kwargs: Any,
220 ) -> None:
221 """Initialize the P2P secondary tier manager.
222
223 All keyword arguments after ``primary_kv_view`` come from the
224 ``secondary_tiers`` entry in ``kv_connector_extra_config``. See
225 ``docs/features/kv_offloading_usage.md`` for the user-facing
226 configuration reference.
227
228 Args:
229 offloading_spec: Owning ``OffloadingSpec`` (provides normalized
230 model, parallel, and cache layout configuration).
231 primary_kv_view: Memoryview over the CPU primary tier; the
232 NIXL agent registers this region for RDMA transfers.
233 tier_type: Tier identifier (defaults to ``"p2p"``).
234 host: Address the ZMQ control socket binds to, used verbatim
235 as both the bind address and the identity peers dial back
236 (mirrors the NIXL connector's ``VLLM_NIXL_SIDE_CHANNEL_HOST``;
237 no auto-detection). Defaults to
238 ``VLLM_P2P_SIDE_CHANNEL_HOST`` (``localhost``) when not set;
239 must be set to the node's routable IP for cross-host P2P so
240 remote peers can reach the socket.
241 port: Base port for the ZMQ control socket. Must be
242 reachable from peers. Defaults to
243 ``VLLM_P2P_SIDE_CHANNEL_PORT`` (``5710``) when not set.
244 The bound port is ``base + data_parallel_index`` so each
245 DP replica gets a distinct port (one socket per replica,
246 like NIXL); for DP=1 the offset is 0.
247 backends: NIXL transport backends (e.g. ``["UCX"]``,
248 ``["MOONCAKE"]``, ``["LIBFABRIC"]``). Defaults to
249 ``["UCX"]``. When any non-UCX backend is requested, the
250 NIXL agent is initialized with ``backends=...``;
251 otherwise it falls back to a UCX-only agent with
252 ``num_threads`` threads.
253 num_threads: NIXL agent worker threads for the UCX-only
254 branch. Ignored when ``backends`` contains a non-UCX
255 entry.
256 unbound_store_timeout_s: Seconds a producer holds stored blocks
257 for a consumer that has not fetched them yet, before
258 ``_reap_unbound_stores`` drops them. Raise it for
259 deployments whose prefills outlast the default; the blocks
260 keep primary-tier slots pinned for the whole window.
261 **kwargs: Reserved for future tier-specific options.
262
263 Raises:
264 ValueError: If ``unbound_store_timeout_s`` is not a positive
265 number, or anything convertible to one.
266
267 """
268 backpressure_detector = kwargs.pop("backpressure_detector", None)
269 if backpressure_detector is not None:
270 # The generic (store-latency) detector is unreliable for P2P: in
271 # PD mode dropping a store can leave the decoder waiting until the
272 # load timeout instead of failing fast, and rendezvous time makes
273 # store latency a poor pressure signal. Reject it until a
274 # P2P-specific fail-fast path exists.
275 raise ValueError(
276 "Backpressure is not supported for the P2P secondary tier. "
277 "The generic store-latency detector cannot fail fast in PD "
278 "mode and rendezvous time makes store latency an unreliable "
279 "pressure signal. Remove the 'backpressure' config from the "
280 "p2p tier."
281 )
282 super().__init__(
283 offloading_spec,
284 primary_kv_view,
285 tier_type,
286 )
287 try:
288 timeout_s = float(unbound_store_timeout_s)
289 except (TypeError, ValueError):
290 timeout_s = float("nan")
291 if not timeout_s > 0:
292 raise ValueError(
293 f"unbound_store_timeout_s must be a positive number, got "
294 f"{unbound_store_timeout_s!r}"
295 )
296 self._unbound_store_timeout_s = timeout_s
297
298 # Block hashes chain from NONE_HASH (see v1/core/kv_cache_utils.py).
299 # Peers whose seeds differ compute different hashes for identical
300 # content, so lookups silently miss and no KV crosses the wire. The
301 # seed is advertised and verified against each peer during the
302 # handshake, so a mismatch is rejected loudly instead of degrading
303 # silently. Resolved lazily in _get_hash_seed: this tier is built
304 # before init_none_hash runs, and a non-cryptographic hash algorithm
305 # seeds NONE_HASH randomly, so the value is only known afterwards.
306 self._hash_seed: str | None = None
307 if host is None:
308 host = envs.VLLM_P2P_SIDE_CHANNEL_HOST
309 if port is None:
310 port = envs.VLLM_P2P_SIDE_CHANNEL_PORT
311 # One control socket per DP replica: offset the base by the global
312 # data-parallel index so replicas on a host don't collide (mirrors
313 # NIXL). For DP=1 the index is 0, leaving the base port unchanged.
314 dp_index = offloading_spec.config.parallel.data_parallel_index
315 port = int(port) + dp_index
316 # Two decoupled identities:
317 # _local_id (``host:port``): the ZMQ control identity that peers
318 # dial back, used verbatim (the socket binds this host/port and
319 # the address is parsed back into host:port by the remote).
320 # _nixl_agent_name (uuid4): the NIXL agent name. It is never dialed
321 # — it travels opaquely inside the agent metadata blob — so it
322 # only needs to be globally unique. A per-process uuid guarantees
323 # that even for peers sharing a host:port (mirrors the NIXL
324 # connector; avoids the "remote agent name equals local" reject).
325 self._local_id = f"{host}:{port}"
326 self._nixl_agent_name = str(uuid.uuid4())
327
328 config_fields = FileMapper.from_offloading_spec(
329 root_dir="",
330 offloading_spec=offloading_spec,
331 blocks_per_file=offloading_spec.blocks_per_chunk,
332 parallel_agnostic=True,
333 ).get_run_config()
334 self._data: DataTransport = NixlTransport(
335 self._nixl_agent_name,
336 primary_kv_view,
337 config_fields=config_fields,
338 backends=backends,
339 num_threads=int(num_threads),
340 )
341 self._control: ControlTransport = ZmqTransport(self._local_id, host, port)
342
343 self._sessions: dict[str, P2PSession] = {}
344 # kv_request_id → session, set when the bound session has received
345 # FetchMsg for that id. submit_store after binding routes directly
346 # to the session; before binding, batches are parked in
347 # _unbound_stores below. Stays in sync with _sessions: entries
348 # pointing to a reaped session are purged in _reap_dead_sessions.
349 self._kv_to_session: dict[str, P2PSession] = {}
350 # kv_request_id → list of batches submit_store'd before any peer
351 # asked for that id. Drained into a session by _on_session_fetch
352 # when the corresponding FetchMsg arrives, or surfaced as failures
353 # by _reap_unbound_stores after _unbound_store_timeout_s.
354 self._unbound_stores: dict[str, list[_UnboundStoreBatch]] = {}
355 # kv_request_id → time its parked batches were reaped. Nothing under
356 # one of these ids can be served any more, so a FetchMsg for it is
357 # rejected on the spot by _poll_once instead of parking demand until
358 # the consumer's own load timeout, and submit_store fails rather than
359 # re-parking under it — a prefill that outran the timeout would
360 # otherwise keep pinning fresh primary-tier slots, one timeout at a
361 # time. Entries are pruned after _REAPED_ID_RETENTION_S.
362 self._reaped_stores: dict[str, float] = {}
363
364 self._finished_jobs: list[JobResult] = []
365 # kv_request_ids that hit a transport/session failure; On load lookup()
366 # rejects them so the request falls back to local prefill.
367 self._failed_req_ids: set[str] = set()
368 # Synthetic lookup ctxs from reaped sessions still owing a
369 # ``parent.on_request_finished`` (the session's failed_serves). The
370 # dead session had no parent handle at teardown; these are flushed
371 # at the top of the next ``serve_external_requests`` where the
372 # handle is valid.
373 self._failed_serve_ctxs: list[ReqContext] = []
374
375 # ------------------------------------------------------------------
376 # SecondaryTierManager interface
377 # ------------------------------------------------------------------
378
379 @override
380 def lookup(self, key: OffloadKey, req_context: ReqContext) -> LookupResult:
381 source = req_context.get_state(P2PSourceInfo)
382 if source is None:
383 return LookupResult.MISS
384 if source.kv_request_id in self._failed_req_ids:
385 return LookupResult.MISS
386
387 # Symmetric-P2P consumer (``remote_kv_source`` sub-dict): probe the
388 # peer asynchronously. First call registers the (kv_request_id,
389 # key) entry and returns RETRY; flush_pending_lookups()
390 # in on_schedule_end batches the LookupMsg; a later step's
391 # lookup() returns HIT/MISS once LookupRespMsg has arrived.
392 # PD path (``remote_prefiller`` sub-dict only) keeps the eager HIT.
393 if source.do_probe:
394 session = self._sessions.get(source.peer_id)
395 if session is None:
396 return LookupResult.MISS
397 result = session.register_lookup(source.kv_request_id, key)
398 if result is True:
399 return LookupResult.HIT
400 if result is False:
401 return LookupResult.MISS
402 return LookupResult.RETRY
403
404 # PD consumer (we are the decoder): all kv blocks should be on the
405 # prefiller side. Return HIT immediately.
406 return LookupResult.HIT
407
408 @override
409 def on_new_request(self, req_context: ReqContext) -> RequestOffloadingContext:
410 """Parse kv_transfer_params once and open the outbound session.
411
412 Parses the P2P routing state onto ``req_context`` (cached for the
413 later lookup/submit/finish calls). On the consumer side
414 (``remote_prefiller`` for PD or ``remote_kv_source`` for symmetric
415 P2P), open a session toward the producer at remote_host:remote_port
416 so submit_load can issue FetchMsg as soon as it fires. On the
417 prefiller side, sessions are created when the consumer's inbound
418 connection arrives in _accept_new_peers — submit_store no longer
419 pre-creates anything.
420
421 Producer-leg requests (``remote_decoder`` present) ask for
422 REQUEST_LEVEL: the peer needs every block of the request, not just
423 the ones this request computed.
424 """
425 _annotate_req_context(req_context)
426 source = req_context.get_state(P2PSourceInfo)
427 if source is not None:
428 self._get_or_create_session(source.peer_id)
429 dest = req_context.get_state(P2PDestInfo)
430 if dest is not None and dest.kv_request_id:
431 return RequestOffloadingContext(policy=OffloadPolicy.REQUEST_LEVEL)
432 return RequestOffloadingContext()
433
434 @override
435 def on_request_finished(self, req_context: ReqContext) -> None:
436 """Cancels pending loads and prunes session-scoped state.
437
438 Consumer side (``remote_prefiller`` for PD or ``remote_kv_source``
439 for symmetric-P2P): looks up the session by peer_id because the
440 producer's address is what addresses the client-role load to
441 cancel; also drops any pending symmetric-P2P lookup state via
442 ``session.finish_request``.
443 Prefiller side (``remote_decoder`` set): looks up via kv_request_id
444 because peer_id is no longer carried on store-time
445 kv_transfer_params; if a session has bound the id, finish it. If
446 no session has bound the id yet, this is a no-op: parked batches
447 in `_unbound_stores` are left in place and cleaned up only by
448 `_reap_unbound_stores` after `_unbound_store_timeout_s`.
449 """
450 source = req_context.get_state(P2PSourceInfo)
451 dest = req_context.get_state(P2PDestInfo)
452 kv_request_id = source.kv_request_id if source is not None else None
453 if kv_request_id is None and dest is not None:
454 kv_request_id = dest.kv_request_id
455 if not kv_request_id:
456 return
457 self._failed_req_ids.discard(kv_request_id)
458
459 if source is not None:
460 session = self._sessions.get(source.peer_id)
461 if session is not None:
462 session.finish_request(kv_request_id)
463 return
464
465 # Prefiller-side finish: identify the session via kv_request_id.
466 session = self._kv_to_session.pop(kv_request_id, None)
467 if session is not None:
468 session.finish_request(kv_request_id)
469 return
470
471 @override
472 def submit_store(self, job_metadata: TransferJob) -> None:
473 job_id = job_metadata.job_id
474 keys = list(job_metadata.keys)
475 block_ids = job_metadata.chunk_ids.tolist()
476
477 assert len(keys) == len(block_ids)
478
479 dest = job_metadata.req_context.get_state(P2PDestInfo)
480 logger.debug(
481 "P2P %s: submit_store ENTRY job_id=%d blocks=%d "
482 "remote_decoder=%s kv_request_id=%s",
483 self._local_id,
484 job_id,
485 len(block_ids),
486 dest is not None,
487 dest.kv_request_id if dest is not None else None,
488 )
489 # Absent ``remote_decoder`` block => not a remote-decode request:
490 # succeed locally without parking. An empty/malformed dict is still
491 # a remote-decode signal and must fail the missing-id check below.
492 if dest is None:
493 self._finished_jobs.append(JobResult(job_id=job_id, success=True))
494 return
495
496 kv_request_id = dest.kv_request_id
497 if not kv_request_id:
498 logger.warning(
499 "P2P %s: submit_store missing kv_request_id",
500 self._local_id,
501 )
502 self._finished_jobs.append(JobResult(job_id=job_id, success=False))
503 return
504
505 # This id's earlier batches were already reaped, so the consumer has
506 # either given up or will be rejected by the fetch path. Parking more
507 # would pin primary-tier slots for another full timeout on blocks
508 # nobody can fetch, so fail the job now — a prefill that outran the
509 # timeout falls back to local recompute on the decoder either way.
510 if kv_request_id in self._reaped_stores:
511 logger.warning(
512 "P2P %s: submit_store for reaped kv_request_id=%s job_id=%d "
513 "— failing without parking",
514 self._local_id,
515 kv_request_id,
516 job_id,
517 )
518 self._finished_jobs.append(JobResult(job_id=job_id, success=False))
519 return
520
521 # Fast path: a session has already received FetchMsg for this id,
522 # so we can route the batch straight into its ServerRole.
523 session = self._kv_to_session.get(kv_request_id)
524 if session is not None:
525 session.add_stored_blocks(kv_request_id, keys, block_ids, job_id)
526 return
527
528 # No session bound yet — park the batch keyed by kv_request_id.
529 # _on_session_fetch drains it on the first FetchMsg; if no peer
530 # ever asks, _reap_unbound_stores surfaces the job as failed.
531 self._unbound_stores.setdefault(kv_request_id, []).append(
532 _UnboundStoreBatch(
533 job_id=job_id,
534 keys=keys,
535 block_ids=block_ids,
536 )
537 )
538 logger.debug(
539 "P2P %s: parked submit_store kv_request_id=%s job_id=%d blocks=%d",
540 self._local_id,
541 kv_request_id,
542 job_id,
543 len(block_ids),
544 )
545
546 @override
547 def submit_load(self, job_metadata: TransferJob) -> None:
548 job_id = job_metadata.job_id
549 keys = list(job_metadata.keys)
550 block_ids = job_metadata.chunk_ids
551
552 source = job_metadata.req_context.get_state(P2PSourceInfo)
553 logger.debug(
554 "P2P %s: submit_load ENTRY job_id=%d blocks=%d kv_request_id=%s peer=%s",
555 self._local_id,
556 job_id,
557 len(block_ids),
558 source.kv_request_id if source is not None else None,
559 source.peer_id if source is not None else None,
560 )
561 if source is None:
562 logger.debug(
563 "P2P %s: submit_load job_id=%d FAILED missing consumer params",
564 self._local_id,
565 job_id,
566 )
567 self._finished_jobs.append(JobResult(job_id=job_id, success=False))
568 return
569
570 kv_request_id = source.kv_request_id
571 peer_id = source.peer_id
572
573 if not keys:
574 logger.debug(
575 "P2P %s: submit_load job_id=%d short-circuit success (no keys)",
576 self._local_id,
577 job_id,
578 )
579 self._finished_jobs.append(JobResult(job_id=job_id, success=True))
580 return
581
582 session = self._sessions.get(peer_id)
583 if session is None:
584 logger.warning(
585 "P2P %s: submit_load job_id=%d NO SESSION for peer=%s",
586 self._local_id,
587 job_id,
588 peer_id,
589 )
590 self._finished_jobs.append(JobResult(job_id=job_id, success=False))
591 self._failed_req_ids.add(kv_request_id)
592 return
593 logger.debug(
594 "P2P %s: submit_load job_id=%d -> request_blocks peer=%s "
595 "kv_request_id=%s blocks=%d session_ready=%s",
596 self._local_id,
597 job_id,
598 peer_id,
599 kv_request_id,
600 len(block_ids),
601 session.ready,
602 )
603 session.request_blocks(job_id, kv_request_id, keys, block_ids)
604
605 @override
606 def get_finished_jobs(self) -> Iterable[JobResult]:
607 # Drive one polling sweep on the scheduler thread, then hand off
608 # whatever has accumulated. The engine calls this once per step
609 # (and keeps stepping while has_pending_work() is True).
610 self._poll_once()
611 result = self._finished_jobs
612 self._finished_jobs = []
613 return result
614
615 @override
616 def has_pending_work(self) -> bool:
617 # The engine tick is the only driver of _control.poll() and
618 # session.poll(); without it we miss new peer connects and
619 # inbound fetch messages on existing sessions. Keep the engine
620 # ticking for the lifetime of this manager.
621 return True
622
623 @override
624 def drain_jobs(self) -> None:
625 """Block until every submitted load/store job has completed or failed.
626
627 Loops calling ``_poll_once()`` until no session has outstanding
628 inbound loads or in-flight outbound stores. Mid-flight transfers
629 are NOT cancelled — the caller (``TieringOffloadingManager.reset_cache``)
630 needs the primary memoryview to be quiescent, not aborted. Results
631 accumulate in ``_finished_jobs`` and are surfaced by the next
632 ``get_finished_jobs()`` call.
633 """
634 start = time.monotonic()
635 warned = False
636 while True:
637 self._poll_once()
638 pending = any(s.has_pending_work for s in self._sessions.values())
639 if not pending:
640 return
641 if not warned and time.monotonic() - start > 5.0:
642 logger.warning(
643 "P2PSecondaryTierManager.drain_jobs: still draining "
644 "after 5s; a stuck transfer will block the engine.",
645 )
646 warned = True
647 time.sleep(_DRAIN_SLEEP_S)
648
649 @override
650 def serve_external_requests(self, parent: ParentManager) -> None:
651 """Serve inbound peer lookups against the tiering manager.
652
653 Called once per scheduler step (before this tier's
654 ``on_schedule_end``) with a ``parent`` handle valid only for the
655 duration of the call — the sole window in which the P2P server
656 role may query the tiering manager. First release bookkeeping for
657 the failed serves left by a reaped session, then let every live
658 session resolve its enqueued inbound LookupMsgs.
659 """
660 if self._failed_serve_ctxs:
661 for ctx in self._failed_serve_ctxs:
662 parent.on_request_finished(ctx)
663 self._failed_serve_ctxs = []
664 for session in self._sessions.values():
665 session.serve_external_requests(parent)
666
667 @override
668 def on_schedule_end(self, context: ScheduleEndContext) -> None:
669 # Flush any p2p lookups aggregated during this step.
670 # One LookupMsg per (peer, kv_request_id) with unsent entries;
671 # send-gating happens inside the session if not yet ready.
672 for session in self._sessions.values():
673 session.flush_pending_lookups()
674
675 # ------------------------------------------------------------------
676 # Internal
677 # ------------------------------------------------------------------
678
679 def _get_hash_seed(self) -> str:
680 """The seed NONE_HASH was derived from, resolved on first session."""
681 if self._hash_seed is None:
682 self._hash_seed = get_none_hash_seed()
683 return self._hash_seed
684
685 def _get_or_create_session(self, peer_id: str) -> P2PSession:
686 """Return the existing session for peer_id, or open one outbound.
687
688 Consumer-side helper for on_new_request: when ``remote_prefiller``
689 (PD) or ``remote_kv_source`` (symmetric P2P) is set, the consumer must reach the
690 producer at peer_id. If we already have a session toward that
691 peer (from a prior load or a peer-initiated inbound), reuse it;
692 otherwise open an outbound ControlConnection and build a
693 connected session.
694 """
695 session = self._sessions.get(peer_id)
696 if session is not None:
697 return session
698 conn = self._control.connect(peer_id)
699 session = P2PSession(
700 peer_id=peer_id,
701 local_id=self._local_id,
702 transport=self._data,
703 local_block_len=self._data.block_len,
704 local_hash_seed=self._get_hash_seed(),
705 conn=conn,
706 )
707 self._sessions[peer_id] = session
708 return session
709
710 def _accept_new_peers(self, new_connections: Sequence[ControlConnection]) -> None:
711 for conn in new_connections:
712 logger.info(
713 "P2P %s: accepting incoming connection from %s",
714 self._local_id,
715 conn.peer_id,
716 )
717 try:
718 existing = self._sessions.get(conn.peer_id)
719 if existing is not None:
720 raise ValueError(f"duplicate connection from {conn.peer_id}")
721 self._sessions[conn.peer_id] = P2PSession(
722 peer_id=conn.peer_id,
723 local_id=self._local_id,
724 transport=self._data,
725 local_block_len=self._data.block_len,
726 local_hash_seed=self._get_hash_seed(),
727 conn=conn,
728 )
729 logger.info(
730 "P2P %s: created connected session for %s",
731 self._local_id,
732 conn.peer_id,
733 )
734 except (ValueError, KeyError, TypeError, AssertionError) as exc:
735 logger.error("P2P %s: rejecting peer: %s", self._local_id, exc)
736 conn.close()
737
738 def _reap_dead_sessions(self) -> None:
739 # Reap connected sessions whose connection died — peer is gone.
740 # Stranded prefiller-side stores are no longer tracked through a
741 # session (they live in _unbound_stores keyed by kv_request_id);
742 # _reap_unbound_stores handles their timeout independently.
743 dead: list[str] | None = None
744 for pid, s in self._sessions.items():
745 if s.connected and not s.alive:
746 if dead is None:
747 dead = []
748 dead.append(pid)
749 if dead is None:
750 return
751 for pid in dead:
752 session = self._sessions.pop(pid)
753 # Purge any kv_request_id → session entries pointing at this
754 # session so subsequent submit_stores fall back to the unbound
755 # path (which will time out into failure if no peer rebinds).
756 stale_kv_ids = [
757 kid for kid, s in self._kv_to_session.items() if s is session
758 ]
759 for kid in stale_kv_ids:
760 del self._kv_to_session[kid]
761 close_result = session.close()
762 for job_id in close_result.failed_jobs:
763 self._finished_jobs.append(JobResult(job_id=job_id, success=False))
764 for job_id in close_result.failed_stores:
765 self._finished_jobs.append(JobResult(job_id=job_id, success=False))
766 # Fail every client-side request (in-flight loads plus unresolved
767 # symmetric-P2P probes) toward the dead peer so lookup() returns
768 # MISS (local prefill) instead of RETRY forever — even if a fresh
769 # session to the same peer is later opened by another request.
770 self._failed_req_ids.update(close_result.failed_req_ids)
771 # Release the TieringManager's per-request bookkeeping for the
772 # dead session's synthetic lookups on the next serve_external_requests.
773 self._failed_serve_ctxs.extend(close_result.failed_serves)
774 self._data.remove_remote_peer(pid)
775 logger.warning("P2P %s: peer %s down", self._local_id, pid)
776
777 def _reap_unbound_stores(self) -> None:
778 """Time out submit_store batches that no peer has ever fetched.
779
780 Walks `_unbound_stores` for entries whose oldest batch is older
781 than `_unbound_store_timeout_s`. Drops the kv_request_id, surfaces
782 every batched job as failed, and records the id in `_reaped_stores`
783 so a late inbound FetchMsg is rejected in one round trip and a late
784 `submit_store` fails instead of re-parking under the reaped id.
785
786 Also expires `_reaped_stores` entries whose consumer can no longer
787 be waiting, which is why this runs before the empty check below.
788 """
789 now = time.monotonic()
790 if self._reaped_stores:
791 retention_deadline = now - _REAPED_ID_RETENTION_S
792 for kid in [
793 kid
794 for kid, reaped_at in self._reaped_stores.items()
795 if reaped_at <= retention_deadline
796 ]:
797 del self._reaped_stores[kid]
798
799 if not self._unbound_stores:
800 return
801 deadline = now - self._unbound_store_timeout_s
802 expired: list[str] | None = None
803 for kid, batches in self._unbound_stores.items():
804 # Batches are appended in arrival order, so the head is oldest.
805 if batches and batches[0].submitted_at <= deadline:
806 if expired is None:
807 expired = []
808 expired.append(kid)
809 if expired is None:
810 return
811 for kid in expired:
812 batches = self._unbound_stores.pop(kid)
813 self._reaped_stores[kid] = now
814 for batch in batches:
815 self._finished_jobs.append(
816 JobResult(job_id=batch.job_id, success=False)
817 )
818 logger.warning(
819 "P2P %s: unbound store kv_request_id=%s timed out after %.0fs "
820 "without a fetch — failing %d job(s)",
821 self._local_id,
822 kid,
823 self._unbound_store_timeout_s,
824 len(batches),
825 )
826
827 # ------------------------------------------------------------------
828 # Polling
829 # ------------------------------------------------------------------
830
831 def _poll_once(self) -> None:
832 """One sweep of the polling work.
833
834 Drains the control transport, polls every session, accumulates
835 their results into ``_finished_jobs``, and reaps any dead sessions.
836 Runs on the scheduler thread.
837 """
838 new_connections = self._control.poll()
839 if new_connections:
840 logger.info(
841 "P2P %s: _poll_once got %d new connection(s): %s",
842 self._local_id,
843 len(new_connections),
844 [c.peer_id for c in new_connections],
845 )
846
847 self._accept_new_peers(new_connections)
848
849 for session in self._sessions.values():
850 result = session.poll()
851 for lr in result.loads:
852 self._finished_jobs.append(
853 JobResult(job_id=lr.job_id, success=lr.success)
854 )
855 if not lr.success:
856 self._failed_req_ids.add(lr.kv_request_id)
857 for sr in result.stores:
858 self._finished_jobs.append(
859 JobResult(job_id=sr.job_id, success=sr.success)
860 )
861 # Bind kv_request_id → session for any FetchMsg this tick and
862 # replay any submit_store batches parked while no peer was
863 # asking. ServerRole.on_fetch already recorded the demand
864 # inline in dispatch, so the replayed add_stored_blocks calls
865 # match that demand and submit transfers immediately.
866 for kv_request_id in result.new_fetch_ids:
867 if kv_request_id in self._reaped_stores:
868 # This id's blocks were already reaped, so no
869 # submit_store will ever satisfy the demand on_fetch
870 # just recorded. Finalize the round now: the peer gets
871 # TransferDoneMsg(success=False) on this tick and falls
872 # back to local prefill, instead of parking until its
873 # own load timeout expires. The id is deliberately left
874 # unbound so any later submit_store keeps taking the
875 # reject path. Batches re-parked between the reap and the
876 # retention prune are failed here rather than left to a
877 # second reap, which would pin their slots for another
878 # full timeout.
879 session.finish_request(kv_request_id)
880 for batch in self._unbound_stores.pop(kv_request_id, ()):
881 self._finished_jobs.append(
882 JobResult(job_id=batch.job_id, success=False)
883 )
884 continue
885 self._kv_to_session[kv_request_id] = session
886 for batch in self._unbound_stores.pop(kv_request_id, ()):
887 session.add_stored_blocks(
888 kv_request_id, batch.keys, batch.block_ids, batch.job_id
889 )
890
891 self._reap_dead_sessions()
892 self._reap_unbound_stores()
893
894 # ------------------------------------------------------------------
895 # Lifecycle
896 # ------------------------------------------------------------------
897
898 @override
899 def shutdown(self) -> None:
900 self._drain_inflight_for_shutdown()
901 for session in self._sessions.values():
902 # Orphan ctxs from close() are intentionally dropped: the manager
903 # is being torn down, so there is no next serve_external_requests
904 # to flush them and no TieringManager left to release.
905 session.close()
906 self._sessions.clear()
907 self._kv_to_session.clear()
908 # Surface buffered store jobs as failed so the engine doesn't
909 # leak them; the manager is going away after this call.
910 for batches in self._unbound_stores.values():
911 for batch in batches:
912 self._finished_jobs.append(
913 JobResult(job_id=batch.job_id, success=False)
914 )
915 self._unbound_stores.clear()
916 self._reaped_stores.clear()
917 self._control.close()
918 self._data.close()
919
920 def _drain_inflight_for_shutdown(self) -> None:
921 """Best-effort drain of inflight transfers before closing _data.
922
923 Mirrors session._drain_abort but as a single bounded loop. Collects
924 inflight transfer_ids from each session, repeatedly calls
925 _data.cancel(..., mode="wait") and _data.poll() so handles can
926 surface as done/failed, and falls back to mode="immediate" once
927 _SHUTDOWN_DRAIN_TIMEOUT_S elapses so a wedged peer can't hang us.
928 """
929 ids = [tid for s in self._sessions.values() for tid in s._server._inflight]
930 if not ids:
931 return
932 deadline = time.monotonic() + _SHUTDOWN_DRAIN_TIMEOUT_S
933 still: list[int] = ids
934 while still and time.monotonic() < deadline:
935 still = list(self._data.cancel(still, mode="wait"))
936 if not still:
937 break
938 # poll() advances NIXL handle state so the next wait-cancel
939 # has a chance to release the handles.
940 self._data.poll()
941 time.sleep(_DRAIN_SLEEP_S)
942 if still:
943 logger.warning(
944 "P2P %s: shutdown drain timed out after %.1fs with %d "
945 "transfers still inflight — force-cancelling",
946 self._local_id,
947 _SHUTDOWN_DRAIN_TIMEOUT_S,
948 len(still),
949 )
950 self._data.cancel(still, mode="immediate")