-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
TransactionRecordStateTest.java
1436 lines (1267 loc) · 65.3 KB
/
TransactionRecordStateTest.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-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.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.kernel.impl.storageengine.impl.recordstorage;
import org.eclipse.collections.api.set.primitive.MutableLongSet;
import org.eclipse.collections.impl.set.mutable.primitive.LongHashSet;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import org.neo4j.graphdb.Direction;
import org.neo4j.graphdb.factory.GraphDatabaseSettings;
import org.neo4j.helpers.collection.Iterables;
import org.neo4j.internal.kernel.api.exceptions.TransactionFailureException;
import org.neo4j.internal.kernel.api.schema.SchemaDescriptor;
import org.neo4j.kernel.api.index.IndexEntryUpdate;
import org.neo4j.kernel.impl.api.BatchTransactionApplier;
import org.neo4j.kernel.impl.api.CommandVisitor;
import org.neo4j.kernel.impl.api.TransactionToApply;
import org.neo4j.kernel.impl.api.index.EntityUpdates;
import org.neo4j.kernel.impl.api.index.IndexingUpdateService;
import org.neo4j.kernel.impl.api.index.PropertyCommandsExtractor;
import org.neo4j.kernel.impl.api.index.PropertyPhysicalToLogicalConverter;
import org.neo4j.kernel.impl.core.CacheAccessBackDoor;
import org.neo4j.kernel.impl.locking.Lock;
import org.neo4j.kernel.impl.locking.LockService;
import org.neo4j.kernel.impl.locking.NoOpClient;
import org.neo4j.kernel.impl.store.DynamicArrayStore;
import org.neo4j.kernel.impl.store.NeoStores;
import org.neo4j.kernel.impl.store.NodeStore;
import org.neo4j.kernel.impl.store.RecordStore;
import org.neo4j.kernel.impl.store.format.standard.Standard;
import org.neo4j.kernel.impl.store.record.DynamicRecord;
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.Record;
import org.neo4j.kernel.impl.store.record.RelationshipGroupRecord;
import org.neo4j.kernel.impl.store.record.RelationshipRecord;
import org.neo4j.kernel.impl.transaction.CommittedTransactionRepresentation;
import org.neo4j.kernel.impl.transaction.TransactionRepresentation;
import org.neo4j.kernel.impl.transaction.command.Command;
import org.neo4j.kernel.impl.transaction.command.Command.NodeCommand;
import org.neo4j.kernel.impl.transaction.command.Command.PropertyCommand;
import org.neo4j.kernel.impl.transaction.command.Command.RelationshipCommand;
import org.neo4j.kernel.impl.transaction.command.Command.RelationshipGroupCommand;
import org.neo4j.kernel.impl.transaction.command.CommandHandlerContract;
import org.neo4j.kernel.impl.transaction.command.NeoStoreBatchTransactionApplier;
import org.neo4j.kernel.impl.transaction.log.FlushableChannel;
import org.neo4j.kernel.impl.transaction.log.InMemoryVersionableReadableClosablePositionAwareChannel;
import org.neo4j.kernel.impl.transaction.log.PhysicalTransactionCursor;
import org.neo4j.kernel.impl.transaction.log.PhysicalTransactionRepresentation;
import org.neo4j.kernel.impl.transaction.log.ReadableLogChannel;
import org.neo4j.kernel.impl.transaction.log.TransactionLogWriter;
import org.neo4j.kernel.impl.transaction.log.entry.LogEntryReader;
import org.neo4j.kernel.impl.transaction.log.entry.LogEntryWriter;
import org.neo4j.kernel.impl.transaction.log.entry.VersionAwareLogEntryReader;
import org.neo4j.kernel.impl.transaction.state.IndexUpdates;
import org.neo4j.kernel.impl.transaction.state.IntegrityValidator;
import org.neo4j.kernel.impl.transaction.state.OnlineIndexUpdates;
import org.neo4j.kernel.impl.transaction.state.PrepareTrackingRecordFormats;
import org.neo4j.kernel.impl.transaction.state.RecordAccess.RecordProxy;
import org.neo4j.kernel.impl.transaction.state.RecordChangeSet;
import org.neo4j.storageengine.api.EntityType;
import org.neo4j.storageengine.api.StorageCommand;
import org.neo4j.storageengine.api.schema.SchemaRule;
import org.neo4j.test.rule.NeoStoresRule;
import org.neo4j.values.storable.Value;
import org.neo4j.values.storable.Values;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.neo4j.graphdb.Direction.INCOMING;
import static org.neo4j.graphdb.Direction.OUTGOING;
import static org.neo4j.helpers.collection.Iterables.count;
import static org.neo4j.helpers.collection.Iterables.filter;
import static org.neo4j.kernel.api.schema.SchemaDescriptorFactory.forLabel;
import static org.neo4j.kernel.api.schema.SchemaDescriptorFactory.forRelType;
import static org.neo4j.kernel.api.schema.constraints.ConstraintDescriptorFactory.uniqueForLabel;
import static org.neo4j.kernel.api.schema.index.IndexDescriptorFactory.forSchema;
import static org.neo4j.kernel.impl.api.index.TestIndexProviderDescriptor.PROVIDER_DESCRIPTOR;
import static org.neo4j.kernel.impl.store.record.ConstraintRule.constraintRule;
import static org.neo4j.kernel.impl.store.record.RecordLoad.FORCE;
import static org.neo4j.kernel.impl.store.record.RecordLoad.NORMAL;
public class TransactionRecordStateTest
{
@Rule
public final NeoStoresRule neoStoresRule = new NeoStoresRule( getClass() );
private static final String LONG_STRING = "string value long enough not to be stored as a short string";
private static final int propertyId1 = 1;
private static final int propertyId2 = 2;
private static final Value value1 = Values.of( "first" );
private static final Value value2 = Values.of( 4 );
private static final long[] noLabels = new long[0];
private final long[] oneLabelId = new long[]{3};
private final long[] secondLabelId = new long[]{4};
private final long[] bothLabelIds = new long[]{3, 4};
private final IntegrityValidator integrityValidator = mock( IntegrityValidator.class );
private RecordChangeSet recordChangeSet;
private static void assertRelationshipGroupDoesNotExist( RecordChangeSet recordChangeSet, NodeRecord node, int type )
{
assertNull( getRelationshipGroup( recordChangeSet, node, type ) );
}
private static void assertDenseRelationshipCounts( RecordChangeSet recordChangeSet, long nodeId, int type, int outCount, int inCount )
{
RelationshipGroupRecord group = getRelationshipGroup( recordChangeSet,
recordChangeSet.getNodeRecords().getOrLoad( nodeId, null ).forReadingData(), type ).forReadingData();
assertNotNull( group );
RelationshipRecord rel;
long relId = group.getFirstOut();
if ( relId != Record.NO_NEXT_RELATIONSHIP.intValue() )
{
rel = recordChangeSet.getRelRecords().getOrLoad( relId, null ).forReadingData();
// count is stored in the back pointer of the first relationship in the chain
assertEquals( "Stored relationship count for OUTGOING differs", outCount, rel.getFirstPrevRel() );
assertEquals( "Manually counted relationships for OUTGOING differs", outCount,
manuallyCountRelationships( recordChangeSet, nodeId, relId ) );
}
relId = group.getFirstIn();
if ( relId != Record.NO_NEXT_RELATIONSHIP.intValue() )
{
rel = recordChangeSet.getRelRecords().getOrLoad( relId, null ).forReadingData();
assertEquals( "Stored relationship count for INCOMING differs", inCount, rel.getSecondPrevRel() );
assertEquals( "Manually counted relationships for INCOMING differs", inCount,
manuallyCountRelationships( recordChangeSet, nodeId, relId ) );
}
}
private static RecordProxy<RelationshipGroupRecord, Integer> getRelationshipGroup(
RecordChangeSet recordChangeSet, NodeRecord node, int type )
{
long groupId = node.getNextRel();
long previousGroupId = Record.NO_NEXT_RELATIONSHIP.intValue();
while ( groupId != Record.NO_NEXT_RELATIONSHIP.intValue() )
{
RecordProxy<RelationshipGroupRecord, Integer> change =
recordChangeSet.getRelGroupRecords().getOrLoad( groupId, type );
RelationshipGroupRecord record = change.forReadingData();
record.setPrev( previousGroupId ); // not persistent so not a "change"
if ( record.getType() == type )
{
return change;
}
previousGroupId = groupId;
groupId = record.getNext();
}
return null;
}
private static int manuallyCountRelationships( RecordChangeSet recordChangeSet, long nodeId, long firstRelId )
{
int count = 0;
long relId = firstRelId;
while ( relId != Record.NO_NEXT_RELATIONSHIP.intValue() )
{
count++;
RelationshipRecord record = recordChangeSet.getRelRecords().getOrLoad( relId, null ).forReadingData();
relId = record.getFirstNode() == nodeId ? record.getFirstNextRel() : record.getSecondNextRel();
}
return count;
}
@Test
public void shouldCreateEqualEntityPropertyUpdatesOnRecoveryOfCreatedEntities() throws Exception
{
/* There was an issue where recovering a tx where a node with a label and a property
* was created resulted in two exact copies of NodePropertyUpdates. */
// GIVEN
NeoStores neoStores = neoStoresRule.builder().build();
long nodeId = 0;
long relId = 1;
int labelId = 5;
int relTypeId = 4;
int propertyKeyId = 7;
// -- indexes
long nodeRuleId = 0;
TransactionRecordState recordState = newTransactionRecordState( neoStores );
SchemaRule nodeRule = forSchema( forLabel( labelId, propertyKeyId ), PROVIDER_DESCRIPTOR ).withId( nodeRuleId );
recordState.createSchemaRule( nodeRule );
long relRuleId = 1;
SchemaRule relRule = forSchema( forRelType( relTypeId, propertyKeyId ), PROVIDER_DESCRIPTOR ).withId( relRuleId );
recordState.createSchemaRule( relRule );
apply( neoStores, recordState );
// -- and a tx creating a node and a rel for those indexes
recordState = newTransactionRecordState( neoStores );
recordState.nodeCreate( nodeId );
recordState.addLabelToNode( labelId, nodeId );
recordState.nodeAddProperty( nodeId, propertyKeyId, Values.of( "Neo" ) );
recordState.relCreate( relId, relTypeId, nodeId, nodeId );
recordState.relAddProperty( relId, propertyKeyId, Values.of( "Oen" ) );
// WHEN
PhysicalTransactionRepresentation transaction = transactionRepresentationOf( recordState );
PropertyCommandsExtractor extractor = new PropertyCommandsExtractor();
transaction.accept( extractor );
// THEN
// -- later recovering that tx, there should be only one update for each type
assertTrue( extractor.containsAnyEntityOrPropertyUpdate() );
MutableLongSet recoveredNodeIds = new LongHashSet();
recoveredNodeIds.addAll( extractor.nodeCommandsById().keySet() );
recoveredNodeIds.addAll( extractor.propertyCommandsByNodeIds().keySet() );
assertEquals( 1, recoveredNodeIds.size() );
assertEquals( nodeId, recoveredNodeIds.longIterator().next() );
MutableLongSet recoveredRelIds = new LongHashSet();
recoveredRelIds.addAll( extractor.relationshipCommandsById().keySet() );
recoveredRelIds.addAll( extractor.propertyCommandsByRelationshipIds().keySet() );
assertEquals( 1, recoveredRelIds.size() );
assertEquals( relId, recoveredRelIds.longIterator().next() );
}
@Test
public void shouldWriteProperPropertyRecordsWhenOnlyChangingLinkage() throws Exception
{
/* There was an issue where GIVEN:
*
* Legend: () = node, [] = property record
*
* ()-->[0:block{size:1}]
*
* WHEN adding a new property record in front of if, not changing any data in that record i.e:
*
* ()-->[1:block{size:4}]-->[0:block{size:1}]
*
* The state of property record 0 would be that it had loaded value records for that block,
* but those value records weren't heavy, so writing that record to the log would fail
* w/ an assertion data != null.
*/
// GIVEN
NeoStores neoStores = neoStoresRule.builder().build();
TransactionRecordState recordState = newTransactionRecordState( neoStores );
int nodeId = 0;
recordState.nodeCreate( nodeId );
int index = 0;
recordState.nodeAddProperty( nodeId, index, string( 70 ) ); // will require a block of size 1
apply( neoStores, recordState );
// WHEN
recordState = newTransactionRecordState( neoStores );
int index2 = 1;
recordState.nodeAddProperty( nodeId, index2, string( 40 ) ); // will require a block of size 4
// THEN
PhysicalTransactionRepresentation representation = transactionRepresentationOf( recordState );
representation.accept( command -> ((Command)command).handle( new CommandVisitor.Adapter()
{
@Override
public boolean visitPropertyCommand( PropertyCommand command )
{
// THEN
verifyPropertyRecord( command.getBefore() );
verifyPropertyRecord( command.getAfter() );
return false;
}
private void verifyPropertyRecord( PropertyRecord record )
{
if ( record.getPrevProp() != Record.NO_NEXT_PROPERTY.intValue() )
{
for ( PropertyBlock block : record )
{
assertTrue( block.isLight() );
}
}
}
} ) );
}
@Test
public void shouldConvertLabelAdditionToNodePropertyUpdates() throws Exception
{
// GIVEN
NeoStores neoStores = neoStoresRule.builder().build();
long nodeId = 0;
TransactionRecordState recordState = newTransactionRecordState( neoStores );
Value value1 = Values.of( LONG_STRING );
Value value2 = Values.of( LONG_STRING.getBytes() );
recordState.nodeCreate( nodeId );
recordState.nodeAddProperty( nodeId, propertyId1, value1 );
recordState.nodeAddProperty( nodeId, propertyId2, value2 );
apply( neoStores, recordState );
// WHEN
recordState = newTransactionRecordState( neoStores );
addLabelsToNode( recordState, nodeId, oneLabelId );
Iterable<EntityUpdates> indexUpdates = indexUpdatesOf( neoStores, recordState );
// THEN
EntityUpdates expected = EntityUpdates.forEntity( nodeId ).withTokens( noLabels ).withTokensAfter( oneLabelId ).build();
assertEquals( expected, Iterables.single( indexUpdates ) );
}
@Test
public void shouldConvertMixedLabelAdditionAndSetPropertyToNodePropertyUpdates() throws Exception
{
// GIVEN
NeoStores neoStores = neoStoresRule.builder().build();
long nodeId = 0;
TransactionRecordState recordState = newTransactionRecordState( neoStores );
recordState.nodeCreate( nodeId );
recordState.nodeAddProperty( nodeId, propertyId1, value1 );
addLabelsToNode( recordState, nodeId, oneLabelId );
apply( neoStores, recordState );
// WHEN
recordState = newTransactionRecordState( neoStores );
recordState.nodeAddProperty( nodeId, propertyId2, value2 );
addLabelsToNode( recordState, nodeId, secondLabelId );
Iterable<EntityUpdates> indexUpdates = indexUpdatesOf( neoStores, recordState );
// THEN
EntityUpdates expected =
EntityUpdates.forEntity( nodeId ).withTokens( oneLabelId ).withTokensAfter( bothLabelIds )
.added( propertyId2, value2 )
.build();
assertEquals( expected, Iterables.single( indexUpdates ) );
}
@Test
public void shouldConvertLabelRemovalToNodePropertyUpdates() throws Exception
{
// GIVEN
NeoStores neoStores = neoStoresRule.builder().build();
long nodeId = 0;
TransactionRecordState recordState = newTransactionRecordState( neoStores );
recordState.nodeCreate( nodeId );
recordState.nodeAddProperty( nodeId, propertyId1, value1 );
recordState.nodeAddProperty( nodeId, propertyId2, value2 );
addLabelsToNode( recordState, nodeId, oneLabelId );
apply( neoStores, recordState );
// WHEN
recordState = newTransactionRecordState( neoStores );
removeLabelsFromNode( recordState, nodeId, oneLabelId );
Iterable<EntityUpdates> indexUpdates = indexUpdatesOf( neoStores, recordState );
// THEN
EntityUpdates expected = EntityUpdates.forEntity( nodeId ).withTokens( oneLabelId ).withTokensAfter( noLabels ).build();
assertEquals( expected, Iterables.single( indexUpdates ) );
}
@Test
public void shouldConvertMixedLabelRemovalAndRemovePropertyToNodePropertyUpdates() throws Exception
{
// GIVEN
NeoStores neoStores = neoStoresRule.builder().build();
long nodeId = 0;
TransactionRecordState recordState = newTransactionRecordState( neoStores );
recordState.nodeCreate( nodeId );
recordState.nodeAddProperty( nodeId, propertyId1, value1 );
addLabelsToNode( recordState, nodeId, bothLabelIds );
apply( neoStores, recordState );
// WHEN
recordState = newTransactionRecordState( neoStores );
recordState.nodeRemoveProperty( nodeId, propertyId1 );
removeLabelsFromNode( recordState, nodeId, secondLabelId );
Iterable<EntityUpdates> indexUpdates = indexUpdatesOf( neoStores, recordState );
// THEN
EntityUpdates expected =
EntityUpdates.forEntity( nodeId ).withTokens( bothLabelIds ).withTokensAfter( oneLabelId )
.removed( propertyId1, value1 )
.build();
assertEquals( expected, Iterables.single( indexUpdates ) );
}
@Test
public void shouldConvertMixedLabelRemovalAndAddPropertyToNodePropertyUpdates() throws Exception
{
// GIVEN
NeoStores neoStores = neoStoresRule.builder().build();
long nodeId = 0;
TransactionRecordState recordState = newTransactionRecordState( neoStores );
recordState.nodeCreate( nodeId );
recordState.nodeAddProperty( nodeId, propertyId1, value1 );
addLabelsToNode( recordState, nodeId, bothLabelIds );
apply( neoStores, recordState );
// WHEN
recordState = newTransactionRecordState( neoStores );
recordState.nodeAddProperty( nodeId, propertyId2, value2 );
removeLabelsFromNode( recordState, nodeId, secondLabelId );
Iterable<EntityUpdates> indexUpdates = indexUpdatesOf( neoStores, recordState );
// THEN
EntityUpdates expected =
EntityUpdates.forEntity( nodeId ).withTokens( bothLabelIds ).withTokensAfter( oneLabelId )
.added( propertyId2, value2 )
.build();
assertEquals( expected, Iterables.single( indexUpdates ) );
}
@Test
public void shouldConvertChangedPropertyToNodePropertyUpdates() throws Exception
{
// GIVEN
NeoStores neoStores = neoStoresRule.builder().build();
int nodeId = 0;
TransactionRecordState recordState = newTransactionRecordState( neoStores );
recordState.nodeCreate( nodeId );
recordState.nodeAddProperty( nodeId, propertyId1, value1 );
recordState.nodeAddProperty( nodeId, propertyId2, value2 );
apply( neoStores, transactionRepresentationOf( recordState ) );
// WHEN
Value newValue1 = Values.of( "new" );
Value newValue2 = Values.of( "new 2" );
recordState = newTransactionRecordState( neoStores );
recordState.nodeChangeProperty( nodeId, propertyId1, newValue1 );
recordState.nodeChangeProperty( nodeId, propertyId2, newValue2 );
Iterable<EntityUpdates> indexUpdates = indexUpdatesOf( neoStores, recordState );
// THEN
EntityUpdates expected =
EntityUpdates.forEntity( nodeId )
.changed( propertyId1, value1, newValue1 )
.changed( propertyId2, value2, newValue2 )
.build();
assertEquals( expected, Iterables.single( indexUpdates ) );
}
@Test
public void shouldConvertRemovedPropertyToNodePropertyUpdates() throws Exception
{
// GIVEN
NeoStores neoStores = neoStoresRule.builder().build();
int nodeId = 0;
TransactionRecordState recordState = newTransactionRecordState( neoStores );
recordState.nodeCreate( nodeId );
addLabelsToNode( recordState, nodeId, oneLabelId );
recordState.nodeAddProperty( nodeId, propertyId1, value1 );
recordState.nodeAddProperty( nodeId, propertyId2, value2 );
apply( neoStores, transactionRepresentationOf( recordState ) );
// WHEN
recordState = newTransactionRecordState( neoStores );
recordState.nodeRemoveProperty( nodeId, propertyId1 );
recordState.nodeRemoveProperty( nodeId, propertyId2 );
Iterable<EntityUpdates> indexUpdates = indexUpdatesOf( neoStores, recordState );
// THEN
EntityUpdates expected =
EntityUpdates.forEntity( (long) nodeId ).withTokens( oneLabelId )
.removed( propertyId1, value1 )
.removed( propertyId2, value2 )
.build();
assertEquals( expected, Iterables.single( indexUpdates ) );
}
@Test
public void shouldDeleteDynamicLabelsForDeletedNode() throws Throwable
{
// GIVEN a store that has got a node with a dynamic label record
NeoStores store = neoStoresRule.builder().build();
BatchTransactionApplier applier = new NeoStoreBatchTransactionApplier( store, mock( CacheAccessBackDoor.class ),
LockService.NO_LOCK_SERVICE );
AtomicLong nodeId = new AtomicLong();
AtomicLong dynamicLabelRecordId = new AtomicLong();
apply( applier, transaction( nodeWithDynamicLabelRecord( store, nodeId, dynamicLabelRecordId ) ) );
assertDynamicLabelRecordInUse( store, dynamicLabelRecordId.get(), true );
// WHEN applying a transaction where the node is deleted
apply( applier, transaction( deleteNode( store, nodeId.get() ) ) );
// THEN the dynamic label record should also be deleted
assertDynamicLabelRecordInUse( store, dynamicLabelRecordId.get(), false );
}
@Test
public void shouldDeleteDynamicLabelsForDeletedNodeForRecoveredTransaction() throws Throwable
{
// GIVEN a store that has got a node with a dynamic label record
NeoStores store = neoStoresRule.builder().build();
BatchTransactionApplier applier = new NeoStoreBatchTransactionApplier( store, mock( CacheAccessBackDoor.class ),
LockService.NO_LOCK_SERVICE );
AtomicLong nodeId = new AtomicLong();
AtomicLong dynamicLabelRecordId = new AtomicLong();
apply( applier, transaction( nodeWithDynamicLabelRecord( store, nodeId, dynamicLabelRecordId ) ) );
assertDynamicLabelRecordInUse( store, dynamicLabelRecordId.get(), true );
// WHEN applying a transaction, which has first round-tripped through a log (written then read)
TransactionRepresentation transaction = transaction( deleteNode( store, nodeId.get() ) );
InMemoryVersionableReadableClosablePositionAwareChannel channel = new InMemoryVersionableReadableClosablePositionAwareChannel();
writeToChannel( transaction, channel );
CommittedTransactionRepresentation recoveredTransaction = readFromChannel( channel );
// and applying that recovered transaction
apply( applier, recoveredTransaction.getTransactionRepresentation() );
// THEN should have the dynamic label record should be deleted as well
assertDynamicLabelRecordInUse( store, dynamicLabelRecordId.get(), false );
}
@Test
public void shouldExtractCreatedCommandsInCorrectOrder() throws Throwable
{
// GIVEN
NeoStores neoStores = neoStoresRule.builder()
.with( GraphDatabaseSettings.dense_node_threshold.name(), "1" ).build();
TransactionRecordState recordState = newTransactionRecordState( neoStores );
long nodeId = 0;
long relId = 1;
recordState.nodeCreate( nodeId );
recordState.relCreate( relId++, 0, nodeId, nodeId );
recordState.relCreate( relId, 0, nodeId, nodeId );
recordState.nodeAddProperty( nodeId, 0, value2 );
// WHEN
Collection<StorageCommand> commands = new ArrayList<>();
recordState.extractCommands( commands );
// THEN
Iterator<StorageCommand> commandIterator = commands.iterator();
assertCommand( commandIterator.next(), PropertyCommand.class );
assertCommand( commandIterator.next(), RelationshipCommand.class );
assertCommand( commandIterator.next(), RelationshipCommand.class );
assertCommand( commandIterator.next(), Command.RelationshipGroupCommand.class );
assertCommand( commandIterator.next(), NodeCommand.class );
assertFalse( commandIterator.hasNext() );
}
@Test
public void shouldExtractUpdateCommandsInCorrectOrder() throws Throwable
{
// GIVEN
NeoStores neoStores = neoStoresRule.builder()
.with( GraphDatabaseSettings.dense_node_threshold.name(), "1" ).build();
TransactionRecordState recordState = newTransactionRecordState( neoStores );
long nodeId = 0;
long relId1 = 1;
long relId2 = 2;
long relId3 = 3;
recordState.nodeCreate( nodeId );
recordState.relCreate( relId1, 0, nodeId, nodeId );
recordState.relCreate( relId2, 0, nodeId, nodeId );
recordState.nodeAddProperty( nodeId, 0, Values.of( 101 ) );
BatchTransactionApplier applier = new NeoStoreBatchTransactionApplier( neoStores, mock( CacheAccessBackDoor.class ),
LockService.NO_LOCK_SERVICE );
apply( applier, transaction( recordState ) );
recordState = newTransactionRecordState( neoStores );
recordState.nodeChangeProperty( nodeId, 0, Values.of( 102 ) );
recordState.relCreate( relId3, 0, nodeId, nodeId );
recordState.relAddProperty( relId1, 0, Values.of( 123 ) );
// WHEN
Collection<StorageCommand> commands = new ArrayList<>();
recordState.extractCommands( commands );
// THEN
Iterator<StorageCommand> commandIterator = commands.iterator();
// added rel property
assertCommand( commandIterator.next(), PropertyCommand.class );
// created relationship relId3
assertCommand( commandIterator.next(), RelationshipCommand.class );
// rest is updates...
assertCommand( commandIterator.next(), PropertyCommand.class );
assertCommand( commandIterator.next(), RelationshipCommand.class );
assertCommand( commandIterator.next(), RelationshipCommand.class );
assertCommand( commandIterator.next(), Command.RelationshipGroupCommand.class );
assertCommand( commandIterator.next(), NodeCommand.class );
assertFalse( commandIterator.hasNext() );
}
@Test
public void shouldIgnoreRelationshipGroupCommandsForGroupThatIsCreatedAndDeletedInThisTx() throws Exception
{
/*
* This test verifies that there are no transaction commands generated for a state diff that contains a
* relationship group that is created and deleted in this tx. This case requires special handling because
* relationship groups can be created and then deleted from disjoint code paths. Look at
* TransactionRecordState.extractCommands() for more details.
*
* The test setup looks complicated but all it does is mock properly a NeoStoreTransactionContext to
* return an Iterable<RecordSet< that contains a RelationshipGroup record which has been created in this
* tx and also is set notInUse.
*/
// Given:
// - dense node threshold of 5
// - node with 4 rels of type relationshipB and 1 rel of type relationshipB
NeoStores neoStore = neoStoresRule.builder()
.with( GraphDatabaseSettings.dense_node_threshold.name(), "5" ).build();
int relationshipA = 0;
int relationshipB = 1;
TransactionRecordState state = newTransactionRecordState( neoStore );
state.nodeCreate( 0 );
state.relCreate( 0, relationshipA, 0, 0 );
state.relCreate( 1, relationshipA, 0, 0 );
state.relCreate( 2, relationshipA, 0, 0 );
state.relCreate( 3, relationshipA, 0, 0 );
state.relCreate( 4, relationshipB, 0, 0 );
apply( neoStore, state );
// When doing a tx where a relationship of type A for the node is create and rel of type relationshipB is deleted
state = newTransactionRecordState( neoStore );
state.relCreate( 5, relationshipA, 0, 0 ); // here this node should be converted to dense and the groups should be created
state.relDelete( 4 ); // here the group relationshipB should be delete
// Then
Collection<StorageCommand> commands = new ArrayList<>();
state.extractCommands( commands );
RelationshipGroupCommand group = singleRelationshipGroupCommand( commands );
assertEquals( relationshipA, group.getAfter().getType() );
}
@Test
public void shouldExtractDeleteCommandsInCorrectOrder() throws Exception
{
// GIVEN
NeoStores neoStores = neoStoresRule.builder()
.with( GraphDatabaseSettings.dense_node_threshold.name(), "1" ).build();
TransactionRecordState recordState = newTransactionRecordState( neoStores );
long nodeId1 = 0;
long nodeId2 = 1;
long relId1 = 1;
long relId2 = 2;
long relId4 = 10;
recordState.nodeCreate( nodeId1 );
recordState.nodeCreate( nodeId2 );
recordState.relCreate( relId1, 0, nodeId1, nodeId1 );
recordState.relCreate( relId2, 0, nodeId1, nodeId1 );
recordState.relCreate( relId4, 1, nodeId1, nodeId1 );
recordState.nodeAddProperty( nodeId1, 0, value1 );
BatchTransactionApplier applier = new NeoStoreBatchTransactionApplier( neoStores, mock( CacheAccessBackDoor.class ),
LockService.NO_LOCK_SERVICE );
apply( applier, transaction( recordState ) );
recordState = newTransactionRecordState( neoStores );
recordState.relDelete( relId4 );
recordState.nodeDelete( nodeId2 );
recordState.nodeRemoveProperty( nodeId1, 0 );
// WHEN
Collection<StorageCommand> commands = new ArrayList<>();
recordState.extractCommands( commands );
// THEN
Iterator<StorageCommand> commandIterator = commands.iterator();
// updated rel group to not point to the deleted one below
assertCommand( commandIterator.next(), Command.RelationshipGroupCommand.class );
// updated node to point to the group after the deleted one
assertCommand( commandIterator.next(), NodeCommand.class );
// rest is deletions below...
assertCommand( commandIterator.next(), PropertyCommand.class );
assertCommand( commandIterator.next(), RelationshipCommand.class );
assertCommand( commandIterator.next(), Command.RelationshipGroupCommand.class );
assertCommand( commandIterator.next(), NodeCommand.class );
assertFalse( commandIterator.hasNext() );
}
@Test
public void shouldValidateConstraintIndexAsPartOfExtraction() throws Throwable
{
// GIVEN
NeoStores neoStores = neoStoresRule.builder().build();
TransactionRecordState recordState = newTransactionRecordState( neoStores );
final long indexId = neoStores.getSchemaStore().nextId();
final long constraintId = neoStores.getSchemaStore().nextId();
recordState.createSchemaRule( constraintRule( constraintId, uniqueForLabel( 1, 1 ), indexId ) );
// WHEN
recordState.extractCommands( new ArrayList<>() );
// THEN
verify( integrityValidator ).validateSchemaRule( any() );
}
@Test
public void shouldCreateProperBeforeAndAfterPropertyCommandsWhenAddingProperty() throws Exception
{
// GIVEN
NeoStores neoStores = neoStoresRule.builder().build();
TransactionRecordState recordState = newTransactionRecordState( neoStores );
int nodeId = 1;
recordState.nodeCreate( nodeId );
// WHEN
recordState.nodeAddProperty( nodeId, propertyId1, value1 );
Collection<StorageCommand> commands = new ArrayList<>();
recordState.extractCommands( commands );
PropertyCommand propertyCommand = singlePropertyCommand( commands );
// THEN
PropertyRecord before = propertyCommand.getBefore();
assertFalse( before.inUse() );
assertFalse( before.iterator().hasNext() );
PropertyRecord after = propertyCommand.getAfter();
assertTrue( after.inUse() );
assertEquals( 1, count( after ) );
}
@Test
public void shouldConvertAddedPropertyToNodePropertyUpdates() throws Exception
{
// GIVEN
NeoStores neoStores = neoStoresRule.builder().build();
long nodeId = 0;
TransactionRecordState recordState = newTransactionRecordState( neoStores );
// WHEN
recordState.nodeCreate( nodeId );
addLabelsToNode( recordState, nodeId, oneLabelId );
recordState.nodeAddProperty( nodeId, propertyId1, value1 );
recordState.nodeAddProperty( nodeId, propertyId2, value2 );
Iterable<EntityUpdates> updates = indexUpdatesOf( neoStores, recordState );
// THEN
EntityUpdates expected =
EntityUpdates.forEntity( nodeId ).withTokens( noLabels ).withTokensAfter( oneLabelId )
.added( propertyId1, value1 )
.added( propertyId2, value2 ).build();
assertEquals( expected, Iterables.single( updates ) );
}
@Test
public void shouldLockUpdatedNodes() throws Exception
{
// given
LockService locks = mock( LockService.class, new Answer<Object>()
{
@Override
public synchronized Object answer( final InvocationOnMock invocation )
{
// This is necessary because finalize() will also be called
String name = invocation.getMethod().getName();
if ( name.equals( "acquireNodeLock" ) || name.equals( "acquireRelationshipLock" ) )
{
return mock( Lock.class, invocationOnMock -> null );
}
return null;
}
} );
NeoStores neoStores = neoStoresRule.builder().build();
NodeStore nodeStore = neoStores.getNodeStore();
long[] nodes = { // allocate ids
nodeStore.nextId(), nodeStore.nextId(), nodeStore.nextId(), nodeStore.nextId(), nodeStore.nextId(),
nodeStore.nextId(), nodeStore.nextId(),};
{
// create the node records that we will modify in our main tx.
TransactionRecordState tx = newTransactionRecordState( neoStores );
for ( int i = 1; i < nodes.length - 1; i++ )
{
tx.nodeCreate( nodes[i] );
}
tx.nodeAddProperty( nodes[3], 0, Values.of( "old" ) );
tx.nodeAddProperty( nodes[4], 0, Values.of( "old" ) );
BatchTransactionApplier applier = new NeoStoreBatchTransactionApplier( neoStores, mock( CacheAccessBackDoor.class ),
locks );
apply( applier, transaction( tx ) );
}
reset( locks );
// These are the changes we want to assert locking on
TransactionRecordState tx = newTransactionRecordState( neoStores );
tx.nodeCreate( nodes[0] );
tx.addLabelToNode( 0, nodes[1] );
tx.nodeAddProperty( nodes[2], 0, Values.of( "value" ) );
tx.nodeChangeProperty( nodes[3], 0, Values.of( "value" ) );
tx.nodeRemoveProperty( nodes[4], 0 );
tx.nodeDelete( nodes[5] );
tx.nodeCreate( nodes[6] );
tx.addLabelToNode( 0, nodes[6] );
tx.nodeAddProperty( nodes[6], 0, Values.of( "value" ) );
//commit( tx );
BatchTransactionApplier applier = new NeoStoreBatchTransactionApplier( neoStores, mock( CacheAccessBackDoor.class ), locks );
apply( applier, transaction( tx ) );
// then
// create node, NodeCommand == 1 update
verify( locks, times( 1 ) ).acquireNodeLock( nodes[0], LockService.LockType.WRITE_LOCK );
// add label, NodeCommand == 1 update
verify( locks, times( 1 ) ).acquireNodeLock( nodes[1], LockService.LockType.WRITE_LOCK );
// add property, NodeCommand and PropertyCommand == 2 updates
verify( locks, times( 2 ) ).acquireNodeLock( nodes[2], LockService.LockType.WRITE_LOCK );
// update property, in place, PropertyCommand == 1 update
verify( locks, times( 1 ) ).acquireNodeLock( nodes[3], LockService.LockType.WRITE_LOCK );
// remove property, updates the Node and the Property == 2 updates
verify( locks, times( 2 ) ).acquireNodeLock( nodes[4], LockService.LockType.WRITE_LOCK );
// delete node, single NodeCommand == 1 update
verify( locks, times( 1 ) ).acquireNodeLock( nodes[5], LockService.LockType.WRITE_LOCK );
// create and add-label goes into the NodeCommand, add property is a PropertyCommand == 2 updates
verify( locks, times( 2 ) ).acquireNodeLock( nodes[6], LockService.LockType.WRITE_LOCK );
}
@Test
public void movingBilaterallyOfTheDenseNodeThresholdIsConsistent() throws Exception
{
// GIVEN
NeoStores neoStores = neoStoresRule.builder()
.with( GraphDatabaseSettings.dense_node_threshold.name(), "10" ).build();
TransactionRecordState tx = newTransactionRecordState( neoStores );
long nodeId = neoStores.getNodeStore().nextId();
tx.nodeCreate( nodeId );
int typeA = (int) neoStores.getRelationshipTypeTokenStore().nextId();
tx.createRelationshipTypeToken( "A", typeA );
createRelationships( neoStores, tx, nodeId, typeA, INCOMING, 20 );
BatchTransactionApplier applier = new NeoStoreBatchTransactionApplier( neoStores, mock( CacheAccessBackDoor.class ),
LockService.NO_LOCK_SERVICE );
apply( applier, transaction( tx ) );
tx = newTransactionRecordState( neoStores );
int typeB = 1;
tx.createRelationshipTypeToken( "B", typeB );
// WHEN
// i remove enough relationships to become dense and remove enough to become not dense
long[] relationshipsOfTypeB = createRelationships( neoStores, tx, nodeId, typeB, OUTGOING, 5 );
for ( long relationshipToDelete : relationshipsOfTypeB )
{
tx.relDelete( relationshipToDelete );
}
PhysicalTransactionRepresentation ptx = transactionRepresentationOf( tx );
apply( applier, ptx );
// THEN
// The dynamic label record in before should be the same id as in after, and should be in use
final AtomicBoolean foundRelationshipGroupInUse = new AtomicBoolean();
ptx.accept( command -> ((Command)command).handle( new CommandVisitor.Adapter()
{
@Override
public boolean visitRelationshipGroupCommand( Command.RelationshipGroupCommand command )
{
if ( command.getAfter().inUse() )
{
if ( !foundRelationshipGroupInUse.get() )
{
foundRelationshipGroupInUse.set( true );
}
else
{
fail();
}
}
return false;
}
} ) );
assertTrue( "Did not create relationship group command", foundRelationshipGroupInUse.get() );
}
@Test
public void shouldConvertToDenseNodeRepresentationWhenHittingThresholdWithDifferentTypes() throws Exception
{
// GIVEN a node with a total of denseNodeThreshold-1 relationships
NeoStores neoStores = neoStoresRule.builder()
.with( GraphDatabaseSettings.dense_node_threshold.name(), "50" ).build();
TransactionRecordState tx = newTransactionRecordState( neoStores );
long nodeId = neoStores.getNodeStore().nextId();
int typeA = 0;
int typeB = 1;
int typeC = 2;
tx.nodeCreate( nodeId );
tx.createRelationshipTypeToken( "A", typeA );
createRelationships( neoStores, tx, nodeId, typeA, OUTGOING, 6 );
createRelationships( neoStores, tx, nodeId, typeA, INCOMING, 7 );
tx.createRelationshipTypeToken( "B", typeB );
createRelationships( neoStores, tx, nodeId, typeB, OUTGOING, 8 );
createRelationships( neoStores, tx, nodeId, typeB, INCOMING, 9 );
tx.createRelationshipTypeToken( "C", typeC );
createRelationships( neoStores, tx, nodeId, typeC, OUTGOING, 10 );
createRelationships( neoStores, tx, nodeId, typeC, INCOMING, 10 );
// here we're at the edge
assertFalse( recordChangeSet.getNodeRecords().getOrLoad( nodeId, null ).forReadingData().isDense() );
// WHEN creating the relationship that pushes us over the threshold
createRelationships( neoStores, tx, nodeId, typeC, INCOMING, 1 );
// THEN the node should have been converted into a dense node
assertTrue( recordChangeSet.getNodeRecords().getOrLoad( nodeId, null ).forReadingData().isDense() );
assertDenseRelationshipCounts( recordChangeSet, nodeId, typeA, 6, 7 );
assertDenseRelationshipCounts( recordChangeSet, nodeId, typeB, 8, 9 );
assertDenseRelationshipCounts( recordChangeSet, nodeId, typeC, 10, 11 );
}
@Test
public void shouldConvertToDenseNodeRepresentationWhenHittingThresholdWithTheSameTypeDifferentDirection()
throws Exception
{
// GIVEN a node with a total of denseNodeThreshold-1 relationships
NeoStores neoStores = neoStoresRule.builder()
.with( GraphDatabaseSettings.dense_node_threshold.name(), "49" ).build();
TransactionRecordState tx = newTransactionRecordState( neoStores );
long nodeId = neoStores.getNodeStore().nextId();
int typeA = 0;
tx.nodeCreate( nodeId );
tx.createRelationshipTypeToken( "A", typeA );
createRelationships( neoStores, tx, nodeId, typeA, OUTGOING, 24 );
createRelationships( neoStores, tx, nodeId, typeA, INCOMING, 25 );
// here we're at the edge
assertFalse( recordChangeSet.getNodeRecords().getOrLoad( nodeId, null ).forReadingData().isDense() );
// WHEN creating the relationship that pushes us over the threshold
createRelationships( neoStores, tx, nodeId, typeA, INCOMING, 1 );
// THEN the node should have been converted into a dense node
assertTrue( recordChangeSet.getNodeRecords().getOrLoad( nodeId, null ).forReadingData().isDense() );
assertDenseRelationshipCounts( recordChangeSet, nodeId, typeA, 24, 26 );
}
@Test
public void shouldConvertToDenseNodeRepresentationWhenHittingThresholdWithTheSameTypeSameDirection()
throws Exception
{
// GIVEN a node with a total of denseNodeThreshold-1 relationships
NeoStores neoStores = neoStoresRule.builder()
.with( GraphDatabaseSettings.dense_node_threshold.name(), "8" ).build();
TransactionRecordState tx = newTransactionRecordState( neoStores );
long nodeId = neoStores.getNodeStore().nextId();
int typeA = 0;
tx.nodeCreate( nodeId );
tx.createRelationshipTypeToken( "A", typeA );
createRelationships( neoStores, tx, nodeId, typeA, OUTGOING, 8 );
// here we're at the edge
assertFalse( recordChangeSet.getNodeRecords().getOrLoad( nodeId, null ).forReadingData().isDense() );
// WHEN creating the relationship that pushes us over the threshold
createRelationships( neoStores, tx, nodeId, typeA, OUTGOING, 1 );
// THEN the node should have been converted into a dense node
assertTrue( recordChangeSet.getNodeRecords().getOrLoad( nodeId, null ).forReadingData().isDense() );
assertDenseRelationshipCounts( recordChangeSet, nodeId, typeA, 9, 0 );
}
@Test
public void shouldMaintainCorrectDataWhenDeletingFromDenseNodeWithOneType() throws Exception
{
// GIVEN a node with a total of denseNodeThreshold-1 relationships
NeoStores neoStores = neoStoresRule.builder()
.with( GraphDatabaseSettings.dense_node_threshold.name(), "13" ).build();
TransactionRecordState tx = newTransactionRecordState( neoStores );
int nodeId = (int) neoStores.getNodeStore().nextId();
int typeA = 0;
tx.nodeCreate( nodeId );
tx.createRelationshipTypeToken( "A", typeA );