-
Notifications
You must be signed in to change notification settings - Fork 54
Expand file tree
/
Copy pathcache_manager.cc
More file actions
4852 lines (4613 loc) · 239 KB
/
Copy pathcache_manager.cc
File metadata and controls
4852 lines (4613 loc) · 239 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
#include "kv_cache_manager/manager/cache_manager.h"
#include <algorithm>
#include <array>
#include <cassert>
#include <charconv>
#include <chrono>
#include <cinttypes>
#include <limits>
#include <map>
#include <memory>
#include <optional>
#include <set>
#include <string>
#include <string_view>
#include <thread>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#include "kv_cache_manager/common/env_util.h"
#include "kv_cache_manager/common/jsonizable.h"
#include "kv_cache_manager/common/logger.h"
#include "kv_cache_manager/common/request_context.h"
#include "kv_cache_manager/common/standard_uri.h"
#include "kv_cache_manager/common/string_util.h"
#include "kv_cache_manager/config/instance_group.h"
#include "kv_cache_manager/config/instance_info.h"
#include "kv_cache_manager/config/meta_cache_policy_config.h"
#include "kv_cache_manager/config/registry_manager.h"
#include "kv_cache_manager/data_storage/data_storage_uri.h"
#include "kv_cache_manager/data_storage/event_report_backend.h"
#include "kv_cache_manager/event/event_manager.h"
#include "kv_cache_manager/event/spec_events/optimizer_event.h"
#include "kv_cache_manager/manager/cache_manager_metrics_recorder.h"
#include "kv_cache_manager/manager/cache_reclaimer.h"
#include "kv_cache_manager/manager/data_storage_selector.h"
#include "kv_cache_manager/manager/hash_util.h"
#include "kv_cache_manager/manager/meta_searcher_manager.h"
#include "kv_cache_manager/manager/migration_manager.h"
#include "kv_cache_manager/manager/reclaimer_task_supervisor.h"
#include "kv_cache_manager/manager/schedule_plan_executor.h"
#include "kv_cache_manager/manager/select_location_policy.h"
#include "kv_cache_manager/manager/startup_config_loader.h"
#include "kv_cache_manager/meta/common.h"
#include "kv_cache_manager/meta/meta_indexer.h"
#include "kv_cache_manager/meta/meta_indexer_manager.h"
#include "kv_cache_manager/meta/types.h"
#include "kv_cache_manager/metrics/metrics_collector.h"
#include "kv_cache_manager/metrics/metrics_lifecycle.h"
#include "kv_cache_manager/metrics/metrics_registry.h"
#include "kv_cache_manager/protocol/protobuf/meta_service.pb.h"
namespace kv_cache_manager {
#define PREFIX_LOG(LEVEL, format, args...) \
do { \
KVCM_LOG_##LEVEL("trace_id [%s] instance [%s] | " format, trace_id.c_str(), instance_id.c_str(), ##args); \
} while (0)
#define RETURN_IF_EC_NOT_OK(ec) \
do { \
if ((ec) != EC_OK) { \
return ec; \
} \
} while (0)
#define RETURN_IF_EC_NOT_OK_WITH_TYPE(ec, Type) \
do { \
if ((ec) != EC_OK) { \
return {ec, Type()}; \
} \
} while (0)
#define RETURN_IF_EC_NOT_OK_WITH_LOG(LEVEL, ec, format, args...) \
do { \
if ((ec) != EC_OK) { \
PREFIX_LOG(LEVEL, format, ##args); \
return ec; \
} \
} while (0)
#define RETURN_IF_EC_NOT_OK_WITH_TYPE_LOG(LEVEL, ec, Type, format, args...) \
do { \
if ((ec) != EC_OK) { \
PREFIX_LOG(LEVEL, format, ##args); \
return {ec, Type()}; \
} \
} while (0)
namespace {
struct ReporterIdentityView {
std::string_view base_host;
std::optional<uint64_t> engine_rank;
};
bool ParseReporterIdentity(std::string_view host_ip_port, ReporterIdentityView &out) {
out = {};
if (host_ip_port.empty()) {
return false;
}
const size_t separator = host_ip_port.find('@');
if (separator == std::string_view::npos) {
out.base_host = host_ip_port;
return true;
}
if (separator == 0 || separator + 1 >= host_ip_port.size() ||
host_ip_port.find('@', separator + 1) != std::string_view::npos) {
return false;
}
const std::string_view rank_text = host_ip_port.substr(separator + 1);
if (rank_text.size() > 1 && rank_text.front() == '0') {
return false;
}
uint64_t rank = 0;
const auto [end, ec] = std::from_chars(rank_text.data(), rank_text.data() + rank_text.size(), rank);
if (ec != std::errc{} || end != rank_text.data() + rank_text.size()) {
return false;
}
out.base_host = host_ip_port.substr(0, separator);
out.engine_rank = rank;
return true;
}
CacheManager::KeyVector GenKeyVector(const CacheManager::TokenIdsVector &tokens, int64_t block_size) {
std::vector<int64_t> block_keys;
size_t total_blocks = tokens.size() / block_size;
int64_t hash = 0;
for (int index = 0; index < total_blocks; index++) {
auto pos = index * block_size;
hash = hashInt64Array(hash, &tokens[pos], &tokens[pos + block_size]);
block_keys.push_back(hash);
}
return block_keys;
}
inline std::pair<kv_cache_manager::ErrorCode, bool>
IsSpecNameInSpecGroup(const std::string &trace_id,
const std::string &instance_id,
std::string_view spec_name,
std::string_view group_name,
const std::vector<kv_cache_manager::LocationSpecGroup> &location_spec_groups) {
// we have sorted location_spec_groups before
auto it_group = std::lower_bound(location_spec_groups.begin(),
location_spec_groups.end(),
group_name,
[](const auto &location_spec_group, std::string_view group_name) {
return location_spec_group.name() < group_name;
});
if (it_group == location_spec_groups.end() || it_group->name() != group_name) {
PREFIX_LOG(WARN, "not find group [%s]", group_name.data());
return {EC_ERROR, false};
}
const auto &group = *it_group;
auto it_spec_name = std::lower_bound(
group.spec_names().begin(),
group.spec_names().end(),
spec_name,
[](const std::string &src_spec_name, std::string_view dst_spec_name) { return src_spec_name < dst_spec_name; });
if (it_spec_name == group.spec_names().end() || *it_spec_name != spec_name) {
PREFIX_LOG(DEBUG, "not find spec_name [%s] in group [%s]", spec_name.data(), group_name.data());
return {EC_OK, false};
}
return {EC_OK, true};
}
class DeltaMutationGuard {
public:
struct LeaseInfo {
std::string snapshot_version;
uint64_t lifecycle_generation = 0;
};
DeltaMutationGuard(std::shared_ptr<EventReportBackend> backend, ReporterSnapshotKey reporter_key)
: backend_(std::move(backend)), reporter_key_(std::move(reporter_key)) {}
DeltaMutationGuard(const DeltaMutationGuard &) = delete;
DeltaMutationGuard &operator=(const DeltaMutationGuard &) = delete;
~DeltaMutationGuard() {
if (lease_) {
backend_->EndDeltaMutation(reporter_key_, lease_->lifecycle_generation, lease_->snapshot_version);
}
}
ErrorCode Acquire(const LeaseInfo *&out_lease, bool &out_created_generation) {
out_lease = nullptr;
if (snapshot_wait_failure_) {
out_created_generation = false;
return *snapshot_wait_failure_;
}
if (lease_) {
out_lease = &*lease_;
out_created_generation = false;
return EC_OK;
}
LeaseInfo lease;
const ErrorCode ec = backend_->BeginDeltaMutation(
reporter_key_, lease.snapshot_version, &lease.lifecycle_generation, &out_created_generation);
if (ec != EC_OK) {
out_created_generation = false;
if (ec == EC_SNAPSHOT_IN_PROGRESS) {
snapshot_wait_failure_ = ec;
}
return ec;
}
lease_.emplace(std::move(lease));
out_lease = &*lease_;
return EC_OK;
}
void AdoptLifecycleGeneration(uint64_t lifecycle_generation) {
if (lease_) {
lease_->lifecycle_generation = lifecycle_generation;
}
}
private:
std::shared_ptr<EventReportBackend> backend_;
ReporterSnapshotKey reporter_key_;
std::optional<LeaseInfo> lease_;
std::optional<ErrorCode> snapshot_wait_failure_;
};
// 共享 helper:收集目标 storage 上指定 status 的 location 联合覆盖的 spec name 集合。
// 一次 O(L·S) 扫描。exclude_loc_ids 用于排除 stale location。
std::unordered_set<std::string> CollectCoveredSpecNames(const CacheLocationMap &loc_map,
const std::string &storage_name,
std::initializer_list<CacheLocationStatus> statuses,
const std::vector<std::string> &exclude_loc_ids = {}) {
std::unordered_set<std::string> covered;
for (const auto &[loc_id, loc_ptr] : loc_map) {
if (!loc_ptr || std::find(statuses.begin(), statuses.end(), loc_ptr->status()) == statuses.end()) {
continue;
}
if (!exclude_loc_ids.empty() &&
std::find(exclude_loc_ids.begin(), exclude_loc_ids.end(), loc_id) != exclude_loc_ids.end()) {
continue;
}
for (const auto &spec : loc_ptr->location_specs()) {
if (DataStorageUri uri(spec.uri()); uri.Valid() && uri.GetHostName() == storage_name) {
covered.insert(spec.name());
}
}
}
return covered;
}
// 判断目标 storage 上是否有 SERVING/WRITING location(联合)覆盖 requested specs。
// requested_spec_names 空时只判"有任何 spec 在该 storage 上"。
bool HasServingOrWritingLocOnStorage(const CacheLocationMap &loc_map,
const std::string &storage_name,
const std::vector<std::string> &requested_spec_names = {},
const std::vector<std::string> &exclude_loc_ids = {}) {
const auto covered = CollectCoveredSpecNames(
loc_map, storage_name, {CacheLocationStatus::CLS_SERVING, CacheLocationStatus::CLS_WRITING}, exclude_loc_ids);
if (requested_spec_names.empty()) {
return !covered.empty();
}
return std::all_of(requested_spec_names.begin(), requested_spec_names.end(), [&covered](const auto &name) {
return covered.count(name) > 0;
});
}
const CacheLocation *FindLocationById(const CacheLocationMap &loc_map, const std::string &location_id) {
auto it = loc_map.find(location_id);
if (it == loc_map.end()) {
return nullptr;
}
return it->second.get();
}
bool LocationHasSpecOnStorage(const CacheLocation &loc, const std::string &storage_name) {
return std::any_of(loc.location_specs().begin(), loc.location_specs().end(), [&storage_name](const auto &spec) {
const DataStorageUri uri(spec.uri());
return uri.Valid() && uri.GetHostName() == storage_name;
});
}
std::vector<std::string> BuildAllLocationSpecNames(const std::shared_ptr<const InstanceInfo> &instance_info) {
std::vector<std::string> spec_names;
if (instance_info == nullptr) {
return spec_names;
}
spec_names.reserve(instance_info->location_spec_infos().size());
for (const auto &spec_info : instance_info->location_spec_infos()) {
spec_names.push_back(spec_info.name());
}
return spec_names;
}
bool LocationsCoverFullBlockOnStorage(const CacheLocationMap &loc_map,
const std::string &storage_name,
const std::shared_ptr<const InstanceInfo> &instance_info) {
if (instance_info == nullptr || instance_info->location_spec_infos().empty()) {
return false;
}
return std::all_of(instance_info->location_spec_infos().begin(),
instance_info->location_spec_infos().end(),
[&loc_map, &storage_name](const LocationSpecInfo &spec_info) {
return std::any_of(
loc_map.begin(), loc_map.end(), [&spec_info, &storage_name](const auto &entry) {
const auto &loc_ptr = entry.second;
if (!loc_ptr || loc_ptr->status() != CacheLocationStatus::CLS_SERVING) {
return false;
}
return std::any_of(loc_ptr->location_specs().begin(),
loc_ptr->location_specs().end(),
[&spec_info, &storage_name](const auto &spec) {
const DataStorageUri uri(spec.uri());
return spec.name() == spec_info.name() && uri.Valid() &&
uri.GetHostName() == storage_name;
});
});
});
}
MigrationMarkClearPolicy GetMigrationMarkClearPolicy(RequestContext *request_context,
const std::shared_ptr<RegistryManager> ®istry_manager,
const std::shared_ptr<const InstanceInfo> &instance_info) {
if (registry_manager == nullptr || instance_info == nullptr) {
return MigrationMarkClearPolicy::CLEAR_ON_NEXT_WRITE_SUCCESS;
}
auto [ec, instance_group] =
registry_manager->GetInstanceGroup(request_context, instance_info->instance_group_name());
if (ec != EC_OK || instance_group == nullptr || instance_group->cache_config() == nullptr) {
return MigrationMarkClearPolicy::CLEAR_ON_NEXT_WRITE_SUCCESS;
}
return instance_group->cache_config()->migration_mark_clear_policy();
}
bool IsTieredMigrationEnabled(RequestContext *request_context,
const std::shared_ptr<RegistryManager> ®istry_manager,
const std::shared_ptr<const InstanceInfo> &instance_info) {
if (registry_manager == nullptr || instance_info == nullptr) {
return false;
}
auto [ec, instance_group] =
registry_manager->GetInstanceGroup(request_context, instance_info->instance_group_name());
return ec == EC_OK && instance_group != nullptr && instance_group->cache_config() != nullptr &&
!instance_group->cache_config()->migration_strategies().empty();
}
const char *StorageTargetAdmissionStatusName(StorageTargetAdmissionStatus status) {
switch (status) {
case StorageTargetAdmissionStatus::kAllowed:
return "allowed";
case StorageTargetAdmissionStatus::kNotFound:
return "not_found";
case StorageTargetAdmissionStatus::kUnavailable:
return "unavailable";
case StorageTargetAdmissionStatus::kGroupQuotaExceeded:
return "group_quota_exceeded";
case StorageTargetAdmissionStatus::kStorageTypeQuotaExceeded:
return "storage_type_quota_exceeded";
case StorageTargetAdmissionStatus::kReadError:
return "read_error";
}
return "unknown";
}
// 只把 target 可用且 quota 未超限的 valid Mark 交给写入过滤逻辑。target 被注销时按查询
// 快照精确清标;unavailable/quota 满属于瞬时状态,保留 Mark 并让本次调用使用普通 write 判定。
void ResolveUsableTieredWriteTargets(RequestContext *request_context,
const std::string &instance_id,
const std::string &instance_group_name,
const CacheManager::KeyVector &keys,
const std::vector<MigrationManager::MarkQueryResult> &mark_results,
const std::shared_ptr<DataStorageManager> &data_storage_manager,
const std::shared_ptr<DataStorageSelector> &data_storage_selector,
const std::shared_ptr<MigrationManager> &migration_manager,
std::vector<std::string> &out_targets) {
const size_t result_count = std::min({keys.size(), mark_results.size(), out_targets.size()});
std::vector<std::string> unique_targets;
std::unordered_map<std::string, std::size_t> target_indexes;
for (size_t i = 0; i < result_count; ++i) {
const auto &mark = mark_results[i];
if (mark.HasValidMark() && target_indexes.emplace(mark.target, unique_targets.size()).second) {
unique_targets.push_back(mark.target);
}
}
std::vector<StorageTargetAdmissionResult> admissions;
if (data_storage_selector != nullptr) {
admissions =
data_storage_selector->CheckExplicitWriteTargets(request_context, instance_group_name, unique_targets);
}
for (size_t i = 0; i < result_count; ++i) {
const auto &mark = mark_results[i];
if (!mark.HasValidMark()) {
continue;
}
StorageTargetAdmissionResult admission;
if (const auto it = target_indexes.find(mark.target);
it != target_indexes.end() && it->second < admissions.size()) {
admission = admissions[it->second];
} else if (data_storage_manager != nullptr) {
const auto backend = data_storage_manager->GetDataStorageBackend(mark.target);
if (backend == nullptr) {
admission.status = StorageTargetAdmissionStatus::kNotFound;
admission.ec = EC_NOENT;
} else if (!backend->Available()) {
admission.status = StorageTargetAdmissionStatus::kUnavailable;
admission.ec = EC_NOENT;
} else {
admission.status = StorageTargetAdmissionStatus::kAllowed;
admission.ec = EC_OK;
admission.type = backend->GetType();
}
}
if (admission.Allowed()) {
out_targets[i] = mark.target;
continue;
}
bool cleared = false;
if (admission.status == StorageTargetAdmissionStatus::kNotFound && migration_manager != nullptr) {
cleared =
migration_manager->ClearTieredWriteMarkIfMatch(instance_id, keys[i], mark.target, mark.deadline_ms);
}
KVCM_LOG_WARN("trace_id [%s] instance [%s] block [%ld] tiered target storage [%s] rejected: %s; "
"conditional mark clear [%s], use ordinary write policy",
request_context->trace_id().c_str(),
instance_id.c_str(),
keys[i],
mark.target.c_str(),
StorageTargetAdmissionStatusName(admission.status),
cleared ? "succeeded" : "skipped");
}
}
} // namespace
CacheManager::CacheManager(std::shared_ptr<MetricsRegistry> metrics_registry,
std::shared_ptr<RegistryManager> registry_manager,
std::shared_ptr<MetricsLifecycle> metrics_lifecycle)
: meta_indexer_manager_(std::make_shared<MetaIndexerManager>())
, write_location_manager_(std::make_shared<WriteLocationManager>())
, meta_searcher_manager_(std::make_shared<MetaSearcherManager>(registry_manager, meta_indexer_manager_))
, data_storage_selector_(std::make_shared<DataStorageSelector>(meta_indexer_manager_, registry_manager))
, metrics_registry_(std::move(metrics_registry))
, registry_manager_(std::move(registry_manager))
, metrics_lifecycle_(metrics_lifecycle ? std::move(metrics_lifecycle) : std::make_shared<MetricsLifecycle>())
, metrics_recorder_(std::make_shared<CacheManagerMetricsRecorder>(
meta_indexer_manager_, write_location_manager_, registry_manager_, metrics_lifecycle_)) {}
CacheManager::~CacheManager() {
if (cache_garbage_collector_) {
cache_garbage_collector_->Stop();
cache_garbage_collector_.reset();
}
ClearEventCleanupCallbacks();
StopRecoverRetryLoop();
DeactivateEventCleanupCallbacks();
if (write_location_manager_) {
write_location_manager_->Stop();
write_location_manager_.reset();
}
if (cache_reclaimer_) {
cache_reclaimer_->Stop();
cache_reclaimer_.reset();
}
reclaimer_task_supervisor_.reset();
// Background plans capture this CacheManager. Stop and join their worker
// threads before member destruction begins.
schedule_plan_executor_.reset();
}
bool CacheManager::Init(int32_t schedule_plan_executor_thread_count,
uint64_t cache_reclaimer_key_sampling_size_total,
uint64_t cache_reclaimer_key_sampling_size_per_task,
uint64_t cache_reclaimer_del_batch_size,
uint32_t cache_reclaimer_idle_interval_ms,
uint32_t cache_reclaimer_worker_size,
CacheReclaimerAsyncDeleteConfig cache_reclaimer_async_delete_config,
uint32_t schedule_plan_migration_worker_budget,
uint32_t meta_query_worker_count,
std::size_t meta_query_parallel_threshold,
std::size_t meta_query_chunk_size,
CacheGarbageCollector::Config cache_gc_config) {
if (schedule_plan_executor_thread_count <= 1 || schedule_plan_migration_worker_budget == 0 ||
schedule_plan_migration_worker_budget >= static_cast<uint32_t>(schedule_plan_executor_thread_count)) {
KVCM_LOG_ERROR("invalid schedule executor budget: worker_count=%d migration_worker_budget=%u",
schedule_plan_executor_thread_count,
schedule_plan_migration_worker_budget);
return false;
}
if (meta_query_worker_count == 0 || meta_query_worker_count > 64 || meta_query_parallel_threshold == 0 ||
meta_query_chunk_size == 0 || meta_query_chunk_size > meta_query_parallel_threshold ||
!meta_indexer_manager_->ConfigureQueryExecutor(
meta_query_worker_count, meta_query_parallel_threshold, meta_query_chunk_size)) {
KVCM_LOG_ERROR("invalid meta query executor config: workers=%u threshold=%zu chunk_size=%zu",
meta_query_worker_count,
meta_query_parallel_threshold,
meta_query_chunk_size);
return false;
}
schedule_plan_executor_ = std::make_shared<SchedulePlanExecutor>(schedule_plan_executor_thread_count,
meta_indexer_manager_,
registry_manager_->data_storage_manager(),
metrics_registry_,
schedule_plan_migration_worker_budget);
event_manager_ = std::make_shared<EventManager>();
if (!event_manager_) {
KVCM_LOG_WARN("create EventManager failed");
}
if (!event_manager_->Init()) {
KVCM_LOG_ERROR("event_manager init failed");
}
migration_manager_ = std::make_shared<MigrationManager>(schedule_plan_executor_,
meta_indexer_manager_,
registry_manager_->data_storage_manager(),
metrics_registry_,
event_manager_,
registry_manager_,
data_storage_selector_);
// Invariant: migration_manager_ is always constructed here. Feature enablement is a per
// instance-group property (IsTieredMigrationEnabled), never expressed via pointer nullness.
assert(migration_manager_ != nullptr);
cache_garbage_collector_ = std::make_shared<CacheGarbageCollector>(std::move(cache_gc_config),
registry_manager_,
meta_indexer_manager_,
registry_manager_->data_storage_manager(),
schedule_plan_executor_,
metrics_registry_,
migration_manager_);
if (cache_garbage_collector_->Validate() != EC_OK) {
KVCM_LOG_ERROR("CacheManager init failed: invalid CacheGarbageCollector config");
return false;
}
cache_reclaimer_ = std::make_shared<CacheReclaimer>(cache_reclaimer_key_sampling_size_total,
cache_reclaimer_key_sampling_size_per_task,
cache_reclaimer_del_batch_size,
cache_reclaimer_idle_interval_ms,
cache_reclaimer_worker_size,
registry_manager_,
meta_indexer_manager_,
meta_searcher_manager_,
schedule_plan_executor_,
metrics_registry_,
event_manager_,
write_location_manager_,
std::move(cache_reclaimer_async_delete_config),
migration_manager_);
if (cache_reclaimer_->Start() != EC_OK) {
KVCM_LOG_ERROR("CacheManager init failed");
return false;
}
reclaimer_task_supervisor_ = std::make_unique<ReclaimerTaskSupervisor>(schedule_plan_executor_);
reclaimer_task_supervisor_->Start();
write_location_manager_->Start();
metrics_recorder_->Start();
KVCM_LOG_INFO("CacheManager init OK");
return true;
}
std::string CacheManager::GetExtraInfo(RequestContext *request_context, const std::string &instance_id) {
auto instance_info = registry_manager_->GetInstanceInfo(request_context, instance_id);
if (!instance_info) {
return "";
}
auto group_name = instance_info->instance_group_name();
auto [ec, group] = registry_manager_->GetInstanceGroup(request_context, group_name);
if (ec == EC_OK && group) {
return group->extra_info();
}
return "";
}
void CacheManager::SetRevisitHistogramConfig(const std::vector<double> &boundaries) {
if (meta_indexer_manager_ && metrics_registry_ && !boundaries.empty()) {
meta_indexer_manager_->SetRevisitHistogramConfig(metrics_registry_, boundaries);
KVCM_LOG_INFO("Set revisit histogram config with %zu boundaries", boundaries.size());
}
}
std::pair<ErrorCode, std::string>
CacheManager::RegisterInstance(RequestContext *request_context,
const std::string &instance_group,
const std::string &instance_id,
int32_t block_size,
const std::vector<LocationSpecInfo> &location_spec_infos,
const ModelDeployment &model_deployment,
const std::vector<LocationSpecGroup> &location_spec_groups,
QueryType default_query_type) {
SPAN_TRACER(request_context);
// TODO : not thread safe now
const auto &trace_id = request_context->trace_id();
auto instance_info = registry_manager_->GetInstanceInfo(request_context, instance_id);
if (instance_info) {
auto mismatched = instance_info->MismatchFields(block_size,
location_spec_infos,
model_deployment,
location_spec_groups,
static_cast<int32_t>(default_query_type));
if (instance_info->instance_group_name() != instance_group) {
mismatched.insert(mismatched.begin(), "instance_group_name");
}
if (!mismatched.empty()) {
auto mismatched_str = StringUtil::Join(mismatched, ", ");
request_context->error_tracer()->AddErrorMsg(
"register instance failed: instance_id '" + instance_id +
"' already exists with different configuration, mismatched fields: [" + mismatched_str + "]");
PREFIX_LOG(
WARN, "register instance failed: duplicate instance, mismatched fields: [%s]", mismatched_str.c_str());
return {EC_DUPLICATE_ENTITY, {}};
}
auto ec = TryCreateMetaSearcher(request_context, instance_id);
RETURN_IF_EC_NOT_OK_WITH_TYPE_LOG(WARN, ec, std::string, "register instance failed with errorcode: %d", ec);
PREFIX_LOG(INFO, "register instance OK");
return {ec, GetStorageConfigStr(request_context, instance_id)};
}
auto ec = registry_manager_->RegisterInstance(request_context,
instance_group,
instance_id,
block_size,
location_spec_infos,
model_deployment,
location_spec_groups,
static_cast<int32_t>(default_query_type));
RETURN_IF_EC_NOT_OK_WITH_TYPE_LOG(WARN, ec, std::string, "register instance failed with errorcode: %d", ec);
ec = TryCreateMetaSearcher(request_context, instance_id);
RETURN_IF_EC_NOT_OK_WITH_TYPE_LOG(WARN, ec, std::string, "register instance failed with errorcode: %d", ec);
PREFIX_LOG(INFO, "register instance OK");
return {ec, GetStorageConfigStr(request_context, instance_id)};
}
ErrorCode CacheManager::RemoveInstance(RequestContext *request_context,
const std::string &instance_group,
const std::string &instance_id) {
SPAN_TRACER(request_context);
const auto &trace_id = request_context->trace_id();
// drain 活跃迁移 copy 后再 trim,避免 trim 与 backend copy 竞态。
// (trim 把 active copy 的 WRITING 目标 CAS→DELETING 删掉 / copy 成功后 promote 的 SERVING 目标被 trim 删)。
// 步骤:draining gate(阻止该 instance 所有新 Copy,覆盖 reclaimer + admin 两路)
// → cancel 活跃 copy → 有界等待完成 → 删除并 trim。
// RAII guard 保证 EndDraining 在任何出口(含宏 return)都执行,避免 draining set 泄漏。
// 不暂停全局 Reclaimer:删除一个 instance 不应阻塞其他 instance,也不能覆盖 Server 生命周期的暂停状态。
struct DrainGuard {
CacheManager *mgr;
std::string instance_id;
bool active = false;
~DrainGuard() {
if (active) {
if (auto mm = mgr->migration_manager()) {
mm->EndDrainingInstance(instance_id);
}
}
}
} drain_guard{this, instance_id, false};
if (migration_manager_ != nullptr) {
migration_manager_->BeginDrainingInstance(instance_id); // 契约保证:happens-before 所有后续提交
drain_guard.active = true;
const auto active_keys = migration_manager_->GetActiveBlockKeysForInstance(instance_id);
if (!active_keys.empty()) {
migration_manager_->BatchCancel(instance_id, active_keys);
// 有界等待:running/cancelling 任务由 monitor 在 copy future 完成后清理;快照中的
// preparing 任务则已被置为 kPrepareCancelling,由提交线程在下一安全边界回滚。
// draining gate 与锁内 reservation 保证快照不漏掉已准入任务,故无需重复 Cancel。
constexpr int kDrainTimeoutMs = 5000;
constexpr int kPollIntervalMs = 50;
int waited_ms = 0;
while (waited_ms < kDrainTimeoutMs) {
if (migration_manager_->GetActiveBlockKeysForInstance(instance_id).empty()) {
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds(kPollIntervalMs));
waited_ms += kPollIntervalMs;
}
if (!migration_manager_->GetActiveBlockKeysForInstance(instance_id).empty()) {
KVCM_LOG_WARN("[%s] RemoveInstance drain timeout (%dms) for instance %s, "
"proceeding with trim; residual WRITING targets will be orphan-cleaned",
trace_id.c_str(),
kDrainTimeoutMs,
instance_id.c_str());
}
}
}
auto ec = registry_manager_->RemoveInstance(request_context, instance_group, instance_id);
RETURN_IF_EC_NOT_OK_WITH_LOG(WARN, ec, "remove instance failed"); // drain_guard 析构自动收尾
InvalidateInstanceMetrics(instance_id);
ec = TrimCache(request_context, instance_id, proto::meta::TrimStrategy::TS_REMOVE_ALL_CACHE);
RETURN_IF_EC_NOT_OK_WITH_LOG(WARN, ec, "remove instance failed"); // drain_guard 析构自动收尾
PREFIX_LOG(INFO, "remove instance OK");
return ec;
}
void CacheManager::InvalidateInstanceMetrics(const std::string &instance_id) const {
if (instance_id.empty()) {
return;
}
// callers must hold a unique lock on metrics_lifecycle_->mut_ while
// invoking this, so that no producer (recorder publish span,
// reporter ReportInterval, MetaServiceMetricsBase slow path) can
// register new instance_id-tagged metrics during the steps below
// 1) prune the recorder snapshot so the reporter cannot recreate
// entries on its next cycle
if (metrics_recorder_) {
metrics_recorder_->RemoveInstance(instance_id);
}
// 2) remove existing metrics entries from the registry
if (metrics_registry_) {
metrics_registry_->RemoveByTagFilter({{"instance_id", instance_id}});
}
// 3) evict cached per-instance collectors so subsequent requests
// do not resurrect entries through stale handles
if (on_instance_removed_) {
on_instance_removed_(instance_id);
}
}
std::pair<ErrorCode, InstanceInfoConstPtr> CacheManager::GetInstanceInfo(RequestContext *request_context,
const std::string &instance_id) {
SPAN_TRACER(request_context);
const auto &trace_id = request_context->trace_id();
InstanceInfoConstPtr info_ptr = registry_manager_->GetInstanceInfo(request_context, instance_id);
if (info_ptr == nullptr) {
PREFIX_LOG(DEBUG, "get instance info failed");
return {EC_INSTANCE_NOT_EXIST, nullptr};
}
return {EC_OK, info_ptr};
}
std::pair<ErrorCode, std::vector<InstanceInfoConstPtr>> ListInstanceInfo(RequestContext *request_context,
const std::string &instance_group) {
SPAN_TRACER(request_context);
return {EC_OK, std::vector<InstanceInfoConstPtr>()};
}
std::pair<ErrorCode, CacheMetaVecWrapper> CacheManager::GetCacheMeta(RequestContext *request_context,
const std::string &instance_id,
const KeyVector &keys,
const TokenIdsVector &tokens,
const BlockMask &block_mask,
int32_t detail_level /*TODO*/) {
SPAN_TRACER(request_context);
const std::string &trace_id = request_context->trace_id();
auto *service_metrics_collector = dynamic_cast<ServiceMetricsCollector *>(request_context->metrics_collector());
auto [ec, meta_searcher] = CheckInputAndGetMetaSearcher(request_context, instance_id, keys, tokens);
RETURN_IF_EC_NOT_OK_WITH_TYPE_LOG(DEBUG, ec, CacheMetaVecWrapper, "get cache meta failed");
std::vector<CacheLocationMap> location_maps;
KVCM_METRICS_COLLECTOR_CHRONO_MARK_BEGIN(service_metrics_collector, ManagerBatchGetLocation);
if (!keys.empty()) {
KVCM_METRICS_COLLECTOR_SET_METRICS(service_metrics_collector, manager, request_key_count, keys.size());
ec = meta_searcher->BatchGetLocation(request_context, keys, block_mask, location_maps);
} else {
auto [ec_temp, block_size] = GetBlockSize(request_context, instance_id);
RETURN_IF_EC_NOT_OK_WITH_TYPE_LOG(DEBUG, ec_temp, CacheMetaVecWrapper, "get cache meta failed");
auto gen_keys = GenKeyVector(tokens, block_size);
KVCM_METRICS_COLLECTOR_SET_METRICS(service_metrics_collector, manager, request_key_count, gen_keys.size());
ec = meta_searcher->BatchGetLocation(request_context, gen_keys, block_mask, location_maps);
}
KVCM_METRICS_COLLECTOR_CHRONO_MARK_END(service_metrics_collector, ManagerBatchGetLocation);
RETURN_IF_EC_NOT_OK_WITH_TYPE_LOG(DEBUG, ec, CacheMetaVecWrapper, "get cache meta failed: BatchGetLocation fail");
// TODO, 现在BatchGetLocation接口还未返回 location properties 信息, 先置空
// 另外现在BatchGetLocation接口返回的是一个block key对应的location map, 和proto定义不同,
// 先临时只返回map里的第一个 location(不管是不是在serving状态), 将serving状态保存在meta里 这里现在非常 ugly
CacheLocationVector cache_locations;
std::vector<std::string> metas;
std::map<std::string, std::string> meta;
for (CacheLocationMap &location_map : location_maps) {
auto iter = location_map.begin();
if (iter != location_map.end() && iter->second) {
cache_locations.push_back(iter->second);
meta["id"] = cache_locations.back()->id();
} else {
auto not_found_loc = std::make_shared<CacheLocation>();
not_found_loc->set_status(CacheLocationStatus::CLS_NOT_FOUND);
cache_locations.push_back(std::move(not_found_loc));
}
meta["status"] = CacheLocation::CacheLocationStatusToString(cache_locations.back()->status());
metas.push_back(Jsonizable::ToJsonString(meta));
}
return {ec, CacheMetaVecWrapper(std::move(metas), std::move(cache_locations))};
}
ErrorCode CacheManager::PerformCacheLocationQuery(RequestContext *request_context,
ServiceMetricsCollector *service_metrics_collector,
MetaSearcher *meta_searcher,
const std::string &instance_id,
QueryType query_type,
const KeyVector &keys,
const TokenIdsVector &tokens,
const BlockMask &block_mask,
int32_t sw_size,
KeyVector &query_keys,
CacheLocationVector &cache_locations) const {
SPAN_TRACER(request_context);
const std::string &trace_id = request_context->trace_id();
ErrorCode ec = EC_ERROR;
if (!keys.empty()) {
KVCM_METRICS_COLLECTOR_SET_METRICS(service_metrics_collector, manager, request_key_count, keys.size());
ec = GetCacheLocationByQueryType(
meta_searcher, request_context, instance_id, query_type, keys, block_mask, sw_size, cache_locations);
} else {
auto [ec_temp, block_size] = GetBlockSize(request_context, instance_id);
RETURN_IF_EC_NOT_OK_WITH_LOG(WARN, ec_temp, "get block_size failed");
auto gen_keys = GenKeyVector(tokens, block_size);
KVCM_METRICS_COLLECTOR_SET_METRICS(service_metrics_collector, manager, request_key_count, gen_keys.size());
query_keys = gen_keys;
ec = GetCacheLocationByQueryType(
meta_searcher, request_context, instance_id, query_type, gen_keys, block_mask, sw_size, cache_locations);
}
return ec;
}
std::pair<ErrorCode, CacheLocationViewVecWrapper>
CacheManager::GetCacheLocation(RequestContext *request_context,
const std::string &instance_id,
QueryType query_type,
const KeyVector &keys,
const TokenIdsVector &tokens,
const BlockMask &block_mask,
int32_t sw_size,
const std::vector<std::string> &location_spec_names) {
SPAN_TRACER(request_context);
const std::string &trace_id = request_context->trace_id();
auto *service_metrics_collector = dynamic_cast<ServiceMetricsCollector *>(request_context->metrics_collector());
auto [ec, meta_searcher] = CheckInputAndGetMetaSearcher(request_context, instance_id, keys, tokens);
RETURN_IF_EC_NOT_OK_WITH_TYPE_LOG(WARN, ec, CacheLocationViewVecWrapper, "check input or get meta searcher failed");
if (query_type == QueryType::QT_UNSPECIFIED) {
RETURN_IF_EC_NOT_OK_WITH_TYPE_LOG(WARN, EC_ERROR, CacheLocationViewVecWrapper, "unknown query type");
}
auto query_scope = (query_type == QueryType::QT_BATCH_GET)
? KVCM_METRICS_COLLECTOR_CHRONO_SCOPE(service_metrics_collector, ManagerBatchGet)
: KVCM_METRICS_COLLECTOR_CHRONO_SCOPE(service_metrics_collector, ManagerPrefixMatch);
CacheLocationVector cache_locations;
KeyVector query_keys = keys;
ec = PerformCacheLocationQuery(request_context,
service_metrics_collector,
meta_searcher,
instance_id,
query_type,
keys,
tokens,
block_mask,
sw_size,
query_keys,
cache_locations);
query_scope = ChronoScopeGuard{};
// prefix_match_len: count actual hits (non-empty id), not total returned entries.
// BatchGet/ReverseRollSW pad misses with empty CacheLocation objects.
{
size_t match_len = 0;
for (const auto &loc : cache_locations) {
if (loc && !loc->id().empty()) {
++match_len;
}
}
KVCM_METRICS_COLLECTOR_SET_METRICS(service_metrics_collector, manager, prefix_match_len, match_len);
}
RETURN_IF_EC_NOT_OK_WITH_TYPE_LOG(WARN, ec, CacheLocationViewVecWrapper, "get cache location failed");
// accumulate hit/query block counters for hit-rate monitoring (only on success)
if (service_metrics_collector) {
size_t query_count = query_keys.size();
size_t hit_count = 0;
if (query_type == QueryType::QT_PREFIX_MATCH) {
// PrefixMatch only returns matched blocks; size() == hit count
hit_count = cache_locations.size();
} else {
// BatchGet / ReverseRollSW pad misses with empty CacheLocation
for (const auto &loc : cache_locations) {
if (loc && !loc->id().empty()) {
++hit_count;
}
}
}
Counter query_counter, hit_counter;
COPY_METRICS_(service_metrics_collector, manager, get_cache_location_query_block_counter, query_counter);
COPY_METRICS_(service_metrics_collector, manager, get_cache_location_hit_block_counter, hit_counter);
query_counter += query_count;
hit_counter += hit_count;
}
FilterLocationSpecByName(cache_locations, location_spec_names);
auto cache_get_event = std::make_shared<CacheGetEvent>(instance_id);
cache_get_event->SetEventTriggerTime();
cache_get_event->SetAddtionalArgs(
QueryTypeToString(query_type), query_keys, tokens, block_mask, sw_size, location_spec_names);
if (event_manager_) {
event_manager_->Publish(cache_get_event);
}
return {ec, CacheLocationViewVecWrapper(std::move(cache_locations))};
}
void CacheManager::FillEmptyLocationSpecs(const std::vector<LocationSpecInfo> &location_spec_infos,
CacheLocationVector &locations) {
for (auto &location : locations) {
if (!location || location->spec_size() == 0) {
auto mutable_loc =
location ? std::make_shared<CacheLocation>(*location) : std::make_shared<CacheLocation>();
mutable_loc->set_spec_size(location_spec_infos.size());
for (auto &spec_info : location_spec_infos) {
mutable_loc->push_location_spec(LocationSpec(spec_info.name(), ""));
}
location = std::move(mutable_loc);
}
}
}
std::pair<ErrorCode, BatchLocationsView>
CacheManager::GetCacheLocationsByBackend(RequestContext *request_context,
const std::string &instance_id,
QueryType query_type,
const KeyVector &keys,
const TokenIdsVector &tokens,
const BlockMask &block_mask,
int32_t sw_size,
const std::vector<std::string> &location_spec_names,
const std::vector<BackendSelector> &backend_selectors) {
SPAN_TRACER(request_context);
const std::string &trace_id = request_context->trace_id();
auto *service_metrics_collector = dynamic_cast<ServiceMetricsCollector *>(request_context->metrics_collector());
auto [ec, meta_searcher] = CheckInputAndGetMetaSearcher(request_context, instance_id, keys, tokens);
RETURN_IF_EC_NOT_OK_WITH_TYPE_LOG(WARN, ec, BatchLocationsView, "check input or get meta searcher failed");
if (query_type != QueryType::QT_BATCH_GET) {
request_context->error_tracer()->AddErrorMsg("GetCacheLocationsByBackend only supports QT_BATCH_GET");
RETURN_IF_EC_NOT_OK_WITH_TYPE_LOG(
WARN, EC_BADARGS, BatchLocationsView, "GetCacheLocationsByBackend only supports QT_BATCH_GET");
}
auto policy = genSelectLocationPolicy(request_context, instance_id);
if (policy == nullptr) {
request_context->error_tracer()->AddErrorMsg("gen select location policy failed");
RETURN_IF_EC_NOT_OK_WITH_TYPE_LOG(WARN, EC_ERROR, BatchLocationsView, "gen select location policy failed");
}
KeyVector query_keys = keys;
if (keys.empty()) {
auto [ec_temp, block_size] = GetBlockSize(request_context, instance_id);
RETURN_IF_EC_NOT_OK_WITH_TYPE_LOG(WARN, ec_temp, BatchLocationsView, "get block_size failed");
query_keys = GenKeyVector(tokens, block_size);
}
const bool has_implicit_empty_mask =
std::holds_alternative<BlockMaskVector>(block_mask) && std::get<BlockMaskVector>(block_mask).empty();
if (!has_implicit_empty_mask && !IsBlockMaskValid(block_mask, query_keys.size())) {
request_context->error_tracer()->AddErrorMsg("block_mask must match the number of query keys");
RETURN_IF_EC_NOT_OK_WITH_TYPE_LOG(
WARN, EC_BADARGS, BatchLocationsView, "block_mask must match the number of query keys");
}
if (!location_spec_names.empty()) {
if (location_spec_names.size() != query_keys.size() ||
std::any_of(location_spec_names.begin(), location_spec_names.end(), [](const std::string &name) {
return name.empty();
})) {
request_context->error_tracer()->AddErrorMsg(
"location_spec_names must be empty or contain one non-empty name per query key");
RETURN_IF_EC_NOT_OK_WITH_TYPE_LOG(
WARN, EC_BADARGS, BatchLocationsView, "invalid per-key location_spec_names");
}
}
auto query_scope = KVCM_METRICS_COLLECTOR_CHRONO_SCOPE(service_metrics_collector, ManagerBatchGet);
KVCM_METRICS_COLLECTOR_SET_METRICS(service_metrics_collector, manager, request_key_count, query_keys.size());
if (backend_selectors.empty()) {
request_context->error_tracer()->AddErrorMsg("backend_selectors must not be empty");
RETURN_IF_EC_NOT_OK_WITH_TYPE_LOG(WARN, EC_BADARGS, BatchLocationsView, "backend_selectors must not be empty");
}
std::unordered_set<DataStorageType> selected_backend_types;
for (const auto &selector : backend_selectors) {
const auto backend_index = ToIndex(selector.backend_type);
if (selector.backend_type == DataStorageType::DATA_STORAGE_TYPE_UNKNOWN ||
backend_index >= ToIndex(DataStorageType::COUNT)) {
request_context->error_tracer()->AddErrorMsg("backend selector has invalid backend_type");
RETURN_IF_EC_NOT_OK_WITH_TYPE_LOG(
WARN, EC_BADARGS, BatchLocationsView, "backend selector has invalid backend_type");
}
if (!selected_backend_types.insert(selector.backend_type).second) {
request_context->error_tracer()->AddErrorMsg("backend selector contains duplicate backend_type");
RETURN_IF_EC_NOT_OK_WITH_TYPE_LOG(
WARN, EC_BADARGS, BatchLocationsView, "backend selector contains duplicate backend_type");
}
switch (selector.strategy) {
case LocationSelectStrategy::LSS_WEIGHTED_RANDOM:
break;
case LocationSelectStrategy::LSS_V6D_PREFIX:
case LocationSelectStrategy::LSS_V6D_COVERAGE:
if (selector.backend_type == DataStorageType::DATA_STORAGE_TYPE_EVENT_REPORT_L2) {
break;
}
[[fallthrough]];
default:
request_context->error_tracer()->AddErrorMsg("backend selector has invalid strategy for backend_type");
RETURN_IF_EC_NOT_OK_WITH_TYPE_LOG(
WARN, EC_BADARGS, BatchLocationsView, "backend selector has invalid strategy for backend_type");
}
}