-
Notifications
You must be signed in to change notification settings - Fork 659
Expand file tree
/
Copy pathStateMachineDriverTests.cs
More file actions
457 lines (388 loc) · 18.8 KB
/
StateMachineDriverTests.cs
File metadata and controls
457 lines (388 loc) · 18.8 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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Allure.NUnit;
using Garnet.test;
using NUnit.Framework;
using NUnit.Framework.Legacy;
using Tsavorite.core;
namespace Tsavorite.test.recovery
{
using static Tsavorite.test.TestUtils;
using LongAllocator = BlittableAllocator<long, long, StoreFunctions<long, long, LongKeyComparer, DefaultRecordDisposer<long, long>>>;
using LongStoreFunctions = StoreFunctions<long, long, LongKeyComparer, DefaultRecordDisposer<long, long>>;
public abstract class StateMachineDriverTestsBase : AllureTestBase
{
readonly int numOpThreads = 2;
protected readonly int numKeys = 4;
readonly int numIterations = 3;
IDevice log;
protected bool opsDone;
protected long[] expectedV1Count;
protected long[] expectedV2Count;
protected int currentIteration;
protected void BaseSetup()
{
opsDone = false;
expectedV1Count = new long[numKeys];
expectedV2Count = new long[numKeys];
log = CreateTestDevice(TestDeviceType.LSD, Path.Join(MethodTestDir, "Test.log"));
}
protected void BaseTearDown()
{
log?.Dispose();
log = null;
OnTearDown(waitForDelete: true);
}
protected abstract void OperationThread(int thread_id, bool useTimingFuzzing, TsavoriteKV<long, long, LongStoreFunctions, LongAllocator> store);
public async ValueTask DoCheckpointVersionSwitchEquivalenceCheck(CheckpointType checkpointType, long indexSize, bool useTimingFuzzing)
{
// Create the original store
using var store1 = new TsavoriteKV<long, long, LongStoreFunctions, LongAllocator>(new()
{
IndexSize = indexSize,
LogDevice = log,
PageSize = 1L << 10,
MemorySize = 1L << 20,
CheckpointDir = MethodTestDir
}, StoreFunctions<long, long>.Create(LongKeyComparer.Instance)
, (allocatorSettings, storeFunctions) => new(allocatorSettings, storeFunctions)
);
for (currentIteration = 0; currentIteration < numIterations; currentIteration++)
{
opsDone = false;
// Start operation threads
var opTasks = new Task[numOpThreads];
for (int i = 0; i < numOpThreads; i++)
{
var thread_id = i;
opTasks[i] = Task.Run(() => OperationThread(thread_id, useTimingFuzzing, store1));
}
// Wait for some operations to complete in v1
await Task.Delay(500).ConfigureAwait(false);
// Initiate checkpoint concurrent to the operation threads
var task = store1.TakeFullCheckpointAsync(checkpointType);
// Wait for the checkpoint to complete
(var checkpointStatus, var checkpointToken) = await task.ConfigureAwait(false);
// Wait for some operations to complete in v2
await Task.Delay(500).ConfigureAwait(false);
// Signal operation threads to stop, and wait for them to finish
opsDone = true;
await Task.WhenAll(opTasks).ConfigureAwait(false);
// Verify the final state of the old store
using var s1 = store1.NewSession<long, long, Empty, SumFunctions>(new SumFunctions(0, false));
var bc1 = s1.BasicContext;
for (long key = 0; key < numKeys; key++)
{
long output = default;
var status = bc1.Read(ref key, ref output);
if (status.IsPending)
{
var completed = bc1.CompletePendingWithOutputs(out var completedOutputs, true);
ClassicAssert.IsTrue(completed);
bool result = completedOutputs.Next();
ClassicAssert.IsTrue(result);
status = completedOutputs.Current.Status;
output = completedOutputs.Current.Output;
result = completedOutputs.Next();
ClassicAssert.IsFalse(result);
}
ClassicAssert.IsTrue(status.Found, $"status = {status}");
// The old store should have the latest state
ClassicAssert.AreEqual(expectedV2Count[key], output, $"output = {output}");
}
// Recover new store from the checkpoint
using var store2 = new TsavoriteKV<long, long, LongStoreFunctions, LongAllocator>(new()
{
IndexSize = indexSize,
LogDevice = log,
MutableFraction = 1,
PageSize = 1L << 10,
MemorySize = 1L << 20,
CheckpointDir = MethodTestDir
}, StoreFunctions<long, long>.Create(LongKeyComparer.Instance)
, (allocatorSettings, storeFunctions) => new(allocatorSettings, storeFunctions));
_ = await store2.RecoverAsync(default, checkpointToken).ConfigureAwait(false);
// Verify the state of the new store
using var s2 = store2.NewSession<long, long, Empty, SumFunctions>(new SumFunctions(0, false));
var bc2 = s2.BasicContext;
for (long key = 0; key < numKeys; key++)
{
long output = default;
var status = bc2.Read(ref key, ref output);
if (status.IsPending)
{
var completed = bc2.CompletePendingWithOutputs(out var completedOutputs, true);
ClassicAssert.IsTrue(completed);
bool result = completedOutputs.Next();
ClassicAssert.IsTrue(result);
status = completedOutputs.Current.Status;
output = completedOutputs.Current.Output;
result = completedOutputs.Next();
ClassicAssert.IsFalse(result);
}
ClassicAssert.IsTrue(status.Found, $"status = {status}");
// The new store should have state as of V1, and not the latest state of the old store
ClassicAssert.AreEqual(expectedV1Count[key], output, $"output = {output}");
}
// Copy V2 counts to V1 counts for the next iteration
for (int i = 0; i < numKeys; i++)
{
expectedV1Count[i] = expectedV2Count[i];
}
}
}
public async ValueTask DoGrowIndexVersionSwitchEquivalenceCheck(long indexSize, bool useTimingFuzzing)
{
// Create the original store
using var store1 = new TsavoriteKV<long, long, LongStoreFunctions, LongAllocator>(new()
{
IndexSize = indexSize,
LogDevice = log,
PageSize = 1L << 10,
MemorySize = 1L << 20,
CheckpointDir = MethodTestDir
}, StoreFunctions<long, long>.Create(LongKeyComparer.Instance)
, (allocatorSettings, storeFunctions) => new(allocatorSettings, storeFunctions)
);
for (currentIteration = 0; currentIteration < numIterations; currentIteration++)
{
opsDone = false;
// Start operation threads
var opTasks = new Task[numOpThreads];
for (int i = 0; i < numOpThreads; i++)
{
var thread_id = i;
opTasks[i] = Task.Run(() => OperationThread(thread_id, useTimingFuzzing, store1));
}
// Wait for some operations to complete in v1
await Task.Delay(500).ConfigureAwait(false);
// Grow index concurrent to the operation threads
var growIndexStatus = await store1.GrowIndexAsync().ConfigureAwait(false);
ClassicAssert.IsTrue(growIndexStatus);
// Wait for some operations to complete in v2
await Task.Delay(500).ConfigureAwait(false);
// Signal operation threads to stop, and wait for them to finish
opsDone = true;
await Task.WhenAll(opTasks).ConfigureAwait(false);
// Verify the final state of the store
using var s1 = store1.NewSession<long, long, Empty, SumFunctions>(new SumFunctions(0, false));
var bc1 = s1.BasicContext;
for (long key = 0; key < numKeys; key++)
{
long output = default;
var status = bc1.Read(ref key, ref output);
if (status.IsPending)
{
var completed = bc1.CompletePendingWithOutputs(out var completedOutputs, true);
ClassicAssert.IsTrue(completed);
bool result = completedOutputs.Next();
ClassicAssert.IsTrue(result);
status = completedOutputs.Current.Status;
output = completedOutputs.Current.Output;
result = completedOutputs.Next();
ClassicAssert.IsFalse(result);
}
ClassicAssert.IsTrue(status.Found, $"status = {status}");
// The store should have the latest expected state
ClassicAssert.AreEqual(expectedV2Count[key], output, $"output = {output}");
}
}
}
public class SumFunctions : SimpleSimpleFunctions<long, long>
{
readonly Random fuzzer;
public SumFunctions(int thread_id, bool useTimingFuzzing) : base((l, r) => l + r)
{
if (useTimingFuzzing) fuzzer = new Random(thread_id);
}
public override bool InPlaceUpdater(ref long key, ref long input, ref long value, ref long output, ref RMWInfo rmwInfo, ref RecordInfo recordInfo)
{
Fuzz();
var ret = base.InPlaceUpdater(ref key, ref input, ref value, ref output, ref rmwInfo, ref recordInfo);
Fuzz();
return ret;
}
public override bool CopyUpdater(ref long key, ref long input, ref long oldValue, ref long newValue, ref long output, ref RMWInfo rmwInfo, ref RecordInfo recordInfo)
{
Fuzz();
var ret = base.CopyUpdater(ref key, ref input, ref oldValue, ref newValue, ref output, ref rmwInfo, ref recordInfo);
Fuzz();
return ret;
}
void Fuzz()
{
if (fuzzer != null) Thread.Sleep(fuzzer.Next(30));
}
}
}
[AllureNUnit]
[TestFixture]
public class CheckpointVersionSwitchRmw : StateMachineDriverTestsBase
{
[SetUp]
public void Setup() => BaseSetup();
[TearDown]
public void TearDown() => BaseTearDown();
protected override void OperationThread(int thread_id, bool useTimingFuzzing, TsavoriteKV<long, long, LongStoreFunctions, LongAllocator> store)
{
using var s = store.NewSession<long, long, Empty, SumFunctions>(new SumFunctions(thread_id, useTimingFuzzing));
var bc = s.BasicContext;
var r = new Random(thread_id);
long key = 0;
long input = 1;
var v1count = new long[numKeys];
var v2count = new long[numKeys];
while (!opsDone)
{
// Generate input for RMW
key = r.Next(numKeys);
// Run the RMW operation
_ = bc.RMW(ref key, ref input);
// Update expected counts for the old and new version of store
if (bc.Session.Version == currentIteration + 1)
v1count[key]++;
v2count[key]++;
}
// Update the global expected counts
for (int i = 0; i < numKeys; i++)
{
_ = Interlocked.Add(ref expectedV1Count[i], v1count[i]);
_ = Interlocked.Add(ref expectedV2Count[i], v2count[i]);
}
}
[Test]
public async ValueTask CheckpointVersionSwitchRmwTest(
[Values(CheckpointType.Snapshot, CheckpointType.FoldOver)] CheckpointType checkpointType,
[Values(1L << 13, 1L << 16)] long indexSize,
[Values] bool useTimingFuzzing)
=> await DoCheckpointVersionSwitchEquivalenceCheck(checkpointType, indexSize, useTimingFuzzing).ConfigureAwait(false);
[Test]
public async ValueTask GrowIndexVersionSwitchRmwTest(
[Values(1L << 13, 1L << 16)] long indexSize,
[Values] bool useTimingFuzzing)
=> await DoGrowIndexVersionSwitchEquivalenceCheck(indexSize, useTimingFuzzing).ConfigureAwait(false);
}
[AllureNUnit]
[TestFixture]
public class CheckpointVersionSwitchTxn : StateMachineDriverTestsBase
{
[SetUp]
public void Setup() => BaseSetup();
[TearDown]
public void TearDown() => BaseTearDown();
protected override void OperationThread(int thread_id, bool useTimingFuzzing, TsavoriteKV<long, long, LongStoreFunctions, LongAllocator> store)
{
using var s = store.NewSession<long, long, Empty, SumFunctions>(new SumFunctions(thread_id, useTimingFuzzing));
var lc = s.LockableContext;
var r = new Random(thread_id);
ClassicAssert.IsTrue(numKeys > 1);
long key1 = 0, key2 = 0;
long input = 1;
var v1count = new long[numKeys];
var v2count = new long[numKeys];
while (!opsDone)
{
// Generate input for transaction
key1 = r.Next(numKeys);
do
{
key2 = r.Next(numKeys);
} while (key2 == key1);
var exclusiveVec = new FixedLengthLockableKeyStruct<long>[] {
new(key1, LockType.Exclusive, lc),
new(key2, LockType.Exclusive, lc)
};
var txnVersion = store.stateMachineDriver.AcquireTransactionVersion();
// Start transaction, session does not acquire version in this call
lc.BeginLockable();
// Lock keys, session acquires version in this call
lc.Lock<FixedLengthLockableKeyStruct<long>>(exclusiveVec);
txnVersion = store.stateMachineDriver.VerifyTransactionVersion(txnVersion);
lc.LocksAcquired(txnVersion);
// Run transaction
_ = lc.RMW(ref key1, ref input);
_ = lc.RMW(ref key2, ref input);
// Unlock keys
lc.Unlock<FixedLengthLockableKeyStruct<long>>(exclusiveVec);
// End transaction
lc.EndLockable();
store.stateMachineDriver.EndTransaction(txnVersion);
// Update expected counts for the old and new version of store
if (txnVersion == currentIteration + 1)
{
v1count[key1]++;
v1count[key2]++;
}
v2count[key1]++;
v2count[key2]++;
}
// Update the global expected counts
for (int i = 0; i < numKeys; i++)
{
_ = Interlocked.Add(ref expectedV1Count[i], v1count[i]);
_ = Interlocked.Add(ref expectedV2Count[i], v2count[i]);
}
}
[Test]
public async ValueTask CheckpointVersionSwitchTxnTest(
[Values(CheckpointType.Snapshot, CheckpointType.FoldOver)] CheckpointType checkpointType,
[Values(1L << 13, 1L << 16)] long indexSize,
[Values] bool useTimingFuzzing)
=> await DoCheckpointVersionSwitchEquivalenceCheck(checkpointType, indexSize, useTimingFuzzing).ConfigureAwait(false);
[Test]
public async ValueTask GrowIndexVersionSwitchTxnTest(
[Values(1L << 13, 1L << 16)] long indexSize,
[Values] bool useTimingFuzzing)
=> await DoGrowIndexVersionSwitchEquivalenceCheck(indexSize, useTimingFuzzing).ConfigureAwait(false);
}
/// <summary>
/// Regression test for checkpoint deadlock with two-store checkpoints.
///
/// TrackLastVersion is called once per store during the IN_PROGRESS phase.
/// Without the fix, the second call overwrites lastVersionTransactionsDone,
/// orphaning the first semaphore in the waitingList. ProcessWaitingListAsync
/// then waits on it forever.
/// </summary>
[AllureNUnit]
[TestFixture]
public class TrackLastVersionTwoStoreDeadlock : AllureTestBase
{
[Test]
public async Task TrackLastVersionCalledTwiceDoesNotDeadlock()
{
var epoch = new LightEpoch();
try
{
var driver = new StateMachineDriver(epoch);
// Simulate an active transaction (e.g. Lua script touching both stores)
var txnVersion = driver.AcquireTransactionVersion();
// GlobalAfterEnteringState calls TrackLastVersion once per store
driver.TrackLastVersion(txnVersion); // MainStore
driver.TrackLastVersion(txnVersion); // ObjectStore
// Transaction completes
driver.EndTransaction(txnVersion);
// Verify all waitingList semaphores are released (not orphaned)
var waitingList = (System.Collections.Generic.List<System.Threading.SemaphoreSlim>)
typeof(StateMachineDriver)
.GetField("waitingList", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)
.GetValue(driver);
ClassicAssert.AreEqual(1, waitingList.Count,
"Expected 1 semaphore in waitingList, not 2. " +
"Two means the second TrackLastVersion call created a new semaphore " +
"that overwrote the first, orphaning it.");
var acquired = await waitingList[0].WaitAsync(System.TimeSpan.FromSeconds(5));
ClassicAssert.IsTrue(acquired,
"Semaphore was not released after EndTransaction. " +
"This causes ProcessWaitingListAsync to deadlock permanently.");
}
finally
{
epoch.Dispose();
}
}
}
}