Skip to content

vllm.v1.kv_offload.tiering.p2p.data

Modules:

  • base –

    Abstract base class for the P2P data-plane transport.

  • nixl –

    NixlTransport: Data-plane transport for RDMA-based KV block transfers via NIXL.

Classes:

  • DataTransport –

    Abstract data-plane transport for RDMA-style block transfers.

  • NixlTransport –

    Manages a NIXL agent, memory registration, and block transfers.

  • PollResult –

    Result of polling inflight transfers.

DataTransport

Bases: ABC

Abstract data-plane transport for RDMA-style block transfers.

Owns the local KV block memory region and manages transfers to/from registered remote peers.

Construction

view: A 2D memoryview (num_blocks × block_len bytes) over the local KV cache block storage. config_fields: Dict of model config values used to compute the compatibility fingerprint. None → empty fingerprint (compatible with any peer).

Methods:

  • add_remote_peer –

    Register a remote peer for block transfers.

  • add_remote_peer_async –

    Register a remote peer without blocking the caller.

  • cancel –

    Cancel inflight transfers by their IDs.

  • close –

    Release all resources (registrations, handles, memory).

  • get_agent_metadata –

    Return opaque metadata needed by remote peers to connect.

  • poll –

    Poll inflight transfers for completion.

  • remove_remote_peer –

    Unregister a remote peer and release associated resources.

  • write_blocks –

    Submit a WRITE transfer: local blocks → remote peer's blocks.

Attributes:

Source code in vllm/v1/kv_offload/tiering/p2p/data/base.py
class DataTransport(ABC):
    """Abstract data-plane transport for RDMA-style block transfers.

    Owns the local KV block memory region and manages transfers to/from
    registered remote peers.

    Construction:
        view: A 2D memoryview (num_blocks × block_len bytes) over the
              local KV cache block storage.
        config_fields: Dict of model config values used to compute the
                       compatibility fingerprint. None → empty fingerprint
                       (compatible with any peer).
    """

    def __init__(self, view: memoryview, config_fields: dict | None = None) -> None:
        assert view.shape is not None
        self._view = view
        self._base_addr = ctypes.addressof(ctypes.c_char.from_buffer(view))
        self._num_blocks = view.shape[0]
        self._block_len = view.shape[1]
        self._config_fingerprint = self._compute_fingerprint(config_fields)

    @property
    def base_addr(self) -> int:
        """Base address of the local block memory region."""
        return self._base_addr

    @property
    def num_blocks(self) -> int:
        """Number of blocks in the local region."""
        return self._num_blocks

    @property
    def block_len(self) -> int:
        """Size of each block in bytes."""
        return self._block_len

    @property
    def config_fingerprint(self) -> str:
        """Content-hash of the model configuration (hex string).

        Peers must have matching fingerprints to exchange blocks.
        Empty string means no fingerprint (always compatible).
        """
        return self._config_fingerprint

    @staticmethod
    def _compute_fingerprint(config_fields: dict | None) -> str:
        if not config_fields:
            return ""
        canonical = json.dumps(config_fields, sort_keys=True, separators=(",", ":"))
        return hashlib.sha256(canonical.encode()).hexdigest()[:16]

    @abstractmethod
    def get_agent_metadata(self) -> bytes:
        """Return opaque metadata needed by remote peers to connect.

        The returned bytes are sent during the control-plane handshake
        and passed to the remote peer's add_remote_peer().
        """
        ...

    @abstractmethod
    def add_remote_peer(
        self,
        peer_id: str,
        agent_metadata: bytes,
        base_addr: int,
        num_blocks: int,
        block_len: int,
    ) -> None:
        """Register a remote peer for block transfers.

        Must be called before write_blocks() to this peer.

        Args:
            peer_id: Unique identifier for the remote peer.
            agent_metadata: Opaque bytes from the peer's get_agent_metadata().
            base_addr: Base address of the peer's block memory region.
            num_blocks: Number of blocks in the peer's region.
            block_len: Size of each block (must match local block_len).

        """
        ...

    def add_remote_peer_async(
        self,
        peer_id: str,
        agent_metadata: bytes,
        base_addr: int,
        num_blocks: int,
        block_len: int,
    ) -> Future[None]:
        """Register a remote peer without blocking the caller.

        Registration is O(num_blocks) and can take seconds for a large
        secondary tier, so the session starts it here and sends
        ``ConnectAckMsg`` only once the returned future resolves. The
        acknowledgement is therefore the peer's guarantee that this side
        is ready to serve, and no ``write_blocks`` can arrive before it.

        The default implementation runs ``add_remote_peer`` inline and
        returns an already-resolved future; transports whose registration
        is cheap need not override it.

        Args:
            peer_id: Unique identifier for the remote peer.
            agent_metadata: Opaque bytes from the peer's get_agent_metadata().
            base_addr: Base address of the peer's block memory region.
            num_blocks: Number of blocks in the peer's region.
            block_len: Size of each block (must match local block_len).

        Returns:
            A future resolving to None on success. A failed future means
            the peer must be rejected rather than acknowledged.

        """
        future: Future[None] = Future()
        try:
            self.add_remote_peer(
                peer_id,
                agent_metadata=agent_metadata,
                base_addr=base_addr,
                num_blocks=num_blocks,
                block_len=block_len,
            )
        except Exception as exc:
            future.set_exception(exc)
        else:
            future.set_result(None)
        return future

    @abstractmethod
    def remove_remote_peer(self, peer_id: str) -> None:
        """Unregister a remote peer and release associated resources.

        Inflight transfers to this peer should be cancelled first.
        """
        ...

    @abstractmethod
    def write_blocks(
        self,
        peer_id: str,
        local_idxs: list[int],
        remote_idxs: list[int],
    ) -> int | None:
        """Submit a WRITE transfer: local blocks → remote peer's blocks.

        Args:
            peer_id: Target peer (must be registered via add_remote_peer).
            local_idxs: Indexes of local blocks to read from.
            remote_idxs: Indexes of remote blocks to write to.
                         Must be same length as local_idxs.

        Returns:
            A unique transfer_id (int) to track this transfer, or
            None if the peer is not registered or submission failed.

        """
        ...

    @abstractmethod
    def poll(self, peer_id: str | None = None) -> PollResult:
        """Poll inflight transfers for completion.

        Args:
            peer_id: If given, only poll (and drain) transfers submitted for
                this peer_id — the value passed to ``write_blocks``. This is
                required when a single transport is shared across multiple
                peer sessions: ``poll()`` pops completed handles, so an
                unscoped poll by one session would consume and discard the
                completions of its siblings, starving them. ``None`` polls
                every peer's transfers (used only for the shutdown drain).

        Returns:
            PollResult with lists of completed and failed transfer_ids.
            Completed/failed transfers are removed from the inflight set.

        Must be called periodically to drive progress checking.

        """
        ...

    @abstractmethod
    def cancel(
        self,
        transfer_ids: Iterable[int],
        mode: CancelMode = "immediate",
    ) -> list[int]:
        """Cancel inflight transfers by their IDs.

        Best-effort: transfers that already completed are ignored.

        Args:
            transfer_ids: IDs to cancel. Unknown IDs are ignored.
            mode:
                "immediate" (default): pop and release each handle and
                    return []. Matches the legacy fire-and-forget
                    behavior — the caller does not wait for the
                    underlying transfer to drain.
                "wait": release only transfers that have stopped. A
                    transfer still PROC/PEND (or whose release fails)
                    stays in the inflight set and its id is included in
                    the returned list. The caller is expected to keep
                    calling poll() until every returned id surfaces in
                    done/failed.

        Returns:
            For mode="wait", the subset of *transfer_ids* still
            tracked as inflight after the cancel attempt. For
            mode="immediate", always [].

        """
        ...

    @abstractmethod
    def close(self) -> None:
        """Release all resources (registrations, handles, memory).

        Cancels any remaining inflight transfers. Idempotent.
        After close(), no other methods may be called.
        """
        ...

base_addr property

Base address of the local block memory region.

block_len property

Size of each block in bytes.

config_fingerprint property

Content-hash of the model configuration (hex string).

Peers must have matching fingerprints to exchange blocks. Empty string means no fingerprint (always compatible).

num_blocks property

Number of blocks in the local region.

add_remote_peer(peer_id, agent_metadata, base_addr, num_blocks, block_len) abstractmethod

Register a remote peer for block transfers.

Must be called before write_blocks() to this peer.

Parameters:

  • peer_id

    (str) –

    Unique identifier for the remote peer.

  • agent_metadata

    (bytes) –

    Opaque bytes from the peer's get_agent_metadata().

  • base_addr

    (int) –

    Base address of the peer's block memory region.

  • num_blocks

    (int) –

    Number of blocks in the peer's region.

  • block_len

    (int) –

    Size of each block (must match local block_len).

Source code in vllm/v1/kv_offload/tiering/p2p/data/base.py
@abstractmethod
def add_remote_peer(
    self,
    peer_id: str,
    agent_metadata: bytes,
    base_addr: int,
    num_blocks: int,
    block_len: int,
) -> None:
    """Register a remote peer for block transfers.

    Must be called before write_blocks() to this peer.

    Args:
        peer_id: Unique identifier for the remote peer.
        agent_metadata: Opaque bytes from the peer's get_agent_metadata().
        base_addr: Base address of the peer's block memory region.
        num_blocks: Number of blocks in the peer's region.
        block_len: Size of each block (must match local block_len).

    """
    ...

add_remote_peer_async(peer_id, agent_metadata, base_addr, num_blocks, block_len)

Register a remote peer without blocking the caller.

Registration is O(num_blocks) and can take seconds for a large secondary tier, so the session starts it here and sends ConnectAckMsg only once the returned future resolves. The acknowledgement is therefore the peer's guarantee that this side is ready to serve, and no write_blocks can arrive before it.

The default implementation runs add_remote_peer inline and returns an already-resolved future; transports whose registration is cheap need not override it.

Parameters:

  • peer_id

    (str) –

    Unique identifier for the remote peer.

  • agent_metadata

    (bytes) –

    Opaque bytes from the peer's get_agent_metadata().

  • base_addr

    (int) –

    Base address of the peer's block memory region.

  • num_blocks

    (int) –

    Number of blocks in the peer's region.

  • block_len

    (int) –

    Size of each block (must match local block_len).

Returns:

  • Future[None] –

    A future resolving to None on success. A failed future means

  • Future[None] –

    the peer must be rejected rather than acknowledged.

Source code in vllm/v1/kv_offload/tiering/p2p/data/base.py
def add_remote_peer_async(
    self,
    peer_id: str,
    agent_metadata: bytes,
    base_addr: int,
    num_blocks: int,
    block_len: int,
) -> Future[None]:
    """Register a remote peer without blocking the caller.

    Registration is O(num_blocks) and can take seconds for a large
    secondary tier, so the session starts it here and sends
    ``ConnectAckMsg`` only once the returned future resolves. The
    acknowledgement is therefore the peer's guarantee that this side
    is ready to serve, and no ``write_blocks`` can arrive before it.

    The default implementation runs ``add_remote_peer`` inline and
    returns an already-resolved future; transports whose registration
    is cheap need not override it.

    Args:
        peer_id: Unique identifier for the remote peer.
        agent_metadata: Opaque bytes from the peer's get_agent_metadata().
        base_addr: Base address of the peer's block memory region.
        num_blocks: Number of blocks in the peer's region.
        block_len: Size of each block (must match local block_len).

    Returns:
        A future resolving to None on success. A failed future means
        the peer must be rejected rather than acknowledged.

    """
    future: Future[None] = Future()
    try:
        self.add_remote_peer(
            peer_id,
            agent_metadata=agent_metadata,
            base_addr=base_addr,
            num_blocks=num_blocks,
            block_len=block_len,
        )
    except Exception as exc:
        future.set_exception(exc)
    else:
        future.set_result(None)
    return future

cancel(transfer_ids, mode='immediate') abstractmethod

Cancel inflight transfers by their IDs.

Best-effort: transfers that already completed are ignored.

Parameters:

  • transfer_ids

    (Iterable[int]) –

    IDs to cancel. Unknown IDs are ignored.

  • mode

    (CancelMode, default: 'immediate' ) –

    "immediate" (default): pop and release each handle and return []. Matches the legacy fire-and-forget behavior — the caller does not wait for the underlying transfer to drain. "wait": release only transfers that have stopped. A transfer still PROC/PEND (or whose release fails) stays in the inflight set and its id is included in the returned list. The caller is expected to keep calling poll() until every returned id surfaces in done/failed.

Returns:

  • list[int] –

    For mode="wait", the subset of transfer_ids still

  • list[int] –

    tracked as inflight after the cancel attempt. For

  • list[int] –

    mode="immediate", always [].

Source code in vllm/v1/kv_offload/tiering/p2p/data/base.py
@abstractmethod
def cancel(
    self,
    transfer_ids: Iterable[int],
    mode: CancelMode = "immediate",
) -> list[int]:
    """Cancel inflight transfers by their IDs.

    Best-effort: transfers that already completed are ignored.

    Args:
        transfer_ids: IDs to cancel. Unknown IDs are ignored.
        mode:
            "immediate" (default): pop and release each handle and
                return []. Matches the legacy fire-and-forget
                behavior — the caller does not wait for the
                underlying transfer to drain.
            "wait": release only transfers that have stopped. A
                transfer still PROC/PEND (or whose release fails)
                stays in the inflight set and its id is included in
                the returned list. The caller is expected to keep
                calling poll() until every returned id surfaces in
                done/failed.

    Returns:
        For mode="wait", the subset of *transfer_ids* still
        tracked as inflight after the cancel attempt. For
        mode="immediate", always [].

    """
    ...

close() abstractmethod

Release all resources (registrations, handles, memory).

Cancels any remaining inflight transfers. Idempotent. After close(), no other methods may be called.

Source code in vllm/v1/kv_offload/tiering/p2p/data/base.py
@abstractmethod
def close(self) -> None:
    """Release all resources (registrations, handles, memory).

    Cancels any remaining inflight transfers. Idempotent.
    After close(), no other methods may be called.
    """
    ...

get_agent_metadata() abstractmethod

Return opaque metadata needed by remote peers to connect.

The returned bytes are sent during the control-plane handshake and passed to the remote peer's add_remote_peer().

Source code in vllm/v1/kv_offload/tiering/p2p/data/base.py
@abstractmethod
def get_agent_metadata(self) -> bytes:
    """Return opaque metadata needed by remote peers to connect.

    The returned bytes are sent during the control-plane handshake
    and passed to the remote peer's add_remote_peer().
    """
    ...

poll(peer_id=None) abstractmethod

Poll inflight transfers for completion.

Parameters:

  • peer_id

    (str | None, default: None ) –

    If given, only poll (and drain) transfers submitted for this peer_id — the value passed to write_blocks. This is required when a single transport is shared across multiple peer sessions: poll() pops completed handles, so an unscoped poll by one session would consume and discard the completions of its siblings, starving them. None polls every peer's transfers (used only for the shutdown drain).

Returns:

  • PollResult –

    PollResult with lists of completed and failed transfer_ids.

  • PollResult –

    Completed/failed transfers are removed from the inflight set.

Must be called periodically to drive progress checking.

Source code in vllm/v1/kv_offload/tiering/p2p/data/base.py
@abstractmethod
def poll(self, peer_id: str | None = None) -> PollResult:
    """Poll inflight transfers for completion.

    Args:
        peer_id: If given, only poll (and drain) transfers submitted for
            this peer_id — the value passed to ``write_blocks``. This is
            required when a single transport is shared across multiple
            peer sessions: ``poll()`` pops completed handles, so an
            unscoped poll by one session would consume and discard the
            completions of its siblings, starving them. ``None`` polls
            every peer's transfers (used only for the shutdown drain).

    Returns:
        PollResult with lists of completed and failed transfer_ids.
        Completed/failed transfers are removed from the inflight set.

    Must be called periodically to drive progress checking.

    """
    ...

remove_remote_peer(peer_id) abstractmethod

Unregister a remote peer and release associated resources.

Inflight transfers to this peer should be cancelled first.

Source code in vllm/v1/kv_offload/tiering/p2p/data/base.py
@abstractmethod
def remove_remote_peer(self, peer_id: str) -> None:
    """Unregister a remote peer and release associated resources.

    Inflight transfers to this peer should be cancelled first.
    """
    ...

write_blocks(peer_id, local_idxs, remote_idxs) abstractmethod

Submit a WRITE transfer: local blocks → remote peer's blocks.

Parameters:

  • peer_id

    (str) –

    Target peer (must be registered via add_remote_peer).

  • local_idxs

    (list[int]) –

    Indexes of local blocks to read from.

  • remote_idxs

    (list[int]) –

    Indexes of remote blocks to write to. Must be same length as local_idxs.

Returns:

  • int | None –

    A unique transfer_id (int) to track this transfer, or

  • int | None –

    None if the peer is not registered or submission failed.

Source code in vllm/v1/kv_offload/tiering/p2p/data/base.py
@abstractmethod
def write_blocks(
    self,
    peer_id: str,
    local_idxs: list[int],
    remote_idxs: list[int],
) -> int | None:
    """Submit a WRITE transfer: local blocks → remote peer's blocks.

    Args:
        peer_id: Target peer (must be registered via add_remote_peer).
        local_idxs: Indexes of local blocks to read from.
        remote_idxs: Indexes of remote blocks to write to.
                     Must be same length as local_idxs.

    Returns:
        A unique transfer_id (int) to track this transfer, or
        None if the peer is not registered or submission failed.

    """
    ...

NixlTransport

Bases: DataTransport

Manages a NIXL agent, memory registration, and block transfers.

Wraps the NIXL C library behind a Python interface so the rest of the P2P tier code never touches NIXL types directly. Tracks inflight handles internally and returns completed/failed tags on poll.

Methods:

  • cancel –

    Cancel inflight transfers by their IDs.

  • poll –

    Poll inflight transfers.

  • write_blocks –

    Submit a WRITE transfer to peer_id.

Source code in vllm/v1/kv_offload/tiering/p2p/data/nixl.py
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
class NixlTransport(DataTransport):
    """Manages a NIXL agent, memory registration, and block transfers.

    Wraps the NIXL C library behind a Python interface so the rest of the
    P2P tier code never touches NIXL types directly. Tracks inflight
    handles internally and returns completed/failed tags on poll.
    """

    def __init__(
        self,
        agent_name: str,
        view: memoryview,
        config_fields: dict | None = None,
        backends: list[str] | None = None,
        num_threads: int = 4,
    ) -> None:
        super().__init__(view, config_fields=config_fields)
        self._agent_name = agent_name
        self._backends = list(backends) if backends else ["UCX"]
        self._num_threads = num_threads
        self._agent: Any = None
        self._reg: Any = None
        self._local_dlist: Any = None
        self._remote_dlists: dict[str, object] = {}
        self._peer_nixl_names: dict[str, str] = {}
        # transfer_id → _Inflight(peer_id, handle).
        self._inflight: dict[int, _Inflight] = {}
        self._next_id = itertools.count()
        # peer_id → transfer-scope failures since its last success.
        self._peer_strikes: dict[str, int] = {}
        # peer_id → fault cause; reported by poll(peer_id) until removal.
        self._peer_faults: dict[str, str] = {}
        # Registration is O(num_blocks) NIXL work — add_remote_agent plus a
        # prep_xfer_dlist over every block of the peer's region — so it runs
        # off the scheduler thread, mirroring the NIXL connector's
        # _handshake_initiation_executor. One worker only: NIXL is not
        # guaranteed to be thread-safe, so registrations stay serialized
        # against each other.
        self._reg_executor = ThreadPoolExecutor(
            max_workers=1, thread_name_prefix="vllm-p2p-nixl-reg"
        )
        # peer_id → registration generation, bumped on every add and remove.
        # A worker that finishes building handles under a stale generation
        # releases them instead of publishing, so a late completion cannot
        # revive a peer that was reaped or superseded meanwhile.
        self._peer_gen: dict[str, int] = {}
        # Guards _peer_gen together with _peer_nixl_names/_remote_dlists so
        # the generation check and the publish are one atomic step.
        self._peer_lock = threading.Lock()

        self._init(view)

    @property
    def available(self) -> bool:
        return self._agent is not None

    def _init(self, view: memoryview) -> None:
        if _NixlAgent is None:
            return

        non_ucx_backends = [b for b in self._backends if b != "UCX"]
        if non_ucx_backends:
            cfg = _NixlAgentConfig(backends=self._backends, capture_telemetry=True)
            logger.info(
                "NixlTransport %s: NIXL backends=%s",
                self._agent_name,
                self._backends,
            )
        else:
            cfg = _NixlAgentConfig(
                num_threads=self._num_threads, capture_telemetry=True
            )
            logger.info(
                "NixlTransport %s: NIXL backends=[UCX] num_threads=%d",
                self._agent_name,
                self._num_threads,
            )
        self._agent = _NixlAgent(self._agent_name, cfg)

        total_size = self._num_blocks * self._block_len
        reg_descs = [(self._base_addr, total_size, 0, "")]
        self._reg = self._agent.register_memory(reg_descs, mem_type="DRAM")

        block_tuples = [
            (self._base_addr + i * self._block_len, self._block_len, 0)
            for i in range(self._num_blocks)
        ]
        xfer_dlist = self._agent.get_xfer_descs(block_tuples, mem_type="DRAM")
        self._local_dlist = self._agent.prep_xfer_dlist("NIXL_INIT_AGENT", xfer_dlist)
        logger.info(
            "NixlTransport %s: registered %d blocks", self._agent_name, self._num_blocks
        )

    def get_agent_metadata(self) -> bytes:
        assert self._agent is not None
        return self._agent.get_agent_metadata()

    # ------------------------------------------------------------------
    # Peer management
    # ------------------------------------------------------------------

    def add_remote_peer(
        self,
        peer_id: str,
        agent_metadata: bytes,
        base_addr: int,
        num_blocks: int,
        block_len: int,
    ) -> None:
        gen = self._begin_registration(peer_id)
        nixl_name, remote_dlist = self._build_peer_handles(
            agent_metadata, base_addr, num_blocks, block_len
        )
        self._publish_peer(peer_id, gen, nixl_name, remote_dlist)

    def add_remote_peer_async(
        self,
        peer_id: str,
        agent_metadata: bytes,
        base_addr: int,
        num_blocks: int,
        block_len: int,
    ) -> Future[None]:
        gen = self._begin_registration(peer_id)

        def register() -> None:
            nixl_name, remote_dlist = self._build_peer_handles(
                agent_metadata, base_addr, num_blocks, block_len
            )
            if not self._publish_peer(peer_id, gen, nixl_name, remote_dlist):
                raise RuntimeError(
                    f"registration for peer {peer_id} was superseded "
                    "(peer removed or re-registered while registering)"
                )

        return self._reg_executor.submit(register)

    def remove_remote_peer(self, peer_id: str) -> None:
        with self._peer_lock:
            # Invalidate any registration still being built for this peer so
            # its worker releases the handles instead of publishing them.
            self._peer_gen[peer_id] = self._peer_gen.get(peer_id, 0) + 1
            nixl_name = self._peer_nixl_names.pop(peer_id, None)
            dlist = self._remote_dlists.pop(peer_id, None)
        self._peer_strikes.pop(peer_id, None)
        self._peer_faults.pop(peer_id, None)
        if self._agent is not None:
            self._release_remote_handles(peer_id, dlist, nixl_name)

    def _begin_registration(self, peer_id: str) -> int:
        """Claim the next registration generation for *peer_id*."""
        with self._peer_lock:
            gen = self._peer_gen.get(peer_id, 0) + 1
            self._peer_gen[peer_id] = gen
            return gen

    def _build_peer_handles(
        self,
        agent_metadata: bytes,
        base_addr: int,
        num_blocks: int,
        block_len: int,
    ) -> tuple[str, Any]:
        """The expensive half: agent wireup plus one descriptor per block.

        Touches no shared state, so it runs unlocked — holding the peer
        lock across it would stall the scheduler thread for exactly as
        long as the registration it is meant to move off that thread.
        """
        nixl_name = self._agent.add_remote_agent(agent_metadata)
        block_descs = [
            (base_addr + i * block_len, block_len, 0) for i in range(num_blocks)
        ]
        xfer_dlist = self._agent.get_xfer_descs(block_descs, mem_type="DRAM")
        remote_dlist = self._agent.prep_xfer_dlist(nixl_name, xfer_dlist)
        return nixl_name, remote_dlist

    def _publish_peer(
        self,
        peer_id: str,
        gen: int,
        nixl_name: str,
        remote_dlist: Any,
    ) -> bool:
        """Install freshly built handles, unless *gen* is stale.

        Returns False when the peer was removed or re-registered while the
        handles were being built; the handles are released here since
        nothing else ever saw them.
        """
        with self._peer_lock:
            fresh = self._peer_gen.get(peer_id) == gen
            if fresh:
                self._peer_nixl_names[peer_id] = nixl_name
                self._remote_dlists[peer_id] = remote_dlist
        if fresh:
            return True
        logger.info(
            "NixlTransport %s: discarding superseded registration for peer=%s",
            self._agent_name,
            peer_id,
        )
        if self._agent is not None:
            self._release_remote_handles(peer_id, remote_dlist, nixl_name)
        return False

    def _release_remote_handles(
        self, peer_id: str, dlist: object | None, nixl_name: str | None
    ) -> None:
        """Release a peer's descriptor list and remote agent independently.

        The two teardown operations are independent: NIXL may reject one
        after a transport failure, and a ``release_dlist_handle`` that
        raises must not skip ``remove_remote_agent``. Skipping it would
        leave a stale remote registration behind after the peer is gone
        (peer removal) or after its registration was superseded.
        """
        if dlist is not None:
            try:
                self._agent.release_dlist_handle(dlist)
            except Exception as exc:
                logger.warning(
                    "NixlTransport %s: releasing dlist handle for peer=%s failed: %s",
                    self._agent_name,
                    peer_id,
                    exc,
                )
        if nixl_name:
            try:
                self._agent.remove_remote_agent(nixl_name)
            except Exception as exc:
                logger.warning(
                    "NixlTransport %s: removing remote agent for peer=%s failed: %s",
                    self._agent_name,
                    peer_id,
                    exc,
                )

    # ------------------------------------------------------------------
    # Transfer submission and polling
    # ------------------------------------------------------------------

    def write_blocks(
        self,
        peer_id: str,
        local_idxs: list[int],
        remote_idxs: list[int],
    ) -> int | None:
        """Submit a WRITE transfer to *peer_id*.

        Returns a transfer ID, or None if the peer is not registered or
        submission fails. The ID is returned via poll() when the transfer
        completes or fails.
        """
        remote_dlist = self._remote_dlists.get(peer_id)
        if remote_dlist is None:
            logger.warning(
                "NixlTransport %s: write_blocks NO REMOTE DLIST for peer=%s "
                "(known peers=%s)",
                self._agent_name,
                peer_id,
                list(self._remote_dlists.keys()),
            )
            return None
        logger.debug(
            "NixlTransport %s: write_blocks NIXL.transfer peer=%s blocks=%d",
            self._agent_name,
            peer_id,
            len(local_idxs),
        )
        local_arr = np.asarray(local_idxs, dtype=np.int32)
        remote_arr = np.asarray(remote_idxs, dtype=np.int32)
        handle = None
        try:
            handle = self._agent.make_prepped_xfer(
                "WRITE", self._local_dlist, local_arr, remote_dlist, remote_arr
            )
            # transfer() reports a failed post as "ERR" instead of raising.
            if self._agent.transfer(handle) == "ERR":
                raise RuntimeError("transfer() posted with status ERR")
        except Exception as exc:
            logger.warning(
                "NixlTransport %s: write_blocks failed for peer=%s: %s",
                self._agent_name,
                peer_id,
                exc,
            )
            if handle is not None:
                self._release_handles([handle])
            self._record_failure(peer_id, exc)
            return None
        transfer_id = next(self._next_id)
        self._inflight[transfer_id] = _Inflight(peer_id, handle)
        return transfer_id

    def poll(self, peer_id: str | None = None) -> PollResult:
        """Poll inflight transfers.

        When *peer_id* is given, only transfers submitted for that peer_id are
        checked and drained — the transport is shared across peer sessions, so
        an unscoped poll by one session would consume and discard siblings'
        completions. *peer_id* None polls every peer (shutdown drain only).

        Returns PollResult(done=..., failed=..., peer_fault=...) with
        transfer IDs. Completed handles are released automatically.
        ``peer_fault`` is set on a scoped poll once *peer_id* is faulted.
        """
        if not self._inflight:
            return self._poll_result(peer_id, None, None)

        done_ids: list[int] | None = None
        failed_ids: list[int] | None = None
        # Strikes are applied once the batch is classified: poll() sees
        # completions, not their order, so a DONE anywhere in the batch is
        # the success "between" its peer's earlier failures.
        succeeded: set[str] | None = None
        failures: list[tuple[str, str]] | None = None

        for transfer_id, entry in self._inflight.items():
            if peer_id is not None and entry.peer_id != peer_id:
                continue
            try:
                state = self._agent.check_xfer_state(entry.handle)
            except Exception as exc:
                # A check that keeps raising warns once, then at debug.
                (logger.debug if entry.struck else logger.warning)(
                    "NixlTransport %s: check_xfer_state failed for transfer_id=%d: %s",
                    self._agent_name,
                    transfer_id,
                    exc,
                )
                if not entry.struck:
                    self._record_state_check_failure(entry.peer_id, exc)
                    entry = self._inflight[transfer_id] = entry._replace(struck=True)
                if not _is_terminal_state_error(exc):
                    # Kept: the WRITE may still be landing. Its peer is now
                    # faulted, so the session disconnects once this drains
                    # or at its drain cap, and the teardown reclaims it.
                    continue
                state = "ERR"
            if state == "DONE":
                if done_ids is None:
                    done_ids = []
                done_ids.append(transfer_id)
                if succeeded is None:
                    succeeded = set()
                succeeded.add(entry.peer_id)
            elif state not in ("PROC", "PEND"):
                if failed_ids is None:
                    failed_ids = []
                failed_ids.append(transfer_id)
                if not entry.struck:
                    if failures is None:
                        failures = []
                    failures.append((entry.peer_id, f"state {state}"))

        for pid in succeeded or ():
            self._peer_strikes.pop(pid, None)
        for pid, cause in failures or ():
            self._record_transfer_failure(pid, cause)

        if done_ids is None and failed_ids is None:
            return self._poll_result(peer_id, None, None)

        handles_to_release = []
        for tid in done_ids or ():
            handles_to_release.append(self._inflight.pop(tid).handle)
        for tid in failed_ids or ():
            handles_to_release.append(self._inflight.pop(tid).handle)
        self._release_handles(handles_to_release)

        return self._poll_result(peer_id, done_ids, failed_ids)

    def _poll_result(
        self,
        peer_id: str | None,
        done_ids: list[int] | None,
        failed_ids: list[int] | None,
    ) -> PollResult:
        fault = self._peer_faults.get(peer_id) if peer_id is not None else None
        if done_ids is None and failed_ids is None and fault is None:
            return _EMPTY_POLL_RESULT
        return PollResult(
            done=done_ids if done_ids is not None else _EMPTY_POLL_RESULT.done,
            failed=failed_ids if failed_ids is not None else _EMPTY_POLL_RESULT.failed,
            peer_fault=fault,
        )

    def cancel(
        self,
        transfer_ids: Iterable[int],
        mode: CancelMode = "immediate",
    ) -> list[int]:
        """Cancel inflight transfers by their IDs.

        See ``DataTransport.cancel`` for the contract. In "wait" mode, a
        transfer is released only once NIXL reports it terminal. Releasing
        a PROC/PEND handle does not stop the WRITE: the UCX backend frees
        the request without cancelling RMA, and the bytes keep landing. So
        PROC/PEND transfers, and those whose state check or
        ``release_xfer_handle`` raises, stay in ``self._inflight`` for a
        later ``poll()`` to observe. A state check that raises faults the
        peer; only a remote disconnect also counts as terminal (see
        ``_is_terminal_state_error``).
        """
        if mode == "immediate":
            handles = [
                self._inflight.pop(tid).handle
                for tid in transfer_ids
                if tid in self._inflight
            ]
            self._release_handles(handles)
            return []

        still_inflight: list[int] = []
        for tid in transfer_ids:
            entry = self._inflight.get(tid)
            if entry is None:
                continue
            try:
                state = self._agent.check_xfer_state(entry.handle)
            except Exception as exc:
                logger.debug(
                    "NixlTransport %s: cancel state check failed for "
                    "transfer_id=%d: %s",
                    self._agent_name,
                    tid,
                    exc,
                )
                self._record_state_check_failure(entry.peer_id, exc)
                if not _is_terminal_state_error(exc):
                    still_inflight.append(tid)
                    continue
                # The handle may no longer be releasable; it is terminal
                # either way, so drop it instead of retrying forever.
                self._release_handles([entry.handle])
                del self._inflight[tid]
                continue
            if state in ("PROC", "PEND"):
                still_inflight.append(tid)
                continue
            try:
                self._agent.release_xfer_handle(entry.handle)
            except Exception as exc:
                logger.debug(
                    "NixlTransport %s: cancel pending for transfer_id=%d: %s",
                    self._agent_name,
                    tid,
                    exc,
                )
                still_inflight.append(tid)
                continue
            del self._inflight[tid]
        return still_inflight

    # ------------------------------------------------------------------
    # Lifecycle
    # ------------------------------------------------------------------

    def close(self) -> None:
        # Stop accepting registrations and let any in-flight one finish
        # before the agent goes away underneath it.
        self._reg_executor.shutdown(wait=True)
        if self._agent is None:
            return
        self._release_handles([entry.handle for entry in self._inflight.values()])
        self._inflight.clear()
        for peer_id in list(self._remote_dlists):
            self.remove_remote_peer(peer_id)
        if self._local_dlist is not None:
            self._agent.release_dlist_handle(self._local_dlist)
            self._local_dlist = None
        if self._reg is not None:
            self._agent.deregister_memory(self._reg)
            self._reg = None
        self._agent = None

    # ------------------------------------------------------------------
    # Internal
    # ------------------------------------------------------------------

    def _record_failure(self, peer_id: str, exc: Exception) -> None:
        """Classify a NIXL exception: a peer fault, or one strike."""
        status = _peer_fault_status(exc)
        if status is not None:
            self._set_peer_fault(peer_id, status)
        else:
            self._record_transfer_failure(peer_id, f"{type(exc).__name__}: {exc}")

    def _record_state_check_failure(self, peer_id: str, exc: Exception) -> None:
        """Fault *peer_id* for a ``check_xfer_state`` that raised.

        The bindings raise for every NIXL error status (only success and
        in-progress are returned), so a raise is a failure NIXL reported,
        not a flaky check. A peer whose transfer state can't be trusted is
        torn down rather than given strikes: with strikes, successes to the
        same peer could keep resetting them while the transfer stays
        inflight, holding its pins, for good.
        """
        self._set_peer_fault(
            peer_id,
            _peer_fault_status(exc)
            or f"check_xfer_state raised {type(exc).__name__}: {exc}",
        )

    def _record_transfer_failure(self, peer_id: str, cause: str) -> None:
        strikes = self._peer_strikes.get(peer_id, 0) + 1
        self._peer_strikes[peer_id] = strikes
        if strikes >= _MAX_CONSECUTIVE_TRANSFER_FAILURES:
            self._set_peer_fault(
                peer_id, f"{strikes} consecutive transfer failures (last: {cause})"
            )

    def _set_peer_fault(self, peer_id: str, cause: str) -> None:
        if peer_id in self._peer_faults:
            return
        self._peer_faults[peer_id] = cause
        logger.warning(
            "NixlTransport %s: registration for peer=%s judged unusable: %s",
            self._agent_name,
            peer_id,
            cause,
        )

    def _release_handles(self, handles: list[object]) -> None:
        if self._agent is None:
            return
        for handle in handles:
            try:
                self._agent.release_xfer_handle(handle)
            except Exception as exc:
                logger.warning(
                    "NixlTransport %s: release_xfer_handle failed: %s",
                    self._agent_name,
                    exc,
                )

_begin_registration(peer_id)

Claim the next registration generation for peer_id.

Source code in vllm/v1/kv_offload/tiering/p2p/data/nixl.py
def _begin_registration(self, peer_id: str) -> int:
    """Claim the next registration generation for *peer_id*."""
    with self._peer_lock:
        gen = self._peer_gen.get(peer_id, 0) + 1
        self._peer_gen[peer_id] = gen
        return gen

_build_peer_handles(agent_metadata, base_addr, num_blocks, block_len)

The expensive half: agent wireup plus one descriptor per block.

Touches no shared state, so it runs unlocked — holding the peer lock across it would stall the scheduler thread for exactly as long as the registration it is meant to move off that thread.

Source code in vllm/v1/kv_offload/tiering/p2p/data/nixl.py
def _build_peer_handles(
    self,
    agent_metadata: bytes,
    base_addr: int,
    num_blocks: int,
    block_len: int,
) -> tuple[str, Any]:
    """The expensive half: agent wireup plus one descriptor per block.

    Touches no shared state, so it runs unlocked — holding the peer
    lock across it would stall the scheduler thread for exactly as
    long as the registration it is meant to move off that thread.
    """
    nixl_name = self._agent.add_remote_agent(agent_metadata)
    block_descs = [
        (base_addr + i * block_len, block_len, 0) for i in range(num_blocks)
    ]
    xfer_dlist = self._agent.get_xfer_descs(block_descs, mem_type="DRAM")
    remote_dlist = self._agent.prep_xfer_dlist(nixl_name, xfer_dlist)
    return nixl_name, remote_dlist

_publish_peer(peer_id, gen, nixl_name, remote_dlist)

Install freshly built handles, unless gen is stale.

Returns False when the peer was removed or re-registered while the handles were being built; the handles are released here since nothing else ever saw them.

Source code in vllm/v1/kv_offload/tiering/p2p/data/nixl.py
def _publish_peer(
    self,
    peer_id: str,
    gen: int,
    nixl_name: str,
    remote_dlist: Any,
) -> bool:
    """Install freshly built handles, unless *gen* is stale.

    Returns False when the peer was removed or re-registered while the
    handles were being built; the handles are released here since
    nothing else ever saw them.
    """
    with self._peer_lock:
        fresh = self._peer_gen.get(peer_id) == gen
        if fresh:
            self._peer_nixl_names[peer_id] = nixl_name
            self._remote_dlists[peer_id] = remote_dlist
    if fresh:
        return True
    logger.info(
        "NixlTransport %s: discarding superseded registration for peer=%s",
        self._agent_name,
        peer_id,
    )
    if self._agent is not None:
        self._release_remote_handles(peer_id, remote_dlist, nixl_name)
    return False

_record_failure(peer_id, exc)

Classify a NIXL exception: a peer fault, or one strike.

Source code in vllm/v1/kv_offload/tiering/p2p/data/nixl.py
def _record_failure(self, peer_id: str, exc: Exception) -> None:
    """Classify a NIXL exception: a peer fault, or one strike."""
    status = _peer_fault_status(exc)
    if status is not None:
        self._set_peer_fault(peer_id, status)
    else:
        self._record_transfer_failure(peer_id, f"{type(exc).__name__}: {exc}")

_record_state_check_failure(peer_id, exc)

Fault peer_id for a check_xfer_state that raised.

The bindings raise for every NIXL error status (only success and in-progress are returned), so a raise is a failure NIXL reported, not a flaky check. A peer whose transfer state can't be trusted is torn down rather than given strikes: with strikes, successes to the same peer could keep resetting them while the transfer stays inflight, holding its pins, for good.

Source code in vllm/v1/kv_offload/tiering/p2p/data/nixl.py
def _record_state_check_failure(self, peer_id: str, exc: Exception) -> None:
    """Fault *peer_id* for a ``check_xfer_state`` that raised.

    The bindings raise for every NIXL error status (only success and
    in-progress are returned), so a raise is a failure NIXL reported,
    not a flaky check. A peer whose transfer state can't be trusted is
    torn down rather than given strikes: with strikes, successes to the
    same peer could keep resetting them while the transfer stays
    inflight, holding its pins, for good.
    """
    self._set_peer_fault(
        peer_id,
        _peer_fault_status(exc)
        or f"check_xfer_state raised {type(exc).__name__}: {exc}",
    )

_release_remote_handles(peer_id, dlist, nixl_name)

Release a peer's descriptor list and remote agent independently.

The two teardown operations are independent: NIXL may reject one after a transport failure, and a release_dlist_handle that raises must not skip remove_remote_agent. Skipping it would leave a stale remote registration behind after the peer is gone (peer removal) or after its registration was superseded.

Source code in vllm/v1/kv_offload/tiering/p2p/data/nixl.py
def _release_remote_handles(
    self, peer_id: str, dlist: object | None, nixl_name: str | None
) -> None:
    """Release a peer's descriptor list and remote agent independently.

    The two teardown operations are independent: NIXL may reject one
    after a transport failure, and a ``release_dlist_handle`` that
    raises must not skip ``remove_remote_agent``. Skipping it would
    leave a stale remote registration behind after the peer is gone
    (peer removal) or after its registration was superseded.
    """
    if dlist is not None:
        try:
            self._agent.release_dlist_handle(dlist)
        except Exception as exc:
            logger.warning(
                "NixlTransport %s: releasing dlist handle for peer=%s failed: %s",
                self._agent_name,
                peer_id,
                exc,
            )
    if nixl_name:
        try:
            self._agent.remove_remote_agent(nixl_name)
        except Exception as exc:
            logger.warning(
                "NixlTransport %s: removing remote agent for peer=%s failed: %s",
                self._agent_name,
                peer_id,
                exc,
            )

cancel(transfer_ids, mode='immediate')

Cancel inflight transfers by their IDs.

See DataTransport.cancel for the contract. In "wait" mode, a transfer is released only once NIXL reports it terminal. Releasing a PROC/PEND handle does not stop the WRITE: the UCX backend frees the request without cancelling RMA, and the bytes keep landing. So PROC/PEND transfers, and those whose state check or release_xfer_handle raises, stay in self._inflight for a later poll() to observe. A state check that raises faults the peer; only a remote disconnect also counts as terminal (see _is_terminal_state_error).

Source code in vllm/v1/kv_offload/tiering/p2p/data/nixl.py
def cancel(
    self,
    transfer_ids: Iterable[int],
    mode: CancelMode = "immediate",
) -> list[int]:
    """Cancel inflight transfers by their IDs.

    See ``DataTransport.cancel`` for the contract. In "wait" mode, a
    transfer is released only once NIXL reports it terminal. Releasing
    a PROC/PEND handle does not stop the WRITE: the UCX backend frees
    the request without cancelling RMA, and the bytes keep landing. So
    PROC/PEND transfers, and those whose state check or
    ``release_xfer_handle`` raises, stay in ``self._inflight`` for a
    later ``poll()`` to observe. A state check that raises faults the
    peer; only a remote disconnect also counts as terminal (see
    ``_is_terminal_state_error``).
    """
    if mode == "immediate":
        handles = [
            self._inflight.pop(tid).handle
            for tid in transfer_ids
            if tid in self._inflight
        ]
        self._release_handles(handles)
        return []

    still_inflight: list[int] = []
    for tid in transfer_ids:
        entry = self._inflight.get(tid)
        if entry is None:
            continue
        try:
            state = self._agent.check_xfer_state(entry.handle)
        except Exception as exc:
            logger.debug(
                "NixlTransport %s: cancel state check failed for "
                "transfer_id=%d: %s",
                self._agent_name,
                tid,
                exc,
            )
            self._record_state_check_failure(entry.peer_id, exc)
            if not _is_terminal_state_error(exc):
                still_inflight.append(tid)
                continue
            # The handle may no longer be releasable; it is terminal
            # either way, so drop it instead of retrying forever.
            self._release_handles([entry.handle])
            del self._inflight[tid]
            continue
        if state in ("PROC", "PEND"):
            still_inflight.append(tid)
            continue
        try:
            self._agent.release_xfer_handle(entry.handle)
        except Exception as exc:
            logger.debug(
                "NixlTransport %s: cancel pending for transfer_id=%d: %s",
                self._agent_name,
                tid,
                exc,
            )
            still_inflight.append(tid)
            continue
        del self._inflight[tid]
    return still_inflight

poll(peer_id=None)

Poll inflight transfers.

When peer_id is given, only transfers submitted for that peer_id are checked and drained — the transport is shared across peer sessions, so an unscoped poll by one session would consume and discard siblings' completions. peer_id None polls every peer (shutdown drain only).

Returns PollResult(done=..., failed=..., peer_fault=...) with transfer IDs. Completed handles are released automatically. peer_fault is set on a scoped poll once peer_id is faulted.

Source code in vllm/v1/kv_offload/tiering/p2p/data/nixl.py
def poll(self, peer_id: str | None = None) -> PollResult:
    """Poll inflight transfers.

    When *peer_id* is given, only transfers submitted for that peer_id are
    checked and drained — the transport is shared across peer sessions, so
    an unscoped poll by one session would consume and discard siblings'
    completions. *peer_id* None polls every peer (shutdown drain only).

    Returns PollResult(done=..., failed=..., peer_fault=...) with
    transfer IDs. Completed handles are released automatically.
    ``peer_fault`` is set on a scoped poll once *peer_id* is faulted.
    """
    if not self._inflight:
        return self._poll_result(peer_id, None, None)

    done_ids: list[int] | None = None
    failed_ids: list[int] | None = None
    # Strikes are applied once the batch is classified: poll() sees
    # completions, not their order, so a DONE anywhere in the batch is
    # the success "between" its peer's earlier failures.
    succeeded: set[str] | None = None
    failures: list[tuple[str, str]] | None = None

    for transfer_id, entry in self._inflight.items():
        if peer_id is not None and entry.peer_id != peer_id:
            continue
        try:
            state = self._agent.check_xfer_state(entry.handle)
        except Exception as exc:
            # A check that keeps raising warns once, then at debug.
            (logger.debug if entry.struck else logger.warning)(
                "NixlTransport %s: check_xfer_state failed for transfer_id=%d: %s",
                self._agent_name,
                transfer_id,
                exc,
            )
            if not entry.struck:
                self._record_state_check_failure(entry.peer_id, exc)
                entry = self._inflight[transfer_id] = entry._replace(struck=True)
            if not _is_terminal_state_error(exc):
                # Kept: the WRITE may still be landing. Its peer is now
                # faulted, so the session disconnects once this drains
                # or at its drain cap, and the teardown reclaims it.
                continue
            state = "ERR"
        if state == "DONE":
            if done_ids is None:
                done_ids = []
            done_ids.append(transfer_id)
            if succeeded is None:
                succeeded = set()
            succeeded.add(entry.peer_id)
        elif state not in ("PROC", "PEND"):
            if failed_ids is None:
                failed_ids = []
            failed_ids.append(transfer_id)
            if not entry.struck:
                if failures is None:
                    failures = []
                failures.append((entry.peer_id, f"state {state}"))

    for pid in succeeded or ():
        self._peer_strikes.pop(pid, None)
    for pid, cause in failures or ():
        self._record_transfer_failure(pid, cause)

    if done_ids is None and failed_ids is None:
        return self._poll_result(peer_id, None, None)

    handles_to_release = []
    for tid in done_ids or ():
        handles_to_release.append(self._inflight.pop(tid).handle)
    for tid in failed_ids or ():
        handles_to_release.append(self._inflight.pop(tid).handle)
    self._release_handles(handles_to_release)

    return self._poll_result(peer_id, done_ids, failed_ids)

write_blocks(peer_id, local_idxs, remote_idxs)

Submit a WRITE transfer to peer_id.

Returns a transfer ID, or None if the peer is not registered or submission fails. The ID is returned via poll() when the transfer completes or fails.

Source code in vllm/v1/kv_offload/tiering/p2p/data/nixl.py
def write_blocks(
    self,
    peer_id: str,
    local_idxs: list[int],
    remote_idxs: list[int],
) -> int | None:
    """Submit a WRITE transfer to *peer_id*.

    Returns a transfer ID, or None if the peer is not registered or
    submission fails. The ID is returned via poll() when the transfer
    completes or fails.
    """
    remote_dlist = self._remote_dlists.get(peer_id)
    if remote_dlist is None:
        logger.warning(
            "NixlTransport %s: write_blocks NO REMOTE DLIST for peer=%s "
            "(known peers=%s)",
            self._agent_name,
            peer_id,
            list(self._remote_dlists.keys()),
        )
        return None
    logger.debug(
        "NixlTransport %s: write_blocks NIXL.transfer peer=%s blocks=%d",
        self._agent_name,
        peer_id,
        len(local_idxs),
    )
    local_arr = np.asarray(local_idxs, dtype=np.int32)
    remote_arr = np.asarray(remote_idxs, dtype=np.int32)
    handle = None
    try:
        handle = self._agent.make_prepped_xfer(
            "WRITE", self._local_dlist, local_arr, remote_dlist, remote_arr
        )
        # transfer() reports a failed post as "ERR" instead of raising.
        if self._agent.transfer(handle) == "ERR":
            raise RuntimeError("transfer() posted with status ERR")
    except Exception as exc:
        logger.warning(
            "NixlTransport %s: write_blocks failed for peer=%s: %s",
            self._agent_name,
            peer_id,
            exc,
        )
        if handle is not None:
            self._release_handles([handle])
        self._record_failure(peer_id, exc)
        return None
    transfer_id = next(self._next_id)
    self._inflight[transfer_id] = _Inflight(peer_id, handle)
    return transfer_id

PollResult

Bases: NamedTuple

Result of polling inflight transfers.

Attributes:

  • done (Sequence[int]) –

    Transfer IDs that completed successfully.

  • failed (Sequence[int]) –

    Transfer IDs that failed (error, timeout, etc.).

  • peer_fault (str | None) –

    Set only on a peer-scoped poll() once the transport has judged the peer unusable (see "Failure model"); a short human-readable cause. None while the peer is healthy.

Source code in vllm/v1/kv_offload/tiering/p2p/data/base.py
class PollResult(NamedTuple):
    """Result of polling inflight transfers.

    Attributes:
        done: Transfer IDs that completed successfully.
        failed: Transfer IDs that failed (error, timeout, etc.).
        peer_fault: Set only on a peer-scoped poll() once the transport
            has judged the peer unusable (see "Failure model"); a short
            human-readable cause. None while the peer is healthy.

    """

    done: Sequence[int]
    failed: Sequence[int]
    peer_fault: str | None = None