|
| 1 | +/* |
| 2 | + * Copyright DataStax, Inc. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package io.github.jbellis.jvector.graph; |
| 18 | + |
| 19 | +import com.carrotsearch.randomizedtesting.RandomizedTest; |
| 20 | +import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope; |
| 21 | +import io.github.jbellis.jvector.graph.similarity.BuildScoreProvider; |
| 22 | +import io.github.jbellis.jvector.graph.similarity.DefaultSearchScoreProvider; |
| 23 | +import io.github.jbellis.jvector.graph.similarity.SearchScoreProvider; |
| 24 | +import io.github.jbellis.jvector.util.FixedBitSet; |
| 25 | +import io.github.jbellis.jvector.vector.VectorSimilarityFunction; |
| 26 | +import io.github.jbellis.jvector.vector.types.VectorFloat; |
| 27 | +import org.junit.Test; |
| 28 | +import org.slf4j.Logger; |
| 29 | +import org.slf4j.LoggerFactory; |
| 30 | + |
| 31 | +import static io.github.jbellis.jvector.TestUtil.createRandomVectors; |
| 32 | +import static io.github.jbellis.jvector.TestUtil.randomVector; |
| 33 | + |
| 34 | +import java.util.Collections; |
| 35 | +import java.util.ArrayList; |
| 36 | +import java.util.List; |
| 37 | +import java.util.Map; |
| 38 | +import java.util.concurrent.ConcurrentHashMap; |
| 39 | +import java.util.concurrent.CopyOnWriteArrayList; |
| 40 | +import java.util.concurrent.ExecutionException; |
| 41 | +import java.util.concurrent.atomic.AtomicInteger; |
| 42 | +import java.util.concurrent.locks.Lock; |
| 43 | +import java.util.concurrent.locks.ReentrantLock; |
| 44 | +import java.util.stream.Collectors; |
| 45 | +import java.util.stream.IntStream; |
| 46 | + |
| 47 | +/** |
| 48 | + * Runs "nVectors" operations, where each operation is either: |
| 49 | + * - an insertion |
| 50 | + * - a mock deletion, instantiated through the use of a BitSet for skipping these nodes during search |
| 51 | + * - a search |
| 52 | + * With probability 0.01, we run cleanup to commit the deletions to the index. The cleanup process and the insertions |
| 53 | + * cannot be concurrently executed (we use a lock to control their execution). |
| 54 | + */ |
| 55 | +@ThreadLeakScope(ThreadLeakScope.Scope.NONE) |
| 56 | +public class TestConcurrentReadWriteDeletes extends RandomizedTest { |
| 57 | + private static final Logger logger = LoggerFactory.getLogger(TestConcurrentReadWriteDeletes.class); |
| 58 | + |
| 59 | + private static final int nVectors = 20_000; |
| 60 | + private static final int dimension = 16; |
| 61 | + private static final double cleanupProbability = 0.01; |
| 62 | + |
| 63 | + private KeySet keysInserted = new KeySet(); |
| 64 | + private List<Integer> keysRemoved = new CopyOnWriteArrayList(); |
| 65 | + |
| 66 | + private List<VectorFloat<?>> vectors = createRandomVectors(nVectors, dimension); |
| 67 | + private RandomAccessVectorValues ravv = new ListRandomAccessVectorValues(vectors, dimension); |
| 68 | + |
| 69 | + private VectorSimilarityFunction similarityFunction = VectorSimilarityFunction.DOT_PRODUCT; |
| 70 | + |
| 71 | + private BuildScoreProvider bsp = BuildScoreProvider.randomAccessScoreProvider(ravv, similarityFunction); |
| 72 | + private GraphIndexBuilder builder = new GraphIndexBuilder(bsp, 2, 2, 10, 1.0f, 1.0f, true); |
| 73 | + |
| 74 | + private FixedBitSet liveNodes = new FixedBitSet(nVectors); |
| 75 | + |
| 76 | + private final Lock writeLock = new ReentrantLock(); |
| 77 | + |
| 78 | + @Test |
| 79 | + public void testConcurrentReadsWritesDeletes() throws ExecutionException, InterruptedException { |
| 80 | + var vv = ravv.threadLocalSupplier(); |
| 81 | + |
| 82 | + testConcurrentOps(i -> { |
| 83 | + var R = getRandom(); |
| 84 | + if (R.nextDouble() < 0.2 || keysInserted.isEmpty()) |
| 85 | + { |
| 86 | + // In the future, we could improve this test by acquiring the lock earlier and executing other |
| 87 | + writeLock.lock(); |
| 88 | + try { |
| 89 | + builder.addGraphNode(i, vv.get().getVector(i)); |
| 90 | + liveNodes.set(i); |
| 91 | + keysInserted.add(i); |
| 92 | + } finally { |
| 93 | + writeLock.unlock(); |
| 94 | + } |
| 95 | + } else if (R.nextDouble() < 0.1) { |
| 96 | + var key = keysInserted.getRandom(); |
| 97 | + if (!keysRemoved.contains(key)) { |
| 98 | + liveNodes.flip(key); |
| 99 | + keysRemoved.add(key); |
| 100 | + } |
| 101 | + } else { |
| 102 | + var queryVector = randomVector(getRandom(), dimension); |
| 103 | + SearchScoreProvider ssp = DefaultSearchScoreProvider.exact(queryVector, similarityFunction, ravv); |
| 104 | + |
| 105 | + int topK = Math.min(1, keysInserted.size()); |
| 106 | + int rerankK = Math.min(50, keysInserted.size()); |
| 107 | + |
| 108 | + GraphSearcher searcher = new GraphSearcher(builder.getGraph()); |
| 109 | + searcher.search(ssp, topK, rerankK, 0.f, 0.f, liveNodes); |
| 110 | + } |
| 111 | + }); |
| 112 | + } |
| 113 | + |
| 114 | + @FunctionalInterface |
| 115 | + private interface Op |
| 116 | + { |
| 117 | + void run(int i) throws Throwable; |
| 118 | + } |
| 119 | + |
| 120 | + private void testConcurrentOps(Op op) throws ExecutionException, InterruptedException { |
| 121 | + AtomicInteger counter = new AtomicInteger(); |
| 122 | + long start = System.currentTimeMillis(); |
| 123 | + |
| 124 | + // Use a simpler approach that doesn't rely on parallel streams |
| 125 | + var keys = IntStream.range(0, nVectors).boxed().collect(Collectors.toList()); |
| 126 | + Collections.shuffle(keys, getRandom()); |
| 127 | + |
| 128 | + // Use a thread-safe approach without relying on RandomizedContext |
| 129 | + int threadCount = Math.min(Runtime.getRuntime().availableProcessors(), 8); // Limit thread count |
| 130 | + List<Thread> threads = new ArrayList<>(); |
| 131 | + int keysPerThread = nVectors / threadCount; |
| 132 | + |
| 133 | + // Create a thread-safe random seed for each thread |
| 134 | + final long randomSeed = getRandom().nextLong(); |
| 135 | + |
| 136 | + for (int t = 0; t < threadCount; t++) { |
| 137 | + final int threadIndex = t; |
| 138 | + final int startIdx = threadIndex * keysPerThread; |
| 139 | + final int endIdx = (threadIndex == threadCount - 1) ? keys.size() : (threadIndex + 1) * keysPerThread; |
| 140 | + |
| 141 | + Thread thread = new Thread(() -> { |
| 142 | + for (int i = startIdx; i < endIdx; i++) { |
| 143 | + int key = keys.get(i); |
| 144 | + wrappedOp(op, key); |
| 145 | + |
| 146 | + if (counter.incrementAndGet() % 1_000 == 0) { |
| 147 | + var elapsed = System.currentTimeMillis() - start; |
| 148 | + logger.info(String.format("%d ops in %dms = %f ops/s", |
| 149 | + counter.get(), elapsed, counter.get() * 1000.0 / elapsed)); |
| 150 | + } |
| 151 | + |
| 152 | + if (getRandom().nextDouble() < cleanupProbability) { |
| 153 | + writeLock.lock(); |
| 154 | + try { |
| 155 | + for (Integer keyToRemove : keysRemoved) { |
| 156 | + builder.markNodeDeleted(keyToRemove); |
| 157 | + } |
| 158 | + keysRemoved.clear(); |
| 159 | + builder.cleanup(); |
| 160 | + } finally { |
| 161 | + writeLock.unlock(); |
| 162 | + } |
| 163 | + } |
| 164 | + } |
| 165 | + }); |
| 166 | + |
| 167 | + threads.add(thread); |
| 168 | + thread.start(); |
| 169 | + } |
| 170 | + |
| 171 | + // Wait for all threads to complete |
| 172 | + for (Thread thread : threads) { |
| 173 | + thread.join(); |
| 174 | + } |
| 175 | + } |
| 176 | + |
| 177 | + private static void wrappedOp(Op op, Integer i) { |
| 178 | + try |
| 179 | + { |
| 180 | + op.run(i); |
| 181 | + } |
| 182 | + catch (Throwable e) |
| 183 | + { |
| 184 | + throw new RuntimeException(e); |
| 185 | + } |
| 186 | + } |
| 187 | + |
| 188 | + private static class KeySet |
| 189 | + { |
| 190 | + private final Map<Integer, Integer> keys = new ConcurrentHashMap<>(); |
| 191 | + private final AtomicInteger ordinal = new AtomicInteger(); |
| 192 | + |
| 193 | + public void add(Integer key) |
| 194 | + { |
| 195 | + var i = ordinal.getAndIncrement(); |
| 196 | + keys.put(i, key); |
| 197 | + } |
| 198 | + |
| 199 | + public int getRandom() |
| 200 | + { |
| 201 | + if (isEmpty()) |
| 202 | + throw new IllegalStateException(); |
| 203 | + var i = TestConcurrentReadWriteDeletes.getRandom().nextInt(ordinal.get()); |
| 204 | + // in case there is race with add(key), retry another random |
| 205 | + return keys.containsKey(i) ? keys.get(i) : getRandom(); |
| 206 | + } |
| 207 | + |
| 208 | + public boolean isEmpty() |
| 209 | + { |
| 210 | + return keys.isEmpty(); |
| 211 | + } |
| 212 | + |
| 213 | + public int size() { |
| 214 | + return keys.size(); |
| 215 | + } |
| 216 | + } |
| 217 | +} |
0 commit comments