-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
GBPTreeConcurrencyIT.java
639 lines (567 loc) · 22.5 KB
/
GBPTreeConcurrencyIT.java
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
/*
* Copyright (c) 2002-2017 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.index.internal.gbptree;
import org.apache.commons.lang3.mutable.MutableLong;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.RuleChain;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Random;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.LongStream;
import org.neo4j.cursor.RawCursor;
import org.neo4j.io.pagecache.IOLimiter;
import org.neo4j.io.pagecache.PageCache;
import org.neo4j.test.rule.PageCacheRule;
import org.neo4j.test.rule.RandomRule;
import org.neo4j.test.rule.TestDirectory;
import org.neo4j.test.rule.fs.DefaultFileSystemRule;
import static java.lang.Math.max;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.rules.RuleChain.outerRule;
import static org.neo4j.index.internal.gbptree.GBPTree.NO_HEADER;
import static org.neo4j.index.internal.gbptree.GBPTree.NO_HEADER_WRITER;
import static org.neo4j.index.internal.gbptree.GBPTree.NO_MONITOR;
import static org.neo4j.test.rule.PageCacheRule.config;
/**
* From a range of keys two disjunct sets are generated, "toAdd" and "toRemove".
* In each "iteration" writer will grab enough work from toAdd and toRemove to fill up one "batch".
* The batch will be applied to the GB+Tree during this iteration. The batch is also used to update
* a set of keys that all readers MUST see.
*
* Readers are allowed to see more keys because they race with concurrent insertions, but they should
* at least see every key that has been inserted in previous iterations or not yet removed in current
* or previous iterations.
*
* The {@link TestCoordinator} is responsible for "planning" the execution of the test. It generates
* toAdd and toRemove, prepare the GB+Tree with entries and serve readers and writer with information
* about what they should do next.
*/
public class GBPTreeConcurrencyIT
{
private final DefaultFileSystemRule fs = new DefaultFileSystemRule();
private final TestDirectory directory = TestDirectory.testDirectory( getClass(), fs.get() );
private final PageCacheRule pageCacheRule = new PageCacheRule();
private final RandomRule random = new RandomRule();
@Rule
public final RuleChain rules = outerRule( fs ).around( directory ).around( pageCacheRule ).around( random );
private final Layout<MutableLong,MutableLong> layout = new SimpleLongLayout();
private GBPTree<MutableLong,MutableLong> index;
private final ExecutorService threadPool =
Executors.newFixedThreadPool( Runtime.getRuntime().availableProcessors() );
private GBPTree<MutableLong,MutableLong> createIndex()
throws IOException
{
return createIndex( NO_MONITOR );
}
private GBPTree<MutableLong,MutableLong> createIndex( GBPTree.Monitor monitor )
throws IOException
{
int pageSize = 256;
PageCache pageCache =
pageCacheRule.getPageCache( fs.get(), config().withPageSize( pageSize ).withAccessChecks( true ) );
return index = new GBPTree<>( pageCache, directory.file( "index" ),
layout, 0/*use whatever page cache says*/, monitor, NO_HEADER, NO_HEADER_WRITER );
}
@After
public void consistencyCheckAndClose() throws IOException
{
threadPool.shutdownNow();
index.consistencyCheck();
index.close();
}
@Test
public void shouldReadForwardCorrectlyWithConcurrentInsert() throws Throwable
{
TestCoordinator testCoordinator = new TestCoordinator( random.random(), true, 1 );
shouldReadCorrectlyWithConcurrentUpdates( testCoordinator );
}
@Test
public void shouldReadBackwardCorrectlyWithConcurrentInsert() throws Throwable
{
TestCoordinator testCoordinator = new TestCoordinator( random.random(), false, 1 );
shouldReadCorrectlyWithConcurrentUpdates( testCoordinator );
}
@Test
public void shouldReadForwardCorrectlyWithConcurrentRemove() throws Throwable
{
TestCoordinator testCoordinator = new TestCoordinator( random.random(), true, 0 );
shouldReadCorrectlyWithConcurrentUpdates( testCoordinator );
}
@Test
public void shouldReadBackwardCorrectlyWithConcurrentRemove() throws Throwable
{
TestCoordinator testCoordinator = new TestCoordinator( random.random(), false, 0 );
shouldReadCorrectlyWithConcurrentUpdates( testCoordinator );
}
@Test
public void shouldReadForwardCorrectlyWithConcurrentUpdates() throws Throwable
{
TestCoordinator testCoordinator = new TestCoordinator( random.random(), true, 0.5 );
shouldReadCorrectlyWithConcurrentUpdates( testCoordinator );
}
@Test
public void shouldReadBackwardCorrectlyWithConcurrentUpdates() throws Throwable
{
TestCoordinator testCoordinator = new TestCoordinator( random.random(), false, 0.5 );
shouldReadCorrectlyWithConcurrentUpdates( testCoordinator );
}
private void shouldReadCorrectlyWithConcurrentUpdates( TestCoordinator testCoordinator ) throws Throwable
{
// Readers config
int readers = max( 1, Runtime.getRuntime().availableProcessors() - 1 );
// Thread communication
CountDownLatch readerReadySignal = new CountDownLatch( readers );
CountDownLatch readerStartSignal = new CountDownLatch( 1 );
AtomicBoolean endSignal = testCoordinator.endSignal();
AtomicBoolean failHalt = new AtomicBoolean(); // Readers signal to writer that there is a failure
AtomicReference<Throwable> readerError = new AtomicReference<>();
// GIVEN
index = createIndex();
testCoordinator.prepare( index );
// WHEN starting the readers
RunnableReader readerTask = new RunnableReader( testCoordinator, readerReadySignal, readerStartSignal,
endSignal, failHalt, readerError );
for ( int i = 0; i < readers; i++ )
{
threadPool.submit( readerTask );
}
// and starting the checkpointer
threadPool.submit( checkpointThread( endSignal, readerError, failHalt ) );
// and starting the writer
try
{
write( testCoordinator, readerReadySignal, readerStartSignal, endSignal, failHalt );
}
finally
{
// THEN no reader should have failed by the time we have finished all the scheduled updates.
// A successful read means that all results were ordered and we saw all inserted values and
// none of the removed values at the point of making the seek call.
endSignal.set( true );
threadPool.shutdown();
threadPool.awaitTermination( 10, TimeUnit.SECONDS );
if ( readerError.get() != null )
{
throw readerError.get();
}
}
}
private class TestCoordinator implements Supplier<ReaderInstruction>
{
private final Random random;
// Range
final long minRange = 0;
final long maxRange = 1 << 13; // 8192
// Instructions for writer
private final int writeBatchSize;
// Instructions for reader
private final boolean forwardsSeek;
private final double writePercentage;
private final AtomicReference<ReaderInstruction> currentReaderInstruction;
TreeSet<Long> readersShouldSee;
// Progress
private final AtomicBoolean endSignal;
// Control for ADD and REMOVE
Queue<Long> toRemove = new LinkedList<>();
Queue<Long> toAdd = new LinkedList<>();
List<UpdateOperation> updatesForNextIteration = new ArrayList<>();
TestCoordinator( Random random, boolean forwardsSeek, double writePercentage )
{
this.endSignal = new AtomicBoolean();
this.random = random;
this.forwardsSeek = forwardsSeek;
this.writePercentage = writePercentage;
this.writeBatchSize = random.nextInt( 990 ) + 10; // 10-999
currentReaderInstruction = new AtomicReference<>();
Comparator<Long> comparator = forwardsSeek ? Comparator.naturalOrder() : Comparator.reverseOrder();
readersShouldSee = new TreeSet<>( comparator );
}
List<Long> shuffleToNewList( List<Long> sourceList, Random random )
{
List<Long> shuffledList = new ArrayList<>( sourceList );
Collections.shuffle( shuffledList, random );
return shuffledList;
}
void prepare( GBPTree<MutableLong,MutableLong> index ) throws IOException
{
prepareIndex( index, readersShouldSee, toRemove, toAdd, random );
iterationFinished();
}
void prepareIndex( GBPTree<MutableLong,MutableLong> index, TreeSet<Long> dataInIndex,
Queue<Long> toRemove, Queue<Long> toAdd, Random random ) throws IOException
{
List<Long> fullRange = LongStream.range( minRange, maxRange ).boxed().collect( Collectors.toList() );
List<Long> rangeOutOfOrder = shuffleToNewList( fullRange, random );
try ( Writer<MutableLong, MutableLong> writer = index.writer() )
{
for ( Long key : rangeOutOfOrder )
{
boolean addForRemoval = random.nextDouble() > writePercentage;
if ( addForRemoval )
{
writer.put( new MutableLong( key ), new MutableLong( key ) );
dataInIndex.add( key );
toRemove.add( key );
}
else
{
toAdd.add( key );
}
}
}
}
void iterationFinished()
{
// Create new set to not modify set that readers use concurrently
TreeSet<Long> tmp = new TreeSet<>( readersShouldSee );
readersShouldSee = tmp;
updateRecentlyInsertedData( readersShouldSee, updatesForNextIteration );
updatesForNextIteration = generateUpdatesForNextIteration();
updateWithSoonToBeRemovedData( readersShouldSee, updatesForNextIteration );
currentReaderInstruction.set( newReaderInstruction( minRange, maxRange, readersShouldSee ) );
}
void updateRecentlyInsertedData( TreeSet<Long> readersShouldSee, List<UpdateOperation> updateBatch )
{
updateBatch.stream().filter( UpdateOperation::isInsert ).forEach( uo -> uo.applyToSet( readersShouldSee ) );
}
void updateWithSoonToBeRemovedData( TreeSet<Long> readersShouldSee, List<UpdateOperation> updateBatch )
{
updateBatch.stream().filter( uo -> !uo.isInsert() ).forEach( uo -> uo.applyToSet( readersShouldSee ) );
}
private ReaderInstruction newReaderInstruction( long minRange, long maxRange,
TreeSet<Long> readersShouldSee )
{
return forwardsSeek ?
new ReaderInstruction( minRange, maxRange, readersShouldSee ) :
new ReaderInstruction( maxRange - 1, minRange, readersShouldSee );
}
private List<UpdateOperation> generateUpdatesForNextIteration()
{
List<UpdateOperation> updateOperations = new ArrayList<>();
if ( toAdd.isEmpty() && toRemove.isEmpty() )
{
endSignal.set( true );
return updateOperations;
}
int operationsInIteration = readersShouldSee.size() < 1000 ? 100 : readersShouldSee.size() / 10;
int count = 0;
while ( count < operationsInIteration && (!toAdd.isEmpty() || !toRemove.isEmpty()) )
{
UpdateOperation operation;
if ( toAdd.isEmpty() )
{
operation = new RemoveOperation( toRemove.poll() );
}
else if ( toRemove.isEmpty() )
{
operation = new PutOperation( toAdd.poll() );
}
else
{
boolean remove = random.nextDouble() > writePercentage;
if ( remove )
{
operation = new RemoveOperation( toRemove.poll() );
}
else
{
operation = new PutOperation( toAdd.poll() );
}
}
updateOperations.add( operation );
count++;
}
return updateOperations;
}
Iterable<UpdateOperation> nextToWrite()
{
return updatesForNextIteration;
}
@Override
public ReaderInstruction get()
{
return currentReaderInstruction.get();
}
AtomicBoolean endSignal()
{
return endSignal;
}
int writeBatchSize()
{
return writeBatchSize;
}
boolean isReallyExpected( long nextToSee )
{
return readersShouldSee.contains( nextToSee );
}
}
private abstract class UpdateOperation
{
final long key;
UpdateOperation( long key )
{
this.key = key;
}
abstract void apply( Writer<MutableLong,MutableLong> writer ) throws IOException;
abstract void applyToSet( Set<Long> set );
abstract boolean isInsert();
}
private class PutOperation extends UpdateOperation
{
PutOperation( long key )
{
super( key );
}
@Override
void apply( Writer<MutableLong,MutableLong> writer ) throws IOException
{
writer.put( new MutableLong( key ), new MutableLong( key ) );
}
@Override
void applyToSet( Set<Long> set )
{
set.add( key );
}
@Override
boolean isInsert()
{
return true;
}
}
private class RemoveOperation extends UpdateOperation
{
RemoveOperation( long key )
{
super( key );
}
@Override
void apply( Writer<MutableLong,MutableLong> writer ) throws IOException
{
writer.remove( new MutableLong( key ) );
}
@Override
void applyToSet( Set<Long> set )
{
set.remove( key );
}
@Override
boolean isInsert()
{
return false;
}
}
private void write( TestCoordinator testCoordinator, CountDownLatch readerReadySignal,
CountDownLatch readerStartSignal,
AtomicBoolean endSignal, AtomicBoolean failHalt ) throws InterruptedException, IOException
{
assertTrue( readerReadySignal.await( 10, SECONDS ) ); // Ready, set...
readerStartSignal.countDown(); // GO!
while ( !failHalt.get() && !endSignal.get() )
{
writeOneIteration( testCoordinator, failHalt );
testCoordinator.iterationFinished();
}
}
private void writeOneIteration( TestCoordinator testCoordinator,
AtomicBoolean failHalt ) throws IOException, InterruptedException
{
int batchSize = testCoordinator.writeBatchSize();
Iterable<UpdateOperation> toWrite = testCoordinator.nextToWrite();
Iterator<UpdateOperation> toWriteIterator = toWrite.iterator();
while ( toWriteIterator.hasNext() )
{
try ( Writer<MutableLong,MutableLong> writer = index.writer() )
{
int inBatch = 0;
while ( toWriteIterator.hasNext() && inBatch < batchSize )
{
UpdateOperation operation = toWriteIterator.next();
operation.apply( writer );
if ( failHalt.get() )
{
break;
}
inBatch++;
}
}
// Sleep to allow checkpointer to step in
MILLISECONDS.sleep( 1 );
}
}
private class RunnableReader implements Runnable
{
private final CountDownLatch readerReadySignal;
private final CountDownLatch readerStartSignal;
private final AtomicBoolean endSignal;
private final AtomicBoolean failHalt;
private final AtomicReference<Throwable> readerError;
private final TestCoordinator testCoordinator;
RunnableReader( TestCoordinator testCoordinator, CountDownLatch readerReadySignal,
CountDownLatch readerStartSignal, AtomicBoolean endSignal,
AtomicBoolean failHalt, AtomicReference<Throwable> readerError )
{
this.readerReadySignal = readerReadySignal;
this.readerStartSignal = readerStartSignal;
this.endSignal = endSignal;
this.failHalt = failHalt;
this.readerError = readerError;
this.testCoordinator = testCoordinator;
}
@Override
public void run()
{
try
{
readerReadySignal.countDown(); // Ready, set...
readerStartSignal.await(); // GO!
while ( !endSignal.get() && !failHalt.get() )
{
doRead();
}
}
catch ( Throwable e )
{
readerError.set( e );
failHalt.set( true );
}
}
private void doRead() throws IOException
{
ReaderInstruction readerInstruction = testCoordinator.get();
Iterator<Long> expectToSee = readerInstruction.expectToSee().iterator();
long start = readerInstruction.start();
long end = readerInstruction.end();
boolean forward = start <= end;
try ( RawCursor<Hit<MutableLong,MutableLong>,IOException> cursor =
index.seek( new MutableLong( start ), new MutableLong( end ) ) )
{
if ( expectToSee.hasNext() )
{
long nextToSee = expectToSee.next();
while ( cursor.next() )
{
// Actual
long lastSeenKey = cursor.get().key().longValue();
long lastSeenValue = cursor.get().value().longValue();
if ( lastSeenKey != lastSeenValue )
{
fail( String.format( "Read mismatching key value pair, key=%d, value=%d%n",
lastSeenKey, lastSeenValue ) );
}
while ( (forward && lastSeenKey > nextToSee) ||
(!forward && lastSeenKey < nextToSee) )
{
if ( testCoordinator.isReallyExpected( nextToSee ) )
{
fail( String.format( "Expected to see %d but went straight to %d. ",
nextToSee, lastSeenKey ) );
}
if ( expectToSee.hasNext() )
{
nextToSee = expectToSee.next();
}
else
{
break;
}
}
if ( nextToSee == lastSeenKey )
{
if ( expectToSee.hasNext() )
{
nextToSee = expectToSee.next();
}
else
{
break;
}
}
}
}
}
}
}
private Runnable checkpointThread( AtomicBoolean endSignal, AtomicReference<Throwable> readerError,
AtomicBoolean failHalt )
{
return () ->
{
while ( !endSignal.get() )
{
try
{
index.checkpoint( IOLimiter.unlimited() );
// Sleep a little in between checkpoints
MILLISECONDS.sleep( 20L );
}
catch ( Throwable e )
{
readerError.set( e );
failHalt.set( true );
}
}
};
}
private class ReaderInstruction
{
private final long startRange;
private final long endRange;
private final TreeSet<Long> expectToSee;
ReaderInstruction( long startRange, long endRange, TreeSet<Long> expectToSee )
{
this.startRange = startRange;
this.endRange = endRange;
this.expectToSee = expectToSee;
}
long start()
{
return startRange;
}
long end()
{
return endRange;
}
TreeSet<Long> expectToSee()
{
return expectToSee;
}
}
}