diff --git a/engine/src/main/java/com/arcadedb/engine/NodeLocalFiles.java b/engine/src/main/java/com/arcadedb/engine/NodeLocalFiles.java index eb36a1f380e..4684a41bcbf 100644 --- a/engine/src/main/java/com/arcadedb/engine/NodeLocalFiles.java +++ b/engine/src/main/java/com/arcadedb/engine/NodeLocalFiles.java @@ -18,6 +18,10 @@ */ package com.arcadedb.engine; +import com.arcadedb.index.vector.LSMVectorIndexGraphFile; +import com.arcadedb.index.vector.LSMVectorIndexGraphManifest; +import com.arcadedb.index.vector.LSMVectorIndexOrdinalMapFile; +import com.arcadedb.index.vector.LSMVectorIndexPQFile; import com.arcadedb.schema.LocalSchema; /** @@ -36,6 +40,19 @@ * Analytical View's persisted CSR and contraction-hierarchy orders. A cache of data the database already holds, written * at close and - in a replicated database - only on the leader, so a cluster has one on the current leader, a stale one * wherever leadership used to be and none elsewhere. + *
  • An LSM vector index's proximity graph and everything derived from it (issue #9751): the {@code .vecgraph} + * component, its {@code .vecgraphfp} manifest and {@code .vecordmap} ordinal map, and the {@code .vecpq} product + * quantization. Every node builds its own graph, on the inner database instance and without the WAL (issues #8292, + * #8905), from the vectors the index pages DO replicate, so the graph pages carry different bytes on every node - the + * JVector build is parallel and not deterministic - and the PQ codebooks are trained from the same node-local pass. + * The three plain side files are not shipped by a snapshot at all; the {@code .vecgraph} component is (it is a + * registered page file), without the manifest beside it (issue #9758). A divergence in any of them is a cache that + * differs, never data that does: the vectors themselves live in the index's own pages, which ARE compared.
  • + *
  • {@link TransactionManager#LAST_TX_ID_FILE_NAME}: the recency marker, holding the highest transaction id this + * node had assigned the last time it rotated its WAL or closed (issue #5277). A snapshot ships a synthesized copy, but + * on a live node the file is rewritten at moments that are this node's own, so two healthy peers at the same commit + * routinely hold different values - or one holds none (issue #9751). Node-local here means "not comparable", not + * "never shipped".
  • * * A new engine side file that is not replicated content belongs here. {@code Issue9638NodeLocalFilesChecksumTest} in * {@code ha-raft} drives a real database through its writers and fails on a file that is neither shipped by a snapshot @@ -53,16 +70,40 @@ private NodeLocalFiles() { /** * True when {@code fileName} (a name, never a path) is one of the node-local files above. Matched by exact name or by * the full prefix-plus-extension shape, never by a substring, so a component file of a type named {@code gav-x} or - * {@code statistics} is still data: a component file's name always ends with its own extension, which is neither of - * the two below. The shapes describe the files the engine itself creates; a user file dropped into the directory that - * happens to take one of them (say {@code gav-notes.csr}) is left out too, which is harmless because nothing in the - * database reads or ships it. + * {@code statistics} is still data: a component file's name always ends with its own extension, and the only component + * extension matched below is the vector graph's own {@code .vecgraph}. The shapes describe the files the engine + * itself creates; a user file dropped into the directory that happens to take one of them (say {@code gav-notes.csr}) + * is left out too, which is harmless because nothing in the database reads or ships it. + *

    + * "Node-local" answers "may two healthy copies differ here?", not "is it shipped?". The {@code .vecgraph} + * component and {@code last-tx-id.bin} are both node-local and both carried by an HA snapshot, so a caller deciding + * what to SHIP or BACK UP must not use this method to skip files. */ public static boolean isNodeLocalFileName(final String fileName) { return fileName.equals(LocalSchema.STATISTICS_FILE_NAME) || fileName.equals(LocalSchema.CACHED_COUNT_FILE_NAME_LEGACY) || fileName.equals(DATABASE_LOCK_FILE_NAME) + || fileName.equals(TransactionManager.LAST_TX_ID_FILE_NAME) + || isVectorGraphFileName(fileName) || (fileName.startsWith(GAV_CSR_FILE_PREFIX) && (fileName.endsWith(GAV_CSR_FILE_EXTENSION) || fileName.endsWith(CCH_ORDER_FILE_EXTENSION))); } + + /** + * True when {@code fileName} is an LSM vector index's node-locally built graph or one of the files derived from it: + * the {@code .vecgraph} component, the {@code .vecgraphfp} manifest, the {@code .vecordmap} ordinal map and the + * {@code .vecpq} product quantization (issue #9751). Matched by the final extension, which is how every one of their + * writers names them ({@code .}); a write in flight ends in {@code .tmp} instead and is not matched here. + */ + public static boolean isVectorGraphFileName(final String fileName) { + return endsWithExtension(fileName, LSMVectorIndexGraphFile.FILE_EXT) + || endsWithExtension(fileName, LSMVectorIndexGraphManifest.FILE_EXT) + || endsWithExtension(fileName, LSMVectorIndexOrdinalMapFile.FILE_EXT) + || endsWithExtension(fileName, LSMVectorIndexPQFile.FILE_EXT); + } + + private static boolean endsWithExtension(final String fileName, final String extension) { + final int dot = fileName.length() - extension.length() - 1; + return dot > 0 && fileName.charAt(dot) == '.' && fileName.endsWith(extension); + } } diff --git a/ha-raft/src/main/java/com/arcadedb/server/ha/raft/PostVerifyDatabaseHandler.java b/ha-raft/src/main/java/com/arcadedb/server/ha/raft/PostVerifyDatabaseHandler.java index d5997832d15..ea6d21353b7 100644 --- a/ha-raft/src/main/java/com/arcadedb/server/ha/raft/PostVerifyDatabaseHandler.java +++ b/ha-raft/src/main/java/com/arcadedb/server/ha/raft/PostVerifyDatabaseHandler.java @@ -20,6 +20,7 @@ import com.arcadedb.GlobalConfiguration; import com.arcadedb.database.DatabaseInternal; +import com.arcadedb.engine.NodeLocalFiles; import com.arcadedb.engine.PageSnapshot; import com.arcadedb.engine.PaginatedComponent; import com.arcadedb.engine.timeseries.ListedSealedStore; @@ -661,7 +662,7 @@ private boolean computeLocalChecksums(final DatabaseInternal db, final JSONObjec try { // #7955: AN INDEX COMPACTION IN FLIGHT HAS A REGISTERED temp_* COMPONENT FILE, SO THE WINDOW CARRIES // IT - AND ONLY THE NODE THAT HAPPENS TO BE COMPACTING HAS ONE. SEE isTemporaryFileName - if (PaginatedComponent.isTemporaryFileName(file.fileName())) + if (isNotCompared(file.fileName())) continue; collectFileInfo(snapshotChecksums, snapshotFiles, file.fileName(), snapshot.calculateChecksum(file.fileId()), file.size()); @@ -700,7 +701,7 @@ private boolean computeLocalChecksums(final DatabaseInternal db, final JSONObjec db.getPageManager().suspendFlushAndExecute(db, () -> { runChecksummingHook(null); for (final var file : db.getFileManager().getFiles()) - if (file != null && !PaginatedComponent.isTemporaryFileName(file.getFileName())) { + if (file != null && !isNotCompared(file.getFileName())) { try { collectFileInfo(localChecksums, localFiles, file.getFileName(), file.calculateChecksum(), file.getSize()); } catch (final Exception e) { @@ -720,6 +721,17 @@ private boolean computeLocalChecksums(final DatabaseInternal db, final JSONObjec return sealedStoresCovered[0]; } + /** + * Whether a registered page file is left out of the comparison because only this node has it, or only this node's + * copy of it: an index-compaction temporary (#7955), or a component the engine declares node-local - in practice an + * LSM vector index's {@code .vecgraph}, which every node builds for itself without the WAL, so its pages differ on a + * healthy cluster (#9751). The vectors it is built from live in the index's own pages, which ARE compared. The same + * declaration {@code SnapshotManager.computeFileChecksums} applies, so the two collectors cannot disagree on it. + */ + static boolean isNotCompared(final String fileName) { + return PaginatedComponent.isTemporaryFileName(fileName) || NodeLocalFiles.isNodeLocalFileName(fileName); + } + /** * The image one verify reads on the window path: the point-in-time page window, and the TimeSeries sealed stores as * they were listed in the same read-locked frame as its t0. {@code sealedFiles} is {@code null} when the compaction diff --git a/ha-raft/src/main/java/com/arcadedb/server/ha/raft/SnapshotManager.java b/ha-raft/src/main/java/com/arcadedb/server/ha/raft/SnapshotManager.java index 436806647d8..2f09c27863b 100644 --- a/ha-raft/src/main/java/com/arcadedb/server/ha/raft/SnapshotManager.java +++ b/ha-raft/src/main/java/com/arcadedb/server/ha/raft/SnapshotManager.java @@ -340,6 +340,10 @@ public static Map computeFileChecksums(final File directory, final * {@code database.lck}, empty today and so matching by accident. They are declared by * {@link NodeLocalFiles#isNodeLocalFileName(String)} in the engine, beside the constants their writers build the names * from, rather than listed here, so a new engine side file is classified where it is written. + *

    + * #9751 adds two more families there: an LSM vector index's node-locally built graph with its manifest, ordinal map + * and product quantization, and the {@code last-tx-id.bin} recency marker, which a snapshot does ship but which a live + * node rewrites at moments of its own. */ private static boolean isNodeLocalFileName(final String name) { return name.endsWith(".wal") diff --git a/ha-raft/src/test/java/com/arcadedb/server/ha/raft/Issue9638NodeLocalFilesChecksumTest.java b/ha-raft/src/test/java/com/arcadedb/server/ha/raft/Issue9638NodeLocalFilesChecksumTest.java index a4858e7a308..aeb0ab9bb3c 100644 --- a/ha-raft/src/test/java/com/arcadedb/server/ha/raft/Issue9638NodeLocalFilesChecksumTest.java +++ b/ha-raft/src/test/java/com/arcadedb/server/ha/raft/Issue9638NodeLocalFilesChecksumTest.java @@ -27,6 +27,7 @@ import com.arcadedb.graph.olap.ContractionHierarchy; import com.arcadedb.graph.olap.GraphAnalyticalView; import com.arcadedb.schema.LocalSchema; +import com.arcadedb.schema.LocalTimeSeriesType; import com.arcadedb.schema.Type; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -157,6 +158,20 @@ void everyFileARealDatabaseWritesIsEitherShippedOrLeftOutOfTheChecksums(@TempDir assertThat(cch).isNotNull(); assertThat(cch.awaitReady(false, 60, TimeUnit.SECONDS)).isTrue(); + // #9751: LSM VECTOR INDEXES, THEIR GRAPHS BUILT, WRITE THE GRAPH COMPONENT AND THREE PLAIN SIDE FILES BESIDE IT - + // ONE WITHOUT AND ONE WITH PRODUCT QUANTIZATION, SINCE ONLY THE FORMER WRITES AN ORDINAL MAP AND ONLY THE LATTER A PQ + Issue9751VectorSideFilesChecksumTest.createVectorIndex(database, "Doc", "NONE"); + Issue9751VectorSideFilesChecksumTest.createVectorIndex(database, "PqDoc", "PRODUCT"); + + // #9751: AND A TIMESERIES TYPE WITH A SEALED STORE, THE OTHER WRITER OF RAW FILES INTO THE DIRECTORY + database.command("sql", "CREATE TIMESERIES TYPE Reading TIMESTAMP ts TAGS (id STRING) FIELDS (value DOUBLE) SHARDS 1"); + database.transaction(() -> { + for (int i = 0; i < 100; i++) + database.command("sql", "INSERT INTO Reading SET ts = ?, id = 's1', value = ?", 1_700_000_000_000L + i * 1000L, + (double) i); + }); + ((LocalTimeSeriesType) database.getSchema().getType("Reading")).getEngine().compactAll(); + for (final File file : listFiles(path)) seenWhileOpen.add(file.getName()); assertThat(seenWhileOpen).as("the open database holds its lock file, so the guard reaches it").contains("database.lck"); @@ -173,6 +188,12 @@ void everyFileARealDatabaseWritesIsEitherShippedOrLeftOutOfTheChecksums(@TempDir assertThat(afterClose).as("the clean close writes the statistics file").contains(LocalSchema.STATISTICS_FILE_NAME); assertThat(afterClose).as("the clean close persists the view's CSR").contains("gav-Routes.csr"); assertThat(afterClose).as("and the contraction hierarchy's order").anyMatch(n -> n.startsWith("gav-Routes.csr.") && n.endsWith(".cchorder")); + assertThat(afterClose).as("the vector index persisted its graph").anyMatch(n -> n.endsWith(".vecgraph")); + assertThat(afterClose).as("and its manifest").anyMatch(n -> n.endsWith(".vecgraphfp")); + assertThat(afterClose).as("and its ordinal map").anyMatch(n -> n.endsWith(".vecordmap")); + assertThat(afterClose).as("and its product quantization").anyMatch(n -> n.endsWith(".vecpq")); + assertThat(afterClose).as("the TimeSeries compaction sealed a store").anyMatch(n -> n.endsWith(TimeSeriesSealedStore.FILE_EXTENSION)); + assertThat(afterClose).as("the clean close wrote the recency marker").contains(TransactionManager.LAST_TX_ID_FILE_NAME); assertUnshippedFilesAreLeftOut(path); } @@ -201,7 +222,8 @@ private static boolean isShippedBySnapshot(final String name) { || name.endsWith(TimeSeriesSealedStore.FILE_EXTENSION) || name.equals(LocalDatabase.CONFIGURATION_FILE_NAME) || name.equals(LocalSchema.SCHEMA_FILE_NAME) - // TODO #9751: shipped, but rewritten per node on WAL rotation and close, so it may still differ between peers + // SYNTHESIZED INTO THE ARCHIVE, BUT LEFT OUT OF THE CHECKSUMS ALL THE SAME: A LIVE NODE REWRITES IT ON ITS OWN WAL + // ROTATIONS AND CLOSES, SO TWO HEALTHY PEERS HOLD DIFFERENT VALUES (#9751) || name.equals(TransactionManager.LAST_TX_ID_FILE_NAME); } diff --git a/ha-raft/src/test/java/com/arcadedb/server/ha/raft/Issue9751VectorSideFilesChecksumTest.java b/ha-raft/src/test/java/com/arcadedb/server/ha/raft/Issue9751VectorSideFilesChecksumTest.java new file mode 100644 index 00000000000..f05c60ae513 --- /dev/null +++ b/ha-raft/src/test/java/com/arcadedb/server/ha/raft/Issue9751VectorSideFilesChecksumTest.java @@ -0,0 +1,229 @@ +/* + * Copyright 2021-present Arcade Data Ltd (info@arcadedata.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-FileCopyrightText: 2021-present Arcade Data Ltd (info@arcadedata.com) + * SPDX-License-Identifier: Apache-2.0 + */ +package com.arcadedb.server.ha.raft; + +import com.arcadedb.GlobalConfiguration; +import com.arcadedb.database.Database; +import com.arcadedb.database.DatabaseFactory; +import com.arcadedb.database.DatabaseInternal; +import com.arcadedb.engine.NodeLocalFiles; +import com.arcadedb.engine.TransactionManager; +import com.arcadedb.index.TypeIndex; +import com.arcadedb.index.vector.LSMVectorIndex; +import com.arcadedb.index.vector.LSMVectorIndexGraphFile; +import com.arcadedb.index.vector.LSMVectorIndexGraphManifest; +import com.arcadedb.index.vector.LSMVectorIndexOrdinalMapFile; +import com.arcadedb.index.vector.LSMVectorIndexPQFile; +import com.arcadedb.serializer.json.JSONArray; +import com.arcadedb.serializer.json.JSONObject; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.io.File; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Issue #9751, the follow-up #9638's completeness sweep left: an LSM vector index writes three plain side files into + * the database directory - the graph manifest ({@code .vecgraphfp}), the ordinal map ({@code .vecordmap}) and the + * product quantization ({@code .vecpq}) - that no snapshot ships, so the {@code /checksums} answer carried keys only + * the node that built its own graph has. The graph they describe ({@code .vecgraph}) is the deeper half: every node + * builds it itself, on the inner instance and without the WAL, so its pages are node-local as well, and BOTH checksum + * collectors - {@code /checksums} and the cluster verify - compared it. And {@code last-tx-id.bin}, the recency marker, + * is rewritten whenever this node rotates its WAL or closes, so two healthy peers hold different values. + */ +class Issue9751VectorSideFilesChecksumTest { + + private static final int DIMENSIONS = 16; + private static final int VECTORS = 400; + + private final PostVerifyDatabaseHandler handler = new PostVerifyDatabaseHandler(null, null); + + @AfterEach + void reset() { + GlobalConfiguration.PAGE_SNAPSHOT_ENABLED.reset(); + handler.close(); + } + + /** The reporter's probe, against the production method, with the names the writers actually build. */ + @Test + void vectorSideFilesAndTheRecencyMarkerAreNotChecksummed(@TempDir final Path dir) throws Exception { + final String index = "Doc_0_123456789.4.262144.v0.lsmvecidx"; + final String graph = "Doc_0_123456789_vecgraph.5.262144.v0." + LSMVectorIndexGraphFile.FILE_EXT; + Files.writeString(dir.resolve("schema.json"), "{\"types\":[]}"); + Files.writeString(dir.resolve(index), "vector pages"); + Files.writeString(dir.resolve(graph), "graph pages built by this node"); + Files.writeString(dir.resolve(graph + "." + LSMVectorIndexGraphManifest.FILE_EXT), "manifest"); + Files.writeString(dir.resolve(graph + "." + LSMVectorIndexOrdinalMapFile.FILE_EXT), "ordinal map"); + Files.writeString(dir.resolve(index + "." + LSMVectorIndexPQFile.FILE_EXT), "codebooks"); + // THE LEGACY PQ NAME createPQFileWithFallback STILL MIGRATES FROM: THE BASE NAME UP TO ITS FIRST DOT + Files.writeString(dir.resolve("Doc_0_123456789." + LSMVectorIndexPQFile.FILE_EXT), "legacy codebooks"); + Files.writeString(dir.resolve(TransactionManager.LAST_TX_ID_FILE_NAME), "12345678"); + + final Map checksums = SnapshotManager.computeFileChecksums(dir.toFile()); + + assertThat(checksums).containsOnlyKeys("schema.json", index); + } + + /** By extension, not by substring: a type whose name merely contains a vector extension is still data. */ + @Test + void dataFilesThatMerelyLookLikeVectorSideFilesAreStillChecksummed(@TempDir final Path dir) throws Exception { + Files.writeString(dir.resolve("vecgraph_0.1.65536.v0.bucket"), "a bucket of a type named vecgraph"); + Files.writeString(dir.resolve("vecpq_0.2.65536.v0.bucket"), "a bucket of a type named vecpq"); + Files.writeString(dir.resolve("vecordmap"), "a file named only the extension, with no base name"); + + final Map checksums = SnapshotManager.computeFileChecksums(dir.toFile()); + + assertThat(checksums).containsOnlyKeys("vecgraph_0.1.65536.v0.bucket", "vecpq_0.2.65536.v0.bucket", "vecordmap"); + } + + /** + * The issue's own scenario, as the property: one node built its graph and closed, the other installed a snapshot + * and has not searched yet, so it has the shipped graph pages but none of the side files, and no recency marker of + * its own. Both hold the same data, so they must agree. + */ + @Test + void aNodeThatBuiltItsGraphAndOneThatInstalledASnapshotAgree(@TempDir final Path tempDir) throws Exception { + final Path builder = Files.createDirectory(tempDir.resolve("builder")); + final Path installed = Files.createDirectory(tempDir.resolve("installed")); + final String index = "Doc_0_1.4.262144.v0.lsmvecidx"; + final String graph = "Doc_0_1_vecgraph.5.262144.v0.vecgraph"; + + for (final Path node : new Path[] { builder, installed }) { + Files.writeString(node.resolve("schema.json"), "{\"types\":[]}"); + Files.writeString(node.resolve(index), "vector pages"); + } + Files.writeString(builder.resolve(graph), "the graph this node built"); + Files.writeString(builder.resolve(graph + ".vecgraphfp"), "manifest"); + Files.writeString(builder.resolve(graph + ".vecordmap"), "ordinal map"); + Files.writeString(builder.resolve(index + ".vecpq"), "codebooks"); + Files.writeString(builder.resolve(TransactionManager.LAST_TX_ID_FILE_NAME), "rotated at 41"); + Files.writeString(installed.resolve(graph), "the graph the leader built, shipped and not yet replaced"); + Files.writeString(installed.resolve(TransactionManager.LAST_TX_ID_FILE_NAME), "rotated at 17"); + + assertThat(SnapshotManager.computeFileChecksums(installed.toFile())) + .isEqualTo(SnapshotManager.computeFileChecksums(builder.toFile())); + } + + /** + * Against a REAL vector index with product quantization: the build has to have written every file the issue names, + * or the exclusion is untested, and the index's own pages - where the replicated vectors live - must still be + * compared, or a node missing vectors would read as healthy. + */ + @Test + void aRealVectorIndexWritesItsSideFilesAndOnlyItsPagesAreChecksummed(@TempDir final Path tempDir) throws Exception { + final String path = tempDir.resolve("db").toString(); + createVectorDatabase(path).close(); + + final List names = fileNames(path); + assertThat(names).as("the build persisted its graph").anyMatch(n -> n.endsWith("." + LSMVectorIndexGraphFile.FILE_EXT)); + assertThat(names).as("and its manifest").anyMatch(n -> n.endsWith("." + LSMVectorIndexGraphManifest.FILE_EXT)); + assertThat(names).as("and its ordinal map").anyMatch(n -> n.endsWith("." + LSMVectorIndexOrdinalMapFile.FILE_EXT)); + assertThat(names).as("and the product quantization").anyMatch(n -> n.endsWith("." + LSMVectorIndexPQFile.FILE_EXT)); + assertThat(names).as("the clean close wrote the recency marker").contains(TransactionManager.LAST_TX_ID_FILE_NAME); + + // THE PRODUCTION PREDICATE AGREES WITH THIS TEST'S INDEPENDENT ORACLE ON EVERY NAME THE WRITERS ACTUALLY PRODUCED + for (final String name : names) + assertThat(NodeLocalFiles.isVectorGraphFileName(name)).as("isVectorGraphFileName('%s')", name) + .isEqualTo(isNodeLocalVectorFile(name)); + + final Map checksums = SnapshotManager.computeFileChecksums(new File(path)); + for (final String name : checksums.keySet()) + assertThat(isNodeLocalVectorFile(name) || name.equals(TransactionManager.LAST_TX_ID_FILE_NAME)) + .as("'%s' is node-local and must not be in the checksum answer", name).isFalse(); + assertThat(checksums.keySet()).as("the vector index's own pages are replicated content and still compared") + .anyMatch(n -> n.endsWith(".lsmvecidx")); + } + + /** + * The cluster verify enumerates REGISTERED files rather than the directory, so the three plain side files never + * reached it - but the {@code .vecgraph} component is registered, and both of its paths compared it. + */ + @Test + void theClusterVerifyLeavesTheVectorGraphOutOnBothPaths(@TempDir final Path tempDir) { + try (final Database database = createVectorDatabase(tempDir.resolve("db").toString())) { + final DatabaseInternal db = (DatabaseInternal) database; + assertThat(db.getFileManager().getFiles().stream() + .anyMatch(f -> f != null && LSMVectorIndexGraphFile.FILE_EXT.equals(f.getFileExtension()))) + .as("the graph is a registered component, so the verify reaches it").isTrue(); + + for (final boolean window : new boolean[] { true, false }) { + GlobalConfiguration.PAGE_SNAPSHOT_ENABLED.setValue(window); + final JSONObject checksums = new JSONObject(); + handler.computeLocalChecksums(db, checksums, new JSONArray()); + + assertThat(checksums.keySet()).as("window=%s: the node-locally built graph is not compared", window) + .noneMatch(Issue9751VectorSideFilesChecksumTest::isNodeLocalVectorFile); + assertThat(checksums.keySet()).as("window=%s: the vector pages still are", window) + .anyMatch(n -> n.endsWith(".lsmvecidx")); + } + } + } + + /** + * Two indexes, because no single one writes every side file: PRODUCT quantization writes the {@code .vecpq} and, by + * design, no {@code .vecordmap} (see {@code LSMVectorIndex.writeGraphManifest}); every other quantization writes the + * map and no PQ. + */ + private static Database createVectorDatabase(final String path) { + final Database database = new DatabaseFactory(path).create(); + createVectorIndex(database, "Doc", "NONE"); + createVectorIndex(database, "PqDoc", "PRODUCT"); + return database; + } + + static void createVectorIndex(final Database database, final String type, final String quantization) { + database.transaction(() -> { + database.command("sql", "CREATE DOCUMENT TYPE " + type); + database.command("sql", "CREATE PROPERTY " + type + ".embedding ARRAY_OF_FLOATS"); + }); + database.command("sql", "CREATE INDEX ON `" + type + "` (`embedding`) LSM_VECTOR METADATA {\"dimensions\":" + DIMENSIONS + + ",\"similarity\":\"COSINE\",\"quantization\":\"" + quantization + "\"}"); + database.transaction(() -> { + for (int i = 0; i < VECTORS; i++) { + final float[] vector = new float[DIMENSIONS]; + for (int j = 0; j < DIMENSIONS; j++) + vector[j] = (float) Math.sin(i * 0.37 + j * 1.13) + 1.5f; + database.newDocument(type).set("embedding", vector).save(); + } + }); + ((LSMVectorIndex) ((TypeIndex) database.getSchema().getIndexByName(type + "[embedding]")).getIndexesOnBuckets()[0]) + .buildVectorGraphNow(); + } + + private static boolean isNodeLocalVectorFile(final String name) { + return name.endsWith("." + LSMVectorIndexGraphFile.FILE_EXT) || name.endsWith("." + LSMVectorIndexGraphManifest.FILE_EXT) + || name.endsWith("." + LSMVectorIndexOrdinalMapFile.FILE_EXT) || name.endsWith("." + LSMVectorIndexPQFile.FILE_EXT); + } + + private static List fileNames(final String path) { + final File[] files = new File(path).listFiles(File::isFile); + assertThat(files).isNotNull(); + final List names = new ArrayList<>(); + for (final File file : files) + names.add(file.getName()); + return names; + } +}