Skip to content

vllm.distributed.ec_transfer.ec_connector.tiering

Tiered encoder-cache connector building blocks.

Modules:

  • config –

    Configuration for the local encoder-cache filesystem tier.

  • connector –

    Public connector shell for tiered encoder-cache offloading.

  • executor –

    Asynchronous filesystem I/O execution for encoder-cache entries.

  • filesystem –

    Non-blocking interface for an encoder-cache filesystem tier.

  • io –

    Raw-tensor filesystem I/O for encoder-cache entries.

  • layout –

    Persistent cache identity and full-block disk layout for encoder cache.

  • lookup –

    EC file probes using the native KV asynchronous lookup lifecycle.

  • manager –

    Asynchronous CPU-primary and secondary-tier transfer orchestration.

  • primary –

    Borrow the CPU scheduler's existing cache and storage for tiering.

  • scheduler –

    Scheduler orchestration for CPU-primary encoder-cache tiering.

Classes:

Functions:

ECCacheNamespace dataclass

Stable factors that determine encoder-output byte compatibility.

The digest excludes process- and request-local identity so compatible model configurations can reuse files across restarts. Model identity and effective configuration are captured by encoder_config_hash.

Source code in vllm/distributed/ec_transfer/ec_connector/tiering/layout.py
@dataclass(frozen=True)
class ECCacheNamespace:
    """Stable factors that determine encoder-output byte compatibility.

    The digest excludes process- and request-local identity so compatible model
    configurations can reuse files across restarts. Model identity and effective
    configuration are captured by `encoder_config_hash`.
    """

    encoder_config_hash: str

    def __post_init__(self) -> None:
        _validate_digest(self.encoder_config_hash, "encoder_config_hash")

    def digest(self) -> str:
        factors = asdict(self)
        factors["format_version"] = EC_FILE_FORMAT_VERSION
        return _sha256_json(factors)

ECFileEntry dataclass

An entry published in the filesystem tier's in-memory index.

Source code in vllm/distributed/ec_transfer/ec_connector/tiering/filesystem.py
@dataclass(frozen=True)
class ECFileEntry:
    """An entry published in the filesystem tier's in-memory index."""

    cache_key: str
    path: Path
    file_size_bytes: int

ECFileSystemBackpressureConfig dataclass

Validated EMA backpressure settings for filesystem stores.

Source code in vllm/distributed/ec_transfer/ec_connector/tiering/config.py
@dataclass(frozen=True)
class ECFileSystemBackpressureConfig:
    """Validated EMA backpressure settings for filesystem stores."""

    enabled: bool
    high_water_s: float
    low_water_s: float

ECFileSystemTier

Bases: Protocol

Scheduler-facing contract for the optional filesystem tier.

Implementations own their worker threads and in-memory entry index. Calls made from the scheduler path must not perform filesystem I/O or wait for an I/O task. The caller keeps submitted buffers alive until the matching completion is returned by a poll method.

Methods:

  • contains –

    Return an in-memory membership decision without filesystem I/O.

  • poll_completed_reads –

    Drain currently available read completions without blocking.

  • poll_completed_writes –

    Drain currently available write completions without blocking.

  • shutdown –

    Stop accepting work and release resources owned by the tier.

  • submit_read –

    Queue a filesystem-to-CPU read without blocking.

  • submit_write –

    Queue a CPU-to-filesystem write without blocking.

Source code in vllm/distributed/ec_transfer/ec_connector/tiering/filesystem.py
@runtime_checkable
class ECFileSystemTier(Protocol):
    """Scheduler-facing contract for the optional filesystem tier.

    Implementations own their worker threads and in-memory entry index. Calls
    made from the scheduler path must not perform filesystem I/O or wait for an
    I/O task. The caller keeps submitted buffers alive until the matching
    completion is returned by a poll method.
    """

    def contains(self, cache_key: str) -> bool:
        """Return an in-memory membership decision without filesystem I/O."""
        ...

    def lookup(
        self, cache_key: str, file_size_bytes: int, request_id: str
    ) -> bool | None: ...

    def release_request(self, request_id: str) -> None: ...

    def submit_read(
        self,
        cache_key: str,
        destinations: Sequence[memoryview],
    ) -> bool:
        """Queue a filesystem-to-CPU read without blocking.

        Return `False` when the tier is no longer accepting work. On
        acceptance, exactly one completion must eventually be returned by
        `poll_completed_reads`.
        """
        ...

    def submit_write(
        self,
        cache_key: str,
        sources: Sequence[memoryview],
        file_size_bytes: int,
    ) -> bool:
        """Queue a CPU-to-filesystem write without blocking.

        `file_size_bytes` is the allocated size of all complete CPU blocks.
        The sources must contain every byte of every block, including undefined
        padding in the final block. On acceptance, exactly one completion must
        eventually be returned by `poll_completed_writes`. Return
        `False` when the tier is no longer accepting work or store pressure
        policy, capacity, or same-key lifecycle state skips this cache
        opportunity.
        """
        ...

    def poll_completed_reads(self) -> list[ECReadResult]:
        """Drain currently available read completions without blocking."""
        ...

    def poll_completed_writes(self) -> list[ECWriteResult]:
        """Drain currently available write completions without blocking."""
        ...

    def shutdown(self) -> None:
        """Stop accepting work and release resources owned by the tier."""
        ...

contains(cache_key)

Return an in-memory membership decision without filesystem I/O.

Source code in vllm/distributed/ec_transfer/ec_connector/tiering/filesystem.py
def contains(self, cache_key: str) -> bool:
    """Return an in-memory membership decision without filesystem I/O."""
    ...

poll_completed_reads()

Drain currently available read completions without blocking.

Source code in vllm/distributed/ec_transfer/ec_connector/tiering/filesystem.py
def poll_completed_reads(self) -> list[ECReadResult]:
    """Drain currently available read completions without blocking."""
    ...

poll_completed_writes()

Drain currently available write completions without blocking.

Source code in vllm/distributed/ec_transfer/ec_connector/tiering/filesystem.py
def poll_completed_writes(self) -> list[ECWriteResult]:
    """Drain currently available write completions without blocking."""
    ...

shutdown()

Stop accepting work and release resources owned by the tier.

Source code in vllm/distributed/ec_transfer/ec_connector/tiering/filesystem.py
def shutdown(self) -> None:
    """Stop accepting work and release resources owned by the tier."""
    ...

submit_read(cache_key, destinations)

Queue a filesystem-to-CPU read without blocking.

Return False when the tier is no longer accepting work. On acceptance, exactly one completion must eventually be returned by poll_completed_reads.

Source code in vllm/distributed/ec_transfer/ec_connector/tiering/filesystem.py
def submit_read(
    self,
    cache_key: str,
    destinations: Sequence[memoryview],
) -> bool:
    """Queue a filesystem-to-CPU read without blocking.

    Return `False` when the tier is no longer accepting work. On
    acceptance, exactly one completion must eventually be returned by
    `poll_completed_reads`.
    """
    ...

submit_write(cache_key, sources, file_size_bytes)

Queue a CPU-to-filesystem write without blocking.

file_size_bytes is the allocated size of all complete CPU blocks. The sources must contain every byte of every block, including undefined padding in the final block. On acceptance, exactly one completion must eventually be returned by poll_completed_writes. Return False when the tier is no longer accepting work or store pressure policy, capacity, or same-key lifecycle state skips this cache opportunity.

Source code in vllm/distributed/ec_transfer/ec_connector/tiering/filesystem.py
def submit_write(
    self,
    cache_key: str,
    sources: Sequence[memoryview],
    file_size_bytes: int,
) -> bool:
    """Queue a CPU-to-filesystem write without blocking.

    `file_size_bytes` is the allocated size of all complete CPU blocks.
    The sources must contain every byte of every block, including undefined
    padding in the final block. On acceptance, exactly one completion must
    eventually be returned by `poll_completed_writes`. Return
    `False` when the tier is no longer accepting work or store pressure
    policy, capacity, or same-key lifecycle state skips this cache
    opportunity.
    """
    ...

ECFileSystemTierConfig dataclass

Validated settings for one local encoder-cache filesystem tier.

Source code in vllm/distributed/ec_transfer/ec_connector/tiering/config.py
@dataclass(frozen=True)
class ECFileSystemTierConfig:
    """Validated settings for one local encoder-cache filesystem tier."""

    root_dir: Path
    capacity_bytes: int
    n_read_threads: int
    n_write_threads: int
    backpressure: ECFileSystemBackpressureConfig
    fsync: bool

ECFileSystemTierManager

Capacity-bounded LRU index and lifecycle around entry I/O.

Methods:

  • contains –

    Return an in-memory membership decision without filesystem I/O.

  • drain –

    Wait for accepted I/O and retain its results for later polling.

  • io_stats –

    Return the executor's current non-blocking pressure snapshot.

  • lookup –

    Use indexed entries immediately; probe unknown files asynchronously.

  • poll_completed_reads –

    Drain currently available read completions without blocking.

  • poll_completed_writes –

    Drain currently available write completions without blocking.

  • shutdown –

    Stop submission, drain accepted I/O, and stop the executor.

  • submit_read –

    Submit a read for an indexed entry without filesystem work here.

  • submit_write –

    Submit a write; publish it in memory only after completion.

Attributes:

  • capacity_bytes (int) –

    Return the configured filesystem capacity.

  • used_bytes (int) –

    Return indexed bytes, write reservations and unconfirmed deletions.

Source code in vllm/distributed/ec_transfer/ec_connector/tiering/filesystem.py
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
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
class ECFileSystemTierManager:
    """Capacity-bounded LRU index and lifecycle around entry I/O."""

    def __init__(
        self,
        root_dir: Path,
        namespace_digest: str,
        capacity_bytes: int,
        n_read_threads: int,
        n_write_threads: int,
        *,
        fsync: bool = False,
        backpressure: ECFileSystemBackpressureConfig | None = None,
        executor: _ECFileIOExecutor | None = None,
    ) -> None:
        if capacity_bytes <= 0:
            raise ValueError("filesystem capacity_bytes must be positive")
        owner = ECTemporaryFileOwner(get_ec_namespace_path(root_dir, namespace_digest))
        if executor is None:
            from vllm.distributed.ec_transfer.ec_connector.tiering.executor import (
                ECFileIOExecutor,
            )

            try:
                executor = ECFileIOExecutor(n_read_threads, n_write_threads)
            except BaseException:
                owner.close(owner.orphaned)
                raise

        self._root_dir = root_dir
        self._namespace_digest = namespace_digest
        self._capacity_bytes = capacity_bytes
        self._used_bytes = 0
        self._reserved_write_bytes = 0
        self._pending_delete_bytes = 0
        self._fsync = fsync
        self._executor = executor
        self._temporary_owner = owner
        self._temporary_cleanup = dict(owner.orphaned)
        self._temporary_cleanup_bytes = sum(self._temporary_cleanup.values())
        self._pending_temporary_deletes: dict[int, Path] = {}
        self._write_temporary: dict[int, Path] = {}
        self._backpressure_detector: BackpressureDetector | None = None
        if backpressure is not None and backpressure.enabled:
            self._backpressure_detector = EMABackpressureDetector(
                high_water_s=backpressure.high_water_s,
                low_water_s=backpressure.low_water_s,
            )
        self._accepting = True
        self._shutdown = False
        self._entries: OrderedDict[str, ECFileEntry] = OrderedDict()
        self._invalid_keys: set[str] = set()
        self._pending_reads: dict[int, ECFileEntry] = {}
        self._pending_writes: dict[int, ECFileEntry] = {}
        self._pending_write_keys: set[str] = set()
        self._pending_deletes: dict[int, ECFileEntry] = {}
        self._deleting_keys: set[str] = set()
        self._read_pins: Counter[str] = Counter()
        self._completed_reads: deque[ECReadResult] = deque()
        self._completed_writes: deque[ECWriteResult] = deque()
        try:
            self._recover_index()
            self._lookup = ECFileLookup(root_dir, namespace_digest)
            self._evict_to_capacity()
            self._retry_temporary_cleanup()
        except BaseException:
            if hasattr(self, "_lookup"):
                self._lookup.shutdown()
            self._executor.shutdown()
            owner.close(self._temporary_cleanup)
            raise

    @property
    def used_bytes(self) -> int:
        """Return indexed bytes, write reservations and unconfirmed deletions."""
        return (
            self._used_bytes
            + self._reserved_write_bytes
            + self._pending_delete_bytes
            + self._temporary_cleanup_bytes
        )

    @property
    def capacity_bytes(self) -> int:
        """Return the configured filesystem capacity."""
        return self._capacity_bytes

    def io_stats(self) -> ECFileIOStats:
        """Return the executor's current non-blocking pressure snapshot."""
        return self._executor.stats()

    def contains(self, cache_key: str) -> bool:
        """Return an in-memory membership decision without filesystem I/O."""
        if cache_key in self._invalid_keys or cache_key not in self._entries:
            return False
        self._entries.move_to_end(cache_key)
        return True

    def lookup(
        self, cache_key: str, file_size_bytes: int, request_id: str
    ) -> bool | None:
        """Use indexed entries immediately; probe unknown files asynchronously."""
        if file_size_bytes <= 0:
            raise ValueError("file_size_bytes must be positive")
        if not self._accepting or file_size_bytes > self._capacity_bytes:
            return False
        if cache_key in self._deleting_keys or cache_key in self._invalid_keys:
            return False
        if cache_key in self._pending_write_keys:
            return None
        entry = self._entries.get(cache_key)
        if entry is not None and entry.file_size_bytes != file_size_bytes:
            self._invalid_keys.add(cache_key)
            self._entries.move_to_end(cache_key, last=False)
            self._evict_to_capacity()
            return False
        key = self._lookup.key(cache_key, file_size_bytes)
        result = self._lookup.lookup(key, ReqContext(req_id=request_id))
        if entry is not None:
            # Register the owner so a failed indexed read can be marked MISS.
            # Supersede the pending probe before flush; no file check is queued.
            self._lookup.mark_present([key])
            self._entries.move_to_end(cache_key)
            result = True
        # EC has no schedule-end callback; flush this non-blocking probe here.
        self._lookup.flush()
        if result and entry is None:
            self._entries[cache_key] = ECFileEntry(
                cache_key,
                get_ec_entry_path(self._root_dir, self._namespace_digest, cache_key),
                file_size_bytes,
            )
            self._used_bytes += file_size_bytes
            self._evict_to_capacity()
            return cache_key in self._entries
        return result

    def release_request(self, request_id: str) -> None:
        self._lookup.cleanup(request_id)

    def submit_read(
        self,
        cache_key: str,
        destinations: Sequence[memoryview],
    ) -> bool:
        """Submit a read for an indexed entry without filesystem work here."""
        if not self._accepting:
            return False

        if cache_key in self._invalid_keys:
            return False
        entry = self._entries.get(cache_key)
        if entry is None:
            raise KeyError(f"encoder-cache entry is not indexed: {cache_key}")

        job_id = self._executor.submit_read(
            cache_key,
            entry.path,
            destinations,
            entry.file_size_bytes,
        )
        if job_id is None:
            return False
        self._pending_reads[job_id] = entry
        self._read_pins[cache_key] += 1
        self._entries.move_to_end(cache_key)
        return True

    def submit_write(
        self,
        cache_key: str,
        sources: Sequence[memoryview],
        file_size_bytes: int,
    ) -> bool:
        """Submit a write; publish it in memory only after completion."""
        if not self._accepting:
            return False
        if file_size_bytes <= 0:
            raise ValueError("file_size_bytes must be positive")
        if file_size_bytes > self._capacity_bytes:
            return False
        self._retry_temporary_cleanup()
        if cache_key in self._invalid_keys:
            self._evict_to_capacity()
            return False
        if (
            cache_key in self._entries
            or cache_key in self._pending_write_keys
            or cache_key in self._deleting_keys
        ):
            return False
        if self._backpressure_detector is not None and not (
            self._backpressure_detector.should_store(len(sources))
        ):
            return False
        if not self._evict_to_capacity(file_size_bytes):
            return False

        entry_path = get_ec_entry_path(
            self._root_dir,
            self._namespace_digest,
            cache_key,
        )
        temporary_path = get_ec_temporary_path(
            entry_path, uuid4().hex, self._temporary_owner.owner_id
        )
        entry = ECFileEntry(cache_key, entry_path, file_size_bytes)
        job_id = self._executor.submit_write(
            cache_key,
            entry_path,
            temporary_path,
            sources,
            file_size_bytes,
            fsync=self._fsync,
        )
        if job_id is None:
            return False
        self._pending_writes[job_id] = entry
        self._write_temporary[job_id] = temporary_path
        self._pending_write_keys.add(cache_key)
        self._reserved_write_bytes += file_size_bytes
        return True

    def poll_completed_reads(self) -> list[ECReadResult]:
        """Drain currently available read completions without blocking."""
        self._collect_executor_completions()
        completed = list(self._completed_reads)
        self._completed_reads.clear()
        return completed

    def poll_completed_writes(self) -> list[ECWriteResult]:
        """Drain currently available write completions without blocking."""
        self._collect_executor_completions()
        completed = list(self._completed_writes)
        self._completed_writes.clear()
        return completed

    def drain(self) -> None:
        """Wait for accepted I/O and retain its results for later polling."""
        self._executor.drain()
        self._collect_executor_completions()
        # Write/read completions can enqueue internal eviction deletes.
        self._executor.drain()
        self._collect_executor_completions()

    def shutdown(self) -> None:
        """Stop submission, drain accepted I/O, and stop the executor."""
        if self._shutdown:
            return
        self._accepting = False
        self._retry_temporary_cleanup()
        self._lookup.shutdown()
        self.drain()
        self._executor.shutdown()
        self._collect_executor_completions()
        self._temporary_owner.close(self._temporary_cleanup)
        self._shutdown = True

    def _collect_executor_completions(self) -> None:
        for completion in self._executor.poll_completed():
            if completion.operation == "read":
                self._complete_read(completion)
            elif completion.operation == "write":
                self._complete_write(completion)
            elif completion.operation == "delete":
                if completion.job_id in self._pending_temporary_deletes:
                    path = self._pending_temporary_deletes.pop(completion.job_id)
                    if completion.success:
                        self._temporary_cleanup_bytes -= self._temporary_cleanup.pop(
                            path
                        )
                    else:
                        logger.warning(
                            "Failed to clean encoder-cache temporary file %s: %s",
                            path,
                            completion.error,
                        )
                else:
                    self._complete_delete(completion)
            else:
                raise RuntimeError(
                    f"unknown filesystem I/O operation: {completion.operation}"
                )

    def _complete_read(self, completion: ECFileIOCompletion) -> None:
        indexed_entry = self._pending_reads.pop(completion.job_id)
        self._read_pins[completion.cache_key] -= 1
        if self._read_pins[completion.cache_key] == 0:
            del self._read_pins[completion.cache_key]
        if not completion.success:
            current_entry = self._entries.get(completion.cache_key)
            if current_entry is indexed_entry:
                self._invalid_keys.add(completion.cache_key)
                self._entries.move_to_end(completion.cache_key, last=False)
            self._lookup.mark_miss(
                [self._lookup.key(completion.cache_key, indexed_entry.file_size_bytes)]
            )
        self._completed_reads.append(
            ECReadResult(
                cache_key=completion.cache_key,
                success=completion.success,
                file_size_bytes=completion.file_size_bytes,
                queue_time=completion.queue_time,
                transfer_time=completion.transfer_time,
                error=completion.error,
            )
        )
        self._evict_to_capacity()

    def _complete_write(self, completion: ECFileIOCompletion) -> None:
        entry = self._pending_writes.pop(completion.job_id)
        temporary_path = self._write_temporary.pop(completion.job_id)
        self._pending_write_keys.remove(completion.cache_key)
        self._reserved_write_bytes -= entry.file_size_bytes
        if completion.success:
            if self._backpressure_detector is not None:
                self._backpressure_detector.on_store_completed(
                    completion.queue_time + completion.transfer_time,
                    completion.file_size_bytes,
                )
            self._entries[completion.cache_key] = entry
            self._used_bytes += entry.file_size_bytes
            self._lookup.mark_present(
                [self._lookup.key(completion.cache_key, entry.file_size_bytes)]
            )
        else:
            self._temporary_cleanup[temporary_path] = entry.file_size_bytes
            self._temporary_cleanup_bytes += entry.file_size_bytes
            self._retry_temporary_cleanup()
        self._completed_writes.append(
            ECWriteResult(
                cache_key=completion.cache_key,
                success=completion.success,
                file_size_bytes=completion.file_size_bytes,
                queue_time=completion.queue_time,
                transfer_time=completion.transfer_time,
                error=completion.error,
            )
        )
        self._evict_to_capacity()

    def _retry_temporary_cleanup(self) -> None:
        pending = set(self._pending_temporary_deletes.values())
        for path, size in self._temporary_cleanup.items():
            if path in pending:
                continue
            try:
                job_id = self._executor.submit_delete(path.name, path, max(1, size))
            except Exception:
                logger.warning(
                    "Failed to submit encoder-cache temporary cleanup for %s",
                    path,
                    exc_info=True,
                )
                continue
            if job_id is not None:
                self._pending_temporary_deletes[job_id] = path

    def _complete_delete(self, completion: ECFileIOCompletion) -> None:
        indexed_entry = self._pending_deletes.pop(completion.job_id)
        self._deleting_keys.remove(indexed_entry.cache_key)
        self._pending_delete_bytes -= indexed_entry.file_size_bytes
        if completion.success:
            self._invalid_keys.discard(indexed_entry.cache_key)
        else:
            self._entries[indexed_entry.cache_key] = indexed_entry
            self._entries.move_to_end(indexed_entry.cache_key, last=False)
            self._used_bytes += indexed_entry.file_size_bytes
            logger.warning(
                "Failed to delete evicted encoder-cache entry %s: %s",
                indexed_entry.path,
                completion.error,
            )

    def _recover_index(self) -> None:
        namespace_path = get_ec_namespace_path(
            self._root_dir,
            self._namespace_digest,
        )
        recovered: list[tuple[int, str, ECFileEntry]] = []
        for path in _iter_entry_files(namespace_path):
            cache_key = path.name.removesuffix(EC_FILE_SUFFIX)
            try:
                expected_path = get_ec_entry_path(
                    self._root_dir,
                    self._namespace_digest,
                    cache_key,
                )
            except ValueError:
                continue
            try:
                stat_result = path.stat()
            except FileNotFoundError:
                continue
            if path != expected_path or not S_ISREG(stat_result.st_mode):
                continue
            if stat_result.st_size <= 0:
                continue
            recovered.append(
                (
                    stat_result.st_mtime_ns,
                    cache_key,
                    ECFileEntry(cache_key, path, stat_result.st_size),
                )
            )

        for _, cache_key, entry in sorted(recovered):
            self._entries[cache_key] = entry
            self._used_bytes += entry.file_size_bytes

    def _evict_to_capacity(self, required_bytes: int = 0) -> bool:
        target_bytes = self._capacity_bytes - required_bytes
        # Pending deletes will free space, but cannot fund a write until confirmed.
        while (
            self._invalid_keys - self._deleting_keys
            or self._used_bytes + self._reserved_write_bytes > target_bytes
        ):
            needs_capacity = (
                self._used_bytes + self._reserved_write_bytes > target_bytes
            )
            victim: tuple[str, ECFileEntry] | None = None
            for cache_key, indexed_entry in self._entries.items():
                if (
                    self._read_pins[cache_key] == 0
                    and cache_key not in self._pending_write_keys
                    and (cache_key in self._invalid_keys or needs_capacity)
                ):
                    victim = (cache_key, indexed_entry)
                    break
            if victim is None:
                return False

            cache_key, indexed_entry = victim
            job_id = self._executor.submit_delete(
                cache_key,
                indexed_entry.path,
                indexed_entry.file_size_bytes,
            )
            if job_id is None:
                return False
            del self._entries[cache_key]
            self._used_bytes -= indexed_entry.file_size_bytes
            self._pending_deletes[job_id] = indexed_entry
            self._pending_delete_bytes += indexed_entry.file_size_bytes
            self._deleting_keys.add(cache_key)
            self._lookup.mark_miss(
                [self._lookup.key(cache_key, indexed_entry.file_size_bytes)]
            )
        return self.used_bytes <= target_bytes

capacity_bytes property

Return the configured filesystem capacity.

used_bytes property

Return indexed bytes, write reservations and unconfirmed deletions.

contains(cache_key)

Return an in-memory membership decision without filesystem I/O.

Source code in vllm/distributed/ec_transfer/ec_connector/tiering/filesystem.py
def contains(self, cache_key: str) -> bool:
    """Return an in-memory membership decision without filesystem I/O."""
    if cache_key in self._invalid_keys or cache_key not in self._entries:
        return False
    self._entries.move_to_end(cache_key)
    return True

drain()

Wait for accepted I/O and retain its results for later polling.

Source code in vllm/distributed/ec_transfer/ec_connector/tiering/filesystem.py
def drain(self) -> None:
    """Wait for accepted I/O and retain its results for later polling."""
    self._executor.drain()
    self._collect_executor_completions()
    # Write/read completions can enqueue internal eviction deletes.
    self._executor.drain()
    self._collect_executor_completions()

io_stats()

Return the executor's current non-blocking pressure snapshot.

Source code in vllm/distributed/ec_transfer/ec_connector/tiering/filesystem.py
def io_stats(self) -> ECFileIOStats:
    """Return the executor's current non-blocking pressure snapshot."""
    return self._executor.stats()

lookup(cache_key, file_size_bytes, request_id)

Use indexed entries immediately; probe unknown files asynchronously.

Source code in vllm/distributed/ec_transfer/ec_connector/tiering/filesystem.py
def lookup(
    self, cache_key: str, file_size_bytes: int, request_id: str
) -> bool | None:
    """Use indexed entries immediately; probe unknown files asynchronously."""
    if file_size_bytes <= 0:
        raise ValueError("file_size_bytes must be positive")
    if not self._accepting or file_size_bytes > self._capacity_bytes:
        return False
    if cache_key in self._deleting_keys or cache_key in self._invalid_keys:
        return False
    if cache_key in self._pending_write_keys:
        return None
    entry = self._entries.get(cache_key)
    if entry is not None and entry.file_size_bytes != file_size_bytes:
        self._invalid_keys.add(cache_key)
        self._entries.move_to_end(cache_key, last=False)
        self._evict_to_capacity()
        return False
    key = self._lookup.key(cache_key, file_size_bytes)
    result = self._lookup.lookup(key, ReqContext(req_id=request_id))
    if entry is not None:
        # Register the owner so a failed indexed read can be marked MISS.
        # Supersede the pending probe before flush; no file check is queued.
        self._lookup.mark_present([key])
        self._entries.move_to_end(cache_key)
        result = True
    # EC has no schedule-end callback; flush this non-blocking probe here.
    self._lookup.flush()
    if result and entry is None:
        self._entries[cache_key] = ECFileEntry(
            cache_key,
            get_ec_entry_path(self._root_dir, self._namespace_digest, cache_key),
            file_size_bytes,
        )
        self._used_bytes += file_size_bytes
        self._evict_to_capacity()
        return cache_key in self._entries
    return result

poll_completed_reads()

Drain currently available read completions without blocking.

Source code in vllm/distributed/ec_transfer/ec_connector/tiering/filesystem.py
def poll_completed_reads(self) -> list[ECReadResult]:
    """Drain currently available read completions without blocking."""
    self._collect_executor_completions()
    completed = list(self._completed_reads)
    self._completed_reads.clear()
    return completed

poll_completed_writes()

Drain currently available write completions without blocking.

Source code in vllm/distributed/ec_transfer/ec_connector/tiering/filesystem.py
def poll_completed_writes(self) -> list[ECWriteResult]:
    """Drain currently available write completions without blocking."""
    self._collect_executor_completions()
    completed = list(self._completed_writes)
    self._completed_writes.clear()
    return completed

shutdown()

Stop submission, drain accepted I/O, and stop the executor.

Source code in vllm/distributed/ec_transfer/ec_connector/tiering/filesystem.py
def shutdown(self) -> None:
    """Stop submission, drain accepted I/O, and stop the executor."""
    if self._shutdown:
        return
    self._accepting = False
    self._retry_temporary_cleanup()
    self._lookup.shutdown()
    self.drain()
    self._executor.shutdown()
    self._collect_executor_completions()
    self._temporary_owner.close(self._temporary_cleanup)
    self._shutdown = True

submit_read(cache_key, destinations)

Submit a read for an indexed entry without filesystem work here.

Source code in vllm/distributed/ec_transfer/ec_connector/tiering/filesystem.py
def submit_read(
    self,
    cache_key: str,
    destinations: Sequence[memoryview],
) -> bool:
    """Submit a read for an indexed entry without filesystem work here."""
    if not self._accepting:
        return False

    if cache_key in self._invalid_keys:
        return False
    entry = self._entries.get(cache_key)
    if entry is None:
        raise KeyError(f"encoder-cache entry is not indexed: {cache_key}")

    job_id = self._executor.submit_read(
        cache_key,
        entry.path,
        destinations,
        entry.file_size_bytes,
    )
    if job_id is None:
        return False
    self._pending_reads[job_id] = entry
    self._read_pins[cache_key] += 1
    self._entries.move_to_end(cache_key)
    return True

submit_write(cache_key, sources, file_size_bytes)

Submit a write; publish it in memory only after completion.

Source code in vllm/distributed/ec_transfer/ec_connector/tiering/filesystem.py
def submit_write(
    self,
    cache_key: str,
    sources: Sequence[memoryview],
    file_size_bytes: int,
) -> bool:
    """Submit a write; publish it in memory only after completion."""
    if not self._accepting:
        return False
    if file_size_bytes <= 0:
        raise ValueError("file_size_bytes must be positive")
    if file_size_bytes > self._capacity_bytes:
        return False
    self._retry_temporary_cleanup()
    if cache_key in self._invalid_keys:
        self._evict_to_capacity()
        return False
    if (
        cache_key in self._entries
        or cache_key in self._pending_write_keys
        or cache_key in self._deleting_keys
    ):
        return False
    if self._backpressure_detector is not None and not (
        self._backpressure_detector.should_store(len(sources))
    ):
        return False
    if not self._evict_to_capacity(file_size_bytes):
        return False

    entry_path = get_ec_entry_path(
        self._root_dir,
        self._namespace_digest,
        cache_key,
    )
    temporary_path = get_ec_temporary_path(
        entry_path, uuid4().hex, self._temporary_owner.owner_id
    )
    entry = ECFileEntry(cache_key, entry_path, file_size_bytes)
    job_id = self._executor.submit_write(
        cache_key,
        entry_path,
        temporary_path,
        sources,
        file_size_bytes,
        fsync=self._fsync,
    )
    if job_id is None:
        return False
    self._pending_writes[job_id] = entry
    self._write_temporary[job_id] = temporary_path
    self._pending_write_keys.add(cache_key)
    self._reserved_write_bytes += file_size_bytes
    return True

ECReadResult dataclass

Completion reported for one accepted filesystem read.

Source code in vllm/distributed/ec_transfer/ec_connector/tiering/filesystem.py
@dataclass(frozen=True)
class ECReadResult:
    """Completion reported for one accepted filesystem read."""

    cache_key: str
    success: bool
    file_size_bytes: int = 0
    queue_time: float = 0.0
    transfer_time: float = 0.0
    error: str | None = None

ECTieringConfig dataclass

Validated top-level configuration for encoder-cache tiering.

Methods:

  • from_vllm_config –

    Build tiering configuration from vLLM EC connector settings.

Attributes:

Source code in vllm/distributed/ec_transfer/ec_connector/tiering/config.py
@dataclass(frozen=True)
class ECTieringConfig:
    """Validated top-level configuration for encoder-cache tiering."""

    filesystem_tier: ECFileSystemTierConfig | None

    @property
    def filesystem_enabled(self) -> bool:
        """Return whether a filesystem secondary tier is configured."""
        return self.filesystem_tier is not None

    @classmethod
    def from_vllm_config(cls, vllm_config: VllmConfig) -> ECTieringConfig:
        """Build tiering configuration from vLLM EC connector settings."""
        ec_config = vllm_config.ec_transfer_config
        if ec_config is None:
            raise ValueError("ECTieringConnector requires ec_transfer_config")
        if ec_config.ec_role != "ec_both":
            raise ValueError("ECTieringConnector requires ec_role='ec_both'")

        extra_config = ec_config.ec_connector_extra_config
        if not isinstance(extra_config, dict):
            raise ValueError("ec_connector_extra_config must be a dictionary")

        secondary_tiers = extra_config.get("secondary_tiers", [])
        if not isinstance(secondary_tiers, list):
            raise ValueError("secondary_tiers must be a list")
        if not secondary_tiers:
            return cls(filesystem_tier=None)
        if len(secondary_tiers) > 1:
            raise ValueError(
                "ECTieringConnector currently supports at most one secondary tier"
            )

        return cls(filesystem_tier=_parse_filesystem_tier(secondary_tiers[0]))

filesystem_enabled property

Return whether a filesystem secondary tier is configured.

from_vllm_config(vllm_config) classmethod

Build tiering configuration from vLLM EC connector settings.

Source code in vllm/distributed/ec_transfer/ec_connector/tiering/config.py
@classmethod
def from_vllm_config(cls, vllm_config: VllmConfig) -> ECTieringConfig:
    """Build tiering configuration from vLLM EC connector settings."""
    ec_config = vllm_config.ec_transfer_config
    if ec_config is None:
        raise ValueError("ECTieringConnector requires ec_transfer_config")
    if ec_config.ec_role != "ec_both":
        raise ValueError("ECTieringConnector requires ec_role='ec_both'")

    extra_config = ec_config.ec_connector_extra_config
    if not isinstance(extra_config, dict):
        raise ValueError("ec_connector_extra_config must be a dictionary")

    secondary_tiers = extra_config.get("secondary_tiers", [])
    if not isinstance(secondary_tiers, list):
        raise ValueError("secondary_tiers must be a list")
    if not secondary_tiers:
        return cls(filesystem_tier=None)
    if len(secondary_tiers) > 1:
        raise ValueError(
            "ECTieringConnector currently supports at most one secondary tier"
        )

    return cls(filesystem_tier=_parse_filesystem_tier(secondary_tiers[0]))

ECWriteResult dataclass

Completion reported for one accepted filesystem write.

Source code in vllm/distributed/ec_transfer/ec_connector/tiering/filesystem.py
@dataclass(frozen=True)
class ECWriteResult:
    """Completion reported for one accepted filesystem write."""

    cache_key: str
    success: bool
    file_size_bytes: int = 0
    queue_time: float = 0.0
    transfer_time: float = 0.0
    error: str | None = None

build_ec_cache_key(namespace_digest, identifier, modality, num_tokens, file_size_bytes)

Return a filesystem-safe digest for one encoder-cache item.

Source code in vllm/distributed/ec_transfer/ec_connector/tiering/layout.py
def build_ec_cache_key(
    namespace_digest: str,
    identifier: str,
    modality: str,
    num_tokens: int,
    file_size_bytes: int,
) -> str:
    """Return a filesystem-safe digest for one encoder-cache item."""
    _validate_digest(namespace_digest, "namespace_digest")
    if not identifier:
        raise ValueError("identifier must not be empty")
    if not modality:
        raise ValueError("modality must not be empty")
    if num_tokens <= 0:
        raise ValueError("num_tokens must be positive")
    if file_size_bytes <= 0:
        raise ValueError("file_size_bytes must be positive")
    return _sha256_json(
        {
            "identifier": identifier,
            "modality": modality,
            "namespace_digest": namespace_digest,
            "num_tokens": num_tokens,
            "file_size_bytes": file_size_bytes,
        }
    )

get_ec_entry_path(root_dir, namespace_digest, cache_key)

Map a cache key to a versioned, hash-prefix-sharded raw tensor file.

Source code in vllm/distributed/ec_transfer/ec_connector/tiering/layout.py
def get_ec_entry_path(
    root_dir: Path,
    namespace_digest: str,
    cache_key: str,
) -> Path:
    """Map a cache key to a versioned, hash-prefix-sharded raw tensor file."""
    _validate_digest(namespace_digest, "namespace_digest")
    _validate_digest(cache_key, "cache_key")
    return (
        get_ec_namespace_path(root_dir, namespace_digest)
        / cache_key[:3]
        / cache_key[3:5]
        / f"{cache_key}{EC_FILE_SUFFIX}"
    )

get_ec_namespace_path(root_dir, namespace_digest)

Return the versioned directory containing one cache namespace.

Source code in vllm/distributed/ec_transfer/ec_connector/tiering/layout.py
def get_ec_namespace_path(root_dir: Path, namespace_digest: str) -> Path:
    """Return the versioned directory containing one cache namespace."""
    _validate_digest(namespace_digest, "namespace_digest")
    return root_dir / f"v{EC_FILE_FORMAT_VERSION}" / namespace_digest

get_ec_temporary_path(entry_path, operation_token, owner_id)

Return a temporary path in the namespace's per-owner staging directory.

Source code in vllm/distributed/ec_transfer/ec_connector/tiering/layout.py
def get_ec_temporary_path(
    entry_path: Path, operation_token: str, owner_id: str
) -> Path:
    """Return a temporary path in the namespace's per-owner staging directory."""
    if not operation_token:
        raise ValueError("operation_token must not be empty")
    token_digest = hashlib.sha256(operation_token.encode("utf-8")).hexdigest()[:16]
    if len(owner_id) != 32 or not set(owner_id) <= _LOWERCASE_HEX_DIGITS:
        raise ValueError("owner_id must be 32 lowercase hexadecimal characters")
    return (
        entry_path.parents[2]
        / ".tmp"
        / owner_id
        / f".{entry_path.name}.{owner_id}.{token_digest}.tmp"
    )