Repository navigation
Expand file tree
/
Copy pathresource_manager.h
More file actions
1519 lines (1426 loc) · 72.4 KB
/
Copy pathresource_manager.h
File metadata and controls
1519 lines (1426 loc) · 72.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#pragma once
#include "core/host_placement.h"
#include "runtime/contract/resources.h"
#include "runtime/engine/context_cache/context_cost.h"
#include "runtime/engine/context_cache/prefix_index.h"
#include "runtime/engine/context_cache/types.h"
#include <algorithm>
#include <array>
#include <cstdint>
#include <optional>
#include <span>
#include <stdexcept>
#include <utility>
#include <vector>
namespace ninfer::runtime {
// Policy owns bounded logical continuations. Native owns checkpoint contents and every byte.
template <class Model>
class ResourceManager {
public:
using Program = typename Model::Program;
using Base = typename Model::RequestBasePlan;
using Handle = typename Model::CheckpointHandle;
using Source = typename Model::SourceCandidate;
using SessionKey = typename Model::CacheSessionKey;
using OwnerToken = ContinuationOwnerToken;
using DemandKey =
typename decltype(std::declval<const Base&>().prefix_shortlist_key(0))::value_type;
// Optional writes carry only their own demand evidence. Necessary execution has no
// admission restriction. The request owns base for the lifetime of the reclaim decision.
struct Admission {
CacheRetentionPriority priority;
CacheRetentionPriority demand;
const Base* base = nullptr;
std::uint32_t frontier = 0;
std::optional<Handle> checkpoint;
std::vector<Handle> sources;
};
struct ReclaimCursor {
struct Victim {
Handle handle;
CacheRetentionPriority priority;
CacheRetentionPriority demand;
};
struct OwnerProtection {
OwnerToken owner;
CacheRetentionPriority priority;
std::uint32_t proven_frontier;
std::vector<Handle> points;
};
// Fixed membership, order and writeback rights for one decision. Native residency
// supplies progress; a history may still have other pages needed by a later shortage.
std::vector<Victim> victims;
std::vector<OwnerProtection> owners;
std::optional<Admission> admission;
std::optional<std::uint64_t> gain_limit;
std::uint64_t sacrificed = 0;
ReclaimRights rights;
};
// What a Host write needs before it can reserve: placement of every run once the chosen
// victims are deleted, or, for an Engine shortage, that many bytes freed. A run needs the
// arena's placement answer; the free byte total never decides it.
struct HostNeed {
std::span<const HostAllocationRun> runs;
std::size_t shortage = 0;
};
struct SourceChoice {
Source source;
OwnerToken owner = 0;
std::uint64_t shared_entry = 0;
bool take_over = false;
std::optional<OwnerToken> resume_owner;
bool session_hint = false;
std::uint64_t publication_order = 0;
std::uint64_t ordinal = 0;
};
explicit ResourceManager(bool enabled, ContextMachineCostModel costs)
: enabled_(enabled), costs_(std::move(costs)) {}
[[nodiscard]] std::vector<SourceChoice>
candidates(Program& program, const Base& base, std::uint32_t maximum_frontier = UINT32_MAX,
std::optional<OwnerToken> own_resume = std::nullopt, std::uint64_t request = 0,
std::uint64_t publication_order = UINT64_MAX) {
prune(program);
std::vector<SourceChoice> result;
if (enabled_) {
for (const auto handle : index_.matches(program, base)) {
if (program.checkpoint_metadata(handle).frontier > maximum_frontier) { continue; }
for (const auto& owner : owners_) {
const auto point =
std::find_if(owner.points.begin(), owner.points.end(),
[&](const auto& p) { return p.handle == handle; });
if (point == owner.points.end()) { continue; }
const auto& advice = base.context_cache();
const bool take =
own_resume
? *own_resume == owner.token
: !owner.active && owner.publication_order <= publication_order &&
(!owner.session || (advice.update_session_index &&
advice.session_key == owner.session));
result.push_back(
{.source = Source{.checkpoint = handle},
.owner = owner.token,
.take_over = take,
.resume_owner = own_resume,
.session_hint = owner.session && owner.session == advice.session_key,
.publication_order = owner.publication_order,
.ordinal = owner.token});
}
for (const auto& shared : shared_) {
if (shared.handle != handle) { continue; }
result.push_back({.source = Source{.checkpoint = handle},
.shared_entry = shared.ordinal,
.resume_owner = own_resume,
.ordinal = shared.ordinal});
}
}
}
result.push_back({.source = Source{}, .resume_owner = own_resume});
if (const auto* waiting = find_waiting(request);
waiting && waiting->choice.source.checkpoint &&
contains(waiting->held, *waiting->choice.source.checkpoint)) {
result.push_back(waiting->choice);
}
std::erase_if(
result, [&](auto& choice) { return !prepare_source(program, base, choice, request); });
const auto cost = [&](const Source& source) {
const auto transfer = price_context_transfer_requirements(costs_, source.transfers);
const auto prefill = costs_.prefill_ns(source.remaining_work);
return transfer > UINT64_MAX - prefill ? UINT64_MAX : transfer + prefill;
};
const auto bytes = [](const Source& source) {
std::uint64_t total = 0;
for (const auto& transfer : source.transfers) {
total = transfer.work.payload_bytes > UINT64_MAX - total
? UINT64_MAX
: total + transfer.work.payload_bytes;
}
return total;
};
std::stable_sort(result.begin(), result.end(), [&](const auto& a, const auto& b) {
const auto left = cost(a.source), right = cost(b.source);
if (left != right) { return left < right; }
if (bytes(a.source) != bytes(b.source)) { return bytes(a.source) < bytes(b.source); }
if (a.source.reused_tokens != b.source.reused_tokens) {
return a.source.reused_tokens > b.source.reused_tokens;
}
if (a.session_hint != b.session_hint) { return a.session_hint; }
if (bool(a.owner) != bool(b.owner)) { return bool(a.owner); }
if (a.publication_order != b.publication_order) {
return a.publication_order > b.publication_order;
}
return a.ordinal < b.ordinal;
});
// Equal handles are the same Native contents. Independently computed states with equal
// semantic keys remain separate candidates; Native must not splice their KV and state.
std::vector<SourceChoice> unique;
for (auto& choice : result) {
const auto duplicate =
std::any_of(unique.begin(), unique.end(), [&](const auto& prior) {
return prior.source.checkpoint == choice.source.checkpoint &&
prior.source.consume_source == choice.source.consume_source &&
prior.source.private_points == choice.source.private_points;
});
if (!duplicate) { unique.push_back(std::move(choice)); }
}
return unique;
}
// Evaluation grants consumption rights but does not retire anything. Native checks the
// complete binding before applying these grants in its ownership handoff.
[[nodiscard]] bool prepare_source(Program& program, const Base& base, SourceChoice& choice,
std::uint64_t request = 0,
std::optional<ReclaimRights> revocation = std::nullopt) {
const auto selected = choice.source.checkpoint;
if (selected && !program.valid_checkpoint(*selected)) { return false; }
auto* owner = find_owner(choice.owner);
if (choice.take_over && (!owner || owner->publication_order != choice.publication_order ||
(owner->active && choice.resume_owner != choice.owner))) {
choice.take_over = false;
}
std::vector<Handle> retired;
if (choice.take_over && selected && owner) {
const auto frontier = program.checkpoint_metadata(*selected).frontier;
for (const auto& point : owner->points) {
if (point.handle == *selected || !program.valid_checkpoint(point.handle)) {
continue;
}
const auto summary = program.checkpoint_metadata(point.handle);
if (summary.frontier > frontier && !summary.leased &&
consumable(point.handle, owner->token, request, revocation)) {
retired.push_back(point.handle);
}
}
}
auto carried = points(choice.resume_owner.value_or(choice.owner));
if (const auto* waiting = find_waiting(request);
waiting && waiting->choice.source.checkpoint == selected) {
carried = waiting->choice.source.private_points;
std::erase_if(carried, [&](auto point) { return !contains(waiting->held, point); });
}
const auto private_owner =
choice.resume_owner.value_or(choice.take_over ? choice.owner : 0);
const bool consume = selected && consumable(*selected, private_owner, request, revocation);
auto inspected = program.inspect_source(base, selected, consume, carried, retired);
if (!inspected) { return false; }
inspected->take_private =
std::all_of(inspected->private_points.begin(), inspected->private_points.end(),
[&](auto point) { return consumable(point, private_owner, request); });
choice.source = std::move(*inspected);
return true;
}
void retain_source(Program& program, std::uint64_t request, const SourceChoice& choice) {
std::vector<Handle> held;
if (choice.source.checkpoint) { held.push_back(*choice.source.checkpoint); }
for (const auto point : choice.source.private_points) {
if (!contains(held, point)) { held.push_back(point); }
}
auto* waiting = find_waiting(request);
if (!waiting) {
if (held.empty()) { return; }
waiting_.push_back({.request = request, .choice = choice, .held = std::move(held)});
return;
}
auto old = std::move(waiting->held);
waiting->choice = choice;
waiting->held = std::move(held);
for (const auto point : old) { release_unreferenced(program, point); }
}
[[nodiscard]] std::optional<SourceChoice> retained_source(std::uint64_t request) const {
const auto* waiting = find_waiting(request);
if (!waiting || !waiting->choice.source.checkpoint ||
!contains(waiting->held, *waiting->choice.source.checkpoint)) {
return std::nullopt;
}
return waiting->choice;
}
[[nodiscard]] bool has_source_record(std::uint64_t request) const {
return find_waiting(request) != nullptr;
}
[[nodiscard]] bool can_transfer_private(OwnerToken owner, std::uint64_t request) const {
const auto carried = points(owner);
return std::all_of(carried.begin(), carried.end(),
[&](auto point) { return consumable(point, owner, request); });
}
[[nodiscard]] std::uint32_t source_revocations(std::uint64_t request) const {
const auto* waiting = find_waiting(request);
return waiting ? waiting->revocations : 0;
}
void binding_started(std::uint64_t request, std::span<const Handle> retired,
std::optional<Handle> consumed) {
if (auto* waiting = find_waiting(request)) { waiting->binding = true; }
for (const auto handle : retired) { forget(handle); }
if (consumed) {
for (auto& waiting : waiting_) {
if (waiting.request != request && std::erase(waiting.held, *consumed)) {
++waiting.revocations;
}
}
}
}
void release_source(Program& program, std::uint64_t request) {
const auto found = std::find_if(waiting_.begin(), waiting_.end(), [=](const auto& entry) {
return entry.request == request;
});
if (found == waiting_.end()) { return; }
auto held = std::move(found->held);
waiting_.erase(found);
for (const auto handle : held) { release_unreferenced(program, handle); }
}
// Called exactly once after Native's irreversible bind commit. The choice preserves logical
// ownership even when Native consumed its original checkpoint handle during that commit.
[[nodiscard]] OwnerToken adopt(Program& program, const SourceChoice& choice, const Base& base,
std::uint64_t publication_order,
std::span<const Handle> carried = {},
std::span<const Handle> retired = {}) {
for (const auto handle : retired) { forget(handle); }
if (!enabled_ || !base.summary().publish_continuation) {
for (const auto handle : carried) { release_unreferenced(program, handle); }
return 0;
}
OwnerToken token = 0;
CacheRetentionPriority priority;
std::uint32_t proven_frontier = 0;
if (choice.resume_owner) {
token = *choice.resume_owner;
if (!find_owner(token)) { throw std::logic_error("resume lost continuation owner"); }
} else {
if (choice.source.reused_tokens) {
const auto used_at = ++clock_;
if (const auto key = base.prefix_shortlist_key(choice.source.reused_tokens)) {
remember_demand(*key, 0,
CacheRetentionPriority{.reused = true, .last_demand = used_at});
}
if (auto* owner = find_owner(choice.owner)) {
priority = {.reused = true, .last_demand = used_at};
proven_frontier = choice.source.reused_tokens;
// Consuming a branch replaces its proof. A shallower independent
// Fork has its own new evidence and leaves its donor's pair intact.
if (choice.take_over || proven_frontier >= owner->proven_frontier) {
owner->priority = priority;
owner->proven_frontier = proven_frontier;
}
if (choice.take_over) { token = owner->token; }
} else if (auto* shared = find_shared(choice.shared_entry)) {
shared->priority = {.reused = true, .last_demand = used_at};
}
}
if (!token) {
token = ++ordinal_;
owners_.push_back({.token = token,
.priority = priority,
.proven_frontier = proven_frontier,
.retained_at = ++clock_});
}
}
auto* owner = find_owner(token);
owner->active = true;
owner->publication_order = publication_order;
replace_points(program, *owner, carried);
prune(program);
balance_reused(program);
return token;
}
void publish(Program& program, OwnerToken token, Handle handle) {
if (!program.valid_checkpoint(handle)) { return; }
const auto summary = program.checkpoint_metadata(handle);
if (!enabled_ || !token) {
release_unreferenced(program, handle);
return;
}
if (summary.role == CheckpointRole::SharedPrefix) {
if (std::none_of(shared_.begin(), shared_.end(),
[&](const auto& entry) { return entry.handle == handle; })) {
shared_.push_back(
{.handle = handle,
.ordinal = ++ordinal_,
.priority = demand_priority(program.checkpoint_key(handle, summary.frontier)),
.retained_at = ++clock_});
index_.insert(program, handle, summary.frontier);
}
} else {
auto* owner = find_owner(token);
if (!owner) {
throw std::logic_error("checkpoint publication lost continuation owner");
}
const auto observed = demand_priority(program.checkpoint_key(handle, summary.frontier));
if (summary.role == CheckpointRole::InputReplay && observed.reused &&
(!owner->priority.reused || observed.last_demand > owner->priority.last_demand)) {
owner->priority = observed;
owner->proven_frontier = summary.frontier;
}
if (std::none_of(owner->points.begin(), owner->points.end(),
[&](const auto& p) { return p.handle == handle; })) {
std::optional<Handle> replace;
std::size_t anchors = 0;
std::optional<Handle> oldest_anchor;
for (const auto& point : owner->points) {
if (point.role != summary.role) { continue; }
if (summary.role != CheckpointRole::LongAnchor) {
replace = point.handle;
break;
}
++anchors;
if (!oldest_anchor) { oldest_anchor = point.handle; }
if (program.checkpoint_metadata(point.handle).frontier == summary.frontier) {
replace = point.handle;
}
}
if (!replace && anchors >= 4) { replace = oldest_anchor; }
if (replace && !remove_point(program, *owner, *replace)) {
// Optional replacement never turns a legitimate request into a failure.
release_unreferenced(program, handle);
return;
}
owner->points.push_back({handle, summary.role});
index_.insert(program, handle, summary.frontier);
}
}
balance_reused(program);
}
void finish(Program& program, OwnerToken token, const Base& base,
std::uint64_t publication_order) {
auto* owner = find_owner(token);
if (!owner) { return; }
owner->active = false;
owner->publication_order = publication_order;
const auto& advice = base.context_cache();
if (advice.update_session_index && advice.session_key) {
const auto newer = std::any_of(owners_.begin(), owners_.end(), [&](const auto& other) {
return other.token != token && other.session == advice.session_key &&
other.publication_order > publication_order;
});
if (!newer) {
for (auto& other : owners_) {
if (other.session == advice.session_key) { other.session.reset(); }
}
owner->session = advice.session_key;
}
}
prune(program);
balance_reused(program);
}
void abandon(Program& program, OwnerToken token) {
auto* owner = find_owner(token);
if (!owner) { return; }
const auto old = points(token);
std::erase_if(owners_, [&](const auto& entry) { return entry.token == token; });
for (const auto handle : old) { release_unreferenced(program, handle); }
}
[[nodiscard]] std::vector<Handle> points(OwnerToken token) const {
std::vector<Handle> out;
if (const auto* owner = find_owner(token)) {
for (const auto& point : owner->points) { out.push_back(point.handle); }
}
return out;
}
[[nodiscard]] CacheRetentionPriority retention(OwnerToken token) const {
const auto* owner = find_owner(token);
return owner ? owner->priority : CacheRetentionPriority{};
}
bool recycle_input(Program& program, OwnerToken token) {
auto* owner = find_owner(token);
if (!owner) { return false; }
const auto point =
std::find_if(owner->points.begin(), owner->points.end(),
[](const auto& p) { return p.role == CheckpointRole::InputReplay; });
if (point == owner->points.end()) { return false; }
const auto handle = point->handle;
if (program.valid_checkpoint(handle) && program.checkpoint_metadata(handle).leased) {
return false;
}
return remove_point(program, *owner, handle);
}
// The caller supplies each request's strictly advancing, non-overlapping committed
// prefill ranges. Replay and preparation never call this; one candidate is crossed at
// most once by a request, including when other requests commit between its chunks.
void observe_committed(const Base& base, std::uint64_t request_id, std::uint32_t begin,
std::uint32_t end) {
if (!enabled_ || begin >= end) { return; }
for (const auto frontier : base.capture_frontiers()) {
if (frontier <= begin || frontier > end) { continue; }
const auto key = base.prefix_shortlist_key(frontier);
if (!key) { continue; }
remember_demand(*key, request_id);
}
}
[[nodiscard]] Admission capture_admission(Program&, OwnerToken owner, const Base& base,
std::uint32_t frontier,
bool inherit_private = true) const {
const auto demand = demand_priority(base.prefix_shortlist_key(frontier));
// A recurrent continuation's heat can rank its owner, but a new optional point
// has not itself demonstrated repeat demand. Its added coverage remains bounded.
auto priority = demand;
if (!demand.reused && inherit_private) { priority = retention(owner); }
return {.priority = priority, .demand = demand, .base = &base, .frontier = frontier};
}
[[nodiscard]] ReclaimCursor begin_reclaim(Program& program,
std::optional<Admission> admission = std::nullopt,
ReclaimRights rights = {}) {
prune(program);
balance_reused(program);
auto cursor = reclaim_order(program);
cursor.admission = admission;
cursor.rights = admission ? ReclaimRights{ReclaimPurpose::OptionalWrite} : rights;
if (admission && !admission->demand.reused) {
cursor.gain_limit = recovery_gain(program, *admission, surviving(program, {}));
}
return cursor;
}
// The victims whose deletion lets every run be placed, in reclaim order; an empty set when
// the runs already fit, nullopt when no admissible set makes them fit.
[[nodiscard]] std::optional<std::vector<Handle>>
host_victims(Program& program, std::span<const HostAllocationRun> runs,
std::optional<Handle> incoming, std::span<const Handle> later_snapshots = {},
std::span<const Handle> excluded = {},
std::optional<Admission> admission = std::nullopt,
const ReclaimCursor* decision = nullptr, ReclaimRights rights = {}) {
prune(program);
Evaluation evaluation;
const HostNeed need{.runs = runs};
if (decision) {
return host_victims_in_order(program, need, incoming, later_snapshots, excluded,
decision->admission, *decision, evaluation);
}
auto cursor = reclaim_order(program);
cursor.rights = admission ? ReclaimRights{ReclaimPurpose::OptionalWrite} : rights;
return host_victims_in_order(program, need, incoming, later_snapshots, excluded, admission,
cursor, evaluation);
}
void commit_host_victims(Program& program, std::span<const Handle> handles,
ReclaimCursor& cursor) {
commit_release(program, handles, cursor);
}
bool erase(Program& program, Handle handle, ReclaimRights rights = {}) {
if (!references(handle)) { return false; }
if (!may_revoke({&handle, 1}, rights)) { return false; }
if (program.valid_checkpoint(handle) && !program.release_checkpoint(handle)) {
return false;
}
forget(handle);
prune(program);
return true;
}
[[nodiscard]] ReclaimProgress reclaim(Program& program, ContextResourceUsage shortage,
std::span<const Handle> excluded = {}) {
if (program.has_context_transaction()) { return ReclaimProgress::Transferring; }
auto cursor = begin_reclaim(program);
return reclaim(program, shortage, excluded, cursor);
}
[[nodiscard]] ReclaimProgress reclaim(Program& program, ContextResourceUsage shortage,
std::span<const Handle> excluded, ReclaimCursor& cursor) {
if (program.has_context_transaction()) { return ReclaimProgress::Transferring; }
prune(program);
if (shortage.host_bytes && program.release_redundant_host(excluded)) {
return ReclaimProgress::Changed;
}
std::vector<Handle> allowed;
for (const auto& victim : cursor.victims) {
if (references(victim.handle) && program.valid_checkpoint(victim.handle) &&
!contains(excluded, victim.handle)) {
allowed.push_back(victim.handle);
}
}
if (shortage.host_bytes) {
Evaluation evaluation;
const auto victims =
host_victims_in_order(program, {.shortage = shortage.host_bytes}, std::nullopt, {},
excluded, cursor.admission, cursor, evaluation);
if (!victims) { return ReclaimProgress::Blocked; }
commit_release(program, *victims, cursor);
return victims->empty() ? ReclaimProgress::Blocked : ReclaimProgress::Changed;
}
auto plans = program.plan_reclaim(allowed, excluded, shortage);
Evaluation evaluation{.native = &plans};
using Demotion = typename decltype(plans.demotions)::value_type;
using Release = typename decltype(plans.releases)::value_type;
struct Action {
std::optional<Demotion> demotion;
std::optional<Release> release;
std::vector<Handle> host_victims;
std::optional<Admission> preservation;
ActionRank rank;
};
const bool needs_host_cleanup =
std::any_of(plans.demotions.begin(), plans.demotions.end(), [&](const auto& plan) {
return plan.host_run.count != 0 &&
!program.host_can_place(std::span(&plan.host_run, 1), {});
});
const bool existing_host_destination =
std::any_of(plans.demotions.begin(), plans.demotions.end(),
[](const auto& plan) { return plan.host_run.count == 0; });
// Redundant-replica cleanup is a distinct capacity change. Quotes below are read
// only and never observe side effects from evaluating another candidate.
if (needs_host_cleanup && !existing_host_destination &&
program.release_redundant_host(excluded)) {
return ReclaimProgress::Changed;
}
std::vector<Action> actions;
actions.reserve(plans.demotions.size() + plans.releases.size());
for (auto& plan : plans.demotions) {
const auto units = useful(plan.released, shortage);
if (!units) { continue; }
auto facts = action_facts(program, plan.sources, cursor, evaluation);
if (!admits(program, plan.sources, facts, cursor.admission, cursor, evaluation, true)) {
continue;
}
auto protected_sources = std::vector<Handle>(excluded.begin(), excluded.end());
protected_sources.insert(protected_sources.end(), plan.sources.begin(),
plan.sources.end());
auto preservation =
preservation_admission(program, plan.sources, cursor, facts.priority);
auto victims = host_victims_in_order(program, {.runs = std::span(&plan.host_run, 1)},
preservation.checkpoint, {}, protected_sources,
preservation, cursor, evaluation);
if (!victims) { continue; }
auto rank = rank_action(program, plan.sources, facts, units, evaluation, true);
auto host_facts = action_facts(program, *victims, cursor, evaluation);
const auto host_rank = rank_action(program, *victims, host_facts, units, evaluation);
rank.loss = host_rank.loss;
rank.waiting = host_rank.waiting;
rank.order = std::max(rank.order, host_rank.order);
if (host_rank.priority.reused &&
(!rank.priority.reused ||
host_rank.priority.last_demand > rank.priority.last_demand)) {
rank.priority = host_rank.priority;
}
actions.push_back({.demotion = std::move(plan),
.host_victims = std::move(*victims),
.preservation = std::move(preservation),
.rank = rank});
}
for (auto& plan : plans.releases) {
const auto units = useful(plan.released, shortage);
if (!units) { continue; }
auto facts = action_facts(program, plan.sources, cursor, evaluation);
if (!admits(program, plan.sources, facts, cursor.admission, cursor, evaluation)) {
continue;
}
auto rank = rank_action(program, plan.sources, facts, units, evaluation);
actions.push_back({.release = std::move(plan), .rank = rank});
}
std::stable_sort(actions.begin(), actions.end(),
[](const auto& a, const auto& b) { return less_rank(a.rank, b.rank); });
for (std::size_t index = 0; index < actions.size(); ++index) {
const auto& action = actions[index];
if (action.demotion) {
if (!shortage.state_slots && action.host_victims.empty()) {
// Preserve the ranked action order. Independent KV groups can share
// one transfer transaction while every holder keeps its own rights.
auto builder = plans.begin_kv_batch(shortage);
std::size_t components = 0;
std::uint64_t released = 0;
const auto needed =
shortage.main_kv_pages ? shortage.main_kv_pages : shortage.backend_kv_pages;
for (std::size_t next = index; next < actions.size() && released < needed;
++next) {
const auto& candidate = actions[next];
if (!candidate.demotion) {
// These are alternative ways to reclaim physical resources.
// A delete covered by earlier migrations adds no pages to this
// deficit; keep it in actions for failure fallback, not the batch.
if (builder.covers(*candidate.release)) { continue; }
break;
}
if (!candidate.host_victims.empty()) { break; }
if (!builder.append(*candidate.demotion)) { break; }
++components;
released += useful(candidate.demotion->released, shortage);
}
if (components > 1) {
if (const auto batch = builder.finish()) {
auto facts = action_facts(program, batch->sources, cursor, evaluation);
if (admits(program, batch->sources, facts, cursor.admission, cursor,
evaluation, true) &&
program.start_demote(*batch)) {
return program.has_context_transaction()
? ReclaimProgress::Transferring
: ReclaimProgress::Changed;
}
}
// A combined reservation may fail without changing any replica.
// The original first action remains the next legal choice.
}
}
const auto& plan = *action.demotion;
auto protected_sources = std::vector<Handle>(excluded.begin(), excluded.end());
protected_sources.insert(protected_sources.end(), plan.sources.begin(),
plan.sources.end());
const auto current =
host_victims_in_order(program, {.runs = std::span(&plan.host_run, 1)},
action.preservation->checkpoint, {}, protected_sources,
action.preservation, cursor, evaluation);
if (!current || *current != action.host_victims) { continue; }
commit_release(program, action.host_victims, cursor, action.rank.loss);
if (program.start_demote(plan)) {
return program.has_context_transaction() ? ReclaimProgress::Transferring
: ReclaimProgress::Changed;
}
if (!action.host_victims.empty()) { return ReclaimProgress::Changed; }
continue;
}
// Native quoted every holder required for this actual physical release.
commit_release(program, action.release->sources, cursor, action.rank.loss);
return ReclaimProgress::Changed;
}
return ReclaimProgress::Blocked;
}
void release_all(Program& program) noexcept {
const auto handles = victims();
index_.clear();
owners_.clear();
shared_.clear();
waiting_.clear();
demand_.clear();
for (const auto handle : handles) {
if (program.valid_checkpoint(handle)) { (void)program.release_checkpoint(handle); }
}
}
private:
struct WaitingSource {
std::uint64_t request;
SourceChoice choice;
std::vector<Handle> held;
std::uint32_t revocations = 0;
bool binding = false;
};
WaitingSource* find_waiting(std::uint64_t request) {
const auto found = std::find_if(waiting_.begin(), waiting_.end(),
[=](const auto& item) { return item.request == request; });
return found == waiting_.end() ? nullptr : &*found;
}
const WaitingSource* find_waiting(std::uint64_t request) const {
const auto found = std::find_if(waiting_.begin(), waiting_.end(),
[=](const auto& item) { return item.request == request; });
return found == waiting_.end() ? nullptr : &*found;
}
bool consumable(Handle handle, OwnerToken owner, std::uint64_t request,
std::optional<ReclaimRights> revocation = std::nullopt) const {
std::size_t allowed = 0;
if (const auto* entry = find_owner(owner)) {
allowed = std::count_if(entry->points.begin(), entry->points.end(),
[&](const auto& point) { return point.handle == handle; });
}
if (catalog_reference_count(handle) != allowed) { return false; }
for (const auto& waiting : waiting_) {
if (!contains(waiting.held, handle)) { continue; }
if (waiting.binding) { return false; }
if (waiting.request != request &&
(!revocation || revocation->purpose == ReclaimPurpose::OptionalWrite ||
(revocation->purpose == ReclaimPurpose::FreshAdmission &&
waiting.request <= revocation->request))) {
return false;
}
++allowed;
}
return allowed != 0;
}
[[nodiscard]] std::uint64_t waiting_ticket(std::span<const Handle> handles) const {
std::uint64_t oldest = 0;
for (const auto& waiting : waiting_) {
if (std::any_of(handles.begin(), handles.end(),
[&](auto handle) { return contains(waiting.held, handle); })) {
oldest = oldest ? std::min(oldest, waiting.request) : waiting.request;
}
}
return oldest;
}
bool may_revoke(std::span<const Handle> handles, ReclaimRights rights) const {
for (const auto& waiting : waiting_) {
if (!std::any_of(handles.begin(), handles.end(),
[&](auto handle) { return contains(waiting.held, handle); })) {
continue;
}
if (waiting.binding || rights.purpose == ReclaimPurpose::OptionalWrite ||
(rights.purpose == ReclaimPurpose::FreshAdmission &&
waiting.request <= rights.request)) {
return false;
}
}
return true;
}
struct Demand {
DemandKey key;
std::uint64_t request_id;
CacheRetentionPriority priority;
std::uint64_t observed_at;
};
void remember_demand(const DemandKey& key, std::uint64_t request_id,
std::optional<CacheRetentionPriority> adopted = std::nullopt) {
auto found = std::find_if(demand_.begin(), demand_.end(),
[&](const auto& entry) { return entry.key == key; });
if (found != demand_.end()) {
if (!adopted && found->request_id == request_id) { return; }
found->request_id = request_id;
found->priority =
adopted.value_or(CacheRetentionPriority{.reused = true, .last_demand = clock_ + 1});
if (!adopted) { ++clock_; }
found->observed_at = clock_;
return;
}
if (demand_.size() == kDemandCapacity) {
const auto oldest =
std::min_element(demand_.begin(), demand_.end(), [](const auto& a, const auto& b) {
return a.observed_at < b.observed_at;
});
demand_.erase(oldest);
}
demand_.push_back({key, request_id, adopted.value_or(CacheRetentionPriority{}), ++clock_});
}
[[nodiscard]] CacheRetentionPriority demand_priority(std::optional<DemandKey> key) const {
if (!key) { return {}; }
const auto found = std::find_if(demand_.begin(), demand_.end(),
[&](const auto& entry) { return entry.key == *key; });
return found == demand_.end() ? CacheRetentionPriority{} : found->priority;
}
struct Point {
Handle handle;
CheckpointRole role;
};
struct Owner {
OwnerToken token;
CacheRetentionPriority priority;
std::uint32_t proven_frontier = 0;
std::uint64_t retained_at = 0;
std::uint64_t publication_order = 0;
bool active = false;
std::optional<SessionKey> session;
std::vector<Point> points;
};
struct Shared {
Handle handle;
std::uint64_t ordinal;
CacheRetentionPriority priority;
std::uint64_t retained_at;
};
static bool contains(std::span<const Handle> handles, Handle handle) {
return std::find(handles.begin(), handles.end(), handle) != handles.end();
}
Owner* find_owner(OwnerToken token) {
const auto it = std::find_if(owners_.begin(), owners_.end(),
[&](const auto& owner) { return owner.token == token; });
return it == owners_.end() ? nullptr : &*it;
}
const Owner* find_owner(OwnerToken token) const {
const auto it = std::find_if(owners_.begin(), owners_.end(),
[&](const auto& owner) { return owner.token == token; });
return it == owners_.end() ? nullptr : &*it;
}
Shared* find_shared(std::uint64_t ordinal) {
const auto it = std::find_if(shared_.begin(), shared_.end(),
[&](const auto& entry) { return entry.ordinal == ordinal; });
return it == shared_.end() ? nullptr : &*it;
}
std::size_t catalog_reference_count(Handle handle) const {
std::size_t count = 0;
for (const auto& owner : owners_) {
count += std::count_if(owner.points.begin(), owner.points.end(),
[&](const auto& point) { return point.handle == handle; });
}
count += std::count_if(shared_.begin(), shared_.end(),
[&](const auto& entry) { return entry.handle == handle; });
return count;
}
std::size_t reference_count(Handle handle) const {
auto count = catalog_reference_count(handle);
for (const auto& waiting : waiting_) { count += contains(waiting.held, handle); }
return count;
}
bool references(Handle handle) const { return reference_count(handle) != 0; }
bool remove_point(Program& program, Owner& owner, Handle handle) {
if (reference_count(handle) == 1 && program.valid_checkpoint(handle) &&
!program.release_checkpoint(handle)) {
return false;
}
std::erase_if(owner.points, [&](const auto& point) { return point.handle == handle; });
if (!catalog_reference_count(handle)) { index_.erase(handle); }
return true;
}
void forget(Handle handle) {
index_.erase(handle);
for (auto& owner : owners_) {
std::erase_if(owner.points, [&](const auto& point) { return point.handle == handle; });
}
std::erase_if(shared_, [&](const auto& entry) { return entry.handle == handle; });
for (auto& waiting : waiting_) {
if (std::erase(waiting.held, handle) && !waiting.binding) { ++waiting.revocations; }
}
}
void release_unreferenced(Program& program, Handle handle) {
if (!catalog_reference_count(handle)) { index_.erase(handle); }
if (references(handle)) { return; }
if (program.valid_checkpoint(handle) && !program.release_checkpoint(handle)) {
throw std::logic_error("Native could not release an unreferenced checkpoint owner");
}
}
void replace_points(Program& program, Owner& owner, std::span<const Handle> carried) {
std::vector<Handle> old;
for (const auto& point : owner.points) { old.push_back(point.handle); }
owner.points.clear();
for (const auto handle : carried) {
if (!program.valid_checkpoint(handle)) { continue; }
const auto summary = program.checkpoint_metadata(handle);
if (summary.role == CheckpointRole::SharedPrefix) {
throw std::logic_error("Native carried a public point as a private continuation");
}
owner.points.push_back({handle, summary.role});
index_.insert(program, handle, summary.frontier);
}
for (const auto handle : old) { release_unreferenced(program, handle); }
}
void prune(Program& program) {
std::vector<Handle> stale;
const auto inspect = [&](Handle handle) {
if (!program.valid_checkpoint(handle) && !contains(stale, handle)) {
stale.push_back(handle);
}
};
for (const auto& owner : owners_) {
for (const auto& point : owner.points) { inspect(point.handle); }
}
for (const auto& shared : shared_) { inspect(shared.handle); }
for (const auto& waiting : waiting_) {
for (const auto handle : waiting.held) { inspect(handle); }
}
for (const auto handle : stale) { forget(handle); }
std::erase_if(owners_,
[](const auto& owner) { return !owner.active && owner.points.empty(); });
}
CacheRetentionPriority priority_for(Handle handle) const {
CacheRetentionPriority result;
const auto include = [&](CacheRetentionPriority priority) {
if (priority.reused && (!result.reused || priority.last_demand > result.last_demand)) {
result = priority;
}
};
for (const auto& owner : owners_) {
if (std::any_of(owner.points.begin(), owner.points.end(),
[&](const auto& point) { return point.handle == handle; })) {
include(owner.priority);
}
}
for (const auto& shared : shared_) {
if (shared.handle == handle) { include(shared.priority); }
}
return result;
}
std::vector<Handle> victims() const {
struct Ranked {
Handle handle;
CacheRetentionPriority priority;
std::uint64_t age;
};
std::vector<Ranked> ranked;
const auto add = [&](Handle handle, CacheRetentionPriority priority, std::uint64_t age) {
const auto it = std::find_if(ranked.begin(), ranked.end(),
[&](const auto& entry) { return entry.handle == handle; });
if (it == ranked.end()) {
ranked.push_back({handle, priority, age});
} else if ((priority.reused && !it->priority.reused) ||
(priority.reused == it->priority.reused &&
(priority.reused ? priority.last_demand > it->priority.last_demand
: age > it->age))) {
*it = {handle, priority, age};
}
};
for (const auto& owner : owners_) {
for (const auto& point : owner.points) {
add(point.handle, owner.priority, owner.retained_at);
}
}
for (const auto& shared : shared_) {
add(shared.handle, shared.priority, shared.retained_at);
}
for (const auto& waiting : waiting_) {
for (const auto handle : waiting.held) { add(handle, {}, waiting.request); }