[KV Offloading] Implement reset_cache for TieringOffloadingManager (#44541)

Signed-off-by: Ronen Schaffer <ronen.schaffer@ibm.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
This commit is contained in:
Ronen Schaffer
2026-06-15 18:42:53 +00:00
committed by GitHub
co-authored by mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
parent 0a1c5034f5
commit 7e612a0f06
10 changed files with 255 additions and 22 deletions
+17
View File
@@ -193,6 +193,23 @@ class SecondaryTierManager(ABC):
"""
return
@abstractmethod
def drain_jobs(self) -> None:
"""Block until every submitted load/store job has completed or failed.
After this returns, no tier I/O is touching the primary memoryview,
and every submitted job's result is available from `get_finished_jobs()`
(yielded by a prior call or queued for the next one). Used by
`TieringOffloadingManager.reset_cache` to release primary slots
without racing with in-flight transfers.
Implementations must not abort a mid-flight transfer: a partial copy
would corrupt either the primary memoryview or the secondary backing
store. Queued (not-yet-started) transfers may be cancelled, but their
failure result must still appear in `get_finished_jobs()`.
"""
pass
def shutdown(self) -> None:
"""Release resources held by this tier (threads, connections, etc.)."""
return
@@ -142,6 +142,12 @@ class ExampleSecondaryTierManager(SecondaryTierManager):
def on_new_request(self, req_context: ReqContext) -> RequestOffloadingContext:
return RequestOffloadingContext()
@override
def drain_jobs(self) -> None:
"""Synchronous tier — submit_*() returns only after the operation
completes, so there is nothing to wait for."""
return
def get_num_blocks(self) -> int:
"""Get the number of blocks currently stored in this tier."""
return len(self.blocks)
+4
View File
@@ -179,6 +179,10 @@ class FileSystemTierManager(SecondaryTierManager):
)
@override
def drain_jobs(self) -> None:
"""Block until all in-flight transfers in the threadpool finish."""
self._pool.wait_idle()
def on_request_finished(self, req_context: ReqContext) -> None:
self._lookup_manager.cleanup(req_context.req_id)
+23 -1
View File
@@ -68,6 +68,7 @@ class DualQueueThreadPool:
self._stop = False
self._threads: list[threading.Thread] = []
self._finished_q: deque[tuple[JobId, bool]] = deque()
self._inflight_jobs = 0 # guarded by _condition
for i in range(n_read_threads):
t = threading.Thread(
@@ -98,6 +99,7 @@ class DualQueueThreadPool:
"""Enqueue load tasks for a job (high-priority for load-priority threads)."""
state = JobState(job_id, n_tasks)
with self._condition:
self._inflight_jobs += 1
for fn in tasks:
self._load_q.append((fn, state))
self._condition.notify(n_tasks)
@@ -111,21 +113,38 @@ class DualQueueThreadPool:
"""Enqueue store tasks for a job (high-priority for store-priority threads)."""
state = JobState(job_id, n_tasks)
with self._condition:
self._inflight_jobs += 1
for fn in tasks:
self._store_q.append((fn, state))
self._condition.notify(n_tasks)
def get_finished(self) -> list[tuple[JobId, bool]]:
# No lock needed: deque is thread-safe for concurrent append/popleft,
# and the manager is the sole popper.
jobs = []
while self._finished_q:
jobs.append(self._finished_q.popleft())
return jobs
def wait_idle(self) -> None:
"""Block until there are no in-flight jobs.
After this returns, every submitted job has had its last task
finish, so no worker thread is still copying data. Note:
completed jobs may still be sitting in ``_finished_q`` waiting
for ``get_finished()`` to drain them.
"""
with self._condition:
self._condition.wait_for(lambda: self._inflight_jobs == 0)
def shutdown(self, wait: bool = True) -> None:
with self._condition:
self._stop = True
self._load_q.clear()
self._store_q.clear()
# Cancelled tasks will not decrement _inflight_jobs; reset it so a
# subsequent wait_idle() returns instead of hanging.
self._inflight_jobs = 0
self._condition.notify_all()
if wait:
for t in self._threads:
@@ -155,4 +174,7 @@ class DualQueueThreadPool:
job_finished, success = state.task_done(False)
if job_finished:
self._finished_q.append((state.job_id, success))
with self._condition:
self._finished_q.append((state.job_id, success))
self._inflight_jobs -= 1
self._condition.notify_all()
+29
View File
@@ -590,6 +590,35 @@ class TieringOffloadingManager(OffloadingManager):
yield from self.primary_tier.take_events()
@override
def reset_cache(self) -> None:
"""Drop all tracked state in the orchestrator and primary tier.
Called during sleep, weight update, or resume. Each secondary tier
drains its in-flight transfers via drain_jobs() so no tier I/O is
touching primary memory before the primary tier is reset. A stuck
tier will block here visibly — preferable to silent corruption
from reusing primary slots while a transfer is mid-copy.
Secondary tiers are intentionally not reset: persistent stores
(FS, network) keep their data across resets.
"""
for tier in self.secondary_tiers:
tier.drain_jobs()
# All tier I/O has stopped; consume their completion notifications
# so manager bookkeeping is consistent before the primary reset.
self._process_finished_jobs()
# Deferred promotion submissions reserve primary slots that the
# reset below invalidates; their submit_load() has not yet been
# called so no tier I/O is touching that memory.
self._pending_load_submissions.clear()
self.primary_tier.reset_cache()
self._request_level_tiers.clear()
self._processed_jobs_this_step = False
@override
def shutdown(self) -> None:
"""Shutdown all tiers and release resources."""
+43 -10
View File
@@ -3,6 +3,7 @@
"""Object store secondary tier implementation."""
import ctypes
import time
from collections.abc import Iterable
from typing import TYPE_CHECKING, NamedTuple
@@ -104,7 +105,10 @@ class ObjectStoreSecondaryTierManager(SecondaryTierManager):
params = {**obj_config.to_nixl_params(), "num_threads": str(io_threads)}
self._agent.create_backend("OBJ", params)
self._transfers: dict[int, TransferEntry] = {}
self._failed_jobs: list[JobResult] = []
# Buffered results awaiting the next get_finished_jobs() call:
# submission-time failures + poll-time completions accumulated
# during drain_jobs().
self._pending_results: list[JobResult] = []
self._primary_reg = None
self._block_size_bytes: int = 0
root_dir = f"{prefix}/" if prefix else ""
@@ -182,14 +186,14 @@ class ObjectStoreSecondaryTierManager(SecondaryTierManager):
files_desc = self._agent.register_memory(nixl_files, "OBJ")
if files_desc is None:
logger.warning("register_memory (OBJ) failed for job %d", job_id)
self._failed_jobs.append(JobResult(job_id=job_id, success=False))
self._pending_results.append(JobResult(job_id=job_id, success=False))
return
obj_handle = self._agent.prep_xfer_dlist("ObjAgent", files_desc.trim())
if not obj_handle:
logger.warning("prep_xfer_dlist (OBJ) failed for job %d", job_id)
self._agent.deregister_memory(files_desc)
self._failed_jobs.append(JobResult(job_id=job_id, success=False))
self._pending_results.append(JobResult(job_id=job_id, success=False))
return
xfer_handle = self._agent.make_prepped_xfer(
@@ -203,7 +207,7 @@ class ObjectStoreSecondaryTierManager(SecondaryTierManager):
logger.warning("make_prepped_xfer failed for job %d", job_id)
self._agent.release_dlist_handle(obj_handle)
self._agent.deregister_memory(files_desc)
self._failed_jobs.append(JobResult(job_id=job_id, success=False))
self._pending_results.append(JobResult(job_id=job_id, success=False))
return
state = self._agent.transfer(xfer_handle)
@@ -212,7 +216,7 @@ class ObjectStoreSecondaryTierManager(SecondaryTierManager):
self._agent.release_dlist_handle(obj_handle)
self._agent.deregister_memory(files_desc)
self._agent.release_xfer_handle(xfer_handle)
self._failed_jobs.append(JobResult(job_id=job_id, success=False))
self._pending_results.append(JobResult(job_id=job_id, success=False))
return
self._transfers[job_id] = TransferEntry(xfer_handle, files_desc, obj_handle)
@@ -241,10 +245,9 @@ class ObjectStoreSecondaryTierManager(SecondaryTierManager):
def on_new_request(self, req_context: ReqContext) -> RequestOffloadingContext:
return RequestOffloadingContext()
def get_finished_jobs(self) -> Iterable[JobResult]:
"""Poll in-flight transfers; return completed (job_id, success) pairs."""
results: list[JobResult] = self._failed_jobs
self._failed_jobs = []
def _poll_active_transfers(self) -> None:
"""Poll all in-flight transfers once; move newly-completed (success or
failure) into ``_pending_results`` and release their NIXL handles."""
for job_id, entry in list(self._transfers.items()):
try:
state = self._agent.check_xfer_state(entry.xfer_handle)
@@ -263,9 +266,39 @@ class ObjectStoreSecondaryTierManager(SecondaryTierManager):
self._agent.release_xfer_handle(entry.xfer_handle)
self._agent.release_dlist_handle(entry.obj_handle)
self._agent.deregister_memory(entry.files_desc)
results.append(JobResult(job_id=job_id, success=success))
self._pending_results.append(JobResult(job_id=job_id, success=success))
def get_finished_jobs(self) -> Iterable[JobResult]:
"""Poll in-flight transfers; return completed (job_id, success) pairs."""
self._poll_active_transfers()
results = self._pending_results
self._pending_results = []
return results
def drain_jobs(self) -> None:
"""Block until every submitted transfer has completed or failed.
nixl exposes only ``check_xfer_state`` (poll-based), so this loops
until ``_transfers`` is empty. Results accumulate in
``_pending_results`` and are surfaced by the next
``get_finished_jobs()`` call.
"""
start = time.monotonic()
warned = False
while self._transfers:
self._poll_active_transfers()
if not self._transfers:
break
if not warned and time.monotonic() - start > 5.0:
logger.warning(
"ObjectStoreSecondaryTierManager.drain_jobs: still "
"draining after 5s (%d transfers in flight); a stuck "
"transfer will block the engine.",
len(self._transfers),
)
warned = True
time.sleep(0.001)
def shutdown(self) -> None:
self._lookup_manager.shutdown()
for job_id, entry in self._transfers.items():