-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
FullCheckIntegrationTest.java
2401 lines (2075 loc) · 90.3 KB
/
FullCheckIntegrationTest.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
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) 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.consistency.checking.full;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.mutable.MutableInt;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.RuleChain;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import org.neo4j.collection.primitive.PrimitiveLongCollections;
import org.neo4j.collection.primitive.PrimitiveLongSet;
import org.neo4j.consistency.ConsistencyCheckSettings;
import org.neo4j.consistency.RecordType;
import org.neo4j.consistency.checking.GraphStoreFixture;
import org.neo4j.consistency.checking.GraphStoreFixture.Applier;
import org.neo4j.consistency.checking.GraphStoreFixture.IdGenerator;
import org.neo4j.consistency.checking.GraphStoreFixture.TransactionDataBuilder;
import org.neo4j.consistency.report.ConsistencyReport;
import org.neo4j.consistency.report.ConsistencyReporter;
import org.neo4j.consistency.report.ConsistencySummaryStatistics;
import org.neo4j.graphdb.DependencyResolver;
import org.neo4j.graphdb.Direction;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.factory.GraphDatabaseSettings;
import org.neo4j.helpers.collection.Iterators;
import org.neo4j.helpers.collection.Pair;
import org.neo4j.helpers.progress.ProgressMonitorFactory;
import org.neo4j.kernel.api.ReadOperations;
import org.neo4j.kernel.api.TokenWriteOperations;
import org.neo4j.kernel.api.direct.DirectStoreAccess;
import org.neo4j.kernel.api.exceptions.KernelException;
import org.neo4j.kernel.api.exceptions.TransactionFailureException;
import org.neo4j.kernel.api.index.IndexAccessor;
import org.neo4j.kernel.api.index.IndexEntryUpdate;
import org.neo4j.kernel.api.index.IndexPopulator;
import org.neo4j.kernel.api.index.IndexUpdater;
import org.neo4j.kernel.api.index.SchemaIndexProvider;
import org.neo4j.kernel.api.labelscan.LabelScanStore;
import org.neo4j.kernel.api.labelscan.LabelScanWriter;
import org.neo4j.kernel.api.labelscan.NodeLabelUpdate;
import org.neo4j.kernel.api.schema.SchemaDescriptorFactory;
import org.neo4j.kernel.api.schema.constaints.ConstraintDescriptorFactory;
import org.neo4j.kernel.configuration.Config;
import org.neo4j.kernel.impl.annotations.Documented;
import org.neo4j.kernel.impl.api.KernelStatement;
import org.neo4j.kernel.impl.api.index.IndexUpdateMode;
import org.neo4j.kernel.impl.api.index.sampling.IndexSamplingConfig;
import org.neo4j.kernel.impl.core.ThreadToStatementContextBridge;
import org.neo4j.kernel.impl.store.AbstractDynamicStore;
import org.neo4j.kernel.impl.store.DynamicRecordAllocator;
import org.neo4j.kernel.impl.store.NodeLabelsField;
import org.neo4j.kernel.impl.store.PropertyType;
import org.neo4j.kernel.impl.store.RecordStore;
import org.neo4j.kernel.impl.store.SchemaStorage;
import org.neo4j.kernel.impl.store.SchemaStore;
import org.neo4j.kernel.impl.store.StoreAccess;
import org.neo4j.kernel.impl.store.allocator.ReusableRecordsAllocator;
import org.neo4j.kernel.impl.store.allocator.ReusableRecordsCompositeAllocator;
import org.neo4j.kernel.impl.store.record.ConstraintRule;
import org.neo4j.kernel.impl.store.record.DynamicRecord;
import org.neo4j.kernel.impl.store.record.IndexRule;
import org.neo4j.kernel.impl.store.record.LabelTokenRecord;
import org.neo4j.kernel.impl.store.record.NodeRecord;
import org.neo4j.kernel.impl.store.record.PropertyBlock;
import org.neo4j.kernel.impl.store.record.PropertyRecord;
import org.neo4j.kernel.impl.store.record.RelationshipGroupRecord;
import org.neo4j.kernel.impl.store.record.RelationshipRecord;
import org.neo4j.kernel.impl.store.record.RelationshipTypeTokenRecord;
import org.neo4j.kernel.impl.util.Bits;
import org.neo4j.kernel.internal.GraphDatabaseAPI;
import org.neo4j.logging.FormattedLog;
import org.neo4j.storageengine.api.schema.SchemaRule;
import org.neo4j.string.UTF8;
import org.neo4j.test.rule.SuppressOutput;
import static java.lang.String.format;
import static java.util.Arrays.asList;
import static java.util.Collections.singleton;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.neo4j.consistency.ConsistencyCheckService.defaultConsistencyCheckThreadsNumber;
import static org.neo4j.consistency.checking.RecordCheckTestBase.inUse;
import static org.neo4j.consistency.checking.RecordCheckTestBase.notInUse;
import static org.neo4j.consistency.checking.SchemaRuleUtil.constraintIndexRule;
import static org.neo4j.consistency.checking.SchemaRuleUtil.indexRule;
import static org.neo4j.consistency.checking.SchemaRuleUtil.nodePropertyExistenceConstraintRule;
import static org.neo4j.consistency.checking.SchemaRuleUtil.relPropertyExistenceConstraintRule;
import static org.neo4j.consistency.checking.SchemaRuleUtil.uniquenessConstraintRule;
import static org.neo4j.consistency.checking.full.FullCheckIntegrationTest.ConsistencySummaryVerifier.on;
import static org.neo4j.graphdb.Label.label;
import static org.neo4j.graphdb.RelationshipType.withName;
import static org.neo4j.helpers.collection.Iterables.asIterable;
import static org.neo4j.helpers.collection.MapUtil.stringMap;
import static org.neo4j.kernel.api.ReadOperations.ANY_LABEL;
import static org.neo4j.kernel.api.ReadOperations.ANY_RELATIONSHIP_TYPE;
import static org.neo4j.kernel.api.labelscan.NodeLabelUpdate.labelChanges;
import static org.neo4j.kernel.api.schema.index.IndexDescriptorFactory.forLabel;
import static org.neo4j.kernel.api.schema.index.IndexDescriptorFactory.uniqueForLabel;
import static org.neo4j.kernel.impl.store.AbstractDynamicStore.readFullByteArrayFromHeavyRecords;
import static org.neo4j.kernel.impl.store.DynamicArrayStore.allocateFromNumbers;
import static org.neo4j.kernel.impl.store.DynamicArrayStore.getRightArray;
import static org.neo4j.kernel.impl.store.DynamicNodeLabels.dynamicPointer;
import static org.neo4j.kernel.impl.store.LabelIdArray.prependNodeId;
import static org.neo4j.kernel.impl.store.PropertyType.ARRAY;
import static org.neo4j.kernel.impl.store.record.Record.NO_LABELS_FIELD;
import static org.neo4j.kernel.impl.store.record.Record.NO_NEXT_PROPERTY;
import static org.neo4j.kernel.impl.store.record.Record.NO_NEXT_RELATIONSHIP;
import static org.neo4j.kernel.impl.store.record.Record.NO_PREV_RELATIONSHIP;
import static org.neo4j.kernel.impl.store.record.RecordLoad.FORCE;
import static org.neo4j.kernel.impl.util.Bits.bits;
import static org.neo4j.test.Property.property;
import static org.neo4j.test.Property.set;
public class FullCheckIntegrationTest
{
private static final SchemaIndexProvider.Descriptor DESCRIPTOR = new SchemaIndexProvider.Descriptor( "lucene", "1.0" );
private static final String PROP1 = "key1";
private static final String PROP2 = "key2";
private static final Object VALUE1 = "value1";
private static final Object VALUE2 = "value2";
private int label1;
private int label2;
private int label3;
private int label4;
private int draconian;
private int key1;
private int key2;
private int mandatory;
private int C;
private int T;
private int M;
private final List<Long> indexedNodes = new ArrayList<>();
private static final Map<Class<?>,Set<String>> allReports = new HashMap<>();
@BeforeClass
public static void collectAllDifferentInconsistencyTypes()
{
Class<?> reportClass = ConsistencyReport.class;
for ( Class<?> cls : reportClass.getDeclaredClasses() )
{
for ( Method method : cls.getDeclaredMethods() )
{
if ( method.getAnnotation( Documented.class ) != null )
{
Set<String> types = allReports.get( cls );
if ( types == null )
{
allReports.put( cls, types = new HashSet<>() );
}
types.add( method.getName() );
}
}
}
}
@AfterClass
public static void verifyThatWeHaveExercisedAllTypesOfInconsistenciesThatWeHave()
{
if ( !allReports.isEmpty() )
{
StringBuilder builder = new StringBuilder( "There are types of inconsistencies not covered by "
+ "this integration test, please add tests that tests for:" );
for ( Map.Entry<Class<?>,Set<String>> reporter : allReports.entrySet() )
{
builder.append( format( "%n%s:", reporter.getKey().getSimpleName() ) );
for ( String type : reporter.getValue() )
{
builder.append( format( "%n %s", type ) );
}
}
System.err.println( builder.toString() );
}
}
private final GraphStoreFixture fixture = new GraphStoreFixture( getRecordFormatName() )
{
@Override
protected void generateInitialData( GraphDatabaseService db )
{
try ( org.neo4j.graphdb.Transaction tx = db.beginTx() )
{
db.schema().indexFor( label( "label3" ) ).on( PROP1 ).create();
// the Core API for composite index creation is not quite merged yet
key1 = tokenWriteOperationsOn( db ).propertyKeyGetOrCreateForName( PROP1 );
key2 = tokenWriteOperationsOn( db ).propertyKeyGetOrCreateForName( PROP2 );
label3 = readOperationsOn( db ).labelGetForName( "label3" );
statementOn( db ).schemaWriteOperations().indexCreate(
SchemaDescriptorFactory.forLabel( label3, key1, key2 ) );
db.schema().constraintFor( label( "label4" ) ).assertPropertyIsUnique( PROP1 ).create();
tx.success();
}
catch ( KernelException e )
{
throw new RuntimeException( e );
}
try ( org.neo4j.graphdb.Transaction ignored = db.beginTx() )
{
db.schema().awaitIndexesOnline( 1, TimeUnit.MINUTES );
}
try ( org.neo4j.graphdb.Transaction tx = db.beginTx() )
{
Node node1 = set( db.createNode( label( "label1" ) ) );
Node node2 = set( db.createNode( label( "label2" ) ), property( PROP1, VALUE1 ) );
node1.createRelationshipTo( node2, withName( "C" ) );
// Just to create one more rel type
db.createNode().createRelationshipTo( db.createNode(), withName( "T" ) );
indexedNodes.add( set( db.createNode( label( "label3" ) ), property( PROP1, VALUE1 ) ).getId() );
indexedNodes.add( set( db.createNode( label( "label3" ) ),
property( PROP1, VALUE1 ), property( PROP2, VALUE2 ) ).getId() );
set( db.createNode( label( "label4" ) ), property( PROP1, VALUE1 ) );
tx.success();
label1 = readOperationsOn( db ).labelGetForName( "label1" );
label2 = readOperationsOn( db ).labelGetForName( "label2" );
label3 = readOperationsOn( db ).labelGetForName( "label3" );
label4 = readOperationsOn( db ).labelGetForName( "label4" );
draconian = tokenWriteOperationsOn( db ).labelGetOrCreateForName( "draconian" );
key1 = readOperationsOn( db ).propertyKeyGetForName( PROP1 );
mandatory = tokenWriteOperationsOn( db ).propertyKeyGetOrCreateForName( "mandatory" );
C = readOperationsOn( db ).relationshipTypeGetForName( "C" );
T = readOperationsOn( db ).relationshipTypeGetForName( "T" );
M = tokenWriteOperationsOn( db ).relationshipTypeGetOrCreateForName( "M" );
}
catch ( KernelException e )
{
throw new RuntimeException( e );
}
}
};
private final SuppressOutput suppressOutput = SuppressOutput.suppress( SuppressOutput.System.out );
@Rule
public RuleChain ruleChain = RuleChain.outerRule( suppressOutput ).around( fixture );
@Test
public void shouldCheckConsistencyOfAConsistentStore() throws Exception
{
// when
ConsistencySummaryStatistics result = check();
// then
assertEquals( result.toString(), 0, result.getTotalInconsistencyCount() );
}
@Test
public void shouldReportNodeInconsistencies() throws Exception
{
// given
fixture.apply( new GraphStoreFixture.Transaction()
{
@Override
protected void transactionData( GraphStoreFixture.TransactionDataBuilder tx,
GraphStoreFixture.IdGenerator next )
{
tx.create( new NodeRecord( next.node(), false, next.relationship(), -1 ) );
}
} );
// when
ConsistencySummaryStatistics stats = check();
// then
on( stats ).verify( RecordType.NODE, 1 )
.andThatsAllFolks();
}
@Test
public void shouldReportInlineNodeLabelInconsistencies() throws Exception
{
// given
fixture.apply( new GraphStoreFixture.Transaction()
{
@Override
protected void transactionData( GraphStoreFixture.TransactionDataBuilder tx,
GraphStoreFixture.IdGenerator next )
{
NodeRecord nodeRecord = new NodeRecord( next.node(), false, -1, -1 );
NodeLabelsField.parseLabelsField( nodeRecord ).add( 10, null, null );
tx.create( nodeRecord );
}
} );
// when
ConsistencySummaryStatistics stats = check();
// then
on( stats ).verify( RecordType.NODE, 1 )
.andThatsAllFolks();
}
@Test
public void shouldReportNodeDynamicLabelContainingUnknownLabelAsNodeInconsistency() throws Exception
{
// given
fixture.apply( new GraphStoreFixture.Transaction()
{
@Override
protected void transactionData( GraphStoreFixture.TransactionDataBuilder tx,
GraphStoreFixture.IdGenerator next )
{
NodeRecord nodeRecord = new NodeRecord( next.node(), false, -1, -1 );
DynamicRecord record = inUse( new DynamicRecord( next.nodeLabel() ) );
Collection<DynamicRecord> newRecords = new ArrayList<>();
allocateFromNumbers( newRecords, prependNodeId( nodeRecord.getId(), new long[]{42L} ),
new ReusableRecordsAllocator( 60, record ) );
nodeRecord.setLabelField( dynamicPointer( newRecords ), newRecords );
tx.create( nodeRecord );
}
} );
// when
ConsistencySummaryStatistics stats = check();
// then
on( stats ).verify( RecordType.NODE, 1 )
.andThatsAllFolks();
}
@Test
public void shouldNotReportAnythingForNodeWithConsistentChainOfDynamicRecordsWithLabels() throws Exception
{
// given
assertEquals( 3, chainOfDynamicRecordsWithLabelsForANode( 130 ).first().size() );
// when
ConsistencySummaryStatistics stats = check();
// then
assertTrue( "should be consistent", stats.isConsistent() );
}
@Test
public void shouldReportLabelScanStoreInconsistencies() throws Exception
{
// given
GraphStoreFixture.IdGenerator idGenerator = fixture.idGenerator();
long nodeId1 = idGenerator.node();
long labelId = idGenerator.label() - 1;
LabelScanStore labelScanStore = fixture.directStoreAccess().labelScanStore();
Iterable<NodeLabelUpdate> nodeLabelUpdates = asIterable(
labelChanges( nodeId1, new long[]{}, new long[]{labelId} )
);
write( labelScanStore, nodeLabelUpdates );
// when
ConsistencySummaryStatistics stats = check();
// then
on( stats ).verify( RecordType.LABEL_SCAN_DOCUMENT, 1 )
.andThatsAllFolks();
}
private void write( LabelScanStore labelScanStore, Iterable<NodeLabelUpdate> nodeLabelUpdates )
throws IOException
{
try ( LabelScanWriter writer = labelScanStore.newWriter() )
{
for ( NodeLabelUpdate update : nodeLabelUpdates )
{
writer.write( update );
}
}
}
@Test
public void shouldReportIndexInconsistencies() throws Exception
{
// given
for ( Long indexedNodeId : indexedNodes )
{
fixture.directStoreAccess().nativeStores().getNodeStore().updateRecord(
notInUse( new NodeRecord( indexedNodeId, false, -1, -1 ) ) );
}
// when
ConsistencySummaryStatistics stats = check();
// then
on( stats ).verify( RecordType.INDEX, 3 ) // 3 index entries are pointing to nodes not in use
.verify( RecordType.LABEL_SCAN_DOCUMENT, 2 ) // the label scan is pointing to 2 nodes not in use
.verify( RecordType.COUNTS, 3 )
.andThatsAllFolks();
}
@Test
public void shouldNotReportIndexInconsistenciesIfIndexIsFailed() throws Exception
{
// this test fails all indexes, and then destroys a record and makes sure we only get a failure for
// the label scan store but not for any index
// given
DirectStoreAccess storeAccess = fixture.directStoreAccess();
// fail all indexes
Iterator<IndexRule> rules = new SchemaStorage( storeAccess.nativeStores().getSchemaStore() ).indexesGetAll();
while ( rules.hasNext() )
{
IndexRule rule = rules.next();
IndexSamplingConfig samplingConfig = new IndexSamplingConfig( Config.empty() );
IndexPopulator populator =
storeAccess.indexes().getPopulator( rule.getId(), rule.getIndexDescriptor(), samplingConfig );
populator.markAsFailed( "Oh noes! I was a shiny index and then I was failed" );
populator.close( false );
}
for ( Long indexedNodeId : indexedNodes )
{
storeAccess.nativeStores().getNodeStore().updateRecord(
notInUse( new NodeRecord( indexedNodeId, false, -1, -1 ) ) );
}
// when
ConsistencySummaryStatistics stats = check();
// then
on( stats ).verify( RecordType.LABEL_SCAN_DOCUMENT, 2 ) // the label scan is pointing to 2 nodes not in use
.verify( RecordType.COUNTS, 3 )
.andThatsAllFolks();
}
@Test
public void shouldReportMismatchedLabels() throws Exception
{
final List<Integer> labels = new ArrayList<>();
// given
final Pair<List<DynamicRecord>, List<Integer>> pair = chainOfDynamicRecordsWithLabelsForANode( 3 );
fixture.apply( new GraphStoreFixture.Transaction()
{
@Override
protected void transactionData( GraphStoreFixture.TransactionDataBuilder tx,
GraphStoreFixture.IdGenerator next )
{
NodeRecord node = new NodeRecord( 42, false, -1, -1 );
node.setInUse( true );
List<DynamicRecord> dynamicRecords;
dynamicRecords = pair.first();
labels.addAll( pair.other() );
node.setLabelField( dynamicPointer( dynamicRecords ), dynamicRecords );
tx.create( node );
}
} );
long[] before = asArray( labels );
labels.remove( 1 );
long[] after = asArray( labels );
write( fixture.directStoreAccess().labelScanStore(), asList( labelChanges( 42, before, after ) ) );
// when
ConsistencySummaryStatistics stats = check();
// then
on( stats ).verify( RecordType.LABEL_SCAN_DOCUMENT, 1 )
.andThatsAllFolks();
}
private long[] asArray( List<? extends Number> in )
{
long[] longs = new long[in.size()];
for ( int i = 0; i < in.size(); i++ )
{
longs[i] = in.get( i ).longValue();
}
return longs;
}
private PrimitiveLongSet asPrimitiveLongSet( List<? extends Number> in )
{
return PrimitiveLongCollections.setOf( asArray( in ) );
}
@Test
public void shouldReportMismatchedInlinedLabels() throws Exception
{
// given
fixture.apply( new GraphStoreFixture.Transaction()
{
@Override
protected void transactionData( GraphStoreFixture.TransactionDataBuilder tx,
GraphStoreFixture.IdGenerator next )
{
NodeRecord node = new NodeRecord( 42, false, -1, -1 );
node.setInUse( true );
node.setLabelField( inlinedLabelsLongRepresentation( label1, label2 ), Collections.<DynamicRecord>emptySet() );
tx.create( node );
}
} );
write( fixture.directStoreAccess().labelScanStore(), asList( labelChanges( 42, new long[]{label1, label2}, new long[]{label1} ) ) );
// when
ConsistencySummaryStatistics stats = check();
// then
on( stats ).verify( RecordType.LABEL_SCAN_DOCUMENT, 1 )
.andThatsAllFolks();
}
@Test
public void shouldReportNodesThatAreNotIndexed() throws Exception
{
// given
IndexSamplingConfig samplingConfig = new IndexSamplingConfig( Config.empty() );
Iterator<IndexRule> indexRuleIterator =
new SchemaStorage( fixture.directStoreAccess().nativeStores().getSchemaStore() ).indexesGetAll();
while ( indexRuleIterator.hasNext() )
{
IndexRule indexRule = indexRuleIterator.next();
IndexAccessor accessor = fixture.directStoreAccess().indexes().getOnlineAccessor(
indexRule.getId(), indexRule.getIndexDescriptor(), samplingConfig );
IndexUpdater updater = accessor.newUpdater( IndexUpdateMode.ONLINE );
updater.remove( asPrimitiveLongSet( indexedNodes ) );
updater.close();
accessor.close();
}
// when
ConsistencySummaryStatistics stats = check();
// then
on( stats ).verify( RecordType.NODE, 3 ) // 1 node missing from 1 index + 1 node missing from 2 indexes
.andThatsAllFolks();
}
@Test
public void shouldReportNodesWithDuplicatePropertyValueInUniqueIndex() throws Exception
{
// given
IndexSamplingConfig samplingConfig = new IndexSamplingConfig( Config.empty() );
Iterator<IndexRule> indexRuleIterator =
new SchemaStorage( fixture.directStoreAccess().nativeStores().getSchemaStore() ).indexesGetAll();
while ( indexRuleIterator.hasNext() )
{
IndexRule indexRule = indexRuleIterator.next();
IndexAccessor accessor = fixture.directStoreAccess().indexes()
.getOnlineAccessor( indexRule.getId(), indexRule.getIndexDescriptor(), samplingConfig );
IndexUpdater updater = accessor.newUpdater( IndexUpdateMode.ONLINE );
updater.process( IndexEntryUpdate.add( 42, indexRule.getIndexDescriptor().schema(), values( indexRule ) ) );
updater.close();
accessor.close();
}
// when
ConsistencySummaryStatistics stats = check();
// then
on( stats ).verify( RecordType.NODE, 1 ) // the duplicate in unique index
.verify( RecordType.INDEX, 3 ) // the index entries pointing to non-existent node 42
.andThatsAllFolks();
}
private Object[] values( IndexRule indexRule )
{
switch ( indexRule.schema().getPropertyIds().length )
{
case 1: return Iterators.array( VALUE1 );
case 2: return Iterators.array( VALUE1, VALUE2 );
default: throw new UnsupportedOperationException();
}
}
@Test
public void shouldReportMissingMandatoryNodeProperty() throws Exception
{
// given
fixture.apply( new GraphStoreFixture.Transaction()
{
@Override
protected void transactionData( GraphStoreFixture.TransactionDataBuilder tx,
GraphStoreFixture.IdGenerator next )
{
// structurally correct, but does not have the 'mandatory' property with the 'draconian' label
NodeRecord node = new NodeRecord( next.node(), false, -1, next.property() );
node.setInUse( true );
node.setLabelField( inlinedLabelsLongRepresentation( draconian ),
Collections.<DynamicRecord>emptySet() );
PropertyRecord property = new PropertyRecord( node.getNextProp(), node );
property.setInUse( true );
PropertyBlock block = new PropertyBlock();
block.setSingleBlock( key1 | (((long) PropertyType.INT.intValue()) << 24) | (1337L << 28) );
property.addPropertyBlock( block );
tx.create( node );
tx.create( property );
}
} );
createNodePropertyExistenceConstraint( draconian, mandatory );
// when
ConsistencySummaryStatistics stats = check();
// then
on( stats ).verify( RecordType.NODE, 1 )
.andThatsAllFolks();
}
@Test
public void shouldReportMissingMandatoryRelationshipProperty() throws Exception
{
// given
fixture.apply( new GraphStoreFixture.Transaction()
{
@Override
protected void transactionData( GraphStoreFixture.TransactionDataBuilder tx,
GraphStoreFixture.IdGenerator next )
{
long nodeId1 = next.node();
long nodeId2 = next.node();
long relId = next.relationship();
long propId = next.property();
NodeRecord node1 = new NodeRecord( nodeId1, true, false, relId, NO_NEXT_PROPERTY.intValue(),
NO_LABELS_FIELD.intValue() );
NodeRecord node2 = new NodeRecord( nodeId2, true, false, relId, NO_NEXT_PROPERTY.intValue(),
NO_LABELS_FIELD.intValue() );
// structurally correct, but does not have the 'mandatory' property with the 'M' rel type
RelationshipRecord relationship = new RelationshipRecord( relId, true, nodeId1, nodeId2, M,
NO_PREV_RELATIONSHIP.intValue(), NO_NEXT_RELATIONSHIP.intValue(),
NO_PREV_RELATIONSHIP.intValue(), NO_NEXT_RELATIONSHIP.intValue(), true, true );
relationship.setNextProp( propId );
PropertyRecord property = new PropertyRecord( propId, relationship );
property.setInUse( true );
PropertyBlock block = new PropertyBlock();
block.setSingleBlock( key1 | (((long) PropertyType.INT.intValue()) << 24) | (1337L << 28) );
property.addPropertyBlock( block );
tx.create( node1 );
tx.create( node2 );
tx.create( relationship );
tx.create( property );
tx.incrementRelationshipCount( ANY_LABEL, ANY_RELATIONSHIP_TYPE, ANY_LABEL, 1 );
tx.incrementRelationshipCount( ANY_LABEL, M, ANY_LABEL, 1 );
}
} );
createRelationshipPropertyExistenceConstraint( M, mandatory );
// when
ConsistencySummaryStatistics stats = check();
// then
on( stats ).verify( RecordType.RELATIONSHIP, 1 )
.andThatsAllFolks();
}
private long inlinedLabelsLongRepresentation( long... labelIds )
{
long header = (long) labelIds.length << 36;
byte bitsPerLabel = (byte) (36 / labelIds.length);
Bits bits = bits( 5 );
for ( long labelId : labelIds )
{
bits.put( labelId, bitsPerLabel );
}
return header | bits.getLongs()[0];
}
@Test
public void shouldReportCyclesInDynamicRecordsWithLabels() throws Exception
{
// given
final List<DynamicRecord> chain = chainOfDynamicRecordsWithLabelsForANode( 176/*3 full records*/ ).first();
assertEquals( "number of records in chain", 3, chain.size() );
assertEquals( "all records full", chain.get( 0 ).getLength(), chain.get( 2 ).getLength() );
fixture.apply( new GraphStoreFixture.Transaction()
{
@Override
protected void transactionData( GraphStoreFixture.TransactionDataBuilder tx,
GraphStoreFixture.IdGenerator next )
{
long nodeId = ((long[]) getRightArray( readFullByteArrayFromHeavyRecords( chain, ARRAY ) ))[0];
NodeRecord before = inUse( new NodeRecord( nodeId, false, -1, -1 ) );
NodeRecord after = inUse( new NodeRecord( nodeId, false, -1, -1 ) );
DynamicRecord record1 = chain.get( 0 ).clone();
DynamicRecord record2 = chain.get( 1 ).clone();
DynamicRecord record3 = chain.get( 2 ).clone();
record3.setNextBlock( record2.getId() );
before.setLabelField( dynamicPointer( chain ), chain );
after.setLabelField( dynamicPointer( chain ), asList( record1, record2, record3 ) );
tx.update( before, after );
}
} );
// when
ConsistencySummaryStatistics stats = check();
// then
on( stats ).verify( RecordType.NODE, 1 )
.verify( RecordType.COUNTS, 177 )
.andThatsAllFolks();
}
private Pair<List<DynamicRecord>,List<Integer>> chainOfDynamicRecordsWithLabelsForANode( int labelCount )
throws TransactionFailureException
{
final long[] labels = new long[labelCount + 1]; // allocate enough labels to need three records
final List<Integer> createdLabels = new ArrayList<>();
try ( Applier applier = fixture.createApplier() )
{
for ( int i = 1/*leave space for the node id*/; i < labels.length; i++ )
{
final int offset = i;
applier.apply( new GraphStoreFixture.Transaction()
{ // Neo4j can create no more than one label per transaction...
@Override
protected void transactionData( GraphStoreFixture.TransactionDataBuilder tx,
GraphStoreFixture.IdGenerator next )
{
Integer label = next.label();
tx.nodeLabel( (int) (labels[offset] = label), "label:" + offset );
createdLabels.add( label );
}
} );
}
}
final List<DynamicRecord> chain = new ArrayList<>();
fixture.apply( new GraphStoreFixture.Transaction()
{
@Override
protected void transactionData( GraphStoreFixture.TransactionDataBuilder tx,
GraphStoreFixture.IdGenerator next )
{
NodeRecord nodeRecord = new NodeRecord( next.node(), false, -1, -1 );
DynamicRecord record1 = inUse( new DynamicRecord( next.nodeLabel() ) );
DynamicRecord record2 = inUse( new DynamicRecord( next.nodeLabel() ) );
DynamicRecord record3 = inUse( new DynamicRecord( next.nodeLabel() ) );
labels[0] = nodeRecord.getId(); // the first id should not be a label id, but the id of the node
ReusableRecordsAllocator allocator = new ReusableRecordsAllocator( 60, record1, record2, record3 );
allocateFromNumbers( chain, labels, allocator );
nodeRecord.setLabelField( dynamicPointer( chain ), chain );
tx.create( nodeRecord );
}
} );
return Pair.of( chain, createdLabels );
}
@Test
public void shouldReportNodeDynamicLabelContainingDuplicateLabelAsNodeInconsistency() throws Exception
{
int nodeId = 1000;
Collection<DynamicRecord> duplicatedLabel = new ArrayList<>();
final Pair<List<DynamicRecord>, List<Integer>> labels = chainOfDynamicRecordsWithLabelsForANode( 1 );
// given
fixture.apply( new GraphStoreFixture.Transaction()
{
@Override
protected void transactionData( GraphStoreFixture.TransactionDataBuilder tx,
GraphStoreFixture.IdGenerator next )
{
NodeRecord node = new NodeRecord( nodeId, false, -1, -1 );
node.setInUse( true );
List<DynamicRecord> labelRecords = labels.first();
node.setLabelField( dynamicPointer( labelRecords ), labelRecords );
tx.create( node );
Integer labelId = labels.other().get( 0 );
DynamicRecord record = inUse( new DynamicRecord( labelId ) );
allocateFromNumbers( duplicatedLabel, new long[]{nodeId, labelId, labelId}, new ReusableRecordsAllocator( 60, record ) );
}
} );
StoreAccess storeAccess = fixture.directStoreAccess().nativeStores();
NodeRecord nodeRecord = new NodeRecord( nodeId );
storeAccess.getNodeStore().getRecord( nodeId, nodeRecord, FORCE );
nodeRecord.setLabelField( dynamicPointer( duplicatedLabel ), duplicatedLabel );
nodeRecord.setInUse( true );
storeAccess.getNodeStore().updateRecord( nodeRecord );
// when
ConsistencySummaryStatistics stats = check();
// then
on( stats ).verify( RecordType.NODE, 1 ) // the duplicated label
.verify( RecordType.COUNTS, 0 )
.andThatsAllFolks();
}
@Test
public void shouldReportOrphanedNodeDynamicLabelAsNodeInconsistency() throws Exception
{
// given
fixture.apply( new GraphStoreFixture.Transaction()
{
@Override
protected void transactionData( GraphStoreFixture.TransactionDataBuilder tx,
GraphStoreFixture.IdGenerator next )
{
tx.nodeLabel( 42, "Label" );
NodeRecord nodeRecord = new NodeRecord( next.node(), false, -1, -1 );
DynamicRecord record = inUse( new DynamicRecord( next.nodeLabel() ) );
Collection<DynamicRecord> newRecords = new ArrayList<>();
allocateFromNumbers( newRecords, prependNodeId( next.node(), new long[]{42L} ),
new ReusableRecordsAllocator( 60, record ) );
nodeRecord.setLabelField( dynamicPointer( newRecords ), newRecords );
tx.create( nodeRecord );
}
} );
// when
ConsistencySummaryStatistics stats = check();
// then
on( stats ).verify( RecordType.NODE_DYNAMIC_LABEL, 1 )
.andThatsAllFolks();
}
@Test
public void shouldReportRelationshipInconsistencies() throws Exception
{
// given
fixture.apply( new GraphStoreFixture.Transaction()
{
@Override
protected void transactionData( GraphStoreFixture.TransactionDataBuilder tx,
GraphStoreFixture.IdGenerator next )
{
tx.create( new RelationshipRecord( next.relationship(), 1, 2, C ) );
}
} );
// when
ConsistencySummaryStatistics stats = check();
// then
on( stats ).verify( RecordType.RELATIONSHIP, 2 )
.verify( RecordType.COUNTS, 3 )
.andThatsAllFolks();
}
@Test
public void shouldReportRelationshipOtherNodeInconsistencies() throws Exception
{
// given
fixture.apply( new GraphStoreFixture.Transaction()
{
@Override
protected void transactionData( GraphStoreFixture.TransactionDataBuilder tx,
GraphStoreFixture.IdGenerator next )
{
long node1 = next.node();
long node2 = next.node();
long rel = next.relationship();
tx.create( inUse( new RelationshipRecord( rel, node1, node2, 0 ) ) );
tx.create( inUse( new NodeRecord( node1, false, rel + 1, -1 ) ) );
tx.create( inUse( new NodeRecord( node2, false, rel + 2, -1 ) ) );
}
} );
// when
ConsistencySummaryStatistics stats = check();
// then
on( stats ).verify( RecordType.RELATIONSHIP, 2 )
.verify( RecordType.NODE, 2 )
.verify( RecordType.COUNTS, 2 )
.andThatsAllFolks();
}
@Test
public void shouldReportPropertyInconsistencies() throws Exception
{
// given
fixture.apply( new GraphStoreFixture.Transaction()
{
@Override
protected void transactionData( GraphStoreFixture.TransactionDataBuilder tx,
GraphStoreFixture.IdGenerator next )
{
NodeRecord node = new NodeRecord( next.node() );
PropertyRecord property = new PropertyRecord( next.property() );
node.setNextProp( property.getId() );
// Mess up the prev/next pointers a bit
property.setNextProp( 1_000 );
PropertyBlock block = new PropertyBlock();
block.setSingleBlock( next.propertyKey() | (((long) PropertyType.INT.intValue()) << 24) | (666L << 28) );
property.addPropertyBlock( block );
tx.create( node );
tx.create( property );
}
} );
// when
ConsistencySummaryStatistics stats = check();
// then
on( stats ).verify( RecordType.PROPERTY, 2 )
.verify( RecordType.NODE, 1 )
.andThatsAllFolks();
}
@Test
public void shouldReportStringPropertyInconsistencies() throws Exception
{
// given
fixture.apply( new GraphStoreFixture.Transaction()
{
@Override
protected void transactionData( GraphStoreFixture.TransactionDataBuilder tx,
GraphStoreFixture.IdGenerator next )
{
DynamicRecord string = new DynamicRecord( next.stringProperty() );
string.setInUse( true );
string.setCreated();
string.setType( PropertyType.STRING.intValue() );
string.setNextBlock( next.stringProperty() );
string.setData( UTF8.encode( "hello world" ) );
PropertyBlock block = new PropertyBlock();
block.setSingleBlock( (((long) PropertyType.STRING.intValue()) << 24) | (string.getId() << 28) );
block.addValueRecord( string );
PropertyRecord property = new PropertyRecord( next.property() );
property.addPropertyBlock( block );
tx.create( property );
}
} );
// when
ConsistencySummaryStatistics stats = check();
// then
on( stats ).verify( RecordType.STRING_PROPERTY, 1 )
.andThatsAllFolks();
}
@Test
public void shouldReportBrokenSchemaRecordChain() throws Exception
{
// given
fixture.apply( new GraphStoreFixture.Transaction()
{
@Override
protected void transactionData( GraphStoreFixture.TransactionDataBuilder tx,
GraphStoreFixture.IdGenerator next )
{
DynamicRecord schema = new DynamicRecord( next.schema() );
DynamicRecord schemaBefore = schema.clone();
schema.setNextBlock( next.schema() ); // Point to a record that isn't in use.
IndexRule rule = indexRule( schema.getId(), label1, key1, DESCRIPTOR );