Search in sources :

Example 1 with INSTANCE

use of org.neo4j.memory.EmptyMemoryTracker.INSTANCE in project neo4j by neo4j.

the class BatchingNeoStoresTest method someDataInTheDatabase.

private void someDataInTheDatabase(Config config) throws Exception {
    NullLog nullLog = NullLog.getInstance();
    try (JobScheduler scheduler = JobSchedulerFactory.createInitialisedScheduler();
        PageCache pageCache = new ConfiguringPageCacheFactory(fileSystem, Config.defaults(), PageCacheTracer.NULL, nullLog, scheduler, Clocks.nanoClock(), new MemoryPools()).getOrCreatePageCache();
        Lifespan life = new Lifespan()) {
        // TODO this little dance with TokenHolders is really annoying and must be solved with a better abstraction
        DeferredInitializedTokenCreator propertyKeyTokenCreator = new DeferredInitializedTokenCreator() {

            @Override
            void create(String name, boolean internal, int id) {
                txState.propertyKeyDoCreateForName(name, internal, id);
            }
        };
        DeferredInitializedTokenCreator labelTokenCreator = new DeferredInitializedTokenCreator() {

            @Override
            void create(String name, boolean internal, int id) {
                txState.labelDoCreateForName(name, internal, id);
            }
        };
        DeferredInitializedTokenCreator relationshipTypeTokenCreator = new DeferredInitializedTokenCreator() {

            @Override
            void create(String name, boolean internal, int id) {
                txState.relationshipTypeDoCreateForName(name, internal, id);
            }
        };
        TokenHolders tokenHolders = new TokenHolders(new DelegatingTokenHolder(propertyKeyTokenCreator, TokenHolder.TYPE_PROPERTY_KEY), new DelegatingTokenHolder(labelTokenCreator, TokenHolder.TYPE_LABEL), new DelegatingTokenHolder(relationshipTypeTokenCreator, TokenHolder.TYPE_RELATIONSHIP_TYPE));
        IndexConfigCompleter indexConfigCompleter = index -> index;
        RecoveryCleanupWorkCollector recoveryCleanupWorkCollector = immediate();
        RecordStorageEngine storageEngine = life.add(new RecordStorageEngine(databaseLayout, Config.defaults(), pageCache, fileSystem, NullLogProvider.getInstance(), tokenHolders, new DatabaseSchemaState(NullLogProvider.getInstance()), new StandardConstraintSemantics(), indexConfigCompleter, LockService.NO_LOCK_SERVICE, new DatabaseHealth(PanicEventGenerator.NO_OP, nullLog), new DefaultIdGeneratorFactory(fileSystem, immediate(), DEFAULT_DATABASE_NAME), new DefaultIdController(), recoveryCleanupWorkCollector, PageCacheTracer.NULL, true, INSTANCE, writable(), CommandLockVerification.Factory.IGNORE, LockVerificationMonitor.Factory.IGNORE));
        // Create the relationship type token
        TxState txState = new TxState();
        NeoStores neoStores = storageEngine.testAccessNeoStores();
        CommandCreationContext commandCreationContext = storageEngine.newCommandCreationContext(INSTANCE);
        commandCreationContext.initialize(NULL);
        propertyKeyTokenCreator.initialize(neoStores.getPropertyKeyTokenStore(), txState);
        labelTokenCreator.initialize(neoStores.getLabelTokenStore(), txState);
        relationshipTypeTokenCreator.initialize(neoStores.getRelationshipTypeTokenStore(), txState);
        int relTypeId = tokenHolders.relationshipTypeTokens().getOrCreateId(RELTYPE.name());
        apply(txState, commandCreationContext, storageEngine);
        // Finally, we're initialized and ready to create two nodes and a relationship
        txState = new TxState();
        long node1 = commandCreationContext.reserveNode();
        long node2 = commandCreationContext.reserveNode();
        txState.nodeDoCreate(node1);
        txState.nodeDoCreate(node2);
        txState.relationshipDoCreate(commandCreationContext.reserveRelationship(), relTypeId, node1, node2);
        apply(txState, commandCreationContext, storageEngine);
        neoStores.flush(NULL);
    }
}
Also used : JobScheduler(org.neo4j.scheduler.JobScheduler) ThreadPoolJobScheduler(org.neo4j.test.scheduler.ThreadPoolJobScheduler) DefaultIdController(org.neo4j.internal.id.DefaultIdController) NullLogService(org.neo4j.logging.internal.NullLogService) Predicates(org.neo4j.function.Predicates) CursorContext(org.neo4j.io.pagecache.context.CursorContext) TokenCreator(org.neo4j.token.TokenCreator) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Config(org.neo4j.configuration.Config) LockVerificationMonitor(org.neo4j.internal.recordstorage.LockVerificationMonitor) NullLogProvider(org.neo4j.logging.NullLogProvider) ANY_LABEL(org.neo4j.token.api.TokenConstants.ANY_LABEL) TransactionToApply(org.neo4j.kernel.impl.api.TransactionToApply) DatabaseLayout(org.neo4j.io.layout.DatabaseLayout) DEFAULT_DATABASE_NAME(org.neo4j.configuration.GraphDatabaseSettings.DEFAULT_DATABASE_NAME) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) PageCacheTracer(org.neo4j.io.pagecache.tracing.PageCacheTracer) AbstractBaseRecord(org.neo4j.kernel.impl.store.record.AbstractBaseRecord) NULL(org.neo4j.io.pagecache.context.CursorContext.NULL) RecoveryCleanupWorkCollector(org.neo4j.index.internal.gbptree.RecoveryCleanupWorkCollector) DatabaseSchemaState(org.neo4j.kernel.impl.api.DatabaseSchemaState) JobSchedulerFactory(org.neo4j.kernel.impl.scheduler.JobSchedulerFactory) NullLog(org.neo4j.logging.NullLog) Input(org.neo4j.internal.batchimport.input.Input) PageCache(org.neo4j.io.pagecache.PageCache) Lifespan(org.neo4j.kernel.lifecycle.Lifespan) DatabaseReadOnlyChecker.writable(org.neo4j.configuration.helpers.DatabaseReadOnlyChecker.writable) TestDirectory(org.neo4j.test.rule.TestDirectory) RecordStorageEngine(org.neo4j.internal.recordstorage.RecordStorageEngine) LockService(org.neo4j.lock.LockService) Neo4jLayoutExtension(org.neo4j.test.extension.Neo4jLayoutExtension) Test(org.junit.jupiter.api.Test) RecordStore(org.neo4j.kernel.impl.store.RecordStore) List(java.util.List) CommandCreationContext(org.neo4j.storageengine.api.CommandCreationContext) INSTANCE(org.neo4j.memory.EmptyMemoryTracker.INSTANCE) Stream(java.util.stream.Stream) DefaultIdGeneratorFactory(org.neo4j.internal.id.DefaultIdGeneratorFactory) StoreType(org.neo4j.kernel.impl.store.StoreType) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) CommandsToApply(org.neo4j.storageengine.api.CommandsToApply) RelationshipType(org.neo4j.graphdb.RelationshipType) ANONYMOUS(org.neo4j.internal.kernel.api.security.AuthSubject.ANONYMOUS) RecordFormatSelector.selectForConfig(org.neo4j.kernel.impl.store.format.RecordFormatSelector.selectForConfig) PhysicalTransactionRepresentation(org.neo4j.kernel.impl.transaction.log.PhysicalTransactionRepresentation) EMPTY(org.neo4j.internal.batchimport.AdditionalInitialIds.EMPTY) Assertions.assertThrows(org.junit.jupiter.api.Assertions.assertThrows) BASE_TX_ID(org.neo4j.storageengine.api.TransactionIdStore.BASE_TX_ID) ConfiguringPageCacheFactory(org.neo4j.kernel.impl.pagecache.ConfiguringPageCacheFactory) ArrayList(java.util.ArrayList) TxState(org.neo4j.kernel.impl.api.state.TxState) RecordFormats(org.neo4j.kernel.impl.store.format.RecordFormats) StorageCommand(org.neo4j.storageengine.api.StorageCommand) Values(org.neo4j.values.storable.Values) TokenHolder(org.neo4j.token.api.TokenHolder) IndexConfigCompleter(org.neo4j.internal.schema.IndexConfigCompleter) NeoStores(org.neo4j.kernel.impl.store.NeoStores) Inject(org.neo4j.test.extension.Inject) DelegatingTokenHolder(org.neo4j.token.DelegatingTokenHolder) PropertyBlock(org.neo4j.kernel.impl.store.record.PropertyBlock) TransactionApplicationMode(org.neo4j.storageengine.api.TransactionApplicationMode) GraphDatabaseInternalSettings(org.neo4j.configuration.GraphDatabaseInternalSettings) GBPTreeCountsStore(org.neo4j.internal.counts.GBPTreeCountsStore) RecordStorageReader(org.neo4j.internal.recordstorage.RecordStorageReader) MemoryPools(org.neo4j.memory.MemoryPools) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) JobScheduler(org.neo4j.scheduler.JobScheduler) MemoryTracker(org.neo4j.memory.MemoryTracker) DOUBLE_RELATIONSHIP_RECORD_UNIT_THRESHOLD(org.neo4j.internal.batchimport.store.BatchingNeoStores.DOUBLE_RELATIONSHIP_RECORD_UNIT_THRESHOLD) PropertyStore(org.neo4j.kernel.impl.store.PropertyStore) BatchingNeoStores.batchingNeoStores(org.neo4j.internal.batchimport.store.BatchingNeoStores.batchingNeoStores) LockTracer(org.neo4j.lock.LockTracer) StandardConstraintSemantics(org.neo4j.kernel.impl.constraints.StandardConstraintSemantics) PageCacheExtension(org.neo4j.test.extension.pagecache.PageCacheExtension) Configuration(org.neo4j.internal.batchimport.Configuration) PropertyRecord(org.neo4j.kernel.impl.store.record.PropertyRecord) PanicEventGenerator(org.neo4j.monitoring.PanicEventGenerator) DirectoryNotEmptyException(java.nio.file.DirectoryNotEmptyException) IOException(java.io.IOException) TransactionState(org.neo4j.kernel.api.txstate.TransactionState) CommandLockVerification(org.neo4j.internal.recordstorage.CommandLockVerification) TokenStore(org.neo4j.kernel.impl.store.TokenStore) DatabaseHealth(org.neo4j.monitoring.DatabaseHealth) LATEST_RECORD_FORMATS(org.neo4j.kernel.impl.store.format.standard.Standard.LATEST_RECORD_FORMATS) ResourceLocker(org.neo4j.lock.ResourceLocker) CountsAccessor(org.neo4j.counts.CountsAccessor) RecoveryCleanupWorkCollector.immediate(org.neo4j.index.internal.gbptree.RecoveryCleanupWorkCollector.immediate) ForcedSecondaryUnitRecordFormats(org.neo4j.kernel.impl.store.format.ForcedSecondaryUnitRecordFormats) TokenHolders(org.neo4j.token.TokenHolders) CountsBuilder(org.neo4j.internal.counts.CountsBuilder) ThreadPoolJobScheduler(org.neo4j.test.scheduler.ThreadPoolJobScheduler) Clocks(org.neo4j.time.Clocks) FileSystemAbstraction(org.neo4j.io.fs.FileSystemAbstraction) DatabaseHealth(org.neo4j.monitoring.DatabaseHealth) DefaultIdGeneratorFactory(org.neo4j.internal.id.DefaultIdGeneratorFactory) NullLog(org.neo4j.logging.NullLog) ConfiguringPageCacheFactory(org.neo4j.kernel.impl.pagecache.ConfiguringPageCacheFactory) RecoveryCleanupWorkCollector(org.neo4j.index.internal.gbptree.RecoveryCleanupWorkCollector) IndexConfigCompleter(org.neo4j.internal.schema.IndexConfigCompleter) DefaultIdController(org.neo4j.internal.id.DefaultIdController) CommandCreationContext(org.neo4j.storageengine.api.CommandCreationContext) MemoryPools(org.neo4j.memory.MemoryPools) DatabaseSchemaState(org.neo4j.kernel.impl.api.DatabaseSchemaState) TxState(org.neo4j.kernel.impl.api.state.TxState) RecordStorageEngine(org.neo4j.internal.recordstorage.RecordStorageEngine) NeoStores(org.neo4j.kernel.impl.store.NeoStores) BatchingNeoStores.batchingNeoStores(org.neo4j.internal.batchimport.store.BatchingNeoStores.batchingNeoStores) TokenHolders(org.neo4j.token.TokenHolders) Lifespan(org.neo4j.kernel.lifecycle.Lifespan) DelegatingTokenHolder(org.neo4j.token.DelegatingTokenHolder) StandardConstraintSemantics(org.neo4j.kernel.impl.constraints.StandardConstraintSemantics) PageCache(org.neo4j.io.pagecache.PageCache)

Example 2 with INSTANCE

use of org.neo4j.memory.EmptyMemoryTracker.INSTANCE in project neo4j by neo4j.

the class EncodingIdMapperTest method shouldDetectCorrectDuplicateInputIdsWhereManyAccidentalInManyGroups.

@Test
public void shouldDetectCorrectDuplicateInputIdsWhereManyAccidentalInManyGroups() {
    // GIVEN
    final ControlledEncoder encoder = new ControlledEncoder(new LongEncoder());
    final int idsPerGroup = 20;
    int groupCount = 5;
    for (int i = 0; i < groupCount; i++) {
        groups.getOrCreate("Group " + i);
    }
    IdMapper mapper = mapper(encoder, Radix.LONG, EncodingIdMapper.NO_MONITOR, ParallelSort.DEFAULT, numberOfCollisions -> new LongCollisionValues(NumberArrayFactories.HEAP, numberOfCollisions, INSTANCE));
    final AtomicReference<Group> group = new AtomicReference<>();
    PropertyValueLookup ids = (nodeId, cursorContext) -> {
        int groupId = toIntExact(nodeId / idsPerGroup);
        if (groupId == groupCount) {
            return null;
        }
        group.set(groups.get(groupId));
        // i.e. all first 10% in each group collides with all other first 10% in each group
        if (nodeId % idsPerGroup < 2) {
            // Let these colliding values encode into the same eId as well,
            // so that they are definitely marked as collisions
            encoder.useThisIdToEncodeNoMatterWhatComesIn(1234567L);
            return nodeId % idsPerGroup;
        }
        // The other 90% will be accidental collisions for something else
        encoder.useThisIdToEncodeNoMatterWhatComesIn((long) (123456 - group.get().id()));
        return nodeId;
    };
    // WHEN
    int count = idsPerGroup * groupCount;
    for (long nodeId = 0; nodeId < count; nodeId++) {
        mapper.put(ids.lookupProperty(nodeId, NULL), nodeId, group.get());
    }
    Collector collector = mock(Collector.class);
    mapper.prepare(ids, collector, NONE);
    // THEN
    verifyNoMoreInteractions(collector);
    for (long nodeId = 0; nodeId < count; nodeId++) {
        assertEquals(nodeId, mapper.get(ids.lookupProperty(nodeId, NULL), group.get()));
    }
    verifyNoMoreInteractions(collector);
    assertFalse(mapper.leftOverDuplicateNodesIds().hasNext());
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) ArgumentMatchers.anyLong(org.mockito.ArgumentMatchers.anyLong) NO_MONITOR(org.neo4j.internal.batchimport.cache.idmapping.string.EncodingIdMapper.NO_MONITOR) NumberArrayFactories(org.neo4j.internal.batchimport.cache.NumberArrayFactories) Collector(org.neo4j.internal.batchimport.input.Collector) CursorContext(org.neo4j.io.pagecache.context.CursorContext) RunWith(org.junit.runner.RunWith) Parameters(org.junit.runners.Parameterized.Parameters) Groups(org.neo4j.internal.batchimport.input.Groups) Random(java.util.Random) DefaultPageCacheTracer(org.neo4j.io.pagecache.tracing.DefaultPageCacheTracer) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) RandomRule(org.neo4j.test.rule.RandomRule) Mockito.verifyNoMoreInteractions(org.mockito.Mockito.verifyNoMoreInteractions) MutableLong(org.apache.commons.lang3.mutable.MutableLong) IdMapper(org.neo4j.internal.batchimport.cache.idmapping.IdMapper) PageCacheTracer(org.neo4j.io.pagecache.tracing.PageCacheTracer) NULL(org.neo4j.io.pagecache.context.CursorContext.NULL) Assert.fail(org.junit.Assert.fail) Math.toIntExact(java.lang.Math.toIntExact) ProgressListener(org.neo4j.internal.helpers.progress.ProgressListener) NONE(org.neo4j.internal.helpers.progress.ProgressListener.NONE) Parameterized(org.junit.runners.Parameterized) LongFunction(java.util.function.LongFunction) PropertyValueLookup(org.neo4j.internal.batchimport.PropertyValueLookup) Collection(java.util.Collection) Set(java.util.Set) Test(org.junit.Test) Mockito.times(org.mockito.Mockito.times) UUID(java.util.UUID) Mockito.when(org.mockito.Mockito.when) Mockito.verify(org.mockito.Mockito.verify) AtomicLong(java.util.concurrent.atomic.AtomicLong) Factory(org.neo4j.function.Factory) GLOBAL(org.neo4j.internal.batchimport.input.Group.GLOBAL) List(java.util.List) INSTANCE(org.neo4j.memory.EmptyMemoryTracker.INSTANCE) Rule(org.junit.Rule) Group(org.neo4j.internal.batchimport.input.Group) Assert.assertFalse(org.junit.Assert.assertFalse) Race(org.neo4j.test.Race) Assert.assertEquals(org.junit.Assert.assertEquals) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Mockito.mock(org.mockito.Mockito.mock) PrimitiveLongCollections.count(org.neo4j.collection.PrimitiveLongCollections.count) Group(org.neo4j.internal.batchimport.input.Group) PropertyValueLookup(org.neo4j.internal.batchimport.PropertyValueLookup) Collector(org.neo4j.internal.batchimport.input.Collector) IdMapper(org.neo4j.internal.batchimport.cache.idmapping.IdMapper) AtomicReference(java.util.concurrent.atomic.AtomicReference) Test(org.junit.Test)

Example 3 with INSTANCE

use of org.neo4j.memory.EmptyMemoryTracker.INSTANCE in project neo4j by neo4j.

the class IndexRecoveryIT method shouldBeAbleToRecoverInTheMiddleOfPopulatingAnIndexWhereLogHasRotated.

@Test
void shouldBeAbleToRecoverInTheMiddleOfPopulatingAnIndexWhereLogHasRotated() throws Exception {
    // Given
    startDb();
    Semaphore populationSemaphore = new Semaphore(0);
    Future<Void> killFuture;
    try {
        when(mockedIndexProvider.getPopulator(any(IndexDescriptor.class), any(IndexSamplingConfig.class), any(), any(), any(TokenNameLookup.class))).thenReturn(indexPopulatorWithControlledCompletionTiming(populationSemaphore));
        createSomeData();
        createIndex(myLabel);
        // And Given
        killFuture = killDbInSeparateThread();
        int iterations = 0;
        do {
            rotateLogsAndCheckPoint();
            Thread.sleep(10);
        } while (iterations++ < 100 && !killFuture.isDone());
    } finally {
        populationSemaphore.release();
    }
    killFuture.get();
    when(mockedIndexProvider.getInitialState(any(IndexDescriptor.class), any(CursorContext.class))).thenReturn(InternalIndexState.POPULATING);
    Semaphore recoverySemaphore = new Semaphore(0);
    try {
        when(mockedIndexProvider.getPopulator(any(IndexDescriptor.class), any(IndexSamplingConfig.class), any(), any(), any(TokenNameLookup.class))).thenReturn(indexPopulatorWithControlledCompletionTiming(recoverySemaphore));
        boolean recoveryRequired = Recovery.isRecoveryRequired(testDirectory.getFileSystem(), databaseLayout, defaults(), INSTANCE);
        monitors.addMonitorListener(new MyRecoveryMonitor(recoverySemaphore));
        // When
        startDb();
        try (Transaction transaction = db.beginTx()) {
            assertThat(transaction.schema().getIndexes(myLabel)).hasSize(1);
            assertThat(transaction.schema().getIndexes(myLabel)).extracting(i -> transaction.schema().getIndexState(i)).containsOnly(Schema.IndexState.POPULATING);
        }
        // in case if kill was not that fast and killed db after flush there will be no need to do recovery and
        // we will not gonna need to get index populators during recovery index service start
        verify(mockedIndexProvider, times(recoveryRequired ? 3 : 2)).getPopulator(any(IndexDescriptor.class), any(IndexSamplingConfig.class), any(), any(), any(TokenNameLookup.class));
        verify(mockedIndexProvider, never()).getOnlineAccessor(any(IndexDescriptor.class), any(IndexSamplingConfig.class), any(TokenNameLookup.class));
    } finally {
        recoverySemaphore.release();
    }
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) SchemaIndexTestHelper.singleInstanceIndexProviderFactory(org.neo4j.kernel.impl.api.index.SchemaIndexTestHelper.singleInstanceIndexProviderFactory) CursorContext(org.neo4j.io.pagecache.context.CursorContext) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) TokenNameLookup(org.neo4j.common.TokenNameLookup) IndexPopulator(org.neo4j.kernel.api.index.IndexPopulator) InternalTransaction(org.neo4j.kernel.impl.coreapi.InternalTransaction) DatabaseLayout(org.neo4j.io.layout.DatabaseLayout) DEFAULT_DATABASE_NAME(org.neo4j.configuration.GraphDatabaseSettings.DEFAULT_DATABASE_NAME) Future(java.util.concurrent.Future) LogRotation(org.neo4j.kernel.impl.transaction.log.rotation.LogRotation) IndexUpdater(org.neo4j.kernel.api.index.IndexUpdater) Monitors(org.neo4j.monitoring.Monitors) Arrays.asList(java.util.Arrays.asList) Transaction(org.neo4j.graphdb.Transaction) Path(java.nio.file.Path) RecoveryMonitor(org.neo4j.kernel.recovery.RecoveryMonitor) PageCache(org.neo4j.io.pagecache.PageCache) TokenIndexProviderFactory(org.neo4j.kernel.impl.index.schema.TokenIndexProviderFactory) Recovery(org.neo4j.kernel.recovery.Recovery) Set(java.util.Set) FileUtils(org.neo4j.io.fs.FileUtils) TestDirectory(org.neo4j.test.rule.TestDirectory) Executors.newSingleThreadExecutor(java.util.concurrent.Executors.newSingleThreadExecutor) IndexEntryUpdate(org.neo4j.storageengine.api.IndexEntryUpdate) Neo4jLayoutExtension(org.neo4j.test.extension.Neo4jLayoutExtension) Schema(org.neo4j.graphdb.schema.Schema) SimpleTriggerInfo(org.neo4j.kernel.impl.transaction.log.checkpoint.SimpleTriggerInfo) GraphDatabaseAPI(org.neo4j.kernel.internal.GraphDatabaseAPI) Test(org.junit.jupiter.api.Test) GraphDatabaseSettings.default_schema_provider(org.neo4j.configuration.GraphDatabaseSettings.default_schema_provider) INSTANCE(org.neo4j.memory.EmptyMemoryTracker.INSTANCE) PROVIDER_DESCRIPTOR(org.neo4j.kernel.impl.api.index.TestIndexProviderDescriptor.PROVIDER_DESCRIPTOR) SchemaDescriptor(org.neo4j.internal.schema.SchemaDescriptor) IndexDescriptor(org.neo4j.internal.schema.IndexDescriptor) DatabaseManagementService(org.neo4j.dbms.api.DatabaseManagementService) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) CollectingIndexUpdater(org.neo4j.kernel.impl.index.schema.CollectingIndexUpdater) Label(org.neo4j.graphdb.Label) Config.defaults(org.neo4j.configuration.Config.defaults) InternalIndexState(org.neo4j.internal.kernel.api.InternalIndexState) CheckPointer(org.neo4j.kernel.impl.transaction.log.checkpoint.CheckPointer) MINUTES(java.util.concurrent.TimeUnit.MINUTES) IndexAccessor(org.neo4j.kernel.api.index.IndexAccessor) Node(org.neo4j.graphdb.Node) IndexProvider(org.neo4j.kernel.api.index.IndexProvider) Values(org.neo4j.values.storable.Values) HashSet(java.util.HashSet) TestDatabaseManagementServiceBuilder(org.neo4j.test.TestDatabaseManagementServiceBuilder) Inject(org.neo4j.test.extension.Inject) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) ONLINE(org.neo4j.internal.kernel.api.InternalIndexState.ONLINE) ExecutorService(java.util.concurrent.ExecutorService) IndexSample(org.neo4j.kernel.api.index.IndexSample) Semaphore(java.util.concurrent.Semaphore) IOException(java.io.IOException) Mockito.times(org.mockito.Mockito.times) LabelSchemaDescriptor(org.neo4j.internal.schema.LabelSchemaDescriptor) LogAppendEvent(org.neo4j.kernel.impl.transaction.tracing.LogAppendEvent) StoreMigrationParticipant(org.neo4j.storageengine.migration.StoreMigrationParticipant) Mockito.when(org.mockito.Mockito.when) Label.label(org.neo4j.graphdb.Label.label) Mockito.verify(org.mockito.Mockito.verify) ExecutionException(java.util.concurrent.ExecutionException) AfterEach(org.junit.jupiter.api.AfterEach) ExtensionFactory(org.neo4j.kernel.extension.ExtensionFactory) Mockito.never(org.mockito.Mockito.never) KernelTransaction(org.neo4j.kernel.api.KernelTransaction) IndexDefinition(org.neo4j.graphdb.schema.IndexDefinition) FileSystemAbstraction(org.neo4j.io.fs.FileSystemAbstraction) TokenNameLookup(org.neo4j.common.TokenNameLookup) InternalTransaction(org.neo4j.kernel.impl.coreapi.InternalTransaction) Transaction(org.neo4j.graphdb.Transaction) KernelTransaction(org.neo4j.kernel.api.KernelTransaction) Semaphore(java.util.concurrent.Semaphore) CursorContext(org.neo4j.io.pagecache.context.CursorContext) IndexDescriptor(org.neo4j.internal.schema.IndexDescriptor) Test(org.junit.jupiter.api.Test)

Example 4 with INSTANCE

use of org.neo4j.memory.EmptyMemoryTracker.INSTANCE in project neo4j by neo4j.

the class NodeRelationshipCacheTest method shouldCacheMultipleDenseNodeRelationshipHeads.

@Test
public void shouldCacheMultipleDenseNodeRelationshipHeads() {
    // GIVEN
    cache = new NodeRelationshipCache(NumberArrayFactories.HEAP, 1, INSTANCE);
    cache.setNodeCount(10);
    long nodeId = 3;
    cache.setCount(nodeId, 10, /*these do not matter ==>*/
    0, OUTGOING);
    // WHEN
    Map<Pair<Integer, Direction>, Long> firstRelationshipIds = new HashMap<>();
    int typeCount = 3;
    for (int typeId = 0, relationshipId = 0; typeId < typeCount; typeId++) {
        for (Direction direction : Direction.values()) {
            long firstRelationshipId = relationshipId++;
            cache.getAndPutRelationship(nodeId, typeId, direction, firstRelationshipId, true);
            firstRelationshipIds.put(Pair.of(typeId, direction), firstRelationshipId);
        }
    }
    AtomicInteger visitCount = new AtomicInteger();
    NodeRelationshipCache.GroupVisitor visitor = (nodeId1, typeId, out, in, loop) -> {
        visitCount.incrementAndGet();
        assertEquals(firstRelationshipIds.get(Pair.of(typeId, OUTGOING)).longValue(), out);
        assertEquals(firstRelationshipIds.get(Pair.of(typeId, INCOMING)).longValue(), in);
        assertEquals(firstRelationshipIds.get(Pair.of(typeId, BOTH)).longValue(), loop);
        return 0;
    };
    cache.getFirstRel(nodeId, visitor);
    // THEN
    assertEquals(typeCount, visitCount.get());
}
Also used : Arrays(java.util.Arrays) ArgumentMatchers.anyLong(org.mockito.ArgumentMatchers.anyLong) Direction(org.neo4j.graphdb.Direction) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) RunWith(org.junit.runner.RunWith) OUTGOING(org.neo4j.graphdb.Direction.OUTGOING) MutableIntObjectMap(org.eclipse.collections.api.map.primitive.MutableIntObjectMap) HashMap(java.util.HashMap) MutableLongObjectMap(org.eclipse.collections.api.map.primitive.MutableLongObjectMap) ArrayList(java.util.ArrayList) IntObjectMaps(org.eclipse.collections.impl.factory.primitive.IntObjectMaps) BOTH(org.neo4j.graphdb.Direction.BOTH) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) RandomRule(org.neo4j.test.rule.RandomRule) LongObjectHashMap(org.eclipse.collections.impl.map.mutable.primitive.LongObjectHashMap) LongHashSet(org.eclipse.collections.impl.set.mutable.primitive.LongHashSet) After(org.junit.After) Map(java.util.Map) Assert.fail(org.junit.Assert.fail) ArgumentMatchers.anyInt(org.mockito.ArgumentMatchers.anyInt) Parameterized(org.junit.runners.Parameterized) Collection(java.util.Collection) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) INCOMING(org.neo4j.graphdb.Direction.INCOMING) Mockito.verify(org.mockito.Mockito.verify) MutableLongSet(org.eclipse.collections.api.set.primitive.MutableLongSet) List(java.util.List) INSTANCE(org.neo4j.memory.EmptyMemoryTracker.INSTANCE) Rule(org.junit.Rule) Assert.assertFalse(org.junit.Assert.assertFalse) Math.max(java.lang.Math.max) Pair(org.neo4j.internal.helpers.collection.Pair) Assert.assertEquals(org.junit.Assert.assertEquals) Mockito.mock(org.mockito.Mockito.mock) HashMap(java.util.HashMap) LongObjectHashMap(org.eclipse.collections.impl.map.mutable.primitive.LongObjectHashMap) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ArgumentMatchers.anyLong(org.mockito.ArgumentMatchers.anyLong) Direction(org.neo4j.graphdb.Direction) Pair(org.neo4j.internal.helpers.collection.Pair) Test(org.junit.Test)

Example 5 with INSTANCE

use of org.neo4j.memory.EmptyMemoryTracker.INSTANCE in project neo4j by neo4j.

the class NumberArrayTest method arrays.

public static Collection<NumberArrayTestData> arrays() {
    PageCache pageCache = fixture.pageCache;
    Path dir = fixture.directory;
    NullLog log = NullLog.getInstance();
    Collection<NumberArrayTestData> list = new ArrayList<>();
    Map<String, NumberArrayFactory> factories = new HashMap<>();
    factories.put("HEAP", NumberArrayFactories.HEAP);
    factories.put("OFF_HEAP", NumberArrayFactories.OFF_HEAP);
    factories.put("AUTO_WITHOUT_PAGECACHE", NumberArrayFactories.AUTO_WITHOUT_PAGECACHE);
    factories.put("CHUNKED_FIXED_SIZE", NumberArrayFactories.CHUNKED_FIXED_SIZE);
    factories.put("autoWithPageCacheFallback", NumberArrayFactories.auto(pageCache, NULL, dir, true, NO_MONITOR, log, DEFAULT_DATABASE_NAME));
    factories.put("PageCachedNumberArrayFactory", new PageCachedNumberArrayFactory(pageCache, NULL, dir, log, DEFAULT_DATABASE_NAME));
    for (Map.Entry<String, NumberArrayFactory> entry : factories.entrySet()) {
        String name = entry.getKey() + " => ";
        NumberArrayFactory factory = entry.getValue();
        list.add(arrayData(name + "IntArray", factory.newIntArray(INDEXES, -1, INSTANCE), random -> random.nextInt(1_000_000_000), (array, index, value) -> array.set(index, (Integer) value), IntArray::get));
        list.add(arrayData(name + "DynamicIntArray", factory.newDynamicIntArray(CHUNK_SIZE, -1, INSTANCE), random -> random.nextInt(1_000_000_000), (array, index, value) -> array.set(index, (Integer) value), IntArray::get));
        list.add(arrayData(name + "LongArray", factory.newLongArray(INDEXES, -1, INSTANCE), random -> random.nextLong(1_000_000_000), (array, index, value) -> array.set(index, (Long) value), LongArray::get));
        list.add(arrayData(name + "DynamicLongArray", factory.newDynamicLongArray(CHUNK_SIZE, -1, INSTANCE), random -> random.nextLong(1_000_000_000), (array, index, value) -> array.set(index, (Long) value), LongArray::get));
        list.add(arrayData(name + "ByteArray5", factory.newByteArray(INDEXES, defaultByteArray(5), INSTANCE), random -> random.nextInt(1_000_000_000), (array, index, value) -> array.setInt(index, 1, (Integer) value), (array, index) -> array.getInt(index, 1)));
        list.add(arrayData(name + "DynamicByteArray5", factory.newDynamicByteArray(CHUNK_SIZE, defaultByteArray(5), INSTANCE), random -> random.nextInt(1_000_000_000), (array, index, value) -> array.setInt(index, 1, (Integer) value), (array, index) -> array.getInt(index, 1)));
        Function<RandomRule, Object> valueGenerator = random -> new long[] { random.nextLong(), random.nextInt(), (short) random.nextInt(), (byte) random.nextInt() };
        Writer<ByteArray> writer = (array, index, value) -> {
            long[] values = (long[]) value;
            array.setLong(index, 0, values[0]);
            array.setInt(index, 8, (int) values[1]);
            array.setShort(index, 12, (short) values[2]);
            array.setByte(index, 14, (byte) values[3]);
        };
        Reader<ByteArray> reader = (array, index) -> new long[] { array.getLong(index, 0), array.getInt(index, 8), array.getShort(index, 12), array.getByte(index, 14) };
        list.add(arrayData(name + "ByteArray15", factory.newByteArray(INDEXES, defaultByteArray(15), INSTANCE), valueGenerator, writer, reader));
        list.add(arrayData(name + "DynamicByteArray15", factory.newDynamicByteArray(CHUNK_SIZE, defaultByteArray(15), INSTANCE), valueGenerator, writer, reader));
    }
    return list;
}
Also used : Path(java.nio.file.Path) PageCache(org.neo4j.io.pagecache.PageCache) Arrays(java.util.Arrays) TestFactory(org.junit.jupiter.api.TestFactory) Collection(java.util.Collection) IOException(java.io.IOException) HashMap(java.util.HashMap) NULL(org.neo4j.io.pagecache.tracing.PageCacheTracer.NULL) Function(java.util.function.Function) NO_MONITOR(org.neo4j.internal.batchimport.cache.NumberArrayFactories.NO_MONITOR) ArrayList(java.util.ArrayList) AfterAll(org.junit.jupiter.api.AfterAll) Assertions.assertArrayEquals(org.junit.jupiter.api.Assertions.assertArrayEquals) Integer.max(java.lang.Integer.max) DEFAULT_DATABASE_NAME(org.neo4j.configuration.GraphDatabaseSettings.DEFAULT_DATABASE_NAME) INSTANCE(org.neo4j.memory.EmptyMemoryTracker.INSTANCE) Stream(java.util.stream.Stream) BeforeAll(org.junit.jupiter.api.BeforeAll) RandomRule(org.neo4j.test.rule.RandomRule) Map(java.util.Map) DynamicTest(org.junit.jupiter.api.DynamicTest) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) NullLog(org.neo4j.logging.NullLog) Path(java.nio.file.Path) ThrowingConsumer(org.junit.jupiter.api.function.ThrowingConsumer) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) RandomRule(org.neo4j.test.rule.RandomRule) NullLog(org.neo4j.logging.NullLog) HashMap(java.util.HashMap) Map(java.util.Map) PageCache(org.neo4j.io.pagecache.PageCache)

Aggregations

INSTANCE (org.neo4j.memory.EmptyMemoryTracker.INSTANCE)10 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)7 Test (org.junit.jupiter.api.Test)7 IOException (java.io.IOException)6 Assertions.assertEquals (org.junit.jupiter.api.Assertions.assertEquals)6 Mockito.mock (org.mockito.Mockito.mock)6 Inject (org.neo4j.test.extension.Inject)6 ArrayList (java.util.ArrayList)5 Mockito.when (org.mockito.Mockito.when)5 DatabaseLayout (org.neo4j.io.layout.DatabaseLayout)5 PageCache (org.neo4j.io.pagecache.PageCache)5 Values (org.neo4j.values.storable.Values)5 Path (java.nio.file.Path)4 List (java.util.List)4 AfterEach (org.junit.jupiter.api.AfterEach)4 ArgumentMatchers.any (org.mockito.ArgumentMatchers.any)4 Mockito.verify (org.mockito.Mockito.verify)4 Config (org.neo4j.configuration.Config)4 NULL (org.neo4j.io.pagecache.tracing.PageCacheTracer.NULL)4 Arrays (java.util.Arrays)3