Skip to content

Commit 374a193

Browse files
fix: skip documents removed between an index lookup and the fetch (#1302)
An index scan is two steps that are not atomic under concurrent writes: the index yields the matching ids, then each document is fetched from the collection map. A document removed in between came back as a (id, null) row. With a residual filter that row reached Filter.apply and threw NullPointerException from the filter's document.get(); without one the cursor handed the caller a null element. The by-id fast path had the same window between containsKey and get. - IndexedStream now prefetches and drops ids whose document is gone; skip() still walks ids without fetching them. - FilteredStream treats a row without a document as a non-match. - The by-id path does one get and yields an empty stream when it is null. The test removes a document from the collection's map behind the index's back, which is what a concurrent remove looks like to a reader that already holds the ids; on the unfixed code its indexed-plus-residual case throws and the others return null rows. Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
1 parent 2c833d6 commit 374a193

4 files changed

Lines changed: 127 additions & 11 deletions

File tree

‎nitrite/src/main/java/org/dizitart/no2/collection/operation/ReadOperations.java‎

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -227,12 +227,11 @@ private RecordStream<Pair<NitriteId, Document>> findSuitableStream(FindPlan find
227227
NitriteId nitriteId = idValue instanceof Long
228228
? NitriteId.createId((long) idValue)
229229
: NitriteId.createId(String.valueOf(idValue));
230-
if (nitriteMap.containsKey(nitriteId)) {
231-
Document document = nitriteMap.get(nitriteId);
232-
rawStream = RecordStream.single(pair(nitriteId, document));
233-
} else {
234-
rawStream = RecordStream.empty();
235-
}
230+
// one lookup: a document removed between containsKey and get would be a null row
231+
Document document = nitriteMap.get(nitriteId);
232+
rawStream = document == null
233+
? RecordStream.empty()
234+
: RecordStream.single(pair(nitriteId, document));
236235
} else {
237236
IndexDescriptor indexDescriptor = findPlan.getIndexDescriptor();
238237
if (indexDescriptor != null) {

‎nitrite/src/main/java/org/dizitart/no2/common/streams/FilteredStream.java‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,8 @@ public void remove() {
8989
private boolean setNextId() {
9090
while (iterator.hasNext()) {
9191
final Pair<NitriteId, Document> pair = iterator.next();
92-
if (filter.apply(pair)) {
92+
// a row whose document is gone is not a match for anything
93+
if (pair.getSecond() != null && filter.apply(pair)) {
9394
nextPair = pair;
9495
nextPairSet = true;
9596
return true;

‎nitrite/src/main/java/org/dizitart/no2/common/streams/IndexedStream.java‎

Lines changed: 29 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
import org.dizitart.no2.store.NitriteMap;
2525

2626
import java.util.Iterator;
27+
import java.util.NoSuchElementException;
2728
import java.util.Set;
2829

2930
/**
@@ -49,6 +50,7 @@ private static class IndexedStreamIterator implements Iterator<Pair<NitriteId, D
4950
SkippableIterator {
5051
private final Iterator<NitriteId> iterator;
5152
private final NitriteMap<NitriteId, Document> nitriteMap;
53+
private Pair<NitriteId, Document> next;
5254

5355
IndexedStreamIterator(Iterator<NitriteId> iterator,
5456
NitriteMap<NitriteId, Document> nitriteMap) {
@@ -58,7 +60,7 @@ private static class IndexedStreamIterator implements Iterator<Pair<NitriteId, D
5860

5961
@Override
6062
public boolean hasNext() {
61-
return iterator.hasNext();
63+
return next != null || advance();
6264
}
6365

6466
/**
@@ -68,6 +70,10 @@ public boolean hasNext() {
6870
@Override
6971
public long skip(long count) {
7072
long skipped = 0;
73+
if (next != null && count > 0) {
74+
next = null;
75+
skipped++;
76+
}
7177
while (skipped < count && iterator.hasNext()) {
7278
iterator.next();
7379
skipped++;
@@ -77,9 +83,28 @@ public long skip(long count) {
7783

7884
@Override
7985
public Pair<NitriteId, Document> next() {
80-
NitriteId id = iterator.next();
81-
Document document = nitriteMap.get(id);
82-
return new Pair<>(id, document);
86+
if (next == null && !advance()) {
87+
throw new NoSuchElementException();
88+
}
89+
Pair<NitriteId, Document> current = next;
90+
next = null;
91+
return current;
92+
}
93+
94+
/**
95+
* A document removed between the index lookup and the fetch is no longer a row: it is
96+
* skipped rather than handed downstream as a null for a residual filter to dereference.
97+
*/
98+
private boolean advance() {
99+
while (iterator.hasNext()) {
100+
NitriteId id = iterator.next();
101+
Document document = nitriteMap.get(id);
102+
if (document != null) {
103+
next = new Pair<>(id, document);
104+
return true;
105+
}
106+
}
107+
return false;
83108
}
84109
}
85110
}
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
/*
2+
* Copyright (c) 2017-2020. Nitrite author or authors.
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 org.dizitart.no2.collection;
18+
19+
import org.dizitart.no2.Nitrite;
20+
import org.dizitart.no2.filters.Filter;
21+
import org.dizitart.no2.index.IndexOptions;
22+
import org.dizitart.no2.index.IndexType;
23+
import org.dizitart.no2.store.NitriteMap;
24+
import org.junit.After;
25+
import org.junit.Before;
26+
import org.junit.Test;
27+
28+
import java.util.List;
29+
30+
import static org.dizitart.no2.filters.FluentFilter.where;
31+
import static org.dizitart.no2.integration.TestUtil.createDb;
32+
import static org.junit.Assert.*;
33+
34+
/**
35+
* An index lookup and the fetch of the documents it names are not atomic: a document removed in
36+
* between must simply be absent from the result, never a null row that a residual filter, or the
37+
* caller, dereferences.
38+
* <p>
39+
* The window is reproduced by removing the document from the collection's map behind the index's
40+
* back, which is exactly what a concurrent remove looks like to a reader that already holds the ids.
41+
*/
42+
public class IndexScanRemovedDocumentTest {
43+
private Nitrite db;
44+
private NitriteCollection collection;
45+
private NitriteId removedId;
46+
47+
@Before
48+
public void setUp() {
49+
db = createDb();
50+
collection = db.getCollection("race");
51+
collection.createIndex(IndexOptions.indexOptions(IndexType.NON_UNIQUE), "group");
52+
for (int n = 1; n <= 3; n++) {
53+
collection.insert(Document.createDocument("group", "a").put("n", n));
54+
}
55+
removedId = collection.find(where("n").eq(2)).firstOrNull().getId();
56+
57+
NitriteMap<NitriteId, Document> map = db.getStore().openMap("race", NitriteId.class, Document.class);
58+
assertNotNull(map.remove(removedId));
59+
}
60+
61+
@After
62+
public void tearDown() {
63+
db.close();
64+
}
65+
66+
@Test
67+
public void testIndexScanWithResidualFilterSkipsRemovedDocument() {
68+
List<Document> found = collection.find(where("group").eq("a").and(where("n").gte(1))).toList();
69+
assertEquals(2, found.size());
70+
assertTrue(found.stream().noneMatch(d -> d == null));
71+
assertTrue(found.stream().noneMatch(d -> d.getId().equals(removedId)));
72+
}
73+
74+
@Test
75+
public void testIndexScanWithoutResidualFilterSkipsRemovedDocument() {
76+
List<Document> found = collection.find(where("group").eq("a")).toList();
77+
assertEquals(2, found.size());
78+
assertTrue(found.stream().noneMatch(d -> d == null));
79+
}
80+
81+
@Test
82+
public void testIndexScanSizeExcludesRemovedDocument() {
83+
assertEquals(2, collection.find(where("group").eq("a").and(where("n").gte(1))).size());
84+
}
85+
86+
@Test
87+
public void testByIdOfRemovedDocumentIsEmpty() {
88+
assertNull(collection.find(Filter.byId(removedId)).firstOrNull());
89+
assertNull(collection.getById(removedId));
90+
}
91+
}

0 commit comments

Comments
 (0)