mirror of
https://github.com/lightseekorg/tokenspeed.git
synced 2026-12-04 10:26:50 +08:00
perf(cache): unify host and device eviction planning (#2922)
## Summary Pick https://github.com/lightseekorg/tokenspeed/pull/2661/changes/2a0ca6a4d3983490455ae85d44b9f7c2e9c50f94 and https://github.com/lightseekorg/tokenspeed/pull/2661/changes/d105c22cc4b70d62519c6d9e36f4055699de5e9e to main. Builds on #2593's global Host LRU. Host replacement could still scan the entire cache and commit placements one row at a time, causing unnecessary evictions or rejecting batches that could fit jointly. - Share eviction ordering, capacity simulation, and removal of unnecessary tentative victims between Device admission and Host placement. Host intentionally adopts Device's equal-age ordering, including checkpoint priorities and suffix-first eviction. Traverse candidates lazily until enough capacity is found. - Plan Host batches before committing placements, preserving pinning, bucket ownership, and Host-specific checkpoint and write-back rules. - Refresh existing Host entries when their keys are reused or republished on Device. Preserve newer Host timestamps without extra allocations, pins, or transfers. ## Test Plan - All 1,107 scheduler C++ tests passed after rebasing. - Regression coverage includes packed parents, joint placement, checkpoint lifetime, and Host recency. - Repository pre-commit checks passed. Earlier planner microbenchmarks reduced two-group Host replacement at 1M entries from 70.8 ms to 9.1 µs. Simple replacements incurred about 0.2–0.5 µs additional overhead. These measurements predate the recency follow-up and rebase; serving throughput and cache-hit rate were not measured. --------- Signed-off-by: Enwei Zhu <21126786+syuoni@users.noreply.github.com>
This commit is contained in:
@@ -1057,33 +1057,32 @@ Its responsibilities:
|
||||
written back instead (below).
|
||||
Under `kWriteThrough` a `pending_stores_` queue drives D2H transfers,
|
||||
alongside Host-side acquire/contains/pin queries. Host L2 uses free
|
||||
capacity first, then global LRU across cache groups: a compatible child in
|
||||
the requested group competes with fully evictable LCM parents across
|
||||
groups. When only one group needs
|
||||
replacement, its own parents are omitted: the initial allocation pass
|
||||
exhausted the requested buckets' holes, so each such parent has a compatible
|
||||
child no newer than its newest child and cannot beat single-child eviction.
|
||||
For a history group in this case, an ordered cursor collects only enough
|
||||
children for each unresolved bucket, then stops after that epoch. The cursor
|
||||
is destroyed before eviction mutates the index. Donor groups, State groups,
|
||||
and batches with multiple replacement groups retain full candidate scans.
|
||||
Cross-group reuse must free a whole parent, ranked by its most recently
|
||||
accessed child, so a cold sibling cannot cause newer data to be discarded.
|
||||
Equal epochs prefer
|
||||
evicting one child; group and physical location break remaining ties. A
|
||||
prefix hit refreshes its access epoch, and earlier reuse grants no
|
||||
additional protection. Pinned entries, partially pinned foreign parents,
|
||||
and blocks allocated earlier in the same batch remain protected. Parent
|
||||
candidates are snapshots; selection skips parents that are now empty or
|
||||
bound to another group. Parent aggregation reuses coordinator-owned scratch
|
||||
storage and resets and examines only touched parents, rather than the whole
|
||||
Host arena on every allocation batch. Child reuse preserves the requested
|
||||
placement bucket. Host eviction removes each selected entry independently,
|
||||
except that a State checkpoint takes the other State groups' checkpoints
|
||||
at its hash along; each block retries free capacity before it picks a
|
||||
victim, so it places in the room such a cascade freed.
|
||||
No group has an eviction preference or a fixed share of the pool; capacity follows the access
|
||||
pattern, without guaranteeing that KV and every required state checkpoint
|
||||
capacity first, then the same `CacheEvictionPlan` as Device admission:
|
||||
access epoch first, then boundary tier and logical position, followed by
|
||||
group and physical location. Equal-age prefix pages leave from the suffix;
|
||||
unproven chunk boundaries leave before established boundaries and prefix
|
||||
pages. The plan tries victims against shadow occupancy until the accepted
|
||||
rows fit, then restores every unnecessary victim, newest first. Failed
|
||||
rows therefore evict nothing they alone needed. Ordinary stores can place
|
||||
later rows after a shortfall; retraction boundaries must fit whole and
|
||||
stop at the first shortfall.
|
||||
A different group can reuse a parent only after its last occupant leaves.
|
||||
A cold sibling cannot force a hot one out: the hot entry participates at
|
||||
its own rank, and tentative holes that cannot fund the allocation are
|
||||
restored. This needs no separate whole-parent ranking or pool-sized scratch
|
||||
array. Candidate traversal stops when demand fits, reading complete equal
|
||||
epochs for the shared tie-breaks. Cursors are destroyed before eviction.
|
||||
Pinned entries and destinations allocated in the initial free-capacity pass
|
||||
remain protected. Host State at one boundary leaves as a set across its
|
||||
unpinned State groups; Host KV eviction does not take Device checkpoints
|
||||
along. The plan accounts for the full State cascade before picking another
|
||||
victim. Every placed block retains its requested owner bucket.
|
||||
Device prefix hits and publications refresh existing Host copies of the
|
||||
same entries without allocating, pinning, or transferring blocks. A refresh
|
||||
never lowers the Host access epoch. Touching history alone does not refresh
|
||||
an unused State checkpoint at the same boundary.
|
||||
No group has a fixed share of the pool; capacity follows the access pattern,
|
||||
without guaranteeing that KV and every required state checkpoint
|
||||
remain resident together. During prefill, each chunk end queues the
|
||||
full-attention pages it published; the prompt end (the first decode's
|
||||
admission, or a junction cut) queues its tail and state checkpoint too;
|
||||
@@ -1428,6 +1427,16 @@ its groups in tries victims the same way. Both Host plans fit on it over Host
|
||||
L2: the segment plan (`AcquireHostSegments`) and the boundary plan
|
||||
(`NumHostBoundariesThatFit`, `AcquireHostBoundaries`).
|
||||
|
||||
`CacheEvictionPlan` (`eviction_plan.h`) shares candidate merging, shadow
|
||||
capacity, selection until demand fits, and reverse minimization between
|
||||
Device admission and both Host block-placement entry points. Its
|
||||
`CacheEvictionCandidates` cursor reads only the access epochs needed, with
|
||||
the same boundary-tier/position ordering on both tiers. The caller defines
|
||||
which blocks leave together: Device segments and request releases, or Host
|
||||
State cascades. Host segment write-back retains its copy-aware ordering and
|
||||
cross-tier checkpoint dependencies; its fallback boundary placement uses the
|
||||
shared planner.
|
||||
|
||||
A victim set is the candidate block alone unless the coordinator evicts by
|
||||
*segments* (`write_back_evictions`, the Host write-back policy). Then the set
|
||||
follows the `BoundaryTree`, so eviction keeps the Device's coverage closed
|
||||
|
||||
@@ -740,9 +740,9 @@ the image as the split planned:
|
||||
The split plans the L2 leg before anything is acquired or evicted for it. The
|
||||
slots to copy are grouped by boundary (a content hash, with every group's slot
|
||||
at it), the shallowest first, and the Host takes the leading boundaries that
|
||||
fit whole (`CacheCoordinator::NumHostBoundariesThatFit`, planned in
|
||||
`AcquireHostBlocks`' order and with its victim ranking against a shadow of the
|
||||
Host); the retraction (`AcquireHostBoundaries`) evicts exactly the planned
|
||||
fit whole (`CacheCoordinator::NumHostBoundariesThatFit`, using the shared
|
||||
eviction planner). All rows fit jointly against shadow capacity before any
|
||||
placement is committed; the retraction (`AcquireHostBoundaries`) evicts exactly the planned
|
||||
victims and places exactly those rows. The first boundary the Host cannot take
|
||||
whole goes to the pool with every later one, even where the Host has room for
|
||||
some of their rows. Under the write-back policy the plan takes Host room for
|
||||
@@ -750,10 +750,9 @@ every boundary as an eviction write-back does, by whole segments first
|
||||
(`AcquireHostSegments`' plan: whole victims, none above a page an eviction
|
||||
write-back is still bringing, boundaries dropped from the deepest), then block
|
||||
by block, as above, for the boundaries the segment step dropped, against the
|
||||
Host less its victims. Where the two steps place fewer boundaries than block
|
||||
by block alone, the block-by-block plan stands, so the Host takes at least as
|
||||
many boundaries as the block-by-block plan would on the same Host, and
|
||||
sometimes more, since its victims differ. Placing block by block may take the
|
||||
Host less its victims. Both policies can use all eligible capacity: the
|
||||
segment step changes victim preference, while the shared block planner fits
|
||||
the remaining rows jointly. Placing block by block may take the
|
||||
Host page above an eviction write-back in flight. The write-back still
|
||||
publishes at its ACK — the settlement reads the tail hint and the checkpoint
|
||||
boundaries under its node, not the gap above — and the next dead-entry
|
||||
|
||||
+299
-459
@@ -20,6 +20,7 @@
|
||||
|
||||
#include "cache/coordinator/cache_coordinator.h"
|
||||
|
||||
#include "cache/coordinator/eviction_plan.h"
|
||||
#include "cache/coordinator/group_geometry.h"
|
||||
#include "cache/coordinator/shadow_occupancy.h"
|
||||
|
||||
@@ -115,7 +116,7 @@ public:
|
||||
evicts_segments_{evicts_segments},
|
||||
evicts_blocks_past_segments_{evicts_blocks_past_segments},
|
||||
victims_{victims},
|
||||
shadow_{pool, groups},
|
||||
eviction_plan_{pool, groups},
|
||||
shape_need_(groups.size()),
|
||||
blocks_needed_(groups.size()) {}
|
||||
|
||||
@@ -125,7 +126,7 @@ public:
|
||||
|
||||
// Existing local holes plus empty parents are the zero-eviction
|
||||
// capacity. Do not discard cache merely to make placement denser.
|
||||
if (shadow_.Fits(shape_need_, blocks_needed_)) {
|
||||
if (eviction_plan_.Fits(shape_need_, blocks_needed_)) {
|
||||
return true;
|
||||
}
|
||||
if (!couldFitAfterEviction()) {
|
||||
@@ -156,377 +157,324 @@ public:
|
||||
// rules passed over, tried again block by block.
|
||||
bool blocks_alone = false;
|
||||
std::size_t next_passed_over = 0;
|
||||
while (!shadow_.Fits(shape_need_, blocks_needed_)) {
|
||||
std::optional<VictimCandidate> candidate = nextVictimCandidate();
|
||||
if (!candidate && next_deferred_shared_page < deferred_shared_pages_.size()) {
|
||||
// The candidates ran out before the demand fits, and pages two
|
||||
// or more checkpoint boundaries share are still in place. Count
|
||||
// the checkpoint boundaries the selected sets take whole: a
|
||||
// page only they depend on may leave now, with everything under
|
||||
// it.
|
||||
if (!candidates_ran_out) {
|
||||
candidates_ran_out = true;
|
||||
std::pmr::unordered_set<const BoundaryTree::Node*> counted{&scratch_};
|
||||
for (const VictimSet& set : victims_) {
|
||||
const bool fits = eviction_plan_.SelectUntilFits(shape_need_, blocks_needed_, [&] {
|
||||
while (true) {
|
||||
std::optional<VictimCandidate> candidate = eviction_plan_.Next(request_reclaim_candidates_);
|
||||
if (!candidate && next_deferred_shared_page < deferred_shared_pages_.size()) {
|
||||
// The candidates ran out before the demand fits, and pages two
|
||||
// or more checkpoint boundaries share are still in place. Count
|
||||
// the checkpoint boundaries the selected sets take whole: a
|
||||
// page only they depend on may leave now, with everything under
|
||||
// it.
|
||||
if (!candidates_ran_out) {
|
||||
candidates_ran_out = true;
|
||||
std::pmr::unordered_set<const BoundaryTree::Node*> counted{&scratch_};
|
||||
for (const VictimSet& set : victims_) {
|
||||
for (const VictimSet::Member& member : set.members) {
|
||||
if (!coordinator_.GroupIsState(member.group_id)) {
|
||||
continue;
|
||||
}
|
||||
const std::optional<CacheKey> key =
|
||||
groups_[member.group_id].Index().KeyOf(pool_, member.location);
|
||||
const BoundaryTree::Node* checkpoint_node =
|
||||
key ? boundary_tree_.Find(key->content_hash) : nullptr;
|
||||
if (checkpoint_node == nullptr || !counted.insert(checkpoint_node).second ||
|
||||
!std::ranges::all_of(coordinator_.NodeEntries(pool_, *checkpoint_node),
|
||||
[&](const NodeEntry& entry) {
|
||||
return !coordinator_.GroupIsState(entry.group_id) ||
|
||||
set_member_by_location_.contains(entry.location);
|
||||
})) {
|
||||
continue;
|
||||
}
|
||||
for (const BoundaryTree::Node* ancestor = checkpoint_node; ancestor != nullptr;
|
||||
ancestor = ancestor->parent) {
|
||||
++leaving_checkpoint_boundary_counts_[ancestor];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
candidate = deferred_shared_pages_[next_deferred_shared_page++];
|
||||
}
|
||||
if (!candidate && evicts_blocks_past_segments_ && next_passed_over < passed_over_.size()) {
|
||||
blocks_alone = true;
|
||||
candidate = passed_over_[next_passed_over++];
|
||||
}
|
||||
if (!candidate) {
|
||||
return false;
|
||||
}
|
||||
const std::uint32_t group_id = candidate->group_id;
|
||||
const CacheBlockLocation location = candidate->location;
|
||||
// Already leaving with an earlier set, or found unable to leave
|
||||
// (passed over: tried again block by block).
|
||||
if (set_member_by_location_.contains(location)) {
|
||||
continue;
|
||||
}
|
||||
if (!blocks_alone && unevictable_locations_.contains(location)) {
|
||||
passed_over_.push_back(*candidate);
|
||||
continue;
|
||||
}
|
||||
VictimSet set{.is_request_reclaim = request_reclaim_locations_.contains(location)};
|
||||
// A segment that takes an earlier segment's lists over in place
|
||||
// keeps them first (the first num_taken_over_members members, their
|
||||
// set_member_by_location_ entries as they are).
|
||||
std::size_t num_taken_over_members = 0;
|
||||
std::optional<std::size_t> taken_over_set_index;
|
||||
// The tree node a segment set starts at.
|
||||
const BoundaryTree::Node* segment_top = nullptr;
|
||||
const BoundaryTree::Node* candidate_node = nullptr;
|
||||
if (evicts_segments_) {
|
||||
if (const std::optional<CacheKey> key = groups_[group_id].Index().KeyOf(pool_, location)) {
|
||||
candidate_node = boundary_tree_.Find(key->content_hash);
|
||||
}
|
||||
}
|
||||
const bool sliding =
|
||||
!groups_[group_id].Matcher().IsPrefixClosed() && !coordinator_.GroupIsState(group_id);
|
||||
if (candidate_node == nullptr || (sliding && !set.is_request_reclaim)) {
|
||||
// Block by block; or a block with no tree node (never
|
||||
// published, or registered straight into an index); or a window
|
||||
// block, which only shortens the boundaries its prefix resumes
|
||||
// at.
|
||||
set.members.push_back(
|
||||
VictimSet::Member{.group_id = group_id, .location = location, .in_stranded_suffix = false});
|
||||
} else if (set.is_request_reclaim) {
|
||||
// The request's released slots at this hash, and at a tail
|
||||
// the tail's other blocks, which their eviction takes along.
|
||||
for (const NodeEntry& entry : coordinator_.NodeEntries(pool_, *candidate_node)) {
|
||||
if (request_reclaim_locations_.contains(entry.location) ||
|
||||
(candidate_node->tail_tokens > 0 && is_evictable(entry))) {
|
||||
set.members.push_back(VictimSet::Member{
|
||||
.group_id = entry.group_id, .location = entry.location, .in_stranded_suffix = false});
|
||||
}
|
||||
}
|
||||
} else if (blocks_alone ? coordinator_.GroupIsState(group_id)
|
||||
: num_staying_checkpoint_boundaries(*candidate_node) >= 2) {
|
||||
// Deeper checkpoint boundaries still read this page. A nested
|
||||
// checkpoint leaves alone, every State group's at once; the
|
||||
// page leaves with the last checkpoint boundary under it, or is
|
||||
// tried again once the candidates run out. Block by block, every
|
||||
// checkpoint leaves so; at a tail its eviction takes the tail's
|
||||
// other unpinned blocks along (evictCachedBlock), uncounted here.
|
||||
if (!coordinator_.GroupIsState(group_id)) {
|
||||
(candidates_ran_out ? passed_over_ : deferred_shared_pages_).push_back(*candidate);
|
||||
continue;
|
||||
}
|
||||
bool evictable = true;
|
||||
for (const NodeEntry& entry : coordinator_.NodeEntries(pool_, *candidate_node)) {
|
||||
if (coordinator_.GroupIsState(entry.group_id)) {
|
||||
evictable = evictable && is_evictable(entry);
|
||||
set.members.push_back(VictimSet::Member{
|
||||
.group_id = entry.group_id, .location = entry.location, .in_stranded_suffix = false});
|
||||
}
|
||||
}
|
||||
if (!evictable) {
|
||||
for (const VictimSet::Member& member : set.members) {
|
||||
if (!coordinator_.GroupIsState(member.group_id)) {
|
||||
continue;
|
||||
}
|
||||
const std::optional<CacheKey> key =
|
||||
groups_[member.group_id].Index().KeyOf(pool_, member.location);
|
||||
const BoundaryTree::Node* checkpoint_node =
|
||||
key ? boundary_tree_.Find(key->content_hash) : nullptr;
|
||||
if (checkpoint_node == nullptr || !counted.insert(checkpoint_node).second ||
|
||||
!std::ranges::all_of(coordinator_.NodeEntries(pool_, *checkpoint_node),
|
||||
[&](const NodeEntry& entry) {
|
||||
return !coordinator_.GroupIsState(entry.group_id) ||
|
||||
set_member_by_location_.contains(entry.location);
|
||||
})) {
|
||||
continue;
|
||||
}
|
||||
for (const BoundaryTree::Node* ancestor = checkpoint_node; ancestor != nullptr;
|
||||
ancestor = ancestor->parent) {
|
||||
++leaving_checkpoint_boundary_counts_[ancestor];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
candidate = deferred_shared_pages_[next_deferred_shared_page++];
|
||||
}
|
||||
if (!candidate && evicts_blocks_past_segments_ && next_passed_over < passed_over_.size()) {
|
||||
blocks_alone = true;
|
||||
candidate = passed_over_[next_passed_over++];
|
||||
}
|
||||
if (!candidate) {
|
||||
return false;
|
||||
}
|
||||
const std::uint32_t group_id = candidate->group_id;
|
||||
const CacheBlockLocation location = candidate->location;
|
||||
// Already leaving with an earlier set, or found unable to leave
|
||||
// (passed over: tried again block by block).
|
||||
if (set_member_by_location_.contains(location)) {
|
||||
continue;
|
||||
}
|
||||
if (!blocks_alone && unevictable_locations_.contains(location)) {
|
||||
passed_over_.push_back(*candidate);
|
||||
continue;
|
||||
}
|
||||
VictimSet set{.is_request_reclaim = request_reclaim_locations_.contains(location)};
|
||||
// A segment that takes an earlier segment's lists over in place
|
||||
// keeps them first (the first num_taken_over_members members, their
|
||||
// set_member_by_location_ entries as they are).
|
||||
std::size_t num_taken_over_members = 0;
|
||||
std::optional<std::size_t> taken_over_set_index;
|
||||
// The tree node a segment set starts at.
|
||||
const BoundaryTree::Node* segment_top = nullptr;
|
||||
const BoundaryTree::Node* candidate_node = nullptr;
|
||||
if (evicts_segments_) {
|
||||
if (const std::optional<CacheKey> key = groups_[group_id].Index().KeyOf(pool_, location)) {
|
||||
candidate_node = boundary_tree_.Find(key->content_hash);
|
||||
}
|
||||
}
|
||||
const bool sliding = !groups_[group_id].Matcher().IsPrefixClosed() && !coordinator_.GroupIsState(group_id);
|
||||
if (candidate_node == nullptr || (sliding && !set.is_request_reclaim)) {
|
||||
// Block by block; or a block with no tree node (never
|
||||
// published, or registered straight into an index); or a window
|
||||
// block, which only shortens the boundaries its prefix resumes
|
||||
// at.
|
||||
set.members.push_back(
|
||||
VictimSet::Member{.group_id = group_id, .location = location, .in_stranded_suffix = false});
|
||||
} else if (set.is_request_reclaim) {
|
||||
// The request's released slots at this hash, and at a tail
|
||||
// the tail's other blocks, which their eviction takes along.
|
||||
for (const NodeEntry& entry : coordinator_.NodeEntries(pool_, *candidate_node)) {
|
||||
if (request_reclaim_locations_.contains(entry.location) ||
|
||||
(candidate_node->tail_tokens > 0 && is_evictable(entry))) {
|
||||
set.members.push_back(VictimSet::Member{
|
||||
.group_id = entry.group_id, .location = entry.location, .in_stranded_suffix = false});
|
||||
}
|
||||
}
|
||||
} else if (blocks_alone ? coordinator_.GroupIsState(group_id)
|
||||
: num_staying_checkpoint_boundaries(*candidate_node) >= 2) {
|
||||
// Deeper checkpoint boundaries still read this page. A nested
|
||||
// checkpoint leaves alone, every State group's at once; the
|
||||
// page leaves with the last checkpoint boundary under it, or is
|
||||
// tried again once the candidates run out. Block by block, every
|
||||
// checkpoint leaves so; at a tail its eviction takes the tail's
|
||||
// other unpinned blocks along (evictCachedBlock), uncounted here.
|
||||
if (!coordinator_.GroupIsState(group_id)) {
|
||||
(candidates_ran_out ? passed_over_ : deferred_shared_pages_).push_back(*candidate);
|
||||
continue;
|
||||
}
|
||||
bool evictable = true;
|
||||
for (const NodeEntry& entry : coordinator_.NodeEntries(pool_, *candidate_node)) {
|
||||
if (coordinator_.GroupIsState(entry.group_id)) {
|
||||
evictable = evictable && is_evictable(entry);
|
||||
set.members.push_back(VictimSet::Member{
|
||||
.group_id = entry.group_id, .location = entry.location, .in_stranded_suffix = false});
|
||||
}
|
||||
}
|
||||
if (!evictable) {
|
||||
for (const VictimSet::Member& member : set.members) {
|
||||
unevictable_locations_.insert(member.location);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
} else {
|
||||
// A segment: the one checkpoint boundary at or under this
|
||||
// boundary with the pages only it depends on -- the climb stops
|
||||
// below a page another checkpoint boundary shares, one in use
|
||||
// or a hit this admission keeps, or one the Device does not
|
||||
// hold -- and everything the Device holds under them, so no
|
||||
// Device page outlives its parent. The climb keeps the entries
|
||||
// of each node it passes, from the candidate's parent up. Block
|
||||
// by block, a page leaves with its boundary's blocks not in use
|
||||
// and everything under it, climbing nowhere.
|
||||
const BoundaryTree::Node* top = candidate_node;
|
||||
const std::vector<NodeEntry> candidate_entries = coordinator_.NodeEntries(pool_, *candidate_node);
|
||||
std::vector<std::pair<const BoundaryTree::Node*, std::vector<NodeEntry>>> climbed;
|
||||
if (!blocks_alone && num_staying_checkpoint_boundaries(*candidate_node) == 1) {
|
||||
while (top->parent != nullptr && top->parent->on_device &&
|
||||
num_staying_checkpoint_boundaries(*top->parent) == 1) {
|
||||
std::vector<NodeEntry> entries = coordinator_.NodeEntries(pool_, *top->parent);
|
||||
if (!std::ranges::all_of(entries, is_evictable)) {
|
||||
break;
|
||||
}
|
||||
top = top->parent;
|
||||
climbed.emplace_back(top, std::move(entries));
|
||||
}
|
||||
}
|
||||
// Post-order: a node after the nodes under it, its own entries
|
||||
// in NodeEntries order. It completes the climbed nodes in climb
|
||||
// order. A child the Device does not hold has nothing on the
|
||||
// Device under it when the model has a prefix-closed group
|
||||
// (eviction keeps the Device's coverage closed from the root),
|
||||
// so the walk skips the Host's subtrees; without one, what such
|
||||
// a child keeps under it on the Device needs none of these pages
|
||||
// either. A page a restore republished below such a child stays
|
||||
// and leaves later as a segment of its own.
|
||||
struct Frame {
|
||||
const BoundaryTree::Node* node;
|
||||
const BoundaryTree::Node* next_child;
|
||||
bool in_stranded_suffix;
|
||||
};
|
||||
std::vector<Frame> stack{
|
||||
Frame{.node = top, .next_child = top->first_child, .in_stranded_suffix = false}};
|
||||
std::size_t next_climbed = 0;
|
||||
bool evictable = true;
|
||||
// A child an earlier segment starts at: that segment holds the
|
||||
// child's whole Device subtree in this order already, so it
|
||||
// goes where the walk reaches it, after the blocks walked so
|
||||
// far, and is not walked again (a chain reclaimed page by page
|
||||
// from its suffix would otherwise be walked once per page).
|
||||
std::vector<std::pair<std::size_t, const BoundaryTree::Node*>> spliced;
|
||||
while (!stack.empty()) {
|
||||
Frame& frame = stack.back();
|
||||
if (const BoundaryTree::Node* child = frame.next_child) {
|
||||
frame.next_child = child->next_sibling;
|
||||
if (segment_at_.contains(child)) {
|
||||
spliced.emplace_back(set.members.size(), child);
|
||||
} else if (child->on_device) {
|
||||
const bool in_stranded_suffix = frame.in_stranded_suffix || frame.node == candidate_node;
|
||||
stack.push_back(Frame{.node = child,
|
||||
.next_child = child->first_child,
|
||||
.in_stranded_suffix = in_stranded_suffix});
|
||||
unevictable_locations_.insert(member.location);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const bool climbed_node =
|
||||
next_climbed < climbed.size() && climbed[next_climbed].first == frame.node;
|
||||
std::vector<NodeEntry> subtree_entries;
|
||||
std::span<const NodeEntry> entries;
|
||||
if (climbed_node) {
|
||||
entries = climbed[next_climbed++].second;
|
||||
} else if (frame.node == candidate_node) {
|
||||
entries = candidate_entries;
|
||||
} else {
|
||||
subtree_entries = coordinator_.NodeEntries(pool_, *frame.node);
|
||||
entries = subtree_entries;
|
||||
} else {
|
||||
// A segment: the one checkpoint boundary at or under this
|
||||
// boundary with the pages only it depends on -- the climb stops
|
||||
// below a page another checkpoint boundary shares, one in use
|
||||
// or a hit this admission keeps, or one the Device does not
|
||||
// hold -- and everything the Device holds under them, so no
|
||||
// Device page outlives its parent. The climb keeps the entries
|
||||
// of each node it passes, from the candidate's parent up. Block
|
||||
// by block, a page leaves with its boundary's blocks not in use
|
||||
// and everything under it, climbing nowhere.
|
||||
const BoundaryTree::Node* top = candidate_node;
|
||||
const std::vector<NodeEntry> candidate_entries = coordinator_.NodeEntries(pool_, *candidate_node);
|
||||
std::vector<std::pair<const BoundaryTree::Node*, std::vector<NodeEntry>>> climbed;
|
||||
if (!blocks_alone && num_staying_checkpoint_boundaries(*candidate_node) == 1) {
|
||||
while (top->parent != nullptr && top->parent->on_device &&
|
||||
num_staying_checkpoint_boundaries(*top->parent) == 1) {
|
||||
std::vector<NodeEntry> entries = coordinator_.NodeEntries(pool_, *top->parent);
|
||||
if (!std::ranges::all_of(entries, is_evictable)) {
|
||||
break;
|
||||
}
|
||||
top = top->parent;
|
||||
climbed.emplace_back(top, std::move(entries));
|
||||
}
|
||||
}
|
||||
for (const NodeEntry& entry : entries) {
|
||||
if (blocks_alone && frame.node == candidate_node && !is_evictable(entry)) {
|
||||
// Post-order: a node after the nodes under it, its own entries
|
||||
// in NodeEntries order. It completes the climbed nodes in climb
|
||||
// order. A child the Device does not hold has nothing on the
|
||||
// Device under it when the model has a prefix-closed group
|
||||
// (eviction keeps the Device's coverage closed from the root),
|
||||
// so the walk skips the Host's subtrees; without one, what such
|
||||
// a child keeps under it on the Device needs none of these pages
|
||||
// either. A page a restore republished below such a child stays
|
||||
// and leaves later as a segment of its own.
|
||||
struct Frame {
|
||||
const BoundaryTree::Node* node;
|
||||
const BoundaryTree::Node* next_child;
|
||||
bool in_stranded_suffix;
|
||||
};
|
||||
std::vector<Frame> stack{
|
||||
Frame{.node = top, .next_child = top->first_child, .in_stranded_suffix = false}};
|
||||
std::size_t next_climbed = 0;
|
||||
bool evictable = true;
|
||||
// A child an earlier segment starts at: that segment holds the
|
||||
// child's whole Device subtree in this order already, so it
|
||||
// goes where the walk reaches it, after the blocks walked so
|
||||
// far, and is not walked again (a chain reclaimed page by page
|
||||
// from its suffix would otherwise be walked once per page).
|
||||
std::vector<std::pair<std::size_t, const BoundaryTree::Node*>> spliced;
|
||||
while (!stack.empty()) {
|
||||
Frame& frame = stack.back();
|
||||
if (const BoundaryTree::Node* child = frame.next_child) {
|
||||
frame.next_child = child->next_sibling;
|
||||
if (segment_at_.contains(child)) {
|
||||
spliced.emplace_back(set.members.size(), child);
|
||||
} else if (child->on_device) {
|
||||
const bool in_stranded_suffix =
|
||||
frame.in_stranded_suffix || frame.node == candidate_node;
|
||||
stack.push_back(Frame{.node = child,
|
||||
.next_child = child->first_child,
|
||||
.in_stranded_suffix = in_stranded_suffix});
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (!is_evictable(entry)) {
|
||||
evictable = false;
|
||||
break;
|
||||
const bool climbed_node =
|
||||
next_climbed < climbed.size() && climbed[next_climbed].first == frame.node;
|
||||
std::vector<NodeEntry> subtree_entries;
|
||||
std::span<const NodeEntry> entries;
|
||||
if (climbed_node) {
|
||||
entries = climbed[next_climbed++].second;
|
||||
} else if (frame.node == candidate_node) {
|
||||
entries = candidate_entries;
|
||||
} else {
|
||||
subtree_entries = coordinator_.NodeEntries(pool_, *frame.node);
|
||||
entries = subtree_entries;
|
||||
}
|
||||
set.members.push_back(VictimSet::Member{.group_id = entry.group_id,
|
||||
.location = entry.location,
|
||||
.in_stranded_suffix = frame.in_stranded_suffix});
|
||||
}
|
||||
if (!evictable) {
|
||||
break;
|
||||
}
|
||||
stack.pop_back();
|
||||
}
|
||||
if (!evictable) {
|
||||
if (!blocks_alone) {
|
||||
passed_over_.push_back(*candidate);
|
||||
}
|
||||
// One unavailable member rejects this whole set; there is
|
||||
// no need to inspect the rest of its subtree. Remember
|
||||
// only candidates that would expand to the same set. A
|
||||
// descendant or sibling can still leave independently.
|
||||
const auto remember_same_set = [&](const BoundaryTree::Node& node,
|
||||
std::span<const NodeEntry> entries) {
|
||||
for (const NodeEntry& entry : entries) {
|
||||
if (blocks_alone && &node == candidate_node && !is_evictable(entry)) {
|
||||
if (blocks_alone && frame.node == candidate_node && !is_evictable(entry)) {
|
||||
continue;
|
||||
}
|
||||
if (!request_reclaim_locations_.contains(entry.location) &&
|
||||
(groups_[entry.group_id].Matcher().IsPrefixClosed() ||
|
||||
coordinator_.GroupIsState(entry.group_id))) {
|
||||
unevictable_locations_.insert(entry.location);
|
||||
if (!is_evictable(entry)) {
|
||||
evictable = false;
|
||||
break;
|
||||
}
|
||||
set.members.push_back(VictimSet::Member{.group_id = entry.group_id,
|
||||
.location = entry.location,
|
||||
.in_stranded_suffix = frame.in_stranded_suffix});
|
||||
}
|
||||
};
|
||||
remember_same_set(*candidate_node, candidate_entries);
|
||||
for (const auto& [node, entries] : climbed) {
|
||||
remember_same_set(*node, entries);
|
||||
if (!evictable) {
|
||||
break;
|
||||
}
|
||||
stack.pop_back();
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (!spliced.empty()) {
|
||||
VictimSet walked = std::exchange(set, VictimSet{});
|
||||
std::size_t next_walked = 0;
|
||||
for (const auto& [walked_before, child] : spliced) {
|
||||
if (!evictable) {
|
||||
if (!blocks_alone) {
|
||||
passed_over_.push_back(*candidate);
|
||||
}
|
||||
// One unavailable member rejects this whole set; there is
|
||||
// no need to inspect the rest of its subtree. Remember
|
||||
// only candidates that would expand to the same set. A
|
||||
// descendant or sibling can still leave independently.
|
||||
const auto remember_same_set = [&](const BoundaryTree::Node& node,
|
||||
std::span<const NodeEntry> entries) {
|
||||
for (const NodeEntry& entry : entries) {
|
||||
if (blocks_alone && &node == candidate_node && !is_evictable(entry)) {
|
||||
continue;
|
||||
}
|
||||
if (!request_reclaim_locations_.contains(entry.location) &&
|
||||
(groups_[entry.group_id].Matcher().IsPrefixClosed() ||
|
||||
coordinator_.GroupIsState(entry.group_id))) {
|
||||
unevictable_locations_.insert(entry.location);
|
||||
}
|
||||
}
|
||||
};
|
||||
remember_same_set(*candidate_node, candidate_entries);
|
||||
for (const auto& [node, entries] : climbed) {
|
||||
remember_same_set(*node, entries);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (!spliced.empty()) {
|
||||
VictimSet walked = std::exchange(set, VictimSet{});
|
||||
std::size_t next_walked = 0;
|
||||
for (const auto& [walked_before, child] : spliced) {
|
||||
set.members.insert(set.members.end(), walked.members.begin() + next_walked,
|
||||
walked.members.begin() + walked_before);
|
||||
next_walked = walked_before;
|
||||
const auto it = segment_at_.find(child);
|
||||
VictimSet& earlier = victims_[it->second];
|
||||
_assert(!earlier.members.empty(), "a segment set still starts at its top");
|
||||
if (set.members.empty()) {
|
||||
// First in the order: its lists become this set's.
|
||||
set = std::exchange(earlier, VictimSet{});
|
||||
taken_over_set_index = it->second;
|
||||
num_taken_over_members = set.members.size();
|
||||
} else {
|
||||
// Moved in below like any other earlier set it holds.
|
||||
set.members.insert(set.members.end(), earlier.members.begin(), earlier.members.end());
|
||||
}
|
||||
segment_at_.erase(it);
|
||||
}
|
||||
set.members.insert(set.members.end(), walked.members.begin() + next_walked,
|
||||
walked.members.begin() + walked_before);
|
||||
next_walked = walked_before;
|
||||
const auto it = segment_at_.find(child);
|
||||
VictimSet& earlier = victims_[it->second];
|
||||
_assert(!earlier.members.empty(), "a segment set still starts at its top");
|
||||
if (set.members.empty()) {
|
||||
// First in the order: its lists become this set's.
|
||||
set = std::exchange(earlier, VictimSet{});
|
||||
taken_over_set_index = it->second;
|
||||
num_taken_over_members = set.members.size();
|
||||
} else {
|
||||
// Moved in below like any other earlier set it holds.
|
||||
set.members.insert(set.members.end(), earlier.members.begin(), earlier.members.end());
|
||||
}
|
||||
segment_at_.erase(it);
|
||||
walked.members.end());
|
||||
}
|
||||
set.members.insert(set.members.end(), walked.members.begin() + next_walked, walked.members.end());
|
||||
// A page leaving block by block may leave blocks in use at its
|
||||
// boundary: no later walk takes it for that node's subtree.
|
||||
segment_top = blocks_alone ? nullptr : top;
|
||||
}
|
||||
// A page leaving block by block may leave blocks in use at its
|
||||
// boundary: no later walk takes it for that node's subtree.
|
||||
segment_top = blocks_alone ? nullptr : top;
|
||||
}
|
||||
_assert(std::ranges::find(set.members.begin() + static_cast<std::ptrdiff_t>(num_taken_over_members),
|
||||
_assert(
|
||||
std::ranges::find(set.members.begin() + static_cast<std::ptrdiff_t>(num_taken_over_members),
|
||||
set.members.end(), location, &VictimSet::Member::location) != set.members.end(),
|
||||
"a victim set holds the candidate it was chosen for");
|
||||
// An earlier set this one contains moves into it whole, each block
|
||||
// keeping why it left; the rest leave the shadow now. The lists
|
||||
// taken over in place are there already.
|
||||
const std::size_t set_index = victims_.size();
|
||||
std::vector<std::size_t> absorbed;
|
||||
std::size_t absorbed_members = 0;
|
||||
for (std::size_t j = num_taken_over_members; j < set.members.size(); ++j) {
|
||||
VictimSet::Member& member = set.members[j];
|
||||
const auto it = set_member_by_location_.find(member.location);
|
||||
if (it == set_member_by_location_.end()) {
|
||||
shadow_.Remove(member.group_id, member.location);
|
||||
set_member_by_location_.emplace(member.location, std::pair{set_index, j});
|
||||
continue;
|
||||
// An earlier set this one contains moves into it whole, each block
|
||||
// keeping why it left; the rest leave the shadow now. The lists
|
||||
// taken over in place are there already.
|
||||
const std::size_t set_index = victims_.size();
|
||||
std::vector<std::size_t> absorbed;
|
||||
std::size_t absorbed_members = 0;
|
||||
for (std::size_t j = num_taken_over_members; j < set.members.size(); ++j) {
|
||||
VictimSet::Member& member = set.members[j];
|
||||
const auto it = set_member_by_location_.find(member.location);
|
||||
if (it == set_member_by_location_.end()) {
|
||||
eviction_plan_.Remove(member.group_id, member.location);
|
||||
set_member_by_location_.emplace(member.location, std::pair{set_index, j});
|
||||
continue;
|
||||
}
|
||||
// The set holding the block now, through the sets that took
|
||||
// lists over.
|
||||
std::size_t earlier = it->second.first;
|
||||
while (taken_by_[earlier] != earlier) {
|
||||
earlier = taken_by_[earlier] = taken_by_[taken_by_[earlier]];
|
||||
}
|
||||
const std::size_t position = it->second.second;
|
||||
member.in_stranded_suffix = victims_[earlier].members[position].in_stranded_suffix;
|
||||
if (std::ranges::find(absorbed, earlier) == absorbed.end()) {
|
||||
absorbed.push_back(earlier);
|
||||
}
|
||||
++absorbed_members;
|
||||
it->second = std::pair{set_index, j};
|
||||
}
|
||||
// The set holding the block now, through the sets that took
|
||||
// lists over.
|
||||
std::size_t earlier = it->second.first;
|
||||
while (taken_by_[earlier] != earlier) {
|
||||
earlier = taken_by_[earlier] = taken_by_[taken_by_[earlier]];
|
||||
for (const std::size_t earlier : absorbed) {
|
||||
absorbed_members -= victims_[earlier].members.size();
|
||||
victims_[earlier] = VictimSet{};
|
||||
}
|
||||
const std::size_t position = it->second.second;
|
||||
member.in_stranded_suffix = victims_[earlier].members[position].in_stranded_suffix;
|
||||
if (std::ranges::find(absorbed, earlier) == absorbed.end()) {
|
||||
absorbed.push_back(earlier);
|
||||
_assert(absorbed_members == 0, "an earlier victim set lies whole inside the set that takes it");
|
||||
if (taken_over_set_index) {
|
||||
taken_by_[*taken_over_set_index] = set_index;
|
||||
}
|
||||
++absorbed_members;
|
||||
it->second = std::pair{set_index, j};
|
||||
victims_.push_back(std::move(set));
|
||||
taken_by_.push_back(set_index);
|
||||
if (segment_top != nullptr) {
|
||||
segment_at_[segment_top] = set_index;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
for (const std::size_t earlier : absorbed) {
|
||||
absorbed_members -= victims_[earlier].members.size();
|
||||
victims_[earlier] = VictimSet{};
|
||||
}
|
||||
_assert(absorbed_members == 0, "an earlier victim set lies whole inside the set that takes it");
|
||||
if (taken_over_set_index) {
|
||||
taken_by_[*taken_over_set_index] = set_index;
|
||||
}
|
||||
victims_.push_back(std::move(set));
|
||||
taken_by_.push_back(set_index);
|
||||
if (segment_top != nullptr) {
|
||||
segment_at_[segment_top] = set_index;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Restore newer sets first, each whole, keeping it unless its capacity
|
||||
// is still needed. All releases and restores affect only shadow
|
||||
// occupancy.
|
||||
std::vector<VictimSet> required_victims;
|
||||
required_victims.reserve(victims_.size());
|
||||
for (std::size_t i = victims_.size(); i > 0; --i) {
|
||||
VictimSet& set = victims_[i - 1];
|
||||
if (set.members.empty()) {
|
||||
continue; // moved into a later set
|
||||
}
|
||||
for (const VictimSet::Member& member : set.members) {
|
||||
shadow_.Restore(member.group_id, member.location);
|
||||
}
|
||||
if (!shadow_.Fits(shape_need_, blocks_needed_)) {
|
||||
for (const VictimSet::Member& member : set.members) {
|
||||
shadow_.Remove(member.group_id, member.location);
|
||||
}
|
||||
required_victims.push_back(std::move(set));
|
||||
}
|
||||
}
|
||||
std::ranges::reverse(required_victims);
|
||||
victims_ = std::move(required_victims);
|
||||
if (!fits) return false;
|
||||
eviction_plan_.Minimize(victims_, shape_need_, blocks_needed_);
|
||||
return true;
|
||||
}
|
||||
|
||||
private:
|
||||
// Current prefix hits are protected before candidates reach this policy.
|
||||
// A request-only block with no CacheEntry is reclaimed first, level with
|
||||
// a superseded input (CacheCoordinator::MarkSupersededStateInput). Cached
|
||||
// entries then compare request access epoch, followed within one epoch by
|
||||
// the tier order below. Position keeps the deeper unproven non-closed
|
||||
// boundary, while a closed prefix is reclaimed from its suffix.
|
||||
enum class EvictionTier {
|
||||
kUncached, // physically allocated, but owned only by the request table
|
||||
kProbationaryBoundary,
|
||||
kEstablishedBoundary,
|
||||
kClosedPrefix,
|
||||
};
|
||||
|
||||
struct VictimCandidate {
|
||||
std::uint32_t group_id;
|
||||
CacheBlockLocation location;
|
||||
std::uint64_t last_access_epoch;
|
||||
EvictionTier eviction_tier;
|
||||
std::int64_t position_rank;
|
||||
};
|
||||
|
||||
static auto evictionKey(const VictimCandidate& candidate) {
|
||||
return std::tuple{candidate.last_access_epoch, candidate.eviction_tier, candidate.position_rank,
|
||||
candidate.group_id, candidate.location.lcm_block_id, candidate.location.slot_index};
|
||||
}
|
||||
|
||||
static bool shouldEvictFirst(const VictimCandidate& lhs, const VictimCandidate& rhs) {
|
||||
return evictionKey(lhs) < evictionKey(rhs);
|
||||
}
|
||||
|
||||
struct CacheGroupVictimCandidates {
|
||||
explicit CacheGroupVictimCandidates(std::uint32_t id) : group_id{id} {}
|
||||
|
||||
const VictimCandidate& CurrentCandidate() const { return candidates[next_candidate_index]; }
|
||||
|
||||
std::uint32_t group_id;
|
||||
bool index_exhausted{false};
|
||||
PrefixCacheIndex::EvictionCursor index_cursor;
|
||||
std::vector<VictimCandidate> candidates;
|
||||
std::size_t next_candidate_index{0};
|
||||
};
|
||||
using VictimCandidate = CacheEvictionCandidates::Candidate;
|
||||
|
||||
void initializeCapacity() {
|
||||
_assert(demands_.size() == groups_.size(), "demands/groups size mismatch");
|
||||
@@ -718,43 +666,6 @@ private:
|
||||
}
|
||||
}
|
||||
|
||||
VictimCandidate makeVictimCandidate(std::uint32_t group_id, CacheBlockLocation location,
|
||||
const std::optional<PrefixCacheIndex::CachedBlockMetadata>& metadata) const {
|
||||
const std::uint64_t last_access_epoch = metadata ? metadata->last_access_epoch : 0;
|
||||
const std::int32_t logical_block_index = metadata ? metadata->logical_block_index : -1;
|
||||
const CacheBoundaryKind boundary_kind = metadata ? metadata->boundary_kind : CacheBoundaryKind::kChunk;
|
||||
const bool is_prefix_closed = groups_[group_id].Matcher().IsPrefixClosed();
|
||||
const bool is_probationary_boundary = !is_prefix_closed && boundary_kind == CacheBoundaryKind::kChunk &&
|
||||
!(metadata && metadata->was_acquired) && logical_block_index >= 0;
|
||||
const EvictionTier eviction_tier = [&] {
|
||||
if (last_access_epoch == 0) {
|
||||
return EvictionTier::kUncached;
|
||||
}
|
||||
if (is_probationary_boundary) {
|
||||
return EvictionTier::kProbationaryBoundary;
|
||||
}
|
||||
return is_prefix_closed ? EvictionTier::kClosedPrefix : EvictionTier::kEstablishedBoundary;
|
||||
}();
|
||||
std::int64_t position_rank = 0;
|
||||
if (is_probationary_boundary) {
|
||||
// Retain the longer unproven frontier.
|
||||
position_rank = logical_block_index;
|
||||
} else if (is_prefix_closed && logical_block_index >= 0) {
|
||||
// Reclaim a closed prefix from its suffix.
|
||||
position_rank = -static_cast<std::int64_t>(logical_block_index);
|
||||
}
|
||||
return VictimCandidate{
|
||||
.group_id = group_id,
|
||||
.location = location,
|
||||
// Access epochs start at one. Zero puts an uncached block, and a
|
||||
// superseded input re-registered there, ahead of every reusable
|
||||
// cache entry.
|
||||
.last_access_epoch = last_access_epoch,
|
||||
.eviction_tier = eviction_tier,
|
||||
.position_rank = position_rank,
|
||||
};
|
||||
}
|
||||
|
||||
bool couldFitAfterEviction() const {
|
||||
std::int64_t parents_needed = 0;
|
||||
for (std::size_t i = 0; i < groups_.size(); ++i) {
|
||||
@@ -794,6 +705,7 @@ private:
|
||||
}
|
||||
|
||||
void collectCandidates() {
|
||||
eviction_plan_.StartCandidates(&protected_locations_, &request_reclaim_locations_);
|
||||
for (std::size_t i = 0; i < groups_.size(); ++i) {
|
||||
const std::vector<CacheBlockLocation> hits = groups_[i].Index().MatchedLocations(
|
||||
pool_, (*prefix_.group_keys)[i], /*begin_blocks=*/0, prefix_.device.per_group[i]);
|
||||
@@ -818,11 +730,6 @@ private:
|
||||
if (num_computed_tokens_) {
|
||||
collectRequestReclaimCandidates(*num_computed_tokens_);
|
||||
}
|
||||
|
||||
cache_group_candidates_.reserve(groups_.size());
|
||||
for (std::size_t i = 0; i < groups_.size(); ++i) {
|
||||
cache_group_candidates_.emplace_back(static_cast<std::uint32_t>(i));
|
||||
}
|
||||
}
|
||||
|
||||
// Ignore segment restrictions, but preserve actual parent occupancy and
|
||||
@@ -907,78 +814,14 @@ private:
|
||||
if (!first_occurrence) {
|
||||
continue;
|
||||
}
|
||||
request_reclaim_candidates_.push_back(
|
||||
makeVictimCandidate(group_id, location, groups_[i].Index().MetadataFor(pool_, location)));
|
||||
request_reclaim_candidates_.push_back(eviction_plan_.Candidates().MakeCandidate(
|
||||
group_id, location, groups_[i].Index().MetadataFor(pool_, location)));
|
||||
}
|
||||
}
|
||||
std::ranges::sort(request_reclaim_candidates_, shouldEvictFirst);
|
||||
eviction_plan_.Candidates().Sort(request_reclaim_candidates_);
|
||||
}
|
||||
|
||||
void loadGroupEpoch(CacheGroupVictimCandidates& group, std::uint64_t epoch) {
|
||||
group.candidates.clear();
|
||||
group.next_candidate_index = 0;
|
||||
epoch_scratch_.clear();
|
||||
groups_[group.group_id].Index().NextEvictionEpoch(pool_, group.index_cursor, epoch, epoch_scratch_);
|
||||
for (const PrefixCacheIndex::EvictionCandidate& entry : epoch_scratch_) {
|
||||
if (protected_locations_.contains(entry.location) || request_reclaim_locations_.contains(entry.location)) {
|
||||
continue;
|
||||
}
|
||||
group.candidates.push_back(makeVictimCandidate(group.group_id, entry.location, entry.metadata));
|
||||
}
|
||||
// The entire epoch participates in boundary and position tie-breaks.
|
||||
std::ranges::sort(group.candidates, shouldEvictFirst);
|
||||
}
|
||||
|
||||
std::optional<VictimCandidate> nextVictimCandidate() {
|
||||
while (true) {
|
||||
CacheGroupVictimCandidates* selected_group = nullptr;
|
||||
CacheGroupVictimCandidates* next_group = nullptr;
|
||||
std::optional<std::uint64_t> next_epoch;
|
||||
for (CacheGroupVictimCandidates& group : cache_group_candidates_) {
|
||||
if (group.next_candidate_index < group.candidates.size()) {
|
||||
if (selected_group == nullptr ||
|
||||
shouldEvictFirst(group.CurrentCandidate(), selected_group->CurrentCandidate())) {
|
||||
selected_group = &group;
|
||||
}
|
||||
} else if (!group.index_exhausted) {
|
||||
const auto epoch = groups_[group.group_id].Index().PeekEvictionEpoch(pool_, group.index_cursor);
|
||||
if (!epoch) {
|
||||
group.index_exhausted = true;
|
||||
} else if (!next_epoch || *epoch < *next_epoch) {
|
||||
next_epoch = epoch;
|
||||
next_group = &group;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const VictimCandidate* selected = selected_group == nullptr ? nullptr : &selected_group->CurrentCandidate();
|
||||
const bool select_request =
|
||||
next_request_candidate_index_ < request_reclaim_candidates_.size() &&
|
||||
(selected == nullptr ||
|
||||
shouldEvictFirst(request_reclaim_candidates_[next_request_candidate_index_], *selected));
|
||||
if (select_request) {
|
||||
selected = &request_reclaim_candidates_[next_request_candidate_index_];
|
||||
}
|
||||
|
||||
// Inspect owners only at the globally oldest unread epoch. Even
|
||||
// a fully pinned group's newer entries cannot precede this victim.
|
||||
// Equal epochs must all be read before applying policy tie-breaks.
|
||||
if (next_group != nullptr && (selected == nullptr || *next_epoch <= selected->last_access_epoch)) {
|
||||
loadGroupEpoch(*next_group, *next_epoch);
|
||||
continue;
|
||||
}
|
||||
if (selected == nullptr) {
|
||||
return std::nullopt;
|
||||
}
|
||||
const VictimCandidate candidate = *selected;
|
||||
if (select_request) {
|
||||
++next_request_candidate_index_;
|
||||
} else {
|
||||
++selected_group->next_candidate_index;
|
||||
}
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
std::optional<VictimCandidate> nextVictimCandidate() { return eviction_plan_.Next(request_reclaim_candidates_); }
|
||||
|
||||
// The coordinator planned for, read through its public views
|
||||
// (ForEachBoundaryKey, NodeEntries); groups_, geometry_ and the pools are
|
||||
@@ -1012,7 +855,7 @@ private:
|
||||
// the general heap while trying and rejecting candidate sets.
|
||||
std::pmr::monotonic_buffer_resource scratch_;
|
||||
// The pool as the tentative victims would leave it.
|
||||
ShadowOccupancy shadow_;
|
||||
CacheEvictionPlan eviction_plan_;
|
||||
// Per group: the bucket-constrained blocks (a restore's rebuilt slots; an
|
||||
// admission's Host-hit destinations and tail copies), and the dense
|
||||
// blocks wanted in any bucket.
|
||||
@@ -1022,11 +865,8 @@ private:
|
||||
// than its own (collectOwnerCopyBuckets, protectDedupedTail).
|
||||
bool owner_copy_changes_bucket_{false};
|
||||
std::vector<VictimCandidate> request_reclaim_candidates_;
|
||||
std::size_t next_request_candidate_index_{0};
|
||||
std::vector<CacheGroupVictimCandidates> cache_group_candidates_;
|
||||
std::pmr::unordered_set<CacheBlockLocation, CacheBlockLocationHash> protected_locations_{&scratch_};
|
||||
std::pmr::unordered_set<CacheBlockLocation, CacheBlockLocationHash> request_reclaim_locations_{&scratch_};
|
||||
std::vector<PrefixCacheIndex::EvictionCandidate> epoch_scratch_;
|
||||
// Every block a selected set holds: the set it joined (or last moved
|
||||
// into) and its position there. A later set may since have taken that
|
||||
// set's lists over in place, positions unchanged: taken_by_ leads there.
|
||||
|
||||
+154
-393
@@ -20,6 +20,8 @@
|
||||
|
||||
#include "cache/coordinator/cache_coordinator.h"
|
||||
|
||||
#include "cache/coordinator/eviction_plan.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <functional>
|
||||
@@ -431,10 +433,22 @@ CoordinatorMatch CacheCoordinator::acquireTierWithKeys(std::span<const std::vect
|
||||
const std::int32_t floor_pages = GroupIsState(i) ? 0 : floor_tokens / geometry_[i].BlockGranularity();
|
||||
out.per_group[i] =
|
||||
groups_[i].Index().AcquireMatched(pool, group_keys[i], floor_pages, probe.per_group[i], access_epoch);
|
||||
if constexpr (Tier == CacheTier::kDevice) {
|
||||
if (host_pool_ != nullptr) {
|
||||
groups_[i].Index().TouchExisting(*host_pool_, std::span{group_keys[i]}.subspan(floor_pages),
|
||||
out.per_group[i].blocks, access_epoch);
|
||||
}
|
||||
}
|
||||
if (probe.tail && !probe.tail->group_keys[i].empty()) {
|
||||
// The tail's blocks follow the full pages in the same table.
|
||||
PrefixMatch tail_match = groups_[i].Index().AcquireMatched(
|
||||
pool, probe.tail->group_keys[i], /*begin_blocks=*/0, probe.tail->per_group[i], access_epoch);
|
||||
if constexpr (Tier == CacheTier::kDevice) {
|
||||
if (host_pool_ != nullptr) {
|
||||
groups_[i].Index().TouchExisting(*host_pool_, probe.tail->group_keys[i], tail_match.blocks,
|
||||
access_epoch);
|
||||
}
|
||||
}
|
||||
out.per_group[i].blocks.insert(out.per_group[i].blocks.end(),
|
||||
std::make_move_iterator(tail_match.blocks.begin()),
|
||||
std::make_move_iterator(tail_match.blocks.end()));
|
||||
@@ -1158,6 +1172,10 @@ CacheCoordinator::AcquiredPrefix CacheCoordinator::acquirePrefix(PrefixProbe&& p
|
||||
PrefixMatch match = groups_[i].Index().AcquireMatched(
|
||||
pool_, probe.state_at_prompt_end->group_keys[i],
|
||||
/*begin_blocks=*/0, probe.state_at_prompt_end->per_group[i], access_epoch);
|
||||
if (host_pool_ != nullptr) {
|
||||
groups_[i].Index().TouchExisting(*host_pool_, probe.state_at_prompt_end->group_keys[i], match.blocks,
|
||||
access_epoch);
|
||||
}
|
||||
out.state_at_prompt_end[i] = std::move(match.blocks.front());
|
||||
if (BoundaryTree::Node* node = boundary_tree_.Find(probe.state_at_prompt_end->hash)) {
|
||||
node->latest_state_access_epoch = std::max(node->latest_state_access_epoch, access_epoch);
|
||||
@@ -1397,6 +1415,9 @@ void CacheCoordinator::cacheBlocksForGroup(std::size_t group_index, std::span<Ca
|
||||
if constexpr (Tier == CacheTier::kHost) {
|
||||
return;
|
||||
}
|
||||
if (host_pool_ != nullptr) {
|
||||
groups_[group_index].Index().TouchExisting(*host_pool_, keys, blocks, access_epoch);
|
||||
}
|
||||
for (auto& [key, block_ref] : newly_cached) {
|
||||
// Every hash an index holds has a tree node: a publication linked its
|
||||
// own before registering; any other entry with no node yet starts one
|
||||
@@ -1439,6 +1460,83 @@ CacheBlockRef CacheCoordinator::AcquireDeviceCachedBlock(const CacheKey& key) co
|
||||
return groups_[key.group_id].Index().Find(pool_, key);
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
class HostEvictionPlanner {
|
||||
public:
|
||||
struct Member {
|
||||
std::uint32_t group_id;
|
||||
CacheBlockLocation location;
|
||||
};
|
||||
struct VictimSet {
|
||||
std::vector<Member> members;
|
||||
};
|
||||
|
||||
HostEvictionPlanner(const CacheCoordinator& coordinator, const std::vector<CacheGroup>& groups,
|
||||
const BlockPool& pool)
|
||||
: coordinator_{coordinator}, groups_{groups}, pool_{pool}, plan_{pool, groups}, no_dense_need_(groups.size()) {
|
||||
plan_.StartCandidates(&taken_, nullptr);
|
||||
}
|
||||
|
||||
bool Fits(std::span<const std::vector<std::int64_t>> needed) const { return plan_.Fits(needed, no_dense_need_); }
|
||||
|
||||
void Seed(std::uint32_t group_id, CacheBlockLocation location) {
|
||||
taken_.insert(location);
|
||||
plan_.Remove(group_id, location);
|
||||
}
|
||||
|
||||
bool Fit(std::span<const std::vector<std::int64_t>> needed) {
|
||||
return plan_.SelectUntilFits(needed, no_dense_need_, [&] {
|
||||
while (const auto candidate = plan_.Next({})) {
|
||||
if (taken_.contains(candidate->location)) continue;
|
||||
VictimSet set;
|
||||
const auto take = [&](std::uint32_t group_id, CacheBlockLocation location) {
|
||||
Seed(group_id, location);
|
||||
set.members.push_back({group_id, location});
|
||||
};
|
||||
take(candidate->group_id, candidate->location);
|
||||
// Host State eviction takes the other unpinned State groups at this boundary.
|
||||
if (coordinator_.GroupIsState(candidate->group_id)) {
|
||||
const auto key = groups_[candidate->group_id].Index().KeyOf(pool_, candidate->location);
|
||||
coordinator_.ForEachBoundaryKey(
|
||||
*key, /*tail_tokens=*/0, [&](std::size_t i, const CacheKey& sibling_key) {
|
||||
if (!coordinator_.GroupIsState(i)) return;
|
||||
const auto sibling = groups_[i].Index().Inspect(pool_, sibling_key);
|
||||
if (sibling && !sibling->pinned && !taken_.contains(sibling->location)) {
|
||||
take(groups_[i].Id(), sibling->location);
|
||||
}
|
||||
});
|
||||
}
|
||||
victims_.push_back(std::move(set));
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
void Minimize(std::span<const std::vector<std::int64_t>> needed) {
|
||||
plan_.Minimize(victims_, needed, no_dense_need_);
|
||||
}
|
||||
const std::vector<VictimSet>& Victims() const { return victims_; }
|
||||
std::vector<VictimSet> TakeVictims() { return std::move(victims_); }
|
||||
CacheCoordinator::HostAllocationStats Stats() const {
|
||||
return {.group_scans = plan_.Candidates().GroupScans(),
|
||||
.block_candidates = plan_.Candidates().ScannedCandidates(),
|
||||
.parent_candidates = plan_.TouchedParents()};
|
||||
}
|
||||
|
||||
private:
|
||||
const CacheCoordinator& coordinator_;
|
||||
const std::vector<CacheGroup>& groups_;
|
||||
const BlockPool& pool_;
|
||||
CacheEvictionPlan plan_;
|
||||
std::vector<std::int64_t> no_dense_need_;
|
||||
CacheEvictionCandidates::LocationSet taken_;
|
||||
std::vector<VictimSet> victims_;
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
CacheCoordinator::HostAllocationBatch CacheCoordinator::AcquireHostBlocks(std::span<const std::uint32_t> group_ids,
|
||||
std::span<const std::int32_t> buckets) {
|
||||
_assert(host_pool_ != nullptr, "AcquireHostBlocks requires a host pool");
|
||||
@@ -1448,209 +1546,50 @@ CacheCoordinator::HostAllocationBatch CacheCoordinator::AcquireHostBlocks(std::s
|
||||
batch.stats.requested = group_ids.size();
|
||||
_assert(group_ids.size() <= static_cast<std::size_t>(std::numeric_limits<std::int32_t>::max()),
|
||||
"Host allocation batch request exceeds int32 range");
|
||||
|
||||
// A Host block lands in the bucket of the Device block it mirrors, so under
|
||||
// page-cyclic sharding both ends of a copy have the same owner.
|
||||
const auto acquire_in_bucket = [&](std::uint32_t group_id, std::int32_t bucket) {
|
||||
const std::array<std::int32_t, 1> one{bucket};
|
||||
std::vector<CacheBlockRef> refs = host_pool_->AcquireBlocksInBuckets(group_id, one);
|
||||
return refs.empty() ? CacheBlockRef{} : std::move(refs.front());
|
||||
};
|
||||
|
||||
std::vector<bool> needs_replacement(groups_.size(), false);
|
||||
for (std::size_t i = 0; i < group_ids.size(); ++i) {
|
||||
_assert(group_ids[i] < groups_.size(), "Host block group id out of range");
|
||||
_assert(buckets[i] >= 0 && buckets[i] < groups_[group_ids[i]].Allocator().ShardCount(),
|
||||
std::vector<std::size_t> unresolved;
|
||||
for (std::size_t row = 0; row < group_ids.size(); ++row) {
|
||||
_assert(group_ids[row] < groups_.size(), "Host block group id out of range");
|
||||
_assert(buckets[row] >= 0 && buckets[row] < groups_[group_ids[row]].Allocator().ShardCount(),
|
||||
"Host block bucket is outside the group's shard count");
|
||||
// Free capacity first, in candidate order.
|
||||
batch.blocks[i] = acquire_in_bucket(group_ids[i], buckets[i]);
|
||||
if (!batch.blocks[i]) {
|
||||
needs_replacement[group_ids[i]] = true;
|
||||
batch.blocks[row] = acquire_in_bucket(group_ids[row], buckets[row]);
|
||||
if (!batch.blocks[row]) unresolved.push_back(row);
|
||||
}
|
||||
if (!unresolved.empty()) {
|
||||
std::vector<HostEvictionPlanner::VictimSet> victims;
|
||||
std::vector<std::size_t> accepted;
|
||||
{
|
||||
HostEvictionPlanner planner{*this, groups_, *host_pool_};
|
||||
std::vector<std::vector<std::int64_t>> needed(groups_.size());
|
||||
for (std::size_t i = 0; i < groups_.size(); ++i) needed[i].resize(groups_[i].Allocator().ShardCount());
|
||||
for (const std::size_t row : unresolved) {
|
||||
auto& need = needed[group_ids[row]][buckets[row]];
|
||||
++need;
|
||||
if (planner.Fit(needed))
|
||||
accepted.push_back(row);
|
||||
else
|
||||
--need;
|
||||
}
|
||||
planner.Minimize(needed);
|
||||
victims = planner.TakeVictims();
|
||||
batch.stats = planner.Stats();
|
||||
batch.stats.requested = group_ids.size();
|
||||
}
|
||||
}
|
||||
const auto replacement_group_count = std::ranges::count(needs_replacement, true);
|
||||
if (replacement_group_count == 0) {
|
||||
batch.stats.allocated = batch.stats.requested;
|
||||
return batch;
|
||||
}
|
||||
|
||||
// Keep the most recently accessed Host entries; location only breaks ties.
|
||||
const auto value = [](std::uint32_t candidate_group, CacheBlockLocation location,
|
||||
const PrefixCacheIndex::CachedBlockMetadata& metadata) {
|
||||
return std::tuple{metadata.last_access_epoch, candidate_group, location.lcm_block_id, location.slot_index};
|
||||
};
|
||||
struct BucketCandidates {
|
||||
std::vector<PrefixCacheIndex::EvictionCandidate> entries;
|
||||
std::size_t next{0};
|
||||
};
|
||||
std::vector<std::vector<BucketCandidates>> children(groups_.size());
|
||||
auto& parents = host_parent_candidates_;
|
||||
for (const std::int32_t parent_id : host_touched_parents_) {
|
||||
parents[parent_id] = {};
|
||||
}
|
||||
host_touched_parents_.clear();
|
||||
// An eligible parent contains only unpinned cache entries. Accumulate
|
||||
// their counts and newest access while collecting each group's entries
|
||||
// once, rather than looking every child up again in a placement scan.
|
||||
for (std::uint32_t group_id = 0; group_id < groups_.size(); ++group_id) {
|
||||
++batch.stats.group_scans;
|
||||
const GroupAllocator& allocator = groups_[group_id].Allocator();
|
||||
// The free-capacity pass exhausted every unsatisfied bucket's holes.
|
||||
// Each fully evictable own parent therefore has a compatible child
|
||||
// no newer than its newest child. With one requesting group the
|
||||
// parent cannot beat that child (ties prefer one child), so omit it.
|
||||
const bool needs_parent = replacement_group_count > 1 || !needs_replacement[group_id];
|
||||
if (needs_replacement[group_id]) {
|
||||
children[group_id].resize(static_cast<std::size_t>(allocator.ShardCount()));
|
||||
}
|
||||
if (!needs_parent && !GroupIsState(group_id)) {
|
||||
// No parent from this group can be donated. Its oldest children,
|
||||
// bounded by demand per bucket, suffice for the global comparison.
|
||||
std::vector<std::size_t> needed(allocator.ShardCount(), 0);
|
||||
std::size_t remaining = 0;
|
||||
for (std::size_t i = 0; i < group_ids.size(); ++i) {
|
||||
if (group_ids[i] == group_id && !batch.blocks[i]) {
|
||||
++needed[buckets[i]];
|
||||
++remaining;
|
||||
for (const auto& set : victims) {
|
||||
for (const auto& [group_id, location] : set.members) {
|
||||
if (groups_[group_id].Index().Contains(*host_pool_, location)) {
|
||||
FatalCheck(evictHostCachedBlock(group_id, location, &HostEvictionStats::lru),
|
||||
"a planned Host victim became pinned");
|
||||
}
|
||||
}
|
||||
PrefixCacheIndex::EvictionCursor cursor;
|
||||
std::vector<PrefixCacheIndex::EvictionCandidate> epoch;
|
||||
// Any epoch may hold the replacement this allocation needs.
|
||||
while (remaining > 0 && groups_[group_id].Index().NextEvictionEpoch(
|
||||
*host_pool_, cursor, std::numeric_limits<std::uint64_t>::max(), epoch)) {
|
||||
batch.stats.block_candidates += epoch.size();
|
||||
for (auto& candidate : epoch) {
|
||||
const std::int32_t bucket = allocator.BucketOf(candidate.location);
|
||||
if (needed[bucket] > 0) {
|
||||
children[group_id][bucket].entries.push_back(std::move(candidate));
|
||||
--needed[bucket];
|
||||
--remaining;
|
||||
}
|
||||
}
|
||||
epoch.clear();
|
||||
}
|
||||
continue;
|
||||
}
|
||||
std::vector<PrefixCacheIndex::EvictionCandidate> entries =
|
||||
groups_[group_id].Index().EvictableCandidates(*host_pool_);
|
||||
batch.stats.block_candidates += entries.size();
|
||||
if (needs_parent && !entries.empty() && parents.empty()) {
|
||||
parents.resize(static_cast<std::size_t>(host_pool_->NumLcmBlocks()) + 1);
|
||||
}
|
||||
for (auto& candidate : entries) {
|
||||
if (needs_parent) {
|
||||
const std::int32_t parent_id = candidate.location.lcm_block_id;
|
||||
HostParentCandidate& parent = parents[parent_id];
|
||||
if (parent.evictable_children == 0) {
|
||||
host_touched_parents_.push_back(parent_id);
|
||||
}
|
||||
++parent.evictable_children;
|
||||
parent.newest_access_epoch = std::max(parent.newest_access_epoch, candidate.metadata.last_access_epoch);
|
||||
}
|
||||
if (children[group_id].size() > 1) {
|
||||
children[group_id][allocator.BucketOf(candidate.location)].entries.push_back(std::move(candidate));
|
||||
}
|
||||
}
|
||||
if (children[group_id].size() == 1) {
|
||||
children[group_id].front().entries = std::move(entries);
|
||||
}
|
||||
for (BucketCandidates& bucket : children[group_id]) {
|
||||
std::ranges::sort(bucket.entries, {}, [&](const PrefixCacheIndex::EvictionCandidate& candidate) {
|
||||
return value(group_id, candidate.location, candidate.metadata);
|
||||
});
|
||||
}
|
||||
}
|
||||
using HostParentValue = std::tuple<std::uint64_t, std::uint32_t>;
|
||||
std::vector<std::pair<HostParentValue, std::int32_t>> victim_parents;
|
||||
victim_parents.reserve(host_touched_parents_.size());
|
||||
for (const std::int32_t parent_id : host_touched_parents_) {
|
||||
++batch.stats.parent_candidates;
|
||||
const HostParentCandidate& parent = parents[parent_id];
|
||||
if (parent.evictable_children > 0 && parent.evictable_children == host_pool_->OccupiedCount(parent_id)) {
|
||||
victim_parents.emplace_back(HostParentValue{parent.newest_access_epoch, *host_pool_->BoundGroup(parent_id)},
|
||||
parent_id);
|
||||
}
|
||||
}
|
||||
// Only a batch's victims are consumed. Build a min-heap in linear time
|
||||
// instead of sorting every eligible parent before selecting the first.
|
||||
std::ranges::make_heap(victim_parents, std::greater{});
|
||||
const auto discard_parent = [&] {
|
||||
std::ranges::pop_heap(victim_parents, std::greater{});
|
||||
victim_parents.pop_back();
|
||||
};
|
||||
for (std::size_t i = 0; i < group_ids.size(); ++i) {
|
||||
if (batch.blocks[i]) {
|
||||
continue;
|
||||
}
|
||||
const std::uint32_t group_id = group_ids[i];
|
||||
const std::int32_t bucket = buckets[i];
|
||||
// An earlier replacement may have opened more slots for this group,
|
||||
// also through the State cascade of another group's victim
|
||||
// (evictHostCachedBlock): that room is used before any victim goes.
|
||||
batch.blocks[i] = acquire_in_bucket(group_id, bucket);
|
||||
if (!batch.blocks[i]) {
|
||||
BucketCandidates& candidates = children[group_id][bucket];
|
||||
while (candidates.next < candidates.entries.size() &&
|
||||
!groups_[group_id].Index().MetadataFor(*host_pool_, candidates.entries[candidates.next].location)) {
|
||||
// Another group's replacement may have rebound this parent,
|
||||
// or an earlier victim's State cascade taken the entry.
|
||||
++candidates.next;
|
||||
}
|
||||
while (!victim_parents.empty()) {
|
||||
const auto& [parent_value, parent_id] = victim_parents.front();
|
||||
// Candidate metadata is a snapshot: check current placement
|
||||
// as well as destinations pinned earlier in this batch. A
|
||||
// State cascade may have emptied a parent (skipped here) or
|
||||
// taken some of its children (the rest still go whole).
|
||||
if (!parents[parent_id].allocated && host_pool_->OccupiedCount(parent_id) > 0 &&
|
||||
host_pool_->BoundGroup(parent_id) == std::get<1>(parent_value)) {
|
||||
break;
|
||||
}
|
||||
discard_parent();
|
||||
}
|
||||
const bool has_child = candidates.next < candidates.entries.size();
|
||||
const bool has_parent = !victim_parents.empty();
|
||||
if (!has_child && !has_parent) {
|
||||
continue;
|
||||
}
|
||||
// Compare feasible reclamations across all groups. A foreign
|
||||
// parent costs every occupied child, so its newest child sets
|
||||
// the epoch. Equal epochs prefer evicting just one child.
|
||||
if (has_child && (!has_parent || candidates.entries[candidates.next].metadata.last_access_epoch <=
|
||||
std::get<0>(victim_parents.front().first))) {
|
||||
// The retry above found no compatible hole. Releasing one
|
||||
// Host child creates the only placement for its refill; its
|
||||
// State cascade takes only other groups' entries.
|
||||
const CacheBlockLocation location = candidates.entries[candidates.next++].location;
|
||||
_assert(evictHostCachedBlock(group_id, location, &HostEvictionStats::lru),
|
||||
"selected Host child is not evictable");
|
||||
} else {
|
||||
const auto [parent_value, victim_parent] = victim_parents.front();
|
||||
discard_parent();
|
||||
const std::uint32_t bound_group = std::get<1>(parent_value);
|
||||
_assert(host_pool_->BoundGroup(victim_parent) == bound_group, "selected Host parent changed groups");
|
||||
const std::int32_t victim_packing = host_pool_->Packing(bound_group);
|
||||
for (std::int32_t slot = 0; slot < victim_packing; ++slot) {
|
||||
const CacheBlockLocation location{.lcm_block_id = victim_parent, .slot_index = slot};
|
||||
if (host_pool_->IsOccupied(location)) {
|
||||
_assert(evictHostCachedBlock(bound_group, location, &HostEvictionStats::lru),
|
||||
"selected Host parent changed before eviction");
|
||||
}
|
||||
}
|
||||
}
|
||||
batch.blocks[i] = acquire_in_bucket(group_id, bucket);
|
||||
_assert(static_cast<bool>(batch.blocks[i]), "evicting a Host victim did not free a placement");
|
||||
}
|
||||
// The result now pins this parent; it cannot be rebound later in
|
||||
// this batch even though the new entry has not been registered yet.
|
||||
if (!victim_parents.empty()) {
|
||||
const std::int32_t parent_id = batch.blocks[i]->Location().lcm_block_id;
|
||||
HostParentCandidate& parent = parents[parent_id];
|
||||
if (parent.evictable_children == 0 && !parent.allocated) {
|
||||
host_touched_parents_.push_back(parent_id);
|
||||
}
|
||||
parent.allocated = true;
|
||||
for (const std::size_t row : accepted) {
|
||||
batch.blocks[row] = acquire_in_bucket(group_ids[row], buckets[row]);
|
||||
FatalCheck(static_cast<bool>(batch.blocks[row]), "planned Host placement failed");
|
||||
}
|
||||
}
|
||||
batch.stats.allocated = static_cast<std::size_t>(
|
||||
@@ -1679,223 +1618,45 @@ CacheCoordinator::HostPlacementPlan CacheCoordinator::planHostBoundaries(std::sp
|
||||
next_row = boundary.past_end_row;
|
||||
}
|
||||
_assert(next_row == group_ids.size(), "Host boundaries cover every row");
|
||||
// The rows so far by group and bucket, the demand the shadow fits.
|
||||
std::vector<std::vector<std::int64_t>> need_by_bucket(groups_.size());
|
||||
for (std::size_t i = 0; i < groups_.size(); ++i) {
|
||||
need_by_bucket[i].assign(static_cast<std::size_t>(groups_[i].Allocator().ShardCount()), 0);
|
||||
}
|
||||
std::vector<std::vector<std::int64_t>> needed(groups_.size());
|
||||
for (std::size_t i = 0; i < groups_.size(); ++i) needed[i].resize(groups_[i].Allocator().ShardCount());
|
||||
for (std::size_t row = 0; row < group_ids.size(); ++row) {
|
||||
_assert(group_ids[row] < groups_.size(), "Host block group id out of range");
|
||||
_assert(buckets[row] >= 0 && buckets[row] < groups_[group_ids[row]].Allocator().ShardCount(),
|
||||
"Host block bucket is outside the group's shard count");
|
||||
++need_by_bucket[group_ids[row]][static_cast<std::size_t>(buckets[row])];
|
||||
++needed[group_ids[row]][buckets[row]];
|
||||
}
|
||||
const std::vector<std::int64_t> no_dense_need(groups_.size(), 0);
|
||||
ShadowOccupancy shadow{*host_pool_, groups_};
|
||||
HostEvictionPlanner planner{*this, groups_, *host_pool_};
|
||||
HostPlacementPlan plan;
|
||||
// Every row fits the free capacity: no victim.
|
||||
if (shadow.Fits(need_by_bucket, no_dense_need)) {
|
||||
if (planner.Fits(needed)) {
|
||||
plan.num_placed = boundaries.size();
|
||||
return plan;
|
||||
}
|
||||
// By segments, every boundary is planned first as AcquireHostSegments
|
||||
// plans an eviction write-back's segments; the per-block plan then places
|
||||
// the ones the segment step dropped, against the Host less its victims.
|
||||
// Where the two steps place fewer than the per-block plan alone, that
|
||||
// plan stands: the image comes before the cache.
|
||||
if (place_by_segments) {
|
||||
plan = planHostSegments(group_ids, buckets, boundaries);
|
||||
if (plan.num_placed == boundaries.size()) {
|
||||
return plan;
|
||||
}
|
||||
}
|
||||
// The demand restarts from the rows the segments place.
|
||||
for (std::vector<std::int64_t>& group_need : need_by_bucket) {
|
||||
std::ranges::fill(group_need, 0);
|
||||
}
|
||||
const std::size_t num_segment_rows = plan.num_placed == 0 ? 0 : boundaries[plan.num_placed - 1].past_end_row;
|
||||
for (std::size_t row = 0; row < num_segment_rows; ++row) {
|
||||
++need_by_bucket[group_ids[row]][static_cast<std::size_t>(buckets[row])];
|
||||
if (plan.num_placed == boundaries.size()) return plan;
|
||||
}
|
||||
for (auto& group_need : needed) std::ranges::fill(group_need, 0);
|
||||
const std::size_t segment_rows = plan.num_placed == 0 ? 0 : boundaries[plan.num_placed - 1].past_end_row;
|
||||
for (std::size_t row = 0; row < segment_rows; ++row) ++needed[group_ids[row]][buckets[row]];
|
||||
for (const auto& victim : plan.victims) planner.Seed(victim.group_id, victim.location);
|
||||
|
||||
// AcquireHostBlocks' candidates, in its order: per group and bucket the
|
||||
// unpinned entries, the least recently accessed first (location breaks
|
||||
// ties), and the parents whose every occupant is an unpinned entry, by
|
||||
// their newest one, then group and id.
|
||||
struct BucketCandidates {
|
||||
std::vector<PrefixCacheIndex::EvictionCandidate> entries;
|
||||
std::size_t next{0};
|
||||
};
|
||||
std::vector<std::vector<BucketCandidates>> children(groups_.size());
|
||||
// Per parent holding an unpinned entry: how many it holds, the newest
|
||||
// access among them, its occupants no victim has taken yet, and whether
|
||||
// a row took the room one of its children left (AcquireHostBlocks places
|
||||
// the row there, which keeps the parent from going whole later on) or
|
||||
// the rows placed need its free slots.
|
||||
struct ParentCandidate {
|
||||
std::uint64_t newest_access_epoch{0};
|
||||
std::int32_t evictable_children{0};
|
||||
std::int32_t untaken_occupants{0};
|
||||
bool allocated{false};
|
||||
};
|
||||
std::unordered_map<std::int32_t, ParentCandidate> parents;
|
||||
for (std::uint32_t group_id = 0; group_id < groups_.size(); ++group_id) {
|
||||
const GroupAllocator& allocator = groups_[group_id].Allocator();
|
||||
children[group_id].resize(static_cast<std::size_t>(allocator.ShardCount()));
|
||||
for (PrefixCacheIndex::EvictionCandidate& candidate :
|
||||
groups_[group_id].Index().EvictableCandidates(*host_pool_)) {
|
||||
ParentCandidate& parent = parents[candidate.location.lcm_block_id];
|
||||
++parent.evictable_children;
|
||||
parent.newest_access_epoch = std::max(parent.newest_access_epoch, candidate.metadata.last_access_epoch);
|
||||
children[group_id][allocator.BucketOf(candidate.location)].entries.push_back(std::move(candidate));
|
||||
}
|
||||
for (BucketCandidates& bucket : children[group_id]) {
|
||||
std::ranges::sort(bucket.entries, {}, [&](const PrefixCacheIndex::EvictionCandidate& candidate) {
|
||||
return std::tuple{candidate.metadata.last_access_epoch, group_id, candidate.location.lcm_block_id,
|
||||
candidate.location.slot_index};
|
||||
});
|
||||
}
|
||||
}
|
||||
std::vector<std::tuple<std::uint64_t, std::uint32_t, std::int32_t>> victim_parents;
|
||||
for (auto& [parent_id, parent] : parents) {
|
||||
parent.untaken_occupants = host_pool_->OccupiedCount(parent_id);
|
||||
if (parent.evictable_children == parent.untaken_occupants) {
|
||||
victim_parents.emplace_back(parent.newest_access_epoch, *host_pool_->BoundGroup(parent_id), parent_id);
|
||||
}
|
||||
}
|
||||
std::ranges::sort(victim_parents);
|
||||
std::size_t next_parent = 0;
|
||||
|
||||
std::unordered_set<CacheBlockLocation, CacheBlockLocationHash> taken;
|
||||
// The segments' victims leave first.
|
||||
for (const HostPlacementPlan::Victim& victim : plan.victims) {
|
||||
shadow.Remove(victim.group_id, victim.location);
|
||||
taken.insert(victim.location);
|
||||
if (const auto parent = parents.find(victim.location.lcm_block_id); parent != parents.end()) {
|
||||
--parent->second.untaken_occupants;
|
||||
}
|
||||
}
|
||||
const auto take_entry = [&](std::uint32_t group_id, CacheBlockLocation location) {
|
||||
shadow.Remove(group_id, location);
|
||||
taken.insert(location);
|
||||
if (const auto parent = parents.find(location.lcm_block_id); parent != parents.end()) {
|
||||
--parent->second.untaken_occupants;
|
||||
}
|
||||
plan.victims.push_back(
|
||||
HostPlacementPlan::Victim{.group_id = group_id, .location = location, .reason = &HostEvictionStats::lru});
|
||||
};
|
||||
// As evictHostCachedBlock evicts: a checkpoint takes the other State
|
||||
// groups' at its hash along, those not pinned (Find's reference is the
|
||||
// second when the index alone holds one).
|
||||
const auto take = [&](std::uint32_t group_id, CacheBlockLocation location) {
|
||||
take_entry(group_id, location);
|
||||
if (!GroupIsState(group_id)) {
|
||||
return;
|
||||
}
|
||||
const std::optional<CacheKey> key = groups_[group_id].Index().KeyOf(*host_pool_, location);
|
||||
ForEachBoundaryKey(*key, /*tail_tokens=*/0, [&](std::size_t i, const CacheKey& sibling_key) {
|
||||
if (!GroupIsState(i)) {
|
||||
return;
|
||||
}
|
||||
const CacheBlockRef sibling = groups_[i].Index().Find(*host_pool_, sibling_key);
|
||||
if (sibling && sibling.use_count() == 2 && !taken.contains(sibling->Location())) {
|
||||
take_entry(groups_[i].Id(), sibling->Location());
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
// A boundary at a time, as AcquireHostBlocks takes a batch: the rows that
|
||||
// fit the capacity left go first, then each other row, in order, takes
|
||||
// victims until it fits. A boundary short of a victim returns those it
|
||||
// took and ends the plan.
|
||||
for (const HostSegmentRows& boundary : boundaries.subspan(plan.num_placed)) {
|
||||
const std::size_t num_victims_before = plan.victims.size();
|
||||
std::vector<std::size_t> short_rows;
|
||||
for (std::size_t row = boundary.first_row; row < boundary.past_end_row; ++row) {
|
||||
std::int64_t& need = need_by_bucket[group_ids[row]][static_cast<std::size_t>(buckets[row])];
|
||||
++need;
|
||||
if (!shadow.Fits(need_by_bucket, no_dense_need)) {
|
||||
--need;
|
||||
short_rows.push_back(row);
|
||||
}
|
||||
}
|
||||
for (const std::size_t row : short_rows) {
|
||||
const std::uint32_t group_id = group_ids[row];
|
||||
const auto bucket = static_cast<std::size_t>(buckets[row]);
|
||||
BucketCandidates& candidates = children[group_id][bucket];
|
||||
++need_by_bucket[group_id][bucket];
|
||||
while (!shadow.Fits(need_by_bucket, no_dense_need)) {
|
||||
while (candidates.next < candidates.entries.size() &&
|
||||
taken.contains(candidates.entries[candidates.next].location)) {
|
||||
++candidates.next;
|
||||
}
|
||||
while (next_parent < victim_parents.size()) {
|
||||
const std::uint32_t bound_group = std::get<1>(victim_parents[next_parent]);
|
||||
const std::int32_t parent_id = std::get<2>(victim_parents[next_parent]);
|
||||
ParentCandidate& parent = parents.at(parent_id);
|
||||
if (parent.untaken_occupants > 0 && !parent.allocated) {
|
||||
// AcquireHostBlocks never takes a parent a row landed
|
||||
// in whole. The shadow does not track where the rows
|
||||
// placed before this one land, so a parent stays when
|
||||
// they need its free slots: with those filled as
|
||||
// well, they would not fit.
|
||||
const GroupAllocator& allocator = groups_[bound_group].Allocator();
|
||||
std::vector<std::int64_t> free_slots(static_cast<std::size_t>(allocator.ShardCount()),
|
||||
host_pool_->Packing(bound_group) / allocator.ShardCount());
|
||||
for (const CacheBlockLocation& location : host_pool_->OccupiedLocations(parent_id)) {
|
||||
if (!taken.contains(location)) {
|
||||
--free_slots[static_cast<std::size_t>(allocator.BucketOf(location))];
|
||||
}
|
||||
}
|
||||
--need_by_bucket[group_id][bucket];
|
||||
for (std::size_t b = 0; b < free_slots.size(); ++b) {
|
||||
need_by_bucket[bound_group][b] += free_slots[b];
|
||||
}
|
||||
const bool rows_need_its_slots = !shadow.Fits(need_by_bucket, no_dense_need);
|
||||
for (std::size_t b = 0; b < free_slots.size(); ++b) {
|
||||
need_by_bucket[bound_group][b] -= free_slots[b];
|
||||
}
|
||||
++need_by_bucket[group_id][bucket];
|
||||
if (!rows_need_its_slots) {
|
||||
break;
|
||||
}
|
||||
parent.allocated = true;
|
||||
}
|
||||
++next_parent;
|
||||
}
|
||||
const bool has_child = candidates.next < candidates.entries.size();
|
||||
const bool has_parent = next_parent < victim_parents.size();
|
||||
if (!has_child && !has_parent) {
|
||||
plan.victims.resize(num_victims_before);
|
||||
if (place_by_segments) {
|
||||
HostPlacementPlan per_block =
|
||||
planHostBoundaries(group_ids, buckets, boundaries, /*place_by_segments=*/false);
|
||||
if (per_block.num_placed > plan.num_placed) {
|
||||
return per_block;
|
||||
}
|
||||
}
|
||||
return plan;
|
||||
}
|
||||
// Equal epochs prefer one child, as in AcquireHostBlocks.
|
||||
if (has_child && (!has_parent || candidates.entries[candidates.next].metadata.last_access_epoch <=
|
||||
std::get<0>(victim_parents[next_parent]))) {
|
||||
const CacheBlockLocation location = candidates.entries[candidates.next++].location;
|
||||
parents.at(location.lcm_block_id).allocated = true;
|
||||
take(group_id, location);
|
||||
} else {
|
||||
const std::uint32_t bound_group = std::get<1>(victim_parents[next_parent]);
|
||||
const std::int32_t parent_id = std::get<2>(victim_parents[next_parent]);
|
||||
++next_parent;
|
||||
for (const CacheBlockLocation& location : host_pool_->OccupiedLocations(parent_id)) {
|
||||
if (!taken.contains(location)) {
|
||||
take(bound_group, location);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (std::size_t row = boundary.first_row; row < boundary.past_end_row; ++row)
|
||||
++needed[group_ids[row]][buckets[row]];
|
||||
if (!planner.Fit(needed)) {
|
||||
for (std::size_t row = boundary.first_row; row < boundary.past_end_row; ++row)
|
||||
--needed[group_ids[row]][buckets[row]];
|
||||
break;
|
||||
}
|
||||
++plan.num_placed;
|
||||
}
|
||||
planner.Minimize(needed);
|
||||
for (const auto& set : planner.Victims()) {
|
||||
for (const auto& [group_id, location] : set.members) {
|
||||
plan.victims.push_back({.group_id = group_id, .location = location, .reason = &HostEvictionStats::lru});
|
||||
}
|
||||
}
|
||||
return plan;
|
||||
}
|
||||
|
||||
|
||||
+11
-34
@@ -571,7 +571,7 @@ public:
|
||||
std::size_t group_scans{0};
|
||||
// Unpinned entries visited while collecting replacement candidates.
|
||||
std::size_t block_candidates{0};
|
||||
// Distinct touched parents checked for whole-parent reclamation.
|
||||
// Distinct parents whose occupancy was simulated during replacement.
|
||||
std::size_t parent_candidates{0};
|
||||
};
|
||||
struct HostAllocationBatch {
|
||||
@@ -584,20 +584,11 @@ public:
|
||||
void QueueCachedBlocksForStore(std::span<const std::string> content_hashes);
|
||||
std::vector<StoreCandidate> TakePendingStores() { return std::exchange(pending_stores_, {}); }
|
||||
CacheBlockRef AcquireDeviceCachedBlock(const CacheKey& key) const;
|
||||
// One Host block per (group, bucket) entry, in the bucket of the Device
|
||||
// block it will mirror -- under page-cyclic sharding the owner of a Host
|
||||
// page must be the owner of its Device page, so a copy's two ends select
|
||||
// the same rows on every rank. Free capacity first, then global LRU over
|
||||
// compatible children and fully evictable parents of any group. A parent
|
||||
// is ranked by its newest child; equal epochs prefer one child. A
|
||||
// shortfall leaves an empty reference. Evicting a State checkpoint takes
|
||||
// the other State groups' at its hash along; every block retries free
|
||||
// capacity before it picks a victim, so it places in the room such a
|
||||
// cascade freed before another victim goes. Block by block: it serves
|
||||
// publication and finish stores and L3 prefetches. A retraction image's
|
||||
// Host blocks come from AcquireHostBoundaries, whose per-block plan ranks
|
||||
// victims as this does (change the two together), and the Host blocks of
|
||||
// what an eviction writes back from AcquireHostSegments.
|
||||
// One Host block per (group, bucket), with free capacity assigned first
|
||||
// in input order. The shared eviction plan funds remaining rows globally;
|
||||
// failed rows and unnecessary tentative victims evict nothing. A State
|
||||
// checkpoint takes its unpinned State siblings at the same boundary along.
|
||||
// A shortfall leaves an empty reference, without blocking later rows.
|
||||
HostAllocationBatch AcquireHostBlocks(std::span<const std::uint32_t> group_ids,
|
||||
std::span<const std::int32_t> buckets);
|
||||
// One segment of an AcquireHostSegments batch, or one boundary of a
|
||||
@@ -650,12 +641,9 @@ public:
|
||||
// covering the rows in order, the shallowest first -- the Host can take
|
||||
// whole from the first on, each row in its Device block's bucket. Nothing
|
||||
// is evicted or acquired; AcquireHostBoundaries carries out the same plan.
|
||||
// It plans block by block with AcquireHostBlocks' victim ranking against
|
||||
// a shadow of the Host, which does not know which parent the pool gives
|
||||
// each row, so where several parents have room the victims can
|
||||
// differ from those AcquireHostBlocks would take. The write-back policy
|
||||
// places by segments first and never places fewer boundaries than block
|
||||
// by block (docs/design/scheduler.md §2).
|
||||
// Uses AcquireHostBlocks' planner, accepting whole boundaries instead of
|
||||
// individual rows. The write-back policy first tries its segment plan,
|
||||
// without placing fewer boundaries than the block plan alone would.
|
||||
std::size_t NumHostBoundariesThatFit(std::span<const std::uint32_t> group_ids,
|
||||
std::span<const std::int32_t> buckets,
|
||||
std::span<const HostSegmentRows> boundaries) const;
|
||||
@@ -911,10 +899,8 @@ private:
|
||||
HostAllocationBatch acquireHostPlacement(const HostPlacementPlan& plan, std::span<const std::uint32_t> group_ids,
|
||||
std::span<const std::int32_t> buckets,
|
||||
std::span<const HostSegmentRows> segments);
|
||||
// The plan NumHostBoundariesThatFit counts and AcquireHostBoundaries
|
||||
// carries out; by whole segments first with place_by_segments (the
|
||||
// write-back policy), else block by block alone. Its per-block victim
|
||||
// ranking is AcquireHostBlocks'; change the two together.
|
||||
// Shared block planning with whole-boundary acceptance. The write-back
|
||||
// policy first tries its segment plan when place_by_segments is set.
|
||||
HostPlacementPlan planHostBoundaries(std::span<const std::uint32_t> group_ids,
|
||||
std::span<const std::int32_t> buckets,
|
||||
std::span<const HostSegmentRows> boundaries, bool place_by_segments) const;
|
||||
@@ -1129,15 +1115,6 @@ private:
|
||||
// and level with the blocks no entry holds, until an acquisition or a
|
||||
// publication touches it again.
|
||||
static constexpr std::uint64_t kSupersededAccessEpoch{0};
|
||||
struct HostParentCandidate {
|
||||
std::uint64_t newest_access_epoch{0};
|
||||
std::int32_t evictable_children{0};
|
||||
bool allocated{false};
|
||||
};
|
||||
// Reuse the direct-indexed scratch buffer; reset only the parents touched
|
||||
// by the previous replacement batch, never the whole Host arena per call.
|
||||
std::vector<HostParentCandidate> host_parent_candidates_;
|
||||
std::vector<std::int32_t> host_touched_parents_;
|
||||
TailTable tails_;
|
||||
// The tree of the boundaries either tier indexes, in step with the indexes.
|
||||
// No match reads it; evicting by segments selects along it.
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
// Copyright (c) 2026 LightSeek Foundation
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <memory_resource>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <tuple>
|
||||
#include <unordered_set>
|
||||
#include <vector>
|
||||
|
||||
#include "cache/cache_group.h"
|
||||
#include "cache/core/block_pool.h"
|
||||
#include "cache/prefix/prefix_index.h"
|
||||
|
||||
namespace tokenspeed {
|
||||
|
||||
// Non-owning candidate traversal. Finish it before changing the pool or indexes.
|
||||
class CacheEvictionCandidates {
|
||||
public:
|
||||
using LocationSet = std::pmr::unordered_set<CacheBlockLocation, CacheBlockLocationHash>;
|
||||
|
||||
enum class BoundaryTier { kUncached, kProbationary, kEstablished, kClosedPrefix };
|
||||
|
||||
struct Candidate {
|
||||
std::uint64_t last_access_epoch;
|
||||
std::int64_t position_rank{0};
|
||||
CacheBlockLocation location;
|
||||
std::uint32_t group_id;
|
||||
BoundaryTier boundary_tier{BoundaryTier::kUncached};
|
||||
};
|
||||
|
||||
CacheEvictionCandidates(const std::vector<CacheGroup>& groups, const BlockPool& pool,
|
||||
const LocationSet* protected_locations, const LocationSet* request_reclaim_locations)
|
||||
: groups_{groups},
|
||||
pool_{pool},
|
||||
protected_locations_{protected_locations},
|
||||
request_reclaim_locations_{request_reclaim_locations} {
|
||||
cursors_.reserve(groups.size());
|
||||
for (std::size_t i = 0; i < groups.size(); ++i) {
|
||||
cursors_.emplace_back(static_cast<std::uint32_t>(i));
|
||||
}
|
||||
}
|
||||
|
||||
Candidate MakeCandidate(std::uint32_t group_id, CacheBlockLocation location,
|
||||
const std::optional<PrefixCacheIndex::CachedBlockMetadata>& metadata) const {
|
||||
Candidate candidate{.last_access_epoch = metadata ? metadata->last_access_epoch : 0,
|
||||
.location = location,
|
||||
.group_id = group_id};
|
||||
const std::int32_t position = metadata ? metadata->logical_block_index : -1;
|
||||
const CacheBoundaryKind kind = metadata ? metadata->boundary_kind : CacheBoundaryKind::kChunk;
|
||||
const bool closed = groups_[group_id].Matcher().IsPrefixClosed();
|
||||
const bool probationary =
|
||||
!closed && kind == CacheBoundaryKind::kChunk && !(metadata && metadata->was_acquired) && position >= 0;
|
||||
if (candidate.last_access_epoch != 0) {
|
||||
candidate.boundary_tier = probationary
|
||||
? BoundaryTier::kProbationary
|
||||
: (closed ? BoundaryTier::kClosedPrefix : BoundaryTier::kEstablished);
|
||||
}
|
||||
if (probationary) {
|
||||
candidate.position_rank = position;
|
||||
} else if (closed && position >= 0) {
|
||||
candidate.position_rank = -static_cast<std::int64_t>(position);
|
||||
}
|
||||
return candidate;
|
||||
}
|
||||
|
||||
static bool Before(const Candidate& lhs, const Candidate& rhs) { return evictionKey(lhs) < evictionKey(rhs); }
|
||||
|
||||
static void Sort(std::vector<Candidate>& candidates) {
|
||||
std::ranges::sort(candidates, {}, [](const Candidate& candidate) { return evictionKey(candidate); });
|
||||
}
|
||||
|
||||
// A request release can precede the cache; never inspect a newer epoch.
|
||||
std::optional<Candidate> Next(std::uint64_t max_access_epoch) {
|
||||
while (true) {
|
||||
GroupCursor* selected = nullptr;
|
||||
GroupCursor* next_group = nullptr;
|
||||
std::optional<std::uint64_t> next_epoch;
|
||||
for (GroupCursor& group : cursors_) {
|
||||
if (group.next_candidate < group.candidates.size()) {
|
||||
if (group.Current().last_access_epoch <= max_access_epoch &&
|
||||
(selected == nullptr || Before(group.Current(), selected->Current()))) {
|
||||
selected = &group;
|
||||
}
|
||||
} else if (!group.index_exhausted) {
|
||||
const auto epoch = groups_[group.group_id].Index().PeekEvictionEpoch(pool_, group.index_cursor);
|
||||
if (!epoch) {
|
||||
group.index_exhausted = true;
|
||||
} else if (*epoch <= max_access_epoch && (!next_epoch || *epoch < *next_epoch)) {
|
||||
next_epoch = epoch;
|
||||
next_group = &group;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Read complete equal epochs before applying policy tie-breaks.
|
||||
if (next_group != nullptr &&
|
||||
(selected == nullptr || *next_epoch <= selected->Current().last_access_epoch)) {
|
||||
loadEpoch(*next_group, *next_epoch);
|
||||
continue;
|
||||
}
|
||||
if (selected == nullptr) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return selected->candidates[selected->next_candidate++];
|
||||
}
|
||||
}
|
||||
|
||||
std::size_t ScannedCandidates() const { return scanned_candidates_; }
|
||||
std::size_t GroupScans() const { return group_scans_; }
|
||||
|
||||
private:
|
||||
static std::tuple<std::uint64_t, BoundaryTier, std::int64_t, std::uint32_t, std::int32_t, std::int32_t> evictionKey(
|
||||
const Candidate& candidate) {
|
||||
return std::tuple{candidate.last_access_epoch, candidate.boundary_tier, candidate.position_rank,
|
||||
candidate.group_id, candidate.location.lcm_block_id, candidate.location.slot_index};
|
||||
}
|
||||
|
||||
bool excluded(CacheBlockLocation location) const {
|
||||
return (protected_locations_ != nullptr && protected_locations_->contains(location)) ||
|
||||
(request_reclaim_locations_ != nullptr && request_reclaim_locations_->contains(location));
|
||||
}
|
||||
|
||||
struct GroupCursor {
|
||||
explicit GroupCursor(std::uint32_t id) : group_id{id} {}
|
||||
const Candidate& Current() const { return candidates[next_candidate]; }
|
||||
|
||||
std::uint32_t group_id;
|
||||
bool index_exhausted{false};
|
||||
bool started{false};
|
||||
PrefixCacheIndex::EvictionCursor index_cursor;
|
||||
std::vector<Candidate> candidates;
|
||||
std::size_t next_candidate{0};
|
||||
};
|
||||
|
||||
void loadEpoch(GroupCursor& group, std::uint64_t epoch) {
|
||||
if (!group.started) {
|
||||
group.started = true;
|
||||
++group_scans_;
|
||||
}
|
||||
group.candidates.clear();
|
||||
group.next_candidate = 0;
|
||||
epoch_scratch_.clear();
|
||||
groups_[group.group_id].Index().NextEvictionEpoch(pool_, group.index_cursor, epoch, epoch_scratch_);
|
||||
scanned_candidates_ += epoch_scratch_.size();
|
||||
for (const auto& entry : epoch_scratch_) {
|
||||
if (excluded(entry.location)) {
|
||||
continue;
|
||||
}
|
||||
group.candidates.push_back(MakeCandidate(group.group_id, entry.location, entry.metadata));
|
||||
}
|
||||
Sort(group.candidates);
|
||||
}
|
||||
|
||||
const std::vector<CacheGroup>& groups_;
|
||||
const BlockPool& pool_;
|
||||
const LocationSet* protected_locations_;
|
||||
const LocationSet* request_reclaim_locations_;
|
||||
std::vector<GroupCursor> cursors_;
|
||||
std::vector<PrefixCacheIndex::EvictionCandidate> epoch_scratch_;
|
||||
std::size_t scanned_candidates_{0};
|
||||
std::size_t group_scans_{0};
|
||||
};
|
||||
|
||||
} // namespace tokenspeed
|
||||
@@ -0,0 +1,109 @@
|
||||
// Copyright (c) 2026 LightSeek Foundation
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <limits>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "cache/coordinator/eviction_candidates.h"
|
||||
#include "cache/coordinator/shadow_occupancy.h"
|
||||
|
||||
namespace tokenspeed {
|
||||
|
||||
// Planning never changes the pool. Callers supply the blocks that must leave together.
|
||||
class CacheEvictionPlan {
|
||||
public:
|
||||
using Candidate = CacheEvictionCandidates::Candidate;
|
||||
using LocationSet = CacheEvictionCandidates::LocationSet;
|
||||
|
||||
CacheEvictionPlan(const BlockPool& pool, const std::vector<CacheGroup>& groups)
|
||||
: pool_{pool}, groups_{groups}, shadow_{pool, groups} {}
|
||||
|
||||
void StartCandidates(const LocationSet* protected_locations, const LocationSet* request_reclaim_locations) {
|
||||
candidates_.emplace(groups_, pool_, protected_locations, request_reclaim_locations);
|
||||
}
|
||||
|
||||
CacheEvictionCandidates& Candidates() { return *candidates_; }
|
||||
const CacheEvictionCandidates& Candidates() const { return *candidates_; }
|
||||
|
||||
std::optional<Candidate> Next(std::span<const Candidate> request_candidates) {
|
||||
const Candidate* request =
|
||||
next_request_ < request_candidates.size() ? &request_candidates[next_request_] : nullptr;
|
||||
if (!next_cached_) {
|
||||
next_cached_ =
|
||||
candidates_->Next(request ? request->last_access_epoch : std::numeric_limits<std::uint64_t>::max());
|
||||
}
|
||||
if (request && (!next_cached_ || CacheEvictionCandidates::Before(*request, *next_cached_))) {
|
||||
++next_request_;
|
||||
return *request;
|
||||
}
|
||||
return std::exchange(next_cached_, std::nullopt);
|
||||
}
|
||||
|
||||
bool Fits(std::span<const std::vector<std::int64_t>> needed, std::span<const std::int64_t> dense) const {
|
||||
return shadow_.Fits(needed, dense);
|
||||
}
|
||||
|
||||
void Remove(std::uint32_t group_id, CacheBlockLocation location) { shadow_.Remove(group_id, location); }
|
||||
void Restore(std::uint32_t group_id, CacheBlockLocation location) { shadow_.Restore(group_id, location); }
|
||||
std::size_t TouchedParents() const { return shadow_.TouchedParents(); }
|
||||
|
||||
template <typename SelectNext>
|
||||
bool SelectUntilFits(std::span<const std::vector<std::int64_t>> needed, std::span<const std::int64_t> dense,
|
||||
SelectNext&& select_next) {
|
||||
while (!Fits(needed, dense)) {
|
||||
if (!select_next()) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Newer sets are returned first; a failed demand must not cost useful cache.
|
||||
template <typename VictimSet>
|
||||
void Minimize(std::vector<VictimSet>& victims, std::span<const std::vector<std::int64_t>> needed,
|
||||
std::span<const std::int64_t> dense) {
|
||||
std::vector<VictimSet> required;
|
||||
required.reserve(victims.size());
|
||||
for (auto it = victims.rbegin(); it != victims.rend(); ++it) {
|
||||
if (it->members.empty()) continue;
|
||||
for (const auto& member : it->members) Restore(member.group_id, member.location);
|
||||
if (!Fits(needed, dense)) {
|
||||
for (const auto& member : it->members) Remove(member.group_id, member.location);
|
||||
required.push_back(std::move(*it));
|
||||
}
|
||||
}
|
||||
std::ranges::reverse(required);
|
||||
victims = std::move(required);
|
||||
}
|
||||
|
||||
private:
|
||||
const BlockPool& pool_;
|
||||
const std::vector<CacheGroup>& groups_;
|
||||
ShadowOccupancy shadow_;
|
||||
std::optional<CacheEvictionCandidates> candidates_;
|
||||
std::optional<Candidate> next_cached_;
|
||||
std::size_t next_request_{0};
|
||||
};
|
||||
|
||||
} // namespace tokenspeed
|
||||
@@ -119,6 +119,8 @@ public:
|
||||
return parents_needed <= empty_parent_count_;
|
||||
}
|
||||
|
||||
std::size_t TouchedParents() const { return remaining_occupied_.size(); }
|
||||
|
||||
private:
|
||||
const BlockPool& pool_;
|
||||
std::span<const CacheGroup> groups_;
|
||||
|
||||
@@ -485,6 +485,25 @@ public:
|
||||
return match;
|
||||
}
|
||||
|
||||
// Present source blocks refresh matching entries without pinning or inserting them.
|
||||
void TouchExisting(const BlockPool& pool, std::span<const CacheKey> keys, std::span<const CacheBlockRef> blocks,
|
||||
std::uint64_t access_epoch) {
|
||||
_assert(blocks.size() <= keys.size(), "source block span exceeds key span");
|
||||
CacheEntries* entries = findCacheEntries(pool);
|
||||
if (entries == nullptr) {
|
||||
return;
|
||||
}
|
||||
for (std::size_t i = 0; i < blocks.size(); ++i) {
|
||||
if (!blocks[i]) {
|
||||
continue;
|
||||
}
|
||||
auto entry = findEntry(*entries, keys[i]);
|
||||
if (entry != entries->entries.end()) {
|
||||
touchEntry(*entries, entry, std::max(entry->last_access_epoch, access_epoch));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<CacheBlockLocation> MatchedLocations(const BlockPool& pool, std::span<const CacheKey> keys,
|
||||
std::int32_t begin_blocks, const GroupPrefixProbe& probe) const {
|
||||
_assert(begin_blocks >= 0 && static_cast<std::size_t>(begin_blocks) + probe.hits.size() <= keys.size(),
|
||||
|
||||
@@ -2952,6 +2952,71 @@ TEST(CacheCoordinatorHostReplacement, SameGroupUsesLastAccessAfterPrefixHits) {
|
||||
}
|
||||
}
|
||||
|
||||
TEST(CacheCoordinatorHostReplacement, DeviceUseRefreshesExistingHostRecency) {
|
||||
enum class Use { kHit, kPublication, kLatePublication };
|
||||
for (const bool state : {false, true}) {
|
||||
for (const Use use : {Use::kHit, Use::kPublication, Use::kLatePublication}) {
|
||||
SCOPED_TRACE(state);
|
||||
SCOPED_TRACE(static_cast<int>(use));
|
||||
BlockPool device_pool(8, {1});
|
||||
BlockPool host_pool(2, {1});
|
||||
const std::array specs{CacheGroupSpec{.attn_kind = state ? AttnKind::kState : AttnKind::kFull,
|
||||
.cache_blocks_per_lcm_block = 1,
|
||||
.block_granularity = state ? 0 : 4}};
|
||||
CacheCoordinator coordinator = MakeCoordinator(
|
||||
specs, 4, device_pool, /*enable_l3_storage=*/false, &host_pool, /*snapshot_pool=*/nullptr,
|
||||
/*stream_device_cache_to_host=*/false, /*write_back_evictions=*/false);
|
||||
const auto a = ContentHashes({{1, 2, 3, 4}});
|
||||
const auto b = ContentHashes({{5, 6, 7, 8}});
|
||||
const auto publish = [&](std::span<const std::string> hashes) {
|
||||
std::vector<BlockTable> tables(1);
|
||||
const auto admitted = AdmitForTest(coordinator, tables, 4);
|
||||
ASSERT_TRUE(admitted);
|
||||
CacheCompletedBlocksForTest(coordinator, tables, hashes, admitted->access_epoch, 0, 4,
|
||||
CacheBoundaryKind::kEndpoint, /*stream_completed_to_host=*/false,
|
||||
/*publish_state=*/state);
|
||||
coordinator.Free(tables);
|
||||
};
|
||||
for (const auto* hashes : {&a, &b}) {
|
||||
ASSERT_NO_FATAL_FAILURE(publish(*hashes));
|
||||
CacheBlockRef host = host_pool.AcquireBlock(0);
|
||||
ASSERT_TRUE(host);
|
||||
coordinator.CacheHostBlock(host, Key(hashes->front(), 0), std::nullopt);
|
||||
}
|
||||
if (use == Use::kHit) {
|
||||
std::vector<BlockTable> tables(1);
|
||||
const auto admitted = AdmitForTest(coordinator, tables, coordinator.ProbePrefix(a),
|
||||
GroupDemand{.extent = DenseGrowth{4}});
|
||||
ASSERT_TRUE(admitted);
|
||||
EXPECT_EQ(admitted->device_prefix_tokens, 4);
|
||||
coordinator.Free(tables);
|
||||
} else if (use == Use::kPublication) {
|
||||
ASSERT_NO_FATAL_FAILURE(publish(a));
|
||||
} else {
|
||||
std::vector<BlockTable> tables(1);
|
||||
const auto admitted = AdmitForTest(coordinator, tables, 4);
|
||||
ASSERT_TRUE(admitted);
|
||||
for (const auto* hashes : {&b, &a}) {
|
||||
CacheBlockRef host = coordinator.FindHostCachedBlock(Key(hashes->front(), 0));
|
||||
ASSERT_TRUE(host);
|
||||
coordinator.CacheHostBlock(host, Key(hashes->front(), 0), std::nullopt);
|
||||
}
|
||||
CacheCompletedBlocksForTest(coordinator, tables, a, admitted->access_epoch, 0, 4,
|
||||
CacheBoundaryKind::kEndpoint, /*stream_completed_to_host=*/false,
|
||||
/*publish_state=*/state);
|
||||
coordinator.Free(tables);
|
||||
}
|
||||
EXPECT_EQ(coordinator.NumHostCachedBlocks(), 2);
|
||||
EXPECT_EQ(coordinator.NumPinnedHostCachedBlocks(), 0);
|
||||
EXPECT_TRUE(coordinator.TakePendingStores().empty());
|
||||
CacheBlockRef incoming = coordinator.AcquireHostBlock(0, 0);
|
||||
ASSERT_TRUE(incoming);
|
||||
EXPECT_TRUE(coordinator.ContainsHostCachedBlock(Key(a.front(), 0)));
|
||||
EXPECT_FALSE(coordinator.ContainsHostCachedBlock(Key(b.front(), 0)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TEST(CacheCoordinatorHostReplacement, CrossGroupUsesMostRecentChildAccess) {
|
||||
for (const bool refresh_old : {false, true}) {
|
||||
SCOPED_TRACE(refresh_old);
|
||||
@@ -3099,29 +3164,107 @@ TEST(CacheCoordinatorHostReplacement, GlobalLruProtectsAParentWithARecentSibling
|
||||
EXPECT_TRUE(coordinator.ContainsHostCachedBlock(Key("hot-sibling", 0)));
|
||||
}
|
||||
|
||||
TEST(CacheCoordinatorHostReplacement, GlobalLruPrefersOneChildWhenAccessEpochsTie) {
|
||||
BlockPool device_pool(2, {2, 1});
|
||||
BlockPool host_pool(2, {2, 1});
|
||||
const std::array specs{
|
||||
CacheGroupSpec{.attn_kind = AttnKind::kFull, .cache_blocks_per_lcm_block = 2, .block_granularity = 2},
|
||||
CacheGroupSpec{.attn_kind = AttnKind::kFull, .cache_blocks_per_lcm_block = 1, .block_granularity = 2},
|
||||
};
|
||||
CacheCoordinator coordinator =
|
||||
MakeCoordinator(specs, 2, device_pool, /*enable_l3_storage=*/false, &host_pool,
|
||||
/*snapshot_pool=*/nullptr,
|
||||
/*stream_device_cache_to_host=*/true, /*write_back_evictions=*/false);
|
||||
const std::uint64_t epoch = NextTestAccessEpoch();
|
||||
CacheBoundaryForGroup(coordinator, host_pool, "other-0", 0, epoch, -1);
|
||||
CacheBoundaryForGroup(coordinator, host_pool, "other-1", 0, epoch, -1);
|
||||
const CacheBlockLocation own = CacheBoundaryForGroup(coordinator, host_pool, "own", 1, epoch, -1);
|
||||
TEST(CacheCoordinatorHostReplacement, EqualEpochParentsRankByTheirMostProtectedChild) {
|
||||
for (const bool by_boundary : {false, true}) {
|
||||
for (const bool parent_has_prefix : {false, true}) {
|
||||
SCOPED_TRACE(by_boundary);
|
||||
SCOPED_TRACE(parent_has_prefix);
|
||||
BlockPool device_pool(2, {2, 1});
|
||||
BlockPool host_pool(2, {2, 1});
|
||||
const std::array specs{
|
||||
CacheGroupSpec{.attn_kind = AttnKind::kFull, .cache_blocks_per_lcm_block = 2, .block_granularity = 2},
|
||||
CacheGroupSpec{.attn_kind = AttnKind::kFull, .cache_blocks_per_lcm_block = 1, .block_granularity = 2},
|
||||
};
|
||||
CacheCoordinator coordinator =
|
||||
MakeCoordinator(specs, 2, device_pool, /*enable_l3_storage=*/false, &host_pool,
|
||||
/*snapshot_pool=*/nullptr,
|
||||
/*stream_device_cache_to_host=*/true, /*write_back_evictions=*/false);
|
||||
const std::uint64_t epoch = NextTestAccessEpoch();
|
||||
const CacheBlockLocation other =
|
||||
CacheBoundaryForGroup(coordinator, host_pool, "other-0", 0, epoch, parent_has_prefix ? 0 : 2);
|
||||
CacheBoundaryForGroup(coordinator, host_pool, "other-1", 0, epoch, 3);
|
||||
const CacheBlockLocation own = CacheBoundaryForGroup(coordinator, host_pool, "own", 1, epoch, 1);
|
||||
const std::array<std::uint32_t, 1> group_ids{1};
|
||||
const std::array<std::int32_t, 1> buckets{0};
|
||||
const std::array boundaries{CacheCoordinator::HostSegmentRows{.first_row = 0, .past_end_row = 1}};
|
||||
|
||||
CacheBlockRef replacement = coordinator.AcquireHostBlock(1, /*bucket=*/0);
|
||||
EXPECT_EQ(coordinator.NumHostBoundariesThatFit(group_ids, buckets, boundaries), 1u);
|
||||
auto batch = by_boundary ? coordinator.AcquireHostBoundaries(group_ids, buckets, boundaries)
|
||||
: coordinator.AcquireHostBlocks(group_ids, buckets);
|
||||
|
||||
ASSERT_TRUE(replacement);
|
||||
EXPECT_EQ(replacement->Location(), own);
|
||||
EXPECT_FALSE(coordinator.ContainsHostCachedBlock(Key("own", 1)));
|
||||
EXPECT_TRUE(coordinator.ContainsHostCachedBlock(Key("other-0", 0)));
|
||||
EXPECT_TRUE(coordinator.ContainsHostCachedBlock(Key("other-1", 0)));
|
||||
ASSERT_EQ(batch.stats.allocated, 1u);
|
||||
EXPECT_EQ(batch.blocks.front()->Location().lcm_block_id,
|
||||
parent_has_prefix ? own.lcm_block_id : other.lcm_block_id);
|
||||
EXPECT_EQ(coordinator.ContainsHostCachedBlock(Key("own", 1)), !parent_has_prefix);
|
||||
EXPECT_EQ(coordinator.ContainsHostCachedBlock(Key("other-0", 0)), parent_has_prefix);
|
||||
EXPECT_EQ(coordinator.ContainsHostCachedBlock(Key("other-1", 0)), parent_has_prefix);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TEST(CacheCoordinatorHostReplacement, HostAndDeviceEvictEqualEpochPrefixesFromTheSuffix) {
|
||||
for (const bool by_boundary : {false, true}) {
|
||||
SCOPED_TRACE(by_boundary);
|
||||
BlockPool device_pool(3, {1});
|
||||
BlockPool host_pool(3, {1});
|
||||
const std::array specs{
|
||||
CacheGroupSpec{.attn_kind = AttnKind::kFull, .cache_blocks_per_lcm_block = 1, .block_granularity = 2}};
|
||||
CacheCoordinator coordinator =
|
||||
MakeCoordinator(specs, 2, device_pool, /*enable_l3_storage=*/false, &host_pool,
|
||||
/*snapshot_pool=*/nullptr,
|
||||
/*stream_device_cache_to_host=*/true, /*write_back_evictions=*/false);
|
||||
const std::uint64_t epoch = NextTestAccessEpoch();
|
||||
for (std::int32_t position = 0; position < 3; ++position) {
|
||||
const std::string hash = "page-" + std::to_string(position);
|
||||
CacheBoundaryForGroup(coordinator, device_pool, hash, 0, epoch, position);
|
||||
CacheBoundaryForGroup(coordinator, host_pool, hash, 0, epoch, position);
|
||||
}
|
||||
|
||||
std::vector<BlockTable> tables(1);
|
||||
ASSERT_TRUE(AdmitForTest(coordinator, tables, 2));
|
||||
EXPECT_TRUE(coordinator.GroupPrefixIndex(0).Contains(device_pool, Key("page-0", 0)));
|
||||
EXPECT_FALSE(coordinator.GroupPrefixIndex(0).Contains(device_pool, Key("page-2", 0)));
|
||||
|
||||
const std::array<std::uint32_t, 1> group_ids{0};
|
||||
const std::array<std::int32_t, 1> buckets{0};
|
||||
const std::array boundaries{CacheCoordinator::HostSegmentRows{.first_row = 0, .past_end_row = 1}};
|
||||
auto batch = by_boundary ? coordinator.AcquireHostBoundaries(group_ids, buckets, boundaries)
|
||||
: coordinator.AcquireHostBlocks(group_ids, buckets);
|
||||
ASSERT_EQ(batch.stats.allocated, 1u);
|
||||
EXPECT_TRUE(coordinator.ContainsHostCachedBlock(Key("page-0", 0)));
|
||||
EXPECT_FALSE(coordinator.ContainsHostCachedBlock(Key("page-2", 0)));
|
||||
}
|
||||
}
|
||||
|
||||
TEST(CacheCoordinatorHostReplacement, EqualEpochUnprovenCheckpointsLeaveBeforeEstablishedCheckpointsAndPrefixes) {
|
||||
for (const bool by_boundary : {false, true}) {
|
||||
SCOPED_TRACE(by_boundary);
|
||||
BlockPool device_pool(3, {1, 1});
|
||||
BlockPool host_pool(3, {1, 1});
|
||||
const std::array specs{
|
||||
CacheGroupSpec{.attn_kind = AttnKind::kFull, .cache_blocks_per_lcm_block = 1, .block_granularity = 2},
|
||||
CacheGroupSpec{.attn_kind = AttnKind::kState, .cache_blocks_per_lcm_block = 1, .block_granularity = 0},
|
||||
};
|
||||
CacheCoordinator coordinator =
|
||||
MakeCoordinator(specs, 2, device_pool, /*enable_l3_storage=*/false, &host_pool,
|
||||
/*snapshot_pool=*/nullptr,
|
||||
/*stream_device_cache_to_host=*/true, /*write_back_evictions=*/false);
|
||||
const std::uint64_t epoch = NextTestAccessEpoch();
|
||||
CacheBoundaryForGroup(coordinator, host_pool, "prefix", 0, epoch, 0);
|
||||
CacheBoundaryForGroup(coordinator, host_pool, "established", 1, epoch, 0, CacheBoundaryKind::kEndpoint);
|
||||
CacheBoundaryForGroup(coordinator, host_pool, "unproven", 1, epoch, 1, CacheBoundaryKind::kChunk);
|
||||
const std::array<std::uint32_t, 1> group_ids{0};
|
||||
const std::array<std::int32_t, 1> buckets{0};
|
||||
const std::array boundaries{CacheCoordinator::HostSegmentRows{.first_row = 0, .past_end_row = 1}};
|
||||
|
||||
auto batch = by_boundary ? coordinator.AcquireHostBoundaries(group_ids, buckets, boundaries)
|
||||
: coordinator.AcquireHostBlocks(group_ids, buckets);
|
||||
|
||||
ASSERT_EQ(batch.stats.allocated, 1u);
|
||||
EXPECT_TRUE(coordinator.ContainsHostCachedBlock(Key("prefix", 0)));
|
||||
EXPECT_TRUE(coordinator.ContainsHostCachedBlock(Key("established", 1)));
|
||||
EXPECT_FALSE(coordinator.ContainsHostCachedBlock(Key("unproven", 1)));
|
||||
}
|
||||
}
|
||||
|
||||
TEST(CacheCoordinatorHostReplacement, GlobalLruSkipsPinnedParentsWithoutFallingBackToSameGroup) {
|
||||
@@ -3153,7 +3296,7 @@ TEST(CacheCoordinatorHostReplacement, GlobalLruSkipsPinnedParentsWithoutFallingB
|
||||
EXPECT_TRUE(coordinator.ContainsHostCachedBlock(Key("cold-sibling", 0)));
|
||||
}
|
||||
|
||||
TEST(CacheCoordinatorHostReplacement, GlobalLruBatchSkipsReboundEntriesAndProtectsNewAllocations) {
|
||||
TEST(CacheCoordinatorHostReplacement, JointBatchRestoresVictimsTheAcceptedRowsDoNotNeed) {
|
||||
BlockPool device_pool(2, {2, 1});
|
||||
BlockPool host_pool(2, {2, 1});
|
||||
const std::array specs{
|
||||
@@ -3173,18 +3316,21 @@ TEST(CacheCoordinatorHostReplacement, GlobalLruBatchSkipsReboundEntriesAndProtec
|
||||
CacheCoordinator::HostAllocationBatch batch = coordinator.AcquireHostBlocks(groups, buckets);
|
||||
|
||||
ASSERT_TRUE(batch.blocks[0]);
|
||||
EXPECT_EQ(batch.blocks[0]->Location().lcm_block_id, older_parent);
|
||||
EXPECT_EQ(batch.blocks[0]->Location().lcm_block_id, newer_parent);
|
||||
ASSERT_TRUE(batch.blocks[1]);
|
||||
EXPECT_EQ(batch.blocks[1]->Location().lcm_block_id, newer_parent);
|
||||
EXPECT_EQ(host_pool.BoundGroup(older_parent), 1u);
|
||||
EXPECT_EQ(host_pool.BoundGroup(newer_parent), 0u);
|
||||
EXPECT_EQ(batch.blocks[1]->Location().lcm_block_id, older_parent);
|
||||
EXPECT_EQ(host_pool.BoundGroup(older_parent), 0u);
|
||||
EXPECT_EQ(host_pool.BoundGroup(newer_parent), 1u);
|
||||
EXPECT_FALSE(batch.blocks[2]);
|
||||
EXPECT_EQ(batch.stats.allocated, 2u);
|
||||
EXPECT_EQ(batch.stats.unallocated, 1u);
|
||||
EXPECT_EQ(coordinator.NumHostCachedBlocks(), 0);
|
||||
EXPECT_EQ(coordinator.NumHostCachedBlocks(), 1);
|
||||
EXPECT_TRUE(coordinator.ContainsHostCachedBlock(Key("old-1", 0)));
|
||||
EXPECT_FALSE(coordinator.ContainsHostCachedBlock(Key("old-0", 0)));
|
||||
EXPECT_FALSE(coordinator.ContainsHostCachedBlock(Key("newer", 1)));
|
||||
}
|
||||
|
||||
TEST(CacheCoordinatorHostReplacement, GlobalLruMixesChildAndParentVictimsAcrossBuckets) {
|
||||
TEST(CacheCoordinatorHostReplacement, JointBatchReusesCompatibleHolesAcrossGroups) {
|
||||
BlockPool device_pool(3, {4, 4});
|
||||
BlockPool host_pool(3, {4, 4});
|
||||
const std::array specs{
|
||||
@@ -3218,18 +3364,17 @@ TEST(CacheCoordinatorHostReplacement, GlobalLruMixesChildAndParentVictimsAcrossB
|
||||
first_group.clear();
|
||||
second_group.clear();
|
||||
|
||||
// Child eviction first, then whole-parent eviction opens holes in both
|
||||
// buckets. Later requests reuse those holes and skip rebound candidates.
|
||||
// Joint planning retains each parent's group and evicts only five entries.
|
||||
const std::array<std::uint32_t, 5> groups{0, 1, 1, 0, 0};
|
||||
const std::array<std::int32_t, 5> buckets{0, 1, 0, 1, 0};
|
||||
CacheCoordinator::HostAllocationBatch batch = coordinator.AcquireHostBlocks(groups, buckets);
|
||||
|
||||
ASSERT_TRUE(std::ranges::all_of(batch.blocks, [](const CacheBlockRef& ref) { return static_cast<bool>(ref); }));
|
||||
EXPECT_EQ(batch.blocks[0]->Location(), cold_child);
|
||||
EXPECT_EQ(batch.blocks[1]->Location().lcm_block_id, cold_parent);
|
||||
EXPECT_EQ(batch.blocks[2]->Location().lcm_block_id, cold_parent);
|
||||
EXPECT_EQ(batch.blocks[3]->Location().lcm_block_id, middle_parent);
|
||||
EXPECT_EQ(batch.blocks[4]->Location().lcm_block_id, middle_parent);
|
||||
EXPECT_EQ(batch.blocks[1]->Location().lcm_block_id, middle_parent);
|
||||
EXPECT_EQ(batch.blocks[2]->Location().lcm_block_id, middle_parent);
|
||||
EXPECT_EQ(batch.blocks[3]->Location().lcm_block_id, cold_parent);
|
||||
EXPECT_EQ(batch.blocks[4]->Location().lcm_block_id, cold_parent);
|
||||
for (std::size_t i = 0; i < groups.size(); ++i) {
|
||||
EXPECT_EQ(host_pool.BoundGroup(batch.blocks[i]->Location().lcm_block_id), groups[i]);
|
||||
EXPECT_EQ(coordinator.Allocator(static_cast<std::int32_t>(groups[i])).BucketOf(batch.blocks[i]->Location()),
|
||||
@@ -3239,12 +3384,13 @@ TEST(CacheCoordinatorHostReplacement, GlobalLruMixesChildAndParentVictimsAcrossB
|
||||
for (int i = 1; i < 4; ++i) {
|
||||
EXPECT_TRUE(coordinator.ContainsHostCachedBlock(Key("first-" + std::to_string(i), 0)));
|
||||
}
|
||||
EXPECT_EQ(coordinator.NumHostCachedBlocks(), 3);
|
||||
EXPECT_EQ(coordinator.NumHostCachedBlocks(), 7);
|
||||
EXPECT_EQ(coordinator.HostEvictions().lru.blocks, 5u);
|
||||
EXPECT_EQ(batch.stats.group_scans, 2u);
|
||||
EXPECT_EQ(batch.stats.parent_candidates, 3u);
|
||||
}
|
||||
|
||||
TEST(CacheCoordinatorHostReplacement, GlobalLruRefreshesParentScratchBetweenBatches) {
|
||||
TEST(CacheCoordinatorHostReplacement, RepeatedBatchesReadCurrentOccupancy) {
|
||||
for (const std::uint32_t first_group : {0u, 1u}) {
|
||||
SCOPED_TRACE(first_group);
|
||||
BlockPool device_pool(2, {1, 1});
|
||||
@@ -3312,7 +3458,7 @@ TEST(CacheCoordinatorHostReplacement, GlobalLruComparesOnlyChildrenInTheRequeste
|
||||
EXPECT_FALSE(coordinator.ContainsHostCachedBlock(Key("other-1", 1)));
|
||||
}
|
||||
|
||||
TEST(CacheCoordinatorHostReplacement, SingleGroupBatchUsesChildrenWithoutParentCandidates) {
|
||||
TEST(CacheCoordinatorHostReplacement, SingleGroupBatchEvictsOnlyTheRequiredChildren) {
|
||||
BlockPool device_pool(4, {2});
|
||||
BlockPool host_pool(2, {2});
|
||||
const std::array specs{CacheGroupSpec{
|
||||
@@ -3340,7 +3486,7 @@ TEST(CacheCoordinatorHostReplacement, SingleGroupBatchUsesChildrenWithoutParentC
|
||||
EXPECT_EQ(batch.stats.allocated, 4u);
|
||||
EXPECT_EQ(batch.stats.unallocated, 0u);
|
||||
EXPECT_EQ(batch.stats.group_scans, 1u);
|
||||
EXPECT_EQ(batch.stats.parent_candidates, 0u);
|
||||
EXPECT_EQ(batch.stats.parent_candidates, 2u);
|
||||
EXPECT_EQ(coordinator.HostEvictions().lru.blocks, 4u);
|
||||
EXPECT_EQ(coordinator.HostEvictions().lru.device_resident, 0u);
|
||||
}
|
||||
@@ -3366,7 +3512,7 @@ TEST(CacheCoordinatorHostReplacement, BoundedHistoryScanPreservesGlobalLruAndRep
|
||||
auto first = coordinator.AcquireHostBlocks(groups, buckets);
|
||||
ASSERT_TRUE(first.blocks[0]);
|
||||
EXPECT_EQ(first.blocks[0]->Location().lcm_block_id, donor_parent);
|
||||
EXPECT_EQ(first.stats.block_candidates, 3u);
|
||||
EXPECT_EQ(first.stats.block_candidates, 2u);
|
||||
EXPECT_FALSE(coordinator.ContainsHostCachedBlock(Key("donor-0", 1)));
|
||||
EXPECT_FALSE(coordinator.ContainsHostCachedBlock(Key("donor-1", 1)));
|
||||
EXPECT_TRUE(coordinator.ContainsHostCachedBlock(Key("old-0", 0)));
|
||||
@@ -3536,7 +3682,7 @@ TEST(CacheCoordinatorHostReplacement, BatchRebindsParentsOnceAcrossMixedGroups)
|
||||
EXPECT_EQ(host_pool.BoundGroup(batch.blocks[0]->Location().lcm_block_id), 1u);
|
||||
EXPECT_EQ(host_pool.BoundGroup(batch.blocks[2]->Location().lcm_block_id), 0u);
|
||||
EXPECT_NE(batch.blocks[0]->Location().lcm_block_id, batch.blocks[2]->Location().lcm_block_id);
|
||||
EXPECT_EQ(batch.stats.group_scans, 2u);
|
||||
EXPECT_EQ(batch.stats.group_scans, 1u);
|
||||
EXPECT_EQ(batch.stats.parent_candidates, 2u);
|
||||
EXPECT_EQ(batch.stats.allocated, 3u);
|
||||
EXPECT_EQ(batch.stats.unallocated, 0u);
|
||||
@@ -12420,11 +12566,8 @@ TEST_F(WriteBackTransactionTest, ASegmentPublishesOnlyAtItsLastAck) {
|
||||
}
|
||||
}
|
||||
|
||||
// The Host holds every block of X already: the eviction copies nothing and
|
||||
// issues no op, and the segment settles at once, each entry with the newer of
|
||||
// its Host and Device epochs -- the Device's for the pages, which a hit
|
||||
// touched after their Host copies were made, the Host's for the tail and its
|
||||
// checkpoints, copied after that hit.
|
||||
// Existing Host copies settle without transfers. The hit already refreshed
|
||||
// the pages, while later Host publications retain their newer epochs.
|
||||
TEST_F(WriteBackTransactionTest, ASegmentAlreadyOnTheHostSettlesWithoutAnOp) {
|
||||
const std::vector<std::int32_t> tokens = MakeTokens(18);
|
||||
std::vector<BlockTable> tables(4);
|
||||
@@ -12443,13 +12586,15 @@ TEST_F(WriteBackTransactionTest, ASegmentAlreadyOnTheHostSettlesWithoutAnOp) {
|
||||
const PrefixCacheIndex& index = coordinator_.GroupPrefixIndex(static_cast<std::int32_t>(key.group_id));
|
||||
return index.MetadataFor(pool, index.Find(pool, key)->Location())->last_access_epoch;
|
||||
};
|
||||
// The epochs each entry is published with: the Device's for a page, the
|
||||
// Host's own for the rest.
|
||||
std::vector<std::uint64_t> expected;
|
||||
for (std::size_t member = 0; member < keys.size(); ++member) {
|
||||
const std::uint64_t device = epoch_on(pool_, keys[member]);
|
||||
const std::uint64_t host = epoch_on(host_pool_, keys[member]);
|
||||
ASSERT_EQ(device > host, member < 4) << "member " << member;
|
||||
if (member < 4) {
|
||||
ASSERT_EQ(device, host) << "member " << member;
|
||||
} else {
|
||||
ASSERT_GE(host, device) << "member " << member;
|
||||
}
|
||||
expected.push_back(std::max(device, host));
|
||||
}
|
||||
|
||||
@@ -13704,18 +13849,9 @@ TEST(RetractionImageSplitTest, ARefusedImageLeavesTheHostAsItWas) {
|
||||
coordinator.Free(tables);
|
||||
}
|
||||
|
||||
// A Full group of four blocks per parent and a State group. The Host's two
|
||||
// parents both hold Full entries: X four unpinned ones, the oldest, and Y one
|
||||
// pinned and three unpinned. The image needs a Full block and a State block
|
||||
// at its one page. Freeing every unpinned entry would make room for both --
|
||||
// the Full block in Y, X emptied for the State block -- but the allocator
|
||||
// takes the oldest Full entry, in X, for the Full block, which keeps X, and
|
||||
// Y never empties: the State block has no parent. The Host takes no
|
||||
// boundary, and keeps every entry: with a snapshot pool for the State
|
||||
// group's working slot alone, the split refuses the image on the Host's
|
||||
// account; with one that holds both rows as well, the retraction takes the
|
||||
// image and evicts nothing for the boundary the Host does not take.
|
||||
TEST(RetractionImageSplitTest, AnImageFitsOnlyWhereTheAllocatorWouldPlaceIt) {
|
||||
// Plan the Full row in the pinned parent's freeable slot, leaving the other
|
||||
// parent available for State; choosing a placement before planning would block it.
|
||||
TEST(RetractionImageSplitTest, JointPlanningPlacesTheImageBesidePinnedHistory) {
|
||||
const std::vector<CacheGroupSpec> specs{
|
||||
CacheGroupSpec{.attn_kind = AttnKind::kFull, .cache_blocks_per_lcm_block = 4, .block_granularity = 2},
|
||||
CacheGroupSpec{.attn_kind = AttnKind::kState, .cache_blocks_per_lcm_block = 1, .block_granularity = 0},
|
||||
@@ -13756,21 +13892,19 @@ TEST(RetractionImageSplitTest, AnImageFitsOnlyWhereTheAllocatorWouldPlaceIt) {
|
||||
ASSERT_EQ(split.boundaries.size(), 1u);
|
||||
EXPECT_EQ(split.group_ids, (std::vector<std::uint32_t>{0, 1}))
|
||||
<< "one boundary: the Full row, then the State row";
|
||||
EXPECT_EQ(split.num_host_boundaries, 0u);
|
||||
if (snapshot_parents == 1) {
|
||||
EXPECT_EQ(split.shortfall, ImageShortfall::kHostL2);
|
||||
} else {
|
||||
ASSERT_FALSE(split.shortfall.has_value());
|
||||
std::optional<TierTransferManager::RetractionStores> stores = transfers.StartRetractionStores(
|
||||
"image", /*request_pool_index=*/1, std::make_shared<SnapshotSlotIndex>(blob_slots.Allocate()), tables,
|
||||
/*num_tokens=*/2, std::move(split));
|
||||
ASSERT_TRUE(stores.has_value());
|
||||
EXPECT_EQ(transfers.WriteBackStatsFor(HostStoreCause::kRetraction).snapshot_fallback, 2u);
|
||||
ASSERT_EQ(split.num_host_boundaries, 1u);
|
||||
ASSERT_FALSE(split.shortfall.has_value());
|
||||
const auto stores = transfers.StartRetractionStores(
|
||||
"image", /*request_pool_index=*/1, std::make_shared<SnapshotSlotIndex>(blob_slots.Allocate()), tables,
|
||||
/*num_tokens=*/2, std::move(split));
|
||||
ASSERT_TRUE(stores.has_value());
|
||||
ASSERT_TRUE(stores->host_store.has_value());
|
||||
EXPECT_EQ(stores->host_store->transfers.size(), 2u);
|
||||
EXPECT_EQ(transfers.WriteBackStatsFor(HostStoreCause::kRetraction).snapshot_fallback, 0u);
|
||||
for (std::size_t i = 0; i < cached.size(); ++i) {
|
||||
EXPECT_EQ(coordinator.ContainsHostCachedBlock(Key(cached[i], 0)), i == 4 || i >= 6) << i;
|
||||
}
|
||||
for (const std::string& hash : cached) {
|
||||
EXPECT_TRUE(coordinator.ContainsHostCachedBlock(Key(hash, 0))) << hash;
|
||||
}
|
||||
EXPECT_EQ(coordinator.HostEvictions().lru.blocks, 0u);
|
||||
EXPECT_EQ(coordinator.HostEvictions().lru.blocks, 5u);
|
||||
coordinator.Free(tables);
|
||||
}
|
||||
}
|
||||
@@ -13828,15 +13962,9 @@ TEST(RetractionImageSplitTest, ACheckpointVictimFreesItsStateSiblingInThePlan) {
|
||||
coordinator.Free(tables);
|
||||
}
|
||||
|
||||
// A Full group of two blocks per parent and a State group. The Host's
|
||||
// parents hold, oldest first, a Full entry c, a State checkpoint w, a second
|
||||
// Full entry beside c and a State checkpoint q. The image's two pages need a
|
||||
// Full block each and a State block at the second. The first Full block
|
||||
// takes c's place, which keeps c's parent from going whole, as in
|
||||
// AcquireHostBlocks; the second Full block takes w's parent, whose other
|
||||
// slot could hold the first Full block as well, and still the State block
|
||||
// takes q, not c's parent: the second Full entry stays.
|
||||
TEST(RetractionImageSplitTest, ARowsChildVictimKeepsItsParentFromGoingWhole) {
|
||||
// Reconsidering tentative placements lets the older Full parent leave for State
|
||||
// while both image pages share the other freed parent. The newer checkpoint stays.
|
||||
TEST(RetractionImageSplitTest, JointPlacementPreservesTheNewerCheckpoint) {
|
||||
const std::vector<CacheGroupSpec> specs{
|
||||
CacheGroupSpec{.attn_kind = AttnKind::kFull, .cache_blocks_per_lcm_block = 2, .block_granularity = 2},
|
||||
CacheGroupSpec{.attn_kind = AttnKind::kState, .cache_blocks_per_lcm_block = 1, .block_granularity = 0},
|
||||
@@ -13878,8 +14006,8 @@ TEST(RetractionImageSplitTest, ARowsChildVictimKeepsItsParentFromGoingWhole) {
|
||||
ASSERT_TRUE(stores.has_value());
|
||||
EXPECT_FALSE(coordinator.ContainsHostCachedBlock(host_keys[0]));
|
||||
EXPECT_FALSE(coordinator.ContainsHostCachedBlock(host_keys[1]));
|
||||
EXPECT_TRUE(coordinator.ContainsHostCachedBlock(host_keys[2])) << "the second Full entry is no victim";
|
||||
EXPECT_FALSE(coordinator.ContainsHostCachedBlock(host_keys[3]));
|
||||
EXPECT_FALSE(coordinator.ContainsHostCachedBlock(host_keys[2]));
|
||||
EXPECT_TRUE(coordinator.ContainsHostCachedBlock(host_keys[3]));
|
||||
coordinator.Free(tables);
|
||||
}
|
||||
|
||||
@@ -14854,22 +14982,9 @@ TEST(ImageSegmentsThenBlocksTest, TheFallbackPlansOnTheHostTheSegmentsLeave) {
|
||||
coordinator.Free(tables);
|
||||
}
|
||||
|
||||
// Where the two steps place fewer boundaries than the per-block plan alone,
|
||||
// the per-block plan stands: the image comes before the cache, and the
|
||||
// write-back policy places it as write-through does. A Full group of two
|
||||
// blocks per parent and two State groups. The Host's five parents hold other
|
||||
// prompts' entries, oldest first: Full entries z and x in one parent; x's
|
||||
// checkpoint in the second State group, pinned; a Full entry y beside a free
|
||||
// slot; a checkpoint w in the first State group; y's checkpoint in that
|
||||
// group. The image's four pages need a Full block each, its last page a
|
||||
// block of each State group too, and the snapshot pool holds the State
|
||||
// groups' working slots alone. Block by block the Host takes all four
|
||||
// boundaries, evicting z, x and y for Full blocks and w and y's checkpoint
|
||||
// for the State blocks. By segments w alone, a dead entry, makes room for the
|
||||
// first three pages; the fallback then finds no parent for the last page's
|
||||
// second State block -- z's parent keeps the Full block that takes z's place,
|
||||
// y's the free slot the rows need -- and the image would be refused.
|
||||
TEST(ImageSegmentsThenBlocksTest, TheBlockByBlockPlanStandsWhereTheStepsPlaceFewer) {
|
||||
// Both Host policies fit the complete image while protecting the pinned checkpoint.
|
||||
// The segment policy can reclaim its dead checkpoint before the shared block plan.
|
||||
TEST(ImageSegmentsThenBlocksTest, BothPoliciesPlaceTheWholeImageWithAPinnedCheckpoint) {
|
||||
const std::vector<CacheGroupSpec> specs{
|
||||
CacheGroupSpec{.attn_kind = AttnKind::kFull, .cache_blocks_per_lcm_block = 2, .block_granularity = 2},
|
||||
CacheGroupSpec{.attn_kind = AttnKind::kState, .cache_blocks_per_lcm_block = 1, .block_granularity = 0},
|
||||
@@ -14927,25 +15042,15 @@ TEST(ImageSegmentsThenBlocksTest, TheBlockByBlockPlanStandsWhereTheStepsPlaceFew
|
||||
EXPECT_FALSE(coordinator.ContainsHostCachedBlock(key)) << key.content_hash << " " << key.group_id;
|
||||
}
|
||||
EXPECT_TRUE(coordinator.ContainsHostCachedBlock(x_checkpoint));
|
||||
EXPECT_EQ(coordinator.HostEvictions().lru.blocks, 5u);
|
||||
EXPECT_EQ(coordinator.HostEvictions().lru.blocks, write_back_evictions ? 4u : 5u);
|
||||
EXPECT_EQ(coordinator.HostEvictions().dead_entry.blocks, write_back_evictions ? 1u : 0u);
|
||||
coordinator.Free(tables);
|
||||
}
|
||||
}
|
||||
|
||||
// The segment step can place more boundaries than the per-block plan alone.
|
||||
// A Full group of two blocks per parent and two State groups, under each Host
|
||||
// write policy. The Host's three parents hold other prompts' entries,
|
||||
// oldest first: a Full entry x, pinned; a checkpoint v in the first State
|
||||
// group; w's checkpoint in that group; w's Full entry, beside x. The image's
|
||||
// one page needs a Full block and a block of each State group, and the
|
||||
// snapshot pool holds the State groups' working slots alone. Block by block
|
||||
// the Full row takes v's parent whole, older than w's Full entry, the first
|
||||
// State row w's checkpoint, and the second State row finds no parent left:
|
||||
// the image would be refused. By segments v and w, dead checkpoint boundaries
|
||||
// (neither has the second State group's checkpoint), go whole, w's Full entry
|
||||
// with its checkpoint, and the three rows fit: the Full row in w's slot, each
|
||||
// State row in a parent.
|
||||
TEST(ImageSegmentsThenBlocksTest, TheSegmentStepPlacesABoundaryTheBlockByBlockPlanCannot) {
|
||||
// The pinned Full entry stays; both policies place Full beside it and reserve
|
||||
// the two empty parents for the State rows.
|
||||
TEST(ImageSegmentsThenBlocksTest, BothPoliciesPlaceABoundaryWithPinnedHistory) {
|
||||
const std::vector<CacheGroupSpec> specs{
|
||||
CacheGroupSpec{.attn_kind = AttnKind::kFull, .cache_blocks_per_lcm_block = 2, .block_granularity = 2},
|
||||
CacheGroupSpec{.attn_kind = AttnKind::kState, .cache_blocks_per_lcm_block = 1, .block_granularity = 0},
|
||||
@@ -14986,12 +15091,6 @@ TEST(ImageSegmentsThenBlocksTest, TheSegmentStepPlacesABoundaryTheBlockByBlockPl
|
||||
|
||||
TierTransferManager::RetractionImageSplit split =
|
||||
transfers.SplitRetractionImage(tables, /*num_tokens=*/2, coordinator.PublishedDataSlots(tables, 2));
|
||||
if (!write_back_evictions) {
|
||||
EXPECT_EQ(split.num_host_boundaries, 0u);
|
||||
EXPECT_EQ(split.shortfall, ImageShortfall::kHostL2);
|
||||
coordinator.Free(tables);
|
||||
continue;
|
||||
}
|
||||
ASSERT_EQ(split.group_ids, (std::vector<std::uint32_t>{0, 1, 2}));
|
||||
ASSERT_EQ(split.num_host_boundaries, 1u);
|
||||
ASSERT_FALSE(split.shortfall.has_value());
|
||||
@@ -15006,23 +15105,15 @@ TEST(ImageSegmentsThenBlocksTest, TheSegmentStepPlacesABoundaryTheBlockByBlockPl
|
||||
EXPECT_FALSE(coordinator.ContainsHostCachedBlock(key)) << key.content_hash << " " << key.group_id;
|
||||
}
|
||||
EXPECT_TRUE(coordinator.ContainsHostCachedBlock(x));
|
||||
EXPECT_EQ(coordinator.HostEvictions().dead_entry.blocks, 3u);
|
||||
EXPECT_EQ(coordinator.HostEvictions().lru.blocks, 0u);
|
||||
EXPECT_EQ(coordinator.HostEvictions().dead_entry.blocks, write_back_evictions ? 3u : 0u);
|
||||
EXPECT_EQ(coordinator.HostEvictions().lru.blocks, write_back_evictions ? 0u : 3u);
|
||||
coordinator.Free(tables);
|
||||
}
|
||||
}
|
||||
|
||||
// The segment step places more boundaries than the per-block plan also where
|
||||
// that plan places some. The previous test's groups and Host, and a fourth
|
||||
// parent holding a pinned Full entry y beside a free slot; the image's first
|
||||
// page needs a Full block, its second a Full block and a block of each State
|
||||
// group. Block by block the first page's row takes the free slot beside y,
|
||||
// and the second page's rows fall short as the previous test's do: the Full
|
||||
// row takes v's parent whole, the first State row w's checkpoint, and the
|
||||
// second State row finds no parent left. By segments v and w go whole as
|
||||
// before, and both pages fit: the Full rows beside y and in w's slot, each
|
||||
// State row in a parent.
|
||||
TEST(ImageSegmentsThenBlocksTest, TheSegmentStepPlacesMoreBoundariesThanTheBlockByBlockPlanDoes) {
|
||||
// An earlier image page uses an existing hole; the remaining page and its
|
||||
// State rows still fit without evicting either pinned Full entry.
|
||||
TEST(ImageSegmentsThenBlocksTest, BothPoliciesPlaceMultipleBoundariesWithPinnedHistory) {
|
||||
const std::vector<CacheGroupSpec> specs{
|
||||
CacheGroupSpec{.attn_kind = AttnKind::kFull, .cache_blocks_per_lcm_block = 2, .block_granularity = 2},
|
||||
CacheGroupSpec{.attn_kind = AttnKind::kState, .cache_blocks_per_lcm_block = 1, .block_granularity = 0},
|
||||
@@ -15065,12 +15156,6 @@ TEST(ImageSegmentsThenBlocksTest, TheSegmentStepPlacesMoreBoundariesThanTheBlock
|
||||
|
||||
TierTransferManager::RetractionImageSplit split =
|
||||
transfers.SplitRetractionImage(tables, /*num_tokens=*/4, coordinator.PublishedDataSlots(tables, 4));
|
||||
if (!write_back_evictions) {
|
||||
EXPECT_EQ(split.num_host_boundaries, 1u);
|
||||
EXPECT_EQ(split.shortfall, ImageShortfall::kHostL2);
|
||||
coordinator.Free(tables);
|
||||
continue;
|
||||
}
|
||||
ASSERT_EQ(split.group_ids, (std::vector<std::uint32_t>{0, 0, 1, 2}));
|
||||
ASSERT_EQ(split.num_host_boundaries, 2u);
|
||||
ASSERT_FALSE(split.shortfall.has_value());
|
||||
@@ -15086,8 +15171,8 @@ TEST(ImageSegmentsThenBlocksTest, TheSegmentStepPlacesMoreBoundariesThanTheBlock
|
||||
}
|
||||
EXPECT_TRUE(coordinator.ContainsHostCachedBlock(x));
|
||||
EXPECT_TRUE(coordinator.ContainsHostCachedBlock(y));
|
||||
EXPECT_EQ(coordinator.HostEvictions().dead_entry.blocks, 3u);
|
||||
EXPECT_EQ(coordinator.HostEvictions().lru.blocks, 0u);
|
||||
EXPECT_EQ(coordinator.HostEvictions().dead_entry.blocks, write_back_evictions ? 3u : 0u);
|
||||
EXPECT_EQ(coordinator.HostEvictions().lru.blocks, write_back_evictions ? 0u : 3u);
|
||||
coordinator.Free(tables);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2616,6 +2616,7 @@ TEST_F(StateCheckpointPrefillHostSuite, AFailedTransferMarksNothing) {
|
||||
// the Host, or without one starts over.
|
||||
TEST_P(StateCheckpointPrefillHostShardSuite, AnEarlierFinishLeavesALaterHittersInputUnmarked) {
|
||||
device_pages_ = 15;
|
||||
host_pages_ = 32; // Keep Host LRU pressure out of this Device input-lifetime test.
|
||||
for (const auto& [policy, host_cache] : {std::pair{SchedulerConfig::HostWritePolicy::kWriteBack, true},
|
||||
std::pair{SchedulerConfig::HostWritePolicy::kWriteThrough, true},
|
||||
std::pair{SchedulerConfig::HostWritePolicy::kWriteThrough, false}}) {
|
||||
@@ -2673,6 +2674,7 @@ TEST_P(StateCheckpointPrefillHostShardSuite, AnEarlierFinishLeavesALaterHittersI
|
||||
AckWriteBacks(plan);
|
||||
SendAbortEvent("f1");
|
||||
AckWriteBacks(PlanOnce());
|
||||
EXPECT_EQ(scheduler_->GetHostCacheStats().host_evictions.lru.blocks, 0u);
|
||||
const Resume again = Probe("g-again", g);
|
||||
const bool from_host = g_finishes && !write_back && host_cache;
|
||||
EXPECT_EQ(again.prefix_tokens, g_finishes && !from_host ? 0 : 22);
|
||||
|
||||
Reference in New Issue
Block a user