-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathFasterKV.cs
2166 lines (1884 loc) · 100 KB
/
FasterKV.cs
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
namespace DurableTask.Netherite.Faster
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Text;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using DurableTask.Core;
using DurableTask.Core.Common;
using DurableTask.Core.Tracing;
using FASTER.core;
using Microsoft.Azure.Storage.Blob.Protocol;
using Newtonsoft.Json;
class FasterKV : TrackedObjectStore
{
readonly FasterKV<Key, Value> fht;
readonly Partition partition;
readonly BlobManager blobManager;
readonly CancellationToken terminationToken;
readonly CacheDebugger cacheDebugger;
readonly MemoryTracker.CacheTracker cacheTracker;
readonly LogSettings storelogsettings;
readonly Stopwatch compactionStopwatch;
readonly Dictionary<(PartitionReadEvent, Key), double> pendingReads;
readonly List<IDisposable> sessionsToDisposeOnShutdown;
TrackedObject[] singletons;
Task persistSingletonsTask;
ClientSession<Key, Value, EffectTracker, Output, object, IFunctions<Key, Value, EffectTracker, Output, object>> mainSession;
const int queryParallelism = 100;
readonly ClientSession<Key, Value, EffectTracker, Output, object, IFunctions<Key, Value, EffectTracker, Output, object>>[] querySessions
= new ClientSession<Key, Value, EffectTracker, Output, object, IFunctions<Key, Value, EffectTracker, Output, object>>[queryParallelism];
static readonly SemaphoreSlim availableQuerySessions = new SemaphoreSlim(queryParallelism);
readonly ConcurrentBag<int> idleQuerySessions = new ConcurrentBag<int>(Enumerable.Range(0, queryParallelism));
async ValueTask<FasterKV<Key, Value>.ReadAsyncResult<EffectTracker, Output, object>> ReadOnQuerySessionAsync(string instanceId, CancellationToken cancellationToken)
{
await availableQuerySessions.WaitAsync();
try
{
bool success = this.idleQuerySessions.TryTake(out var session);
this.partition.Assert(success, "available sessions must be larger than or equal to semaphore count");
try
{
var result = await this.querySessions[session].ReadAsync(TrackedObjectKey.Instance(instanceId), token: cancellationToken).ConfigureAwait(false);
return result;
}
finally
{
this.idleQuerySessions.Add(session);
}
}
finally
{
availableQuerySessions.Release();
}
}
double nextHangCheck;
const int HangCheckPeriod = 30000;
const int ReadRetryAfter = 20000;
EffectTracker effectTracker;
public FasterTraceHelper TraceHelper => this.blobManager.TraceHelper;
public int PageSizeBits => this.storelogsettings.PageSizeBits;
public FasterKV(Partition partition, BlobManager blobManager, MemoryTracker memoryTracker)
{
this.partition = partition;
this.blobManager = blobManager;
this.cacheDebugger = partition.Settings.TestHooks?.CacheDebugger;
partition.ErrorHandler.Token.ThrowIfCancellationRequested();
this.storelogsettings = blobManager.GetStoreLogSettings(
partition.Settings.UseSeparatePageBlobStorage,
memoryTracker.MaxCacheSize,
partition.Settings.FasterTuningParameters);
this.fht = new FasterKV<Key, Value>(
BlobManager.HashTableSize,
this.storelogsettings,
blobManager.StoreCheckpointSettings,
new SerializerSettings<Key, Value>
{
keySerializer = () => new Key.Serializer(partition.ErrorHandler),
valueSerializer = () => new Value.Serializer(this.StoreStats, partition.TraceHelper, this.cacheDebugger, partition.ErrorHandler),
});
this.cacheTracker = memoryTracker.NewCacheTracker(this, (int) partition.PartitionId, this.cacheDebugger);
this.pendingReads = new Dictionary<(PartitionReadEvent, Key), double>();
this.sessionsToDisposeOnShutdown = new List<IDisposable>();
this.fht.Log.SubscribeEvictions(new EvictionObserver(this));
this.fht.Log.Subscribe(new ReadonlyObserver(this));
partition.Assert(this.fht.ReadCache == null, "Unexpected read cache");
this.terminationToken = partition.ErrorHandler.Token;
partition.ErrorHandler.AddDisposeTask($"{nameof(FasterKV)}.{nameof(this.Dispose)}", TimeSpan.FromMinutes(2), this.Dispose);
this.compactionStopwatch = new Stopwatch();
this.compactionStopwatch.Start();
this.nextHangCheck = partition.CurrentTimeMs + HangCheckPeriod;
this.blobManager.TraceHelper.FasterProgress("Constructed FasterKV");
}
void Dispose()
{
this.TraceHelper.FasterProgress("Disposing CacheTracker");
this.cacheTracker?.Dispose();
foreach (var s in this.sessionsToDisposeOnShutdown)
{
this.TraceHelper.FasterStorageProgress($"Disposing Temporary Session");
s.Dispose();
}
this.TraceHelper.FasterProgress("Disposing Main Session");
try
{
this.mainSession?.Dispose();
}
catch (OperationCanceledException)
{
// can happen during shutdown
}
this.TraceHelper.FasterProgress("Disposing Query Sessions");
foreach (var s in this.querySessions)
{
try
{
s?.Dispose();
}
catch (OperationCanceledException)
{
// can happen during shutdown
}
}
this.TraceHelper.FasterProgress("Disposing FasterKV");
this.fht.Dispose();
this.TraceHelper.FasterProgress($"Disposing Devices");
this.blobManager.DisposeDevices();
if (this.blobManager.FaultInjector != null)
{
this.TraceHelper.FasterProgress($"Unregistering from FaultInjector");
this.blobManager.FaultInjector.Disposed(this.blobManager);
}
this.TraceHelper.FasterProgress("Disposed FasterKV");
}
double GetElapsedCompactionMilliseconds()
{
double elapsedMs = this.compactionStopwatch.Elapsed.TotalMilliseconds;
this.compactionStopwatch.Restart();
return elapsedMs;
}
ClientSession<Key, Value, EffectTracker, Output, object, IFunctions<Key, Value, EffectTracker, Output, object>> CreateASession(string id, bool isScan)
{
var functions = new Functions(this.partition, this, this.cacheTracker, isScan);
ReadCopyOptions readCopyOptions = isScan
? new ReadCopyOptions(ReadCopyFrom.None, ReadCopyTo.None)
: new ReadCopyOptions(ReadCopyFrom.AllImmutable, ReadCopyTo.MainLog);
return this.fht.NewSession(functions, id, default, readCopyOptions);
}
public IDisposable TrackTemporarySession(ClientSession<Key, Value, EffectTracker, Output, object, IFunctions<Key, Value, EffectTracker, Output, object>> session)
{
return new SessionTracker() { Store = this, Session = session };
}
class SessionTracker : IDisposable
{
public FasterKV Store;
public ClientSession<Key, Value, EffectTracker, Output, object, IFunctions<Key, Value, EffectTracker, Output, object>> Session;
public void Dispose()
{
if (this.Store.terminationToken.IsCancellationRequested)
{
this.Store.sessionsToDisposeOnShutdown.Add(this.Session);
}
else
{
this.Session.Dispose();
}
}
}
public LogAccessor<Key, Value> Log => this.fht?.Log;
public override void InitMainSession()
{
this.singletons = new TrackedObject[TrackedObjectKey.NumberSingletonTypes];
string suffix = DateTime.UtcNow.ToString("O");
// The main session is the session used by all reads and writes performed by the storeworker.
// Using a single session means that the store worker sees a consistent state at all times.
// A single session is sufficient since the storeworker performs only one operation at a time.
this.mainSession = this.CreateASession($"main-{suffix}", false);
// Since queries may require scans that can take a significant time, it is not advisable to perform
// queries on the main session. We therefore create a pool of read-only sessions available for queries.
// Query sessions may see a slightly stale store than the main session, i.e. may not contain
// all the same updates.
for (int i = 0; i < this.querySessions.Length; i++)
{
this.querySessions[i] = this.CreateASession($"query{i:D2}-{suffix}", true);
}
this.cacheTracker.MeasureCacheSize(true);
this.CheckInvariants();
}
public override Task<bool> FindCheckpointAsync(bool logIsEmpty)
{
return this.blobManager.FindCheckpointsAsync(logIsEmpty);
}
public override async Task<(long commitLogPosition, (long,int) inputQueuePosition, string inputQueueFingerprint)> RecoverAsync()
{
try
{
// recover singletons
this.blobManager.TraceHelper.FasterProgress($"Recovering Singletons");
using (var stream = await this.blobManager.RecoverSingletonsAsync())
{
this.singletons = Serializer.DeserializeSingletons(stream);
}
foreach (var singleton in this.singletons)
{
singleton.Partition = this.partition;
}
// recover Faster
this.blobManager.TraceHelper.FasterProgress($"Recovering FasterKV - Entering fht.RecoverAsync");
await this.fht.RecoverAsync(this.partition.Settings.FasterTuningParameters?.NumPagesToPreload ?? 1, true, -1, this.terminationToken);
this.blobManager.TraceHelper.FasterProgress($"Recovering FasterKV - Returned from fht.RecoverAsync");
this.mainSession = this.CreateASession($"main-{this.blobManager.IncarnationTimestamp:o}", false);
for (int i = 0; i < this.querySessions.Length; i++)
{
this.querySessions[i] = this.CreateASession($"query{i:D2}-{this.blobManager.IncarnationTimestamp:o}", true);
}
this.cacheTracker.MeasureCacheSize(true);
this.CheckInvariants();
return (
this.blobManager.CheckpointInfo.CommitLogPosition,
(this.blobManager.CheckpointInfo.InputQueuePosition, this.blobManager.CheckpointInfo.InputQueueBatchPosition),
this.blobManager.CheckpointInfo.InputQueueFingerprint);
}
catch (Exception exception)
when (this.terminationToken.IsCancellationRequested && !Utils.IsFatal(exception))
{
throw new OperationCanceledException("Partition was terminated.", exception, this.terminationToken);
}
}
public override bool CompletePending()
{
try
{
var result = this.mainSession.CompletePending(false, false);
if (this.nextHangCheck <= this.partition.CurrentTimeMs)
{
this.RetrySlowReads();
this.nextHangCheck = this.partition.CurrentTimeMs + HangCheckPeriod;
}
return result;
}
catch (Exception exception)
when (this.terminationToken.IsCancellationRequested && !Utils.IsFatal(exception))
{
throw new OperationCanceledException("Partition was terminated.", exception, this.terminationToken);
}
}
public override ValueTask ReadyToCompletePendingAsync(CancellationToken token)
{
return this.mainSession.ReadyToCompletePendingAsync(token);
}
public override bool TakeFullCheckpoint(long commitLogPosition, (long,int) inputQueuePosition, string inputQueueFingerprint, out Guid checkpointGuid)
{
try
{
this.blobManager.CheckpointInfo.CommitLogPosition = commitLogPosition;
this.blobManager.CheckpointInfo.InputQueuePosition = inputQueuePosition.Item1;
this.blobManager.CheckpointInfo.InputQueueBatchPosition = inputQueuePosition.Item2;
this.blobManager.CheckpointInfo.InputQueueFingerprint = inputQueueFingerprint;
if (this.fht.TryInitiateFullCheckpoint(out checkpointGuid, CheckpointType.FoldOver))
{
byte[] serializedSingletons = Serializer.SerializeSingletons(this.singletons);
this.persistSingletonsTask = this.blobManager.PersistSingletonsAsync(serializedSingletons, checkpointGuid);
return true;
}
else
{
return false;
}
}
catch (Exception exception)
when (this.terminationToken.IsCancellationRequested && !Utils.IsFatal(exception))
{
throw new OperationCanceledException("Partition was terminated.", exception, this.terminationToken);
}
}
public override async ValueTask CompleteCheckpointAsync()
{
try
{
// workaround for hanging in CompleteCheckpointAsync: use custom thread.
await RunOnDedicatedThreadAsync("CompleteCheckpointAsync", () => this.fht.CompleteCheckpointAsync(this.terminationToken).AsTask());
//await this.fht.CompleteCheckpointAsync(this.terminationToken);
await this.persistSingletonsTask;
}
catch (Exception exception)
when (this.terminationToken.IsCancellationRequested && !Utils.IsFatal(exception))
{
throw new OperationCanceledException("Partition was terminated.", exception, this.terminationToken);
}
}
public override async Task RemoveObsoleteCheckpoints()
{
await this.blobManager.RemoveObsoleteCheckpoints();
}
public async static Task RunOnDedicatedThreadAsync(string name, Func<Task> asyncAction)
{
Task<Task> tasktask = new Task<Task>(() => asyncAction());
var thread = TrackedThreads.MakeTrackedThread(RunTask, name);
void RunTask() {
try
{
tasktask.RunSynchronously();
}
catch
{
}
}
thread.Start();
await await tasktask;
}
public override async Task FinalizeCheckpointCompletedAsync(Guid guid)
{
await this.blobManager.FinalizeCheckpointCompletedAsync();
if (this.cacheDebugger == null)
{
// update the cache size tracker after each checkpoint, to compensate for inaccuracies in the tracking
try
{
this.cacheTracker.MeasureCacheSize(false);
}
catch (Exception e)
{
this.TraceHelper.FasterStorageError("Measuring CacheSize", e);
}
}
}
public override Guid? StartIndexCheckpoint()
{
try
{
if (this.fht.TryInitiateIndexCheckpoint(out var token))
{
this.persistSingletonsTask = Task.CompletedTask;
return token;
}
else
{
return null;
}
}
catch (Exception exception)
when (this.terminationToken.IsCancellationRequested && !Utils.IsFatal(exception))
{
throw new OperationCanceledException("Partition was terminated.", exception, this.terminationToken);
}
}
public override Guid? StartStoreCheckpoint(long commitLogPosition, (long,int) inputQueuePosition, string inputQueueFingerprint, long? shiftBeginAddress)
{
try
{
this.blobManager.CheckpointInfo.CommitLogPosition = commitLogPosition;
this.blobManager.CheckpointInfo.InputQueuePosition = inputQueuePosition.Item1;
this.blobManager.CheckpointInfo.InputQueueBatchPosition = inputQueuePosition.Item2;
this.blobManager.CheckpointInfo.InputQueueFingerprint = inputQueueFingerprint;
if (shiftBeginAddress > this.fht.Log.BeginAddress)
{
this.fht.Log.ShiftBeginAddress(shiftBeginAddress.Value);
}
long versionBeforeCheckpoint = this.mainSession.Version;
if (this.fht.TryInitiateHybridLogCheckpoint(out var token, CheckpointType.FoldOver))
{
// After the checkpoint is initiated, any subsequent writes done in the mainSession must create a later version of the
// object than the one being checkpointed. This is important to guarantee that the checkpoint contains an atomic snapshot of all objects
// at the time the checkpoint is initiated.
//
// according to Badrish the loop below ensures this desired "fencing" of updates.
// It works because the mainSession is the only session that updates tracked objects.
// So, by waiting for it to advance its version, we make sure any later writes do not race
// with the checkpointing thread.
//
// This is expected to complete very quickly; to avoid hanging
// the store worker indefinitely should there be bugs, we add a timeout after
// which we terminate and recover the partition.
//
Stopwatch stopwatch = Stopwatch.StartNew();
TimeSpan timeLimit = TimeSpan.FromMinutes(1);
while (stopwatch.Elapsed < timeLimit)
{
this.mainSession.Refresh();
if (this.mainSession.Version > versionBeforeCheckpoint)
{
break;
}
System.Threading.Thread.Sleep(5);
}
if (this.mainSession.Version == versionBeforeCheckpoint)
{
string message = $"FASTER did not advance version of main session after initiating checkpoint for over {timeLimit}. Terminating partition.";
this.partition.ErrorHandler.HandleError(nameof(StartStoreCheckpoint), message, e: null, terminatePartition: true, reportAsWarning: false);
return null;
}
byte[] serializedSingletons = Serializer.SerializeSingletons(this.singletons);
this.persistSingletonsTask = this.blobManager.PersistSingletonsAsync(serializedSingletons, token);
return token;
}
else
{
return null;
}
throw new InvalidOperationException("Faster refused store checkpoint");
}
catch (Exception exception)
when (this.terminationToken.IsCancellationRequested && !Utils.IsFatal(exception))
{
throw new OperationCanceledException("Partition was terminated.", exception, this.terminationToken);
}
}
long MinimalLogSize
{
get
{
var stats = (StatsState)this.singletons[(int)TrackedObjectKey.Stats.ObjectType];
return this.fht.Log.FixedRecordSize * stats.InstanceCount * 2;
}
}
public override long? GetCompactionTarget()
{
// TODO empiric validation of the heuristics
var stats = (StatsState) this.singletons[(int)TrackedObjectKey.Stats.ObjectType];
long actualLogSize = this.fht.Log.TailAddress - this.fht.Log.BeginAddress;
long minimalLogSize = this.MinimalLogSize;
long compactionAreaSize = Math.Min(50000, this.fht.Log.SafeReadOnlyAddress - this.fht.Log.BeginAddress);
if (actualLogSize > 2 * minimalLogSize // there must be significant bloat
&& compactionAreaSize >= 5000) // and enough compaction area to justify the overhead
{
return this.fht.Log.BeginAddress + compactionAreaSize;
}
else
{
this.TraceHelper.FasterCompactionProgress(
FasterTraceHelper.CompactionProgress.Skipped,
"",
this.Log.BeginAddress,
this.Log.SafeReadOnlyAddress,
this.Log.TailAddress,
minimalLogSize,
compactionAreaSize,
this.GetElapsedCompactionMilliseconds());
return null;
}
}
readonly static SemaphoreSlim maxCompactionThreads = new SemaphoreSlim((Environment.ProcessorCount + 1) / 2);
public override async Task<long> RunCompactionAsync(long target)
{
string id = DateTime.UtcNow.ToString("O"); // for tracing purposes
this.blobManager.TraceHelper.FasterProgress($"Compaction {id} is requesting to enter semaphore with {maxCompactionThreads.CurrentCount} threads available");
await maxCompactionThreads.WaitAsync();
this.blobManager.TraceHelper.FasterProgress($"Compaction {id} entered semaphore");
try
{
long beginAddressBeforeCompaction = this.Log.BeginAddress;
this.TraceHelper.FasterCompactionProgress(
FasterTraceHelper.CompactionProgress.Started,
id,
beginAddressBeforeCompaction,
this.Log.SafeReadOnlyAddress,
this.Log.TailAddress,
this.MinimalLogSize,
target - this.Log.BeginAddress,
this.GetElapsedCompactionMilliseconds());
var tokenSource = new CancellationTokenSource();
var timeoutTask = Task.Delay(TimeSpan.FromMinutes(10), tokenSource.Token);
var tcs = new TaskCompletionSource<long>(TaskCreationOptions.RunContinuationsAsynchronously);
var thread = TrackedThreads.MakeTrackedThread(RunCompaction, $"Compaction.{id}");
thread.Start();
var winner = await Task.WhenAny(tcs.Task, timeoutTask);
if (winner == timeoutTask)
{
// compaction timed out. Terminate partition
var exceptionMessage = $"Compaction {id} time out";
this.partition.ErrorHandler.HandleError(nameof(RunCompactionAsync), exceptionMessage, e: null, terminatePartition: true, reportAsWarning: true);
// we need resolve the task to ensure the 'finally' block is executed which frees up another thread to start compating
tcs.TrySetException(new OperationCanceledException(exceptionMessage));
}
else
{
// cancel the timeout task since compaction completed
tokenSource.Cancel();
}
await timeoutTask.ContinueWith(_ => tokenSource.Dispose());
// return result of compaction task
return await tcs.Task;
void RunCompaction()
{
try
{
this.blobManager.TraceHelper.FasterProgress($"Compaction {id} started");
var session = this.CreateASession($"compaction-{id}", true);
this.blobManager.TraceHelper.FasterProgress($"Compaction {id} obtained a FASTER session");
using (this.TrackTemporarySession(session))
{
this.blobManager.TraceHelper.FasterProgress($"Compaction {id} is invoking FASTER's compaction routine");
long compactedUntil = session.Compact(target, CompactionType.Scan);
this.TraceHelper.FasterCompactionProgress(
FasterTraceHelper.CompactionProgress.Completed,
id,
compactedUntil,
this.Log.SafeReadOnlyAddress,
this.Log.TailAddress,
this.MinimalLogSize,
this.Log.BeginAddress - beginAddressBeforeCompaction,
this.GetElapsedCompactionMilliseconds());
tcs.TrySetResult(compactedUntil);
}
}
catch (Exception exception)
when (this.terminationToken.IsCancellationRequested && !Utils.IsFatal(exception))
{
tcs.TrySetException(new OperationCanceledException("Partition was terminated.", exception, this.terminationToken));
}
catch (Exception e)
{
tcs.TrySetException(e);
}
}
}
finally
{
maxCompactionThreads.Release();
this.blobManager.TraceHelper.FasterProgress($"Compaction {id} done");
}
}
// perform a query
public override async Task QueryAsync(PartitionQueryEvent queryEvent, EffectTracker effectTracker)
{
try
{
this.terminationToken.ThrowIfCancellationRequested();
DateTime attempt = DateTime.UtcNow;
IAsyncEnumerable<(string, OrchestrationState)> orchestrationStates;
var stats = (StatsState)this.singletons[(int)TrackedObjectKey.Stats.ObjectType];
if (stats.HasInstanceIds)
{
TimeSpan timeBudget = queryEvent.TimeoutUtc.HasValue ? (queryEvent.TimeoutUtc.Value - attempt) - TimeSpan.FromSeconds(10) : TimeSpan.FromSeconds(15);
orchestrationStates = this.QueryEnumeratedStates(
effectTracker,
queryEvent,
stats.GetEnumerator(queryEvent.InstanceQuery.InstanceIdPrefix, queryEvent.ContinuationToken),
queryEvent.PageSize,
timeBudget,
attempt);
}
else
{
orchestrationStates = this.ScanOrchestrationStates(effectTracker, queryEvent, attempt);
}
// process the stream of results, and any exceptions or cancellations
await effectTracker.ProcessQueryResultAsync(queryEvent, orchestrationStates, attempt);
}
catch (Exception exception)
when (this.terminationToken.IsCancellationRequested && !Utils.IsFatal(exception))
{
throw new OperationCanceledException("Partition was terminated.", exception, this.terminationToken);
}
}
// kick off a prefetch
public override async Task RunPrefetchSession(IAsyncEnumerable<TrackedObjectKey> keys)
{
int maxConcurrency = 500;
using SemaphoreSlim prefetchSemaphore = new SemaphoreSlim(maxConcurrency);
Guid sessionId = Guid.NewGuid();
this.blobManager.TraceHelper.FasterProgress($"PrefetchSession {sessionId} started (maxConcurrency={maxConcurrency})");
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
long numberIssued = 0;
long numberMisses = 0;
long numberHits = 0;
long lastReport = 0;
void ReportProgress(int elapsedMillisecondsThreshold)
{
if (stopwatch.ElapsedMilliseconds - lastReport >= elapsedMillisecondsThreshold)
{
this.blobManager.TraceHelper.FasterProgress(
$"FasterKV PrefetchSession {sessionId} elapsed={stopwatch.Elapsed.TotalSeconds:F2}s issued={numberIssued} pending={maxConcurrency - prefetchSemaphore.CurrentCount} hits={numberHits} misses={numberMisses}");
lastReport = stopwatch.ElapsedMilliseconds;
}
}
try
{
// these are disposed after the prefetch thread is done
var prefetchSession = this.CreateASession($"prefetch-{DateTime.UtcNow:O}", false);
using (this.TrackTemporarySession(prefetchSession))
{
// for each key, issue a prefetch
await foreach (TrackedObjectKey key in keys)
{
// wait for an available prefetch semaphore token
while (!await prefetchSemaphore.WaitAsync(50, this.terminationToken))
{
prefetchSession.CompletePending();
ReportProgress(1000);
}
FasterKV.Key k = key;
EffectTracker noInput = null;
Output ignoredOutput = default;
var status = prefetchSession.Read(ref k, ref noInput, ref ignoredOutput, userContext: prefetchSemaphore, 0);
numberIssued++;
if (status.IsCompletedSuccessfully)
{
numberHits++;
prefetchSemaphore.Release();
}
else if (status.IsPending)
{
// slow path: upon completion
numberMisses++;
}
else
{
this.partition.ErrorHandler.HandleError(nameof(RunPrefetchSession), $"FASTER reported ERROR status 0x{status.Value:X2}", null, true, this.partition.ErrorHandler.IsTerminated);
}
this.terminationToken.ThrowIfCancellationRequested();
prefetchSession.CompletePending();
ReportProgress(1000);
}
ReportProgress(0);
this.blobManager.TraceHelper.FasterProgress($"PrefetchSession {sessionId} is waiting for completion");
// all prefetches were issued; now we wait for them all to complete
// by acquiring ALL the semaphore tokens
for (int i = 0; i < maxConcurrency; i++)
{
while (!await prefetchSemaphore.WaitAsync(50, this.terminationToken))
{
prefetchSession.CompletePending();
ReportProgress(1000);
}
}
ReportProgress(0);
}
this.blobManager.TraceHelper.FasterProgress($"PrefetchSession {sessionId} completed");
}
catch (OperationCanceledException) when (this.terminationToken.IsCancellationRequested)
{
// partition is terminating
this.blobManager.TraceHelper.FasterProgress($"PrefetchSession {sessionId} cancelled");
}
catch (Exception e)
{
this.partition.ErrorHandler.HandleError(nameof(RunPrefetchSession), "PrefetchSession {sessionId} encountered exception", e, false, this.partition.ErrorHandler.IsTerminated);
}
}
// kick off a read of a tracked object on the main session, completing asynchronously if necessary
public override void Read(PartitionReadEvent readEvent, EffectTracker effectTracker)
{
this.partition.Assert(readEvent != null, "null readEvent in ReadAsync");
try
{
if (readEvent.Prefetch.HasValue)
{
this.TryRead(readEvent, effectTracker, readEvent.Prefetch.Value);
}
this.TryRead(readEvent, effectTracker, readEvent.ReadTarget);
}
catch (Exception exception)
when (this.terminationToken.IsCancellationRequested && !Utils.IsFatal(exception))
{
throw new OperationCanceledException("Partition was terminated.", exception, this.terminationToken);
}
}
void TryRead(PartitionReadEvent readEvent, EffectTracker effectTracker, Key key)
{
this.partition.Assert(!key.Val.IsSingleton, "singletons are not read asynchronously");
Output output = default;
this.cacheDebugger?.Record(key.Val, CacheDebugger.CacheEvent.StartingRead, null, readEvent.EventIdString, 0);
var status = this.mainSession.Read(ref key, ref effectTracker, ref output, readEvent, 0);
if (status.IsCompletedSuccessfully)
{
// fast path: we hit in the cache and complete the read
this.StoreStats.HitCount++;
this.cacheDebugger?.Record(key.Val, CacheDebugger.CacheEvent.CompletedRead, null, readEvent.EventIdString, 0);
var target = status.Found ? output.Read(this, readEvent.EventIdString) : null;
this.cacheDebugger?.CheckVersionConsistency(key.Val, target, null);
effectTracker.ProcessReadResult(readEvent, key, target);
}
else if (status.IsPending)
{
// slow path: read continuation will be called when complete
this.StoreStats.MissCount++;
this.cacheDebugger?.Record(key.Val, CacheDebugger.CacheEvent.PendingRead, null, readEvent.EventIdString, 0);
this.effectTracker ??= effectTracker;
this.partition.Assert(this.effectTracker == effectTracker, "Only one EffectTracker per FasterKV");
this.pendingReads.Add((readEvent, key), this.partition.CurrentTimeMs);
}
else
{
this.partition.ErrorHandler.HandleError(nameof(ReadAsync), $"FASTER reported ERROR status 0x{status.Value:X2}", null, true, this.partition.ErrorHandler.IsTerminated);
}
}
void RetrySlowReads()
{
double threshold = this.partition.CurrentTimeMs - ReadRetryAfter;
var toRetry = this.pendingReads.Where(kvp => kvp.Value < threshold).ToList();
this.TraceHelper.FasterStorageProgress($"HangDetection limit={ReadRetryAfter / 1000:f0}s pending={this.pendingReads.Count} retry={toRetry.Count}");
//if (toRetry.Count > 0)
//{
// this.partition.Assert(toRetry.Count == 0, $"found a hanging read for {toRetry[0].Key.Item2}");
//}
foreach (var kvp in toRetry)
{
if (this.pendingReads.Remove(kvp.Key))
{
this.TryRead(kvp.Key.Item1, this.effectTracker, kvp.Key.Item2);
}
}
}
// read a tracked object on the main session and wait for the response (only one of these is executing at a time)
public override ValueTask<TrackedObject> ReadAsync(Key key, EffectTracker effectTracker)
{
this.partition.Assert(key.Val.IsSingleton, "only singletons expected in ReadAsync");
return new ValueTask<TrackedObject>(this.singletons[(int)key.Val.ObjectType]);
}
// create a tracked object on the main session (only one of these is executing at a time)
public override ValueTask<TrackedObject> CreateAsync(Key key)
{
this.partition.Assert(key.Val.IsSingleton, "only singletons expected in CreateAsync");
try
{
TrackedObject newObject = TrackedObjectKey.Factory(key);
newObject.Partition = this.partition;
this.singletons[(int)key.Val.ObjectType] = newObject;
return new ValueTask<TrackedObject>(newObject);
}
catch (Exception exception)
when (this.terminationToken.IsCancellationRequested && !Utils.IsFatal(exception))
{
throw new OperationCanceledException("Partition was terminated.", exception, this.terminationToken);
}
}
public async override ValueTask ProcessEffectOnTrackedObject(Key k, EffectTracker tracker)
{
try
{
if (k.Val.IsSingleton)
{
tracker.ProcessEffectOn(this.singletons[(int)k.Val.ObjectType]);
}
else
{
this.cacheDebugger?.Record(k, CacheDebugger.CacheEvent.StartingRMW, null, tracker.CurrentEventId, 0);
await this.PerformFasterRMWAsync(k, tracker);
this.cacheDebugger?.Record(k, CacheDebugger.CacheEvent.CompletedRMW, null, tracker.CurrentEventId, 0);
}
}
catch (Exception exception)
when (this.terminationToken.IsCancellationRequested && !Utils.IsFatal(exception))
{
throw new OperationCanceledException("Partition was terminated.", exception, this.terminationToken);
}
}
async ValueTask PerformFasterRMWAsync(Key k, EffectTracker tracker)
{
int numTries = 10;
while (true)
{
try
{
var rmwAsyncResult = await this.mainSession.RMWAsync(ref k, ref tracker, token: this.terminationToken);
bool IsComplete()
{
if (rmwAsyncResult.Status.IsCompletedSuccessfully)
{
return true;
}
else if (rmwAsyncResult.Status.IsPending)
{
return false;
}
else
{
string msg = $"Could not execute RMW in Faster, received status=0x{rmwAsyncResult.Status:X2}";
this.cacheDebugger?.Fail(msg, k);
throw new FasterException(msg);
}
}
if (IsComplete())
{
return;
}
while (true)
{
this.cacheDebugger?.Record(k, CacheDebugger.CacheEvent.PendingRMW, null, tracker.CurrentEventId, 0);
rmwAsyncResult = await rmwAsyncResult.CompleteAsync();
if (IsComplete())
{
return;
}
if (--numTries == 0)
{
this.cacheDebugger?.Fail($"Failed to execute RMW in Faster: status={rmwAsyncResult.Status.ToString()}", k);
throw new FasterException("Could not complete RMW even after all retries");
}
}
}
catch (Exception exception) when (!Utils.IsFatal(exception))
{
if (--numTries == 0)
{
this.cacheDebugger?.Fail($"Failed to execute RMW in Faster, encountered exception: {exception}", k);
throw;
}
}
}
}
public override ValueTask RemoveKeys(IEnumerable<TrackedObjectKey> keys)
{
foreach (var key in keys)
{
this.partition.Assert(!key.IsSingleton, "singletons cannot be deleted");
this.mainSession.Delete(key);
}
return default;
}
async IAsyncEnumerable<(string,OrchestrationState)> QueryEnumeratedStates(
EffectTracker effectTracker,
PartitionQueryEvent queryEvent,
IEnumerator<string> enumerator,
int pageSize,
TimeSpan timeBudget,
DateTime attempt
)
{
var instanceQuery = queryEvent.InstanceQuery;
string queryId = queryEvent.EventIdString;
int? pageLimit = pageSize > 0 ? pageSize : null;
this.partition.EventDetailTracer?.TraceEventProcessingDetail($"query {queryId} attempt {attempt:o} enumeration from {queryEvent.ContinuationToken} with pageLimit={(pageLimit.HasValue ? pageLimit.ToString() : "none")} timeBudget={timeBudget}");
Stopwatch stopwatch = Stopwatch.StartNew();
var channel = Channel.CreateBounded<(bool last, ValueTask<FasterKV<Key, Value>.ReadAsyncResult<EffectTracker, Output, object>> responseTask)>(200);
using var leftToFill = new SemaphoreSlim(pageLimit.HasValue ? pageLimit.Value : 100);
using var cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(this.partition.ErrorHandler.Token);
var cancellationToken = cancellationTokenSource.Token;
Task readIssueLoop = Task.Run(ReadIssueLoop);
async Task ReadIssueLoop()
{
try
{
while (enumerator.MoveNext())
{
if ((!string.IsNullOrEmpty(instanceQuery?.InstanceIdPrefix) && !enumerator.Current.StartsWith(instanceQuery.InstanceIdPrefix))
|| (instanceQuery.ExcludeEntities && DurableTask.Core.Common.Entities.IsEntityInstance(enumerator.Current)))
{
// the instance does not match the prefix
continue;
}
await leftToFill.WaitAsync(cancellationToken);
await channel.Writer.WaitToWriteAsync(cancellationToken).ConfigureAwait(false);
var readTask = this.ReadOnQuerySessionAsync(enumerator.Current, cancellationToken);
await channel.Writer.WriteAsync((false, readTask), cancellationToken).ConfigureAwait(false);
}
await channel.Writer.WriteAsync((true, default), cancellationToken).ConfigureAwait(false); // marks end of index
channel.Writer.Complete();
this.partition.EventDetailTracer?.TraceEventProcessingDetail($"query {queryId} attempt {attempt:o} enumeration finished because it reached end");
}
catch (OperationCanceledException)
{
this.partition.EventDetailTracer?.TraceEventProcessingDetail($"query {queryId} attempt {attempt:o} enumeration cancelled");
channel.Writer.TryComplete();
}
catch (Exception exception) when (this.terminationToken.IsCancellationRequested && !Utils.IsFatal(exception))
{