Search in sources :

Example 56 with CursorContext

use of org.neo4j.io.pagecache.context.CursorContext in project neo4j by neo4j.

the class MuninnPageCacheTest method markCursorContextAsDirtyWhenReadingDataFromMoreRecentTransactions.

@Test
void markCursorContextAsDirtyWhenReadingDataFromMoreRecentTransactions() throws IOException {
    TestVersionContext versionContext = new TestVersionContext(() -> 3);
    try (MuninnPageCache pageCache = createPageCache(fs, 2, PageCacheTracer.NULL);
        PagedFile pagedFile = map(pageCache, file("a"), 8);
        CursorContext cursorContext = new CursorContext(PageCursorTracer.NULL, versionContext)) {
        versionContext.initWrite(7);
        try (PageCursor cursor = pagedFile.io(0, PF_SHARED_WRITE_LOCK, cursorContext)) {
            assertTrue(cursor.next());
            cursor.putLong(3);
        }
        versionContext.initRead();
        assertFalse(versionContext.isDirty());
        try (PageCursor cursor = pagedFile.io(0, PF_SHARED_READ_LOCK, cursorContext)) {
            assertTrue(cursor.next());
            assertEquals(3, cursor.getLong());
            assertTrue(versionContext.isDirty());
        }
    }
}
Also used : PagedFile(org.neo4j.io.pagecache.PagedFile) CursorContext(org.neo4j.io.pagecache.context.CursorContext) PageCursor(org.neo4j.io.pagecache.PageCursor) PageCacheTest(org.neo4j.io.pagecache.PageCacheTest) Test(org.junit.jupiter.api.Test)

Example 57 with CursorContext

use of org.neo4j.io.pagecache.context.CursorContext 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 58 with CursorContext

use of org.neo4j.io.pagecache.context.CursorContext in project neo4j by neo4j.

the class StageTest method shouldCloseOnPanic.

@Test
void shouldCloseOnPanic() {
    // given
    // a producer, a processor, a forked processor and a final step
    Configuration configuration = DEFAULT;
    TrackingPanicMonitor panicMonitor = new TrackingPanicMonitor();
    Stage stage = new Stage("test close on panic", null, configuration, random.nextBoolean() ? Step.ORDER_SEND_DOWNSTREAM : 0, ProcessorScheduler.SPAWN_THREAD, panicMonitor) {

        {
            // Producer
            add(new PullingProducerStep(control(), configuration) {

                private volatile long ticket;

                private final ChaosMonkey chaosMonkey = new ChaosMonkey();

                @Override
                protected Object nextBatchOrNull(long ticket, int batchSize) {
                    chaosMonkey.makeChaos();
                    this.ticket = ticket;
                    return new int[batchSize];
                }

                @Override
                protected long position() {
                    return ticket;
                }
            });
            // Processor
            add(new ProcessorStep<>(control(), "processor", configuration, 2, NULL) {

                private final ChaosMonkey chaosMonkey = new ChaosMonkey();

                @Override
                protected void process(Object batch, BatchSender sender, CursorContext cursorContext) {
                    chaosMonkey.makeChaos();
                    sender.send(batch);
                }
            });
            // Forked processor
            add(new ForkedProcessorStep<>(control(), "forked processor", configuration) {

                private final ChaosMonkey chaosMonkey = new ChaosMonkey();

                @Override
                protected void forkedProcess(int id, int processors, Object batch) {
                    chaosMonkey.makeChaos();
                }
            });
            // Final consumer
            add(new ProcessorStep<>(control(), "consumer", configuration, 1, NULL) {

                private final ChaosMonkey chaosMonkey = new ChaosMonkey();

                @Override
                protected void process(Object batch, BatchSender sender, CursorContext cursorContext) throws Throwable {
                    chaosMonkey.makeChaos();
                // don't pass the batch further, i.e. end of the line
                }
            });
        }
    };
    // when/then
    assertThrows(RuntimeException.class, () -> superviseDynamicExecution(stage));
    assertTrue(panicMonitor.hasReceivedPanic());
    assertTrue(panicMonitor.getReceivedPanic().getMessage().contains("Chaos monkey"));
}
Also used : Configuration(org.neo4j.internal.batchimport.Configuration) CursorContext(org.neo4j.io.pagecache.context.CursorContext) Test(org.junit.jupiter.api.Test)

Example 59 with CursorContext

use of org.neo4j.io.pagecache.context.CursorContext in project neo4j by neo4j.

the class ReadEntityIdsStep method process.

@Override
protected void process() {
    cursorContext = new CursorContext(pageCacheTracer.createPageCursorTracer(CURSOR_TRACER_TAG));
    entityIdIterator = entityIdIteratorSupplier.apply(cursorContext);
    super.process();
}
Also used : CursorContext(org.neo4j.io.pagecache.context.CursorContext)

Example 60 with CursorContext

use of org.neo4j.io.pagecache.context.CursorContext in project neo4j by neo4j.

the class GBPTreeGenericCountsStore method directUpdater.

/**
 * Opens and returns a {@link CountUpdater} which makes direct insertions into the backing tree. This comes from the use case of having a way
 * to build the initial data set without the context of transactions, such as batch-insertion or initial import.
 *
 * @param applyDeltas if {@code true} the writer will apply the changes as deltas, which means reading from the tree.
 * If {@code false} all changes will be written as-is, i.e. as if they are absolute counts.
 */
protected CountUpdater directUpdater(boolean applyDeltas, CursorContext cursorContext) throws IOException {
    boolean success = false;
    Lock lock = this.lock.writeLock();
    lock.lock();
    try {
        CountUpdater.CountWriter writer = applyDeltas ? new DeltaTreeWriter(() -> tree.writer(cursorContext), key -> readCountFromTree(key, cursorContext), layout, maxCacheSize) : new TreeWriter(tree.writer(cursorContext));
        CountUpdater updater = new CountUpdater(writer, lock);
        success = true;
        return updater;
    } finally {
        if (!success) {
            lock.unlock();
        }
    }
}
Also used : GBPTreeVisitor(org.neo4j.index.internal.gbptree.GBPTreeVisitor) MetadataMismatchException(org.neo4j.index.internal.gbptree.MetadataMismatchException) Writer(org.neo4j.index.internal.gbptree.Writer) Sets.immutable(org.eclipse.collections.api.factory.Sets.immutable) OutOfOrderSequence(org.neo4j.util.concurrent.OutOfOrderSequence) DatabaseReadOnlyChecker.readOnly(org.neo4j.configuration.helpers.DatabaseReadOnlyChecker.readOnly) Seeker(org.neo4j.index.internal.gbptree.Seeker) GBPTreeConsistencyCheckVisitor(org.neo4j.index.internal.gbptree.GBPTreeConsistencyCheckVisitor) CursorContext(org.neo4j.io.pagecache.context.CursorContext) IOUtils.closeAllUnchecked(org.neo4j.io.IOUtils.closeAllUnchecked) ReporterFactory(org.neo4j.annotations.documented.ReporterFactory) TreeFileNotFoundException(org.neo4j.index.internal.gbptree.TreeFileNotFoundException) ArrayUtils(org.apache.commons.lang3.ArrayUtils) NULL(org.neo4j.io.pagecache.tracing.PageCacheTracer.NULL) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) BASE_TX_ID(org.neo4j.storageengine.api.TransactionIdStore.BASE_TX_ID) Function(java.util.function.Function) GBPTree(org.neo4j.index.internal.gbptree.GBPTree) UnderlyingStorageException(org.neo4j.exceptions.UnderlyingStorageException) PrimitiveLongArrayQueue(org.neo4j.collection.PrimitiveLongArrayQueue) LongHashSet(org.eclipse.collections.impl.set.mutable.primitive.LongHashSet) Map(java.util.Map) PageCacheTracer(org.neo4j.io.pagecache.tracing.PageCacheTracer) RecoveryCleanupWorkCollector(org.neo4j.index.internal.gbptree.RecoveryCleanupWorkCollector) CountsKey.strayTxId(org.neo4j.internal.counts.CountsKey.strayTxId) Path(java.nio.file.Path) ReadWriteLock(java.util.concurrent.locks.ReadWriteLock) MemoryTracker(org.neo4j.memory.MemoryTracker) PrintStream(java.io.PrintStream) PageCache(org.neo4j.io.pagecache.PageCache) EMPTY_LONG_ARRAY(org.neo4j.collection.PrimitiveLongCollections.EMPTY_LONG_ARRAY) ArrayQueueOutOfOrderSequence(org.neo4j.util.concurrent.ArrayQueueOutOfOrderSequence) IOException(java.io.IOException) LongConsumer(java.util.function.LongConsumer) MutableLongSet(org.eclipse.collections.api.set.primitive.MutableLongSet) UncheckedIOException(java.io.UncheckedIOException) AtomicLong(java.util.concurrent.atomic.AtomicLong) Lock(java.util.concurrent.locks.Lock) CountsStorage(org.neo4j.counts.CountsStorage) MIN_STRAY_TX_ID(org.neo4j.internal.counts.CountsKey.MIN_STRAY_TX_ID) Preconditions.checkState(org.neo4j.util.Preconditions.checkState) MAX_STRAY_TX_ID(org.neo4j.internal.counts.CountsKey.MAX_STRAY_TX_ID) DatabaseReadOnlyChecker(org.neo4j.configuration.helpers.DatabaseReadOnlyChecker) ABSENT(org.neo4j.internal.counts.CountsChanges.ABSENT) FileSystemAbstraction(org.neo4j.io.fs.FileSystemAbstraction) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) ReadWriteLock(java.util.concurrent.locks.ReadWriteLock) Lock(java.util.concurrent.locks.Lock)

Aggregations

CursorContext (org.neo4j.io.pagecache.context.CursorContext)161 Test (org.junit.jupiter.api.Test)74 DefaultPageCacheTracer (org.neo4j.io.pagecache.tracing.DefaultPageCacheTracer)52 PageCursor (org.neo4j.io.pagecache.PageCursor)40 IOException (java.io.IOException)31 UncheckedIOException (java.io.UncheckedIOException)27 PageCursorTracer (org.neo4j.io.pagecache.tracing.cursor.PageCursorTracer)27 Path (java.nio.file.Path)17 PagedFile (org.neo4j.io.pagecache.PagedFile)17 ArrayList (java.util.ArrayList)16 PageCacheTest (org.neo4j.io.pagecache.PageCacheTest)15 MutableLong (org.apache.commons.lang3.mutable.MutableLong)13 MemoryTracker (org.neo4j.memory.MemoryTracker)12 PageCache (org.neo4j.io.pagecache.PageCache)11 ProgressListener (org.neo4j.internal.helpers.progress.ProgressListener)10 DynamicRecord (org.neo4j.kernel.impl.store.record.DynamicRecord)10 List (java.util.List)9 RepeatedTest (org.junit.jupiter.api.RepeatedTest)9 NodeRecord (org.neo4j.kernel.impl.store.record.NodeRecord)9 PageCacheTracer (org.neo4j.io.pagecache.tracing.PageCacheTracer)8