Skip to content

Commit 00e0526

Browse files
authored
fix: settle H2's ObjectDataType key type when a map is opened (#1311)
1 parent 3d519ef commit 00e0526

3 files changed

Lines changed: 37 additions & 11 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
## Unreleased
22

3-
Eleven changes from [@brettwooldridge](https://github.com/brettwooldridge), most of them found on a production system. Four are data-integrity fixes, three of which can end with a store that will not reopen or a query that quietly returns the wrong rows.
3+
Eleven changes from [@brettwooldridge](https://github.com/brettwooldridge), most of them found on a production system, and one H2 workaround found while testing them. Four are data-integrity fixes, three of which can end with a store that will not reopen or a query that quietly returns the wrong rows.
44

55
### Issue Fixes
66

@@ -32,6 +32,11 @@ Eleven changes from [@brettwooldridge](https://github.com/brettwooldridge), most
3232
- Observed on a production system on the first multi-threaded lookup after every restart, because every close before [#1295](https://github.com/nitrite/nitrite-java/pull/1295) left an empty map under the legacy name for the next start to drop.
3333
- The indexer and the MVStore map and R-tree registries now create their entries with `computeIfAbsent`, so there is one index instance and one map wrapper per name. `NitriteMVMap` keeps the name it was opened with and acts only when its compare-and-set wins, so `drop()` and `close()` run once; `removeMap` ignores a null name and no longer creates an empty map only to remove it.
3434

35+
- **Concurrent first reads of a map on an in-memory MVStore no longer fail inside H2** ([#1311](https://github.com/nitrite/nitrite-java/pull/1311))
36+
- H2's `ObjectDataType` picks the delegate that compares serialized keys on first use, through an unsynchronized field, and `SerializedObjectType.compare` checks delegates by identity. Threads making a map's first key comparison together could each install their own and fail with `UnsupportedOperationException: Can not compare`. The code is the same in h2 2.4.240 and 2.5.250.
37+
- **Only an in-memory MVStore was exposed.** A file-backed map is settled before any reader gets it, by reading its root page at open or by estimating the memory of a write. Through the public API, 32 threads making the first reads of a one-document indexed collection failed in 1 round of 5,000 on an in-memory MVStore, and in none of 10,000 rounds on a file-backed store, fresh or reopened. The shape that exposed it, the legacy-index migration of [#1309](https://github.com/nitrite/nitrite-java/pull/1309) handing sixteen threads a map it had just created, failed about 1 round in 100.
38+
- `NitriteMVStore` now settles each `ObjectDataType` key type once when it opens the map, on the one thread running `computeIfAbsent`. Nothing is serialized. It can go once H2 fixes the type upstream.
39+
3540
- **A unique index no longer rejects a document over a key that document already holds** ([#1295](https://github.com/nitrite/nitrite-java/pull/1295))
3641
- `addNitriteIds` treated any existing id under the key as a violation, so it counted the writer's own id against it. Another document under the key is a violation; the same document again is not - which is what a unique index over an array field with a repeated element does, and what an index rebuild or a replayed write does.
3742

‎nitrite-mvstore-adapter/src/main/java/org/dizitart/no2/mvstore/NitriteMVStore.java‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,8 @@
3939
import org.h2.mvstore.MVStore;
4040
import org.h2.mvstore.MVStoreException;
4141
import org.h2.mvstore.rtree.MVRTreeMap;
42+
import org.h2.mvstore.type.DataType;
43+
import org.h2.mvstore.type.ObjectDataType;
4244

4345
import lombok.extern.slf4j.Slf4j;
4446

@@ -51,6 +53,8 @@ public class NitriteMVStore extends AbstractNitriteStore<MVStoreConfig> {
5153

5254
private static final String COMPACT_THREADS_PROPERTY = "h2.compactThreads";
5355
private static final Object COMPACT_THREADS_LOCK = new Object();
56+
// any object H2 has no dedicated type for; see settleKeyType
57+
private static final Object SERIALIZED_KEY_SAMPLE = new Object();
5458

5559
private MVStore mvStore;
5660
private final Map<String, NitriteMap<?, ?>> nitriteMapRegistry;
@@ -246,6 +250,26 @@ private void initEventBus() {
246250
}
247251
}
248252

253+
/**
254+
* Settles an {@link ObjectDataType} key type on its serialized-object delegate while one
255+
* thread holds the map ({@code openMap} runs inside {@code computeIfAbsent}).
256+
*
257+
* <p>H2 picks that delegate on first use through an unsynchronized field, and
258+
* {@code SerializedObjectType.compare} checks delegates by identity, so threads making a
259+
* map's first key comparison at once can each install their own and fail with
260+
* {@code UnsupportedOperationException: Can not compare}. A file-backed map is settled
261+
* already, by reading its root page at open or estimating the memory of a write; an
262+
* in-memory store does neither. Every Nitrite map with {@code ObjectDataType} keys holds
263+
* serialized objects or strings, and a string map switches back on its first key through
264+
* a singleton delegate that compares without the identity check. Nothing is serialized.
265+
* The same code is in h2 2.4.240 and 2.5.250; drop this once H2 fixes it.
266+
*/
267+
private static void settleKeyType(DataType<?> keyType) {
268+
if (keyType instanceof ObjectDataType) {
269+
((ObjectDataType) keyType).getMemory(SERIALIZED_KEY_SAMPLE);
270+
}
271+
}
272+
249273
@SuppressWarnings({"rawtypes", "unchecked"})
250274
private MVMap openMVMap(String mapName, MVMap.MapBuilder builder) {
251275
Exception exception = null;
@@ -256,6 +280,7 @@ private MVMap openMVMap(String mapName, MVMap.MapBuilder builder) {
256280
while (version >= 0) {
257281
try {
258282
MVMap map = mvStore.openMap(mapName, mapBuilder);
283+
settleKeyType(map.getKeyType());
259284
enableAutoCommitIfPending();
260285
return map;
261286
} catch (MVStoreException me) {

‎nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/mvstore/NitriteMVStoreTest.java‎

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -34,10 +34,8 @@
3434
import java.nio.file.Files;
3535
import java.nio.file.Path;
3636
import java.util.ArrayList;
37-
import java.util.Arrays;
3837
import java.util.Collections;
3938
import java.util.Iterator;
40-
import java.util.LinkedHashSet;
4139
import java.util.List;
4240
import java.util.Set;
4341
import java.util.concurrent.CountDownLatch;
@@ -208,21 +206,19 @@ public void testDropThroughAWrapperWhoseMapIsAlreadyGone() {
208206
@Test
209207
public void testConcurrentFirstReadOfALegacyIndexMigratesOnce() throws Exception {
210208
// the first multi-threaded read after a reopen used to build one index instance per
211-
// thread, each migrating and dropping the legacy map; the second drop failed
209+
// thread, each migrating and dropping the legacy map; the second drop failed.
210+
// One id: the migration's single put makes no key comparison, so the readers make the
211+
// composite map's first one together, which failed inside H2 with "Can not compare"
212+
// (about 1 round in 100) until NitriteMVStore.settleKeyType
212213
final int threads = 16;
213214
final ExecutorService executorService = Executors.newFixedThreadPool(threads);
214215
try {
215-
for (int round = 0; round < 50; round++) {
216+
for (int round = 0; round < 300; round++) {
216217
final NitriteMVStore store = openInMemoryStore();
217218
try {
218219
final IndexDescriptor desc = new IndexDescriptor(IndexType.NON_UNIQUE,
219220
Fields.withNames("a"), "c");
220-
// two ids, so the migration's second put is the composite map's first key
221-
// comparison: H2's ObjectDataType settles its key type on first use without
222-
// any synchronization, and sixteen readers making that first comparison at
223-
// once can fail inside H2 with "Can not compare" (h2 2.4.240 and 2.5.250)
224-
final Set<NitriteId> ids = new LinkedHashSet<>(Arrays.asList(
225-
NitriteId.createId(1L), NitriteId.createId(2L)));
221+
final Set<NitriteId> ids = Collections.singleton(NitriteId.createId(1L));
226222
store.openMap(deriveIndexMapName(desc), DBValue.class, ArrayList.class)
227223
.put(new DBValue("k"), new ArrayList<>(ids));
228224

0 commit comments

Comments
 (0)