Apache Lucene open-source search software
Let a merge read the vectors through its own mapping (#16749)
Jim Ferenczic95aa21a7b76
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txtindex e53e0d9ec75..6b32b554965 100644--- a/lucene/CHANGES.txt+++ b/lucene/CHANGES.txt@@ -475,6 +475,11 @@ Optimizationsordinal to group ordinal mapping at the minimum bit width required for the largest group ordinal,instead of a fixed 32-bit width. (Pranshu Shukla)+* GITHUB#16749: Merges now open the raw vectors for themselves and state that they read the data+ file sequentially, instead of changing the advice on the mapping searches read at random. The+ vectors writers now state what file they are writing, and the raw vectors a quantized format keeps+ only to rescore say so as they are written. (Jim Ferenczi)+* GITHUB#16682: Carry file open hints on merge and flush contexts, which used to drop them. An HNSWformat now carries the random access hint for the vectors it reads, rather than the flat formatholding them claiming it whatever reads them. Add NoReuseHint, set by stored fields, term vectorsdiff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene104/Lucene104ScalarQuantizedVectorsFormat.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene104/Lucene104ScalarQuantizedVectorsFormat.javaindex c49d8499733..f28cdf53b6d 100644--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene104/Lucene104ScalarQuantizedVectorsFormat.java+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene104/Lucene104ScalarQuantizedVectorsFormat.java@@ -155,7 +155,7 @@ public class Lucene104ScalarQuantizedVectorsFormat extends FlatVectorsFormat {@Overridepublic FlatVectorsWriter fieldsWriter(SegmentWriteState state) throws IOException {return new Lucene104ScalarQuantizedVectorsWriter(- state, encoding, rawVectorFormat.fieldsWriter(state), scorer);+ state, encoding, rawVectorFormat.fieldsWriter(rescoreOnly(state)), scorer);}@Override@@ -186,4 +186,8 @@ public class Lucene104ScalarQuantizedVectorsFormat extends FlatVectorsFormat {private static SegmentReadState rescoreOnly(SegmentReadState state) {return new SegmentReadState(state, state.context.union(NoReuseHint.INSTANCE));}++ private static SegmentWriteState rescoreOnly(SegmentWriteState state) {+ return new SegmentWriteState(state, state.context.union(NoReuseHint.INSTANCE));+ }}diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene104/Lucene104ScalarQuantizedVectorsWriter.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene104/Lucene104ScalarQuantizedVectorsWriter.javaindex 57bdb8c3301..874718371ed 100644--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene104/Lucene104ScalarQuantizedVectorsWriter.java+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene104/Lucene104ScalarQuantizedVectorsWriter.java@@ -105,7 +105,9 @@ public class Lucene104ScalarQuantizedVectorsWriter extends FlatVectorsWriter {this.rawVectorDelegate = rawVectorDelegate;try {meta = state.directory.createOutput(metaFileName, state.context);- vectorData = state.directory.createOutput(vectorDataFileName, state.context);+ vectorData =+ state.directory.createOutput(+ vectorDataFileName, state.context.union(FileTypeHint.DATA, FileDataHint.KNN_VECTORS));CodecUtil.writeIndexHeader(meta,diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99FlatVectorsReader.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99FlatVectorsReader.javaindex d7aa0f1ff6e..2754dbac007 100644--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99FlatVectorsReader.java+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99FlatVectorsReader.java@@ -20,7 +20,9 @@ package org.apache.lucene.codecs.lucene99;import static org.apache.lucene.codecs.lucene99.Lucene99HnswVectorsReader.readSimilarityFunction;import static org.apache.lucene.codecs.lucene99.Lucene99HnswVectorsReader.readVectorEncoding;+import java.io.FileNotFoundException;import java.io.IOException;+import java.nio.file.NoSuchFileException;import java.util.Map;import org.apache.lucene.codecs.CodecUtil;import org.apache.lucene.codecs.hnsw.FlatVectorsReader;@@ -43,10 +45,12 @@ import org.apache.lucene.index.VectorSimilarityFunction;import org.apache.lucene.internal.hppc.IntObjectHashMap;import org.apache.lucene.store.ChecksumIndexInput;import org.apache.lucene.store.DataAccessHint;+import org.apache.lucene.store.Directory;import org.apache.lucene.store.FileDataHint;import org.apache.lucene.store.FileTypeHint;import org.apache.lucene.store.IOContext;import org.apache.lucene.store.IndexInput;+import org.apache.lucene.store.NoReuseHint;import org.apache.lucene.util.IOUtils;import org.apache.lucene.util.RamUsageEstimator;import org.apache.lucene.util.hnsw.RandomVectorScorer;@@ -61,25 +65,40 @@ public final class Lucene99FlatVectorsReader extends FlatVectorsReader {private static final long SHALLOW_SIZE =RamUsageEstimator.shallowSizeOfInstance(Lucene99FlatVectorsFormat.class);- private final IntObjectHashMap<FieldEntry> fields = new IntObjectHashMap<>();+ private final IntObjectHashMap<FieldEntry> fields;private final FlatVectorsScorer vectorScorer;private final IndexInput vectorData;private final FieldInfos fieldInfos;private final IOContext dataContext;+ private final Directory directory;+ private final String vectorDataFN;+ // the reader that owns the mapping merges read+ private final Lucene99FlatVectorsReader original;+ private IndexInput mergeVectorData;+ // merge instances handed out and not yet finished+ private int mergeInstances;public Lucene99FlatVectorsReader(SegmentReadState state, FlatVectorsScorer scorer)throws IOException {+ this.fields = new IntObjectHashMap<>();int versionMeta = readMetadata(state);this.vectorScorer = scorer;this.fieldInfos = state.fieldInfos;+ this.directory = state.directory;+ this.original = this;// how these are read is up to whoever wraps this formatdataContext = state.context.union(FileTypeHint.DATA, FileDataHint.KNN_VECTORS);+ this.vectorDataFN =+ IndexFileNames.segmentFileName(+ state.segmentInfo.name,+ state.segmentSuffix,+ Lucene99FlatVectorsFormat.VECTOR_DATA_EXTENSION);try {vectorData =openDataInput(state,versionMeta,- Lucene99FlatVectorsFormat.VECTOR_DATA_EXTENSION,+ vectorDataFN,Lucene99FlatVectorsFormat.VECTOR_DATA_CODEC_NAME,dataContext);} catch (Throwable t) {@@ -88,6 +107,18 @@ public final class Lucene99FlatVectorsReader extends FlatVectorsReader {}}+ /** Reads the same fields as {@code reader}, through the mapping a merge opened for itself. */+ private Lucene99FlatVectorsReader(Lucene99FlatVectorsReader reader, IndexInput vectorData) {+ this.fields = reader.fields;+ this.vectorScorer = reader.vectorScorer;+ this.fieldInfos = reader.fieldInfos;+ this.dataContext = reader.dataContext;+ this.directory = reader.directory;+ this.vectorDataFN = reader.vectorDataFN;+ this.original = reader.original;+ this.vectorData = vectorData;+ }+private int readMetadata(SegmentReadState state) throws IOException {String metaFileName =IndexFileNames.segmentFileName(@@ -115,14 +146,8 @@ public final class Lucene99FlatVectorsReader extends FlatVectorsReader {}private static IndexInput openDataInput(- SegmentReadState state,- int versionMeta,- String fileExtension,- String codecName,- IOContext context)+ SegmentReadState state, int versionMeta, String fileName, String codecName, IOContext context)throws IOException {- String fileName =- IndexFileNames.segmentFileName(state.segmentInfo.name, state.segmentSuffix, fileExtension);IndexInput in = state.directory.openInput(fileName, context);try {int versionVectorData =@@ -185,9 +210,48 @@ public final class Lucene99FlatVectorsReader extends FlatVectorsReader {@Overridepublic FlatVectorsReader getMergeInstance() throws IOException {- // Update the read advice since vectors are guaranteed to be accessed sequentially for merge- vectorData.updateIOContext(dataContext.withHints(DataAccessHint.SEQUENTIAL));- return this;+ IndexInput data = original.mergeVectorData();+ boolean success = false;+ try {+ FlatVectorsReader mergeInstance = new Lucene99FlatVectorsReader(this, data.clone());+ success = true;+ return mergeInstance;+ } finally {+ if (success == false) {+ original.releaseMergeVectorData();+ }+ }+ }++ /**+ * The vectors as a merge reads them, front to back and once. Advice belongs to a mapping, so a+ * merge maps the file again. Mapped on the first merge, released by {@link #finishMerge()}.+ */+ private synchronized IndexInput mergeVectorData() throws IOException {+ assert original == this;+ if (mergeVectorData == null) {+ if (dataContext.context() == IOContext.Context.MERGE) {+ // opened by a merge to begin with, so it already reads the file front to back+ mergeVectorData = vectorData;+ } else {+ try {+ mergeVectorData =+ directory.openInput(+ vectorDataFN,+ IOContext.merge()+ .withHints(+ FileTypeHint.DATA,+ FileDataHint.KNN_VECTORS,+ DataAccessHint.SEQUENTIAL,+ NoReuseHint.INSTANCE));+ } catch (FileNotFoundException | NoSuchFileException _) {+ // an open reader outlives its files, so fall back to the mapping it already holds+ mergeVectorData = vectorData;+ }+ }+ }+ mergeInstances++;+ return mergeVectorData;}private FieldEntry getFieldEntryOrThrow(String field) {@@ -312,16 +376,34 @@ public final class Lucene99FlatVectorsReader extends FlatVectorsReader {target);}+ /**+ * Closes the mapping a merge used, once no merge instance holds it. A later merge maps the file+ * again.+ */@Overridepublic void finishMerge() throws IOException {- // This makes sure that the access pattern hint is reverted back since HNSW implementation- // needs it- vectorData.updateIOContext(dataContext);+ original.releaseMergeVectorData();+ }++ private synchronized void releaseMergeVectorData() throws IOException {+ assert original == this;+ if (--mergeInstances > 0) {+ return;+ }+ if (mergeVectorData != null && mergeVectorData != vectorData) {+ mergeVectorData.close();+ }+ mergeVectorData = null;}@Overridepublic void close() throws IOException {- IOUtils.close(vectorData);+ IOUtils.close(vectorData, mergeVectorDataToClose());+ }++ /** The mapping a merge opened, read under the lock that guards it, closed outside it. */+ private synchronized IndexInput mergeVectorDataToClose() {+ return original == this && mergeVectorData != vectorData ? mergeVectorData : null;}private record FieldEntry(diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99FlatVectorsWriter.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99FlatVectorsWriter.javaindex d63d494c7f0..58608cad433 100644--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99FlatVectorsWriter.java+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99FlatVectorsWriter.java@@ -43,6 +43,8 @@ import org.apache.lucene.index.MergeState;import org.apache.lucene.index.SegmentWriteState;import org.apache.lucene.index.Sorter;import org.apache.lucene.index.VectorEncoding;+import org.apache.lucene.store.FileDataHint;+import org.apache.lucene.store.FileTypeHint;import org.apache.lucene.store.IndexOutput;import org.apache.lucene.util.ArrayUtil;import org.apache.lucene.util.IOFunction;@@ -115,7 +117,10 @@ public final class Lucene99FlatVectorsWriter extends FlatVectorsWriter {try {meta = state.directory.createOutput(metaFileName, state.context);- vectorData = state.directory.createOutput(vectorDataFileName, state.context);+ // how these are read is up to whoever wraps this format+ vectorData =+ state.directory.createOutput(+ vectorDataFileName, state.context.union(FileTypeHint.DATA, FileDataHint.KNN_VECTORS));CodecUtil.writeIndexHeader(meta,diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99HnswVectorsWriter.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99HnswVectorsWriter.javaindex e7e2b869541..631416cbaf1 100644--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99HnswVectorsWriter.java+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99HnswVectorsWriter.java@@ -178,7 +178,9 @@ public final class Lucene99HnswVectorsWriter extends KnnVectorsWriter {try {meta = state.directory.createOutput(metaFileName, state.context);- vectorIndex = state.directory.createOutput(indexDataFileName, state.context);+ vectorIndex =+ state.directory.createOutput(+ indexDataFileName, state.context.union(FileTypeHint.DATA, FileDataHint.KNN_VECTORS));CodecUtil.writeIndexHeader(meta,diff --git a/lucene/core/src/java/org/apache/lucene/store/IOContext.java b/lucene/core/src/java/org/apache/lucene/store/IOContext.javaindex dabbe9c6d1d..2bda91ee398 100644--- a/lucene/core/src/java/org/apache/lucene/store/IOContext.java+++ b/lucene/core/src/java/org/apache/lucene/store/IOContext.java@@ -66,11 +66,19 @@ public interface IOContext {/** Returns an {@link IOContext} for merging with the specified {@link MergeInfo} */static IOContext merge(MergeInfo mergeInfo) {+ Objects.requireNonNull(mergeInfo);return merge(mergeInfo, Set.of());}+ /**+ * Returns an {@link IOContext} for merging when the caller does not know how large the merge is.+ * Unlike {@link #merge(MergeInfo)}, {@link #mergeInfo()} on the returned context is {@code null}.+ */+ static IOContext merge() {+ return merge(null, Set.of());+ }+private static IOContext merge(MergeInfo mergeInfo, Set<FileOpenHint> hints) {- Objects.requireNonNull(mergeInfo);Set<FileOpenHint> copy = DefaultIOContext.checkOneHintPerType(hints);return new IOContext() {@Override@@ -139,7 +147,10 @@ public interface IOContext {/** The {@link Context} this context is for */Context context();- /** Merge info, if {@link #context()} is {@link Context#MERGE} */+ /**+ * Merge info, or {@code null} if {@link #context()} is not {@link Context#MERGE}, or if it is but+ * the caller does not know how large the merge is (see {@link #merge()}).+ */MergeInfo mergeInfo();/** Flush info, if {@link #context()} is {@link Context#FLUSH} */diff --git a/lucene/core/src/test/org/apache/lucene/codecs/lucene99/TestVectorAccessHints.java b/lucene/core/src/test/org/apache/lucene/codecs/lucene99/TestVectorAccessHints.javaindex 89f856b499b..be9129195d6 100644--- a/lucene/core/src/test/org/apache/lucene/codecs/lucene99/TestVectorAccessHints.java+++ b/lucene/core/src/test/org/apache/lucene/codecs/lucene99/TestVectorAccessHints.java@@ -43,6 +43,8 @@ import org.apache.lucene.store.FileTypeHint;import org.apache.lucene.store.FilterDirectory;import org.apache.lucene.store.IOContext;import org.apache.lucene.store.IndexInput;+import org.apache.lucene.store.IndexOutput;+import org.apache.lucene.store.NoReuseHint;import org.apache.lucene.store.ReadOnceHint;import org.apache.lucene.tests.index.BaseKnnVectorsFormatTestCase;import org.apache.lucene.tests.util.LuceneTestCase;@@ -205,6 +207,60 @@ public class TestVectorAccessHints extends LuceneTestCase {}}+ /** What a writer says about the vector files it creates. */+ public void testWrittenVectorsSayWhatTheyHold() throws Exception {+ Opens creates = new Opens();+ try (Directory dir = new RecordingDirectory(newDirectory(), new Opens(), creates)) {+ try (IndexWriter w = new IndexWriter(dir, writerConfig(new Lucene99HnswVectorsFormat()))) {+ addDocuments(w, 16);+ }+ for (String extension :+ List.of(+ Lucene99FlatVectorsFormat.VECTOR_DATA_EXTENSION,+ Lucene99HnswVectorsFormat.VECTOR_INDEX_EXTENSION)) {+ List<Open> written = creates.endingWith(extension);+ MatcherAssert.assertThat("nothing was created: " + creates, written, not(empty()));+ for (Open create : written) {+ MatcherAssert.assertThat(+ "created without saying it holds vectors: " + create,+ create.context().hints(),+ hasItem(FileDataHint.KNN_VECTORS));+ MatcherAssert.assertThat(+ "the vectors a graph searches are worth keeping: " + create,+ create.context().hints(),+ not(hasItem(NoReuseHint.INSTANCE)));+ }+ }+ }+ }++ /** The raw vectors a quantized format keeps only to rescore, as they are written. */+ public void testWrittenRescoreVectorsSayTheyAreNotReused() throws Exception {+ Opens creates = new Opens();+ try (Directory dir = new RecordingDirectory(newDirectory(), new Opens(), creates)) {+ try (IndexWriter w =+ new IndexWriter(dir, writerConfig(new Lucene104HnswScalarQuantizedVectorsFormat()))) {+ addDocuments(w, 16);+ }+ List<Open> raw = creates.endingWith(Lucene99FlatVectorsFormat.VECTOR_DATA_EXTENSION);+ MatcherAssert.assertThat("no raw vectors were created: " + creates, raw, not(empty()));+ for (Open create : raw) {+ MatcherAssert.assertThat(+ "the raw vectors are only read back to rescore: " + create,+ create.context().hints(),+ hasItem(NoReuseHint.INSTANCE));+ }+ List<Open> quantized = creates.endingWith("veq");+ MatcherAssert.assertThat("no quantized vectors created: " + creates, quantized, not(empty()));+ for (Open create : quantized) {+ MatcherAssert.assertThat(+ "the quantized vectors a graph searches are worth keeping: " + create,+ create.context().hints(),+ not(hasItem(NoReuseHint.INSTANCE)));+ }+ }+ }+/** A read state for the flat format holding the vectors of the single segment in {@code dir}. */private static SegmentReadState flatReadState(Directory dir, IOContext context)throws IOException {@@ -265,7 +321,7 @@ public class TestVectorAccessHints extends LuceneTestCase {}}- /** One {@link Directory#openInput} call. */+ /** One {@link Directory#openInput} or {@link Directory#createOutput} call. */private record Open(String name, IOContext context) {DataAccessHint hint() {return context.hints(DataAccessHint.class).findFirst().orElse(null);@@ -306,10 +362,16 @@ public class TestVectorAccessHints extends LuceneTestCase {private static final class RecordingDirectory extends FilterDirectory {private final Opens opens;+ private final Opens creates;RecordingDirectory(Directory in, Opens opens) {+ this(in, opens, new Opens());+ }++ RecordingDirectory(Directory in, Opens opens, Opens creates) {super(in);this.opens = opens;+ this.creates = creates;}@Override@@ -317,5 +379,11 @@ public class TestVectorAccessHints extends LuceneTestCase {opens.record(name, context);return super.openInput(name, context);}++ @Override+ public IndexOutput createOutput(String name, IOContext context) throws IOException {+ creates.record(name, context);+ return super.createOutput(name, context);+ }}}diff --git a/lucene/core/src/test/org/apache/lucene/codecs/lucene99/TestVectorsMergeReadAdvice.java b/lucene/core/src/test/org/apache/lucene/codecs/lucene99/TestVectorsMergeReadAdvice.javanew file mode 100644index 00000000000..df7d7b20c5f--- /dev/null+++ b/lucene/core/src/test/org/apache/lucene/codecs/lucene99/TestVectorsMergeReadAdvice.java@@ -0,0 +1,364 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You 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.+ */+package org.apache.lucene.codecs.lucene99;++import java.io.IOException;+import java.util.ArrayList;+import java.util.List;+import java.util.Set;+import java.util.concurrent.atomic.AtomicBoolean;+import org.apache.lucene.codecs.KnnVectorsReader;+import org.apache.lucene.document.Document;+import org.apache.lucene.document.KnnFloatVectorField;+import org.apache.lucene.index.CodecReader;+import org.apache.lucene.index.DirectoryReader;+import org.apache.lucene.index.IndexWriter;+import org.apache.lucene.index.IndexWriterConfig;+import org.apache.lucene.index.VectorSimilarityFunction;+import org.apache.lucene.store.DataAccessHint;+import org.apache.lucene.store.Directory;+import org.apache.lucene.store.FilterDirectory;+import org.apache.lucene.store.FilterIndexInput;+import org.apache.lucene.store.IOContext;+import org.apache.lucene.store.IndexInput;+import org.apache.lucene.store.NoReuseHint;+import org.apache.lucene.store.ReadOnceHint;+import org.apache.lucene.tests.util.LuceneTestCase;+import org.apache.lucene.tests.util.TestUtil;++/**+ * A merge reads the raw vectors front to back while a graph search reads them at random, and read+ * advice applies to a whole mapping, so a merge opens the data file for itself.+ */+public class TestVectorsMergeReadAdvice extends LuceneTestCase {++ private static final int DIM = 8;++ public void testMergeOpensItsOwnVectors() throws Exception {+ Opens opens = new Opens();+ try (Directory dir = new RecordingDirectory(newDirectory(), opens)) {+ IndexWriterConfig iwc = new IndexWriterConfig();+ iwc.setCodec(TestUtil.alwaysKnnVectorsFormat(new Lucene99HnswVectorsFormat()));+ iwc.setUseCompoundFile(false); // so the directory sees the data file by name+ try (IndexWriter w = new IndexWriter(dir, iwc)) {+ for (int segment = 0; segment < 2; segment++) {+ for (int i = 0; i < 64; i++) {+ Document doc = new Document();+ doc.add(+ new KnnFloatVectorField("field", vector(), VectorSimilarityFunction.DOT_PRODUCT));+ w.addDocument(doc);+ }+ w.commit();+ }++ // searches open the segments first, so the merge finds readers that are already open+ try (DirectoryReader reader = DirectoryReader.open(w)) {+ assertEquals(2, reader.leaves().size());+ opens.clear();+ w.forceMerge(1);++ // the merge is over, so what it opened is gone even though the segments are still open+ List<Open> sequential = sequentialOpens(opens);+ assertFalse(+ "the merge never opened the vectors for itself: " + opens, sequential.isEmpty());+ for (Open open : sequential) {+ assertTrue("the merge kept its vectors open: " + open, open.closed());+ }+ }+ }++ assertEquals(+ "the merge re-advised the vectors searches are reading: " + opens,+ List.of(),+ opens.advised());+ }+ }++ public void testTheMappingIsSharedThenReleasedByTheLastMergeInstance() throws Exception {+ Opens opens = new Opens();+ try (Directory dir = new RecordingDirectory(newDirectory(), opens)) {+ IndexWriterConfig iwc = new IndexWriterConfig();+ iwc.setCodec(TestUtil.alwaysKnnVectorsFormat(new Lucene99HnswVectorsFormat()));+ iwc.setUseCompoundFile(false);+ try (IndexWriter w = new IndexWriter(dir, iwc)) {+ for (int i = 0; i < 16; i++) {+ Document doc = new Document();+ doc.add(new KnnFloatVectorField("field", vector(), VectorSimilarityFunction.DOT_PRODUCT));+ w.addDocument(doc);+ }+ w.commit();+ }+ try (DirectoryReader reader = DirectoryReader.open(dir)) {+ KnnVectorsReader vectors =+ ((CodecReader) getOnlyLeafReader(reader))+ .getVectorReader()+ .unwrapReaderForField("field");+ opens.clear();++ KnnVectorsReader first = vectors.getMergeInstance();+ List<Open> mapped = sequentialOpens(opens);+ assertEquals("one mapping for the first merge instance: " + opens, 1, mapped.size());++ KnnVectorsReader second = vectors.getMergeInstance();+ assertEquals(+ "a second merge instance shares it: " + opens, 1, sequentialOpens(opens).size());++ first.finishMerge();+ assertFalse("still held by the second instance: " + opens, mapped.get(0).closed());++ second.finishMerge();+ assertTrue("released by the last instance: " + opens, mapped.get(0).closed());++ KnnVectorsReader third = vectors.getMergeInstance();+ assertEquals("a later merge maps it again: " + opens, 2, sequentialOpens(opens).size());+ third.finishMerge();+ }+ }+ }++ /** The mapping goes with the reader, even if no merge ever says it is finished. */+ public void testTheMappingIsClosedWithTheReader() throws Exception {+ Opens opens = new Opens();+ try (Directory dir = new RecordingDirectory(newDirectory(), opens)) {+ IndexWriterConfig iwc = new IndexWriterConfig();+ iwc.setCodec(TestUtil.alwaysKnnVectorsFormat(new Lucene99HnswVectorsFormat()));+ iwc.setUseCompoundFile(false);+ try (IndexWriter w = new IndexWriter(dir, iwc)) {+ for (int i = 0; i < 16; i++) {+ Document doc = new Document();+ doc.add(new KnnFloatVectorField("field", vector(), VectorSimilarityFunction.DOT_PRODUCT));+ w.addDocument(doc);+ }+ w.commit();+ }+ List<Open> mapped;+ try (DirectoryReader reader = DirectoryReader.open(dir)) {+ KnnVectorsReader vectors =+ ((CodecReader) getOnlyLeafReader(reader))+ .getVectorReader()+ .unwrapReaderForField("field");+ opens.clear();++ // a merge instance nobody finishes, as an abandoned merge leaves behind+ assertNotNull(vectors.getMergeInstance());+ mapped = sequentialOpens(opens);+ assertEquals("one mapping for the merge instance: " + opens, 1, mapped.size());+ assertFalse("still held by the merge instance: " + opens, mapped.get(0).closed());+ }+ assertTrue("closed with the reader: " + mapped.get(0), mapped.get(0).closed());+ }+ }++ /** A merge open that fails leaves nothing behind, so a later merge still releases the mapping. */+ public void testAFailedMergeOpenIsNotCountedAsAMergeInstance() throws Exception {+ Opens opens = new Opens();+ AtomicBoolean failMergeOpens = new AtomicBoolean();+ try (Directory dir =+ new RecordingDirectory(newDirectory(), opens) {+ @Override+ public IndexInput openInput(String name, IOContext context) throws IOException {+ if (failMergeOpens.get()+ && name.endsWith(".vec")+ && context.context() == IOContext.Context.MERGE) {+ throw new IOException("injected");+ }+ return super.openInput(name, context);+ }+ }) {+ IndexWriterConfig iwc = new IndexWriterConfig();+ iwc.setCodec(TestUtil.alwaysKnnVectorsFormat(new Lucene99HnswVectorsFormat()));+ iwc.setUseCompoundFile(false);+ try (IndexWriter w = new IndexWriter(dir, iwc)) {+ for (int i = 0; i < 16; i++) {+ Document doc = new Document();+ doc.add(new KnnFloatVectorField("field", vector(), VectorSimilarityFunction.DOT_PRODUCT));+ w.addDocument(doc);+ }+ w.commit();+ }+ try (DirectoryReader reader = DirectoryReader.open(dir)) {+ KnnVectorsReader vectors =+ ((CodecReader) getOnlyLeafReader(reader))+ .getVectorReader()+ .unwrapReaderForField("field");+ opens.clear();++ failMergeOpens.set(true);+ expectThrows(IOException.class, vectors::getMergeInstance);+ assertEquals("a failed open maps nothing: " + opens, List.of(), sequentialOpens(opens));++ failMergeOpens.set(false);+ KnnVectorsReader merging = vectors.getMergeInstance();+ List<Open> mapped = sequentialOpens(opens);+ assertEquals("one mapping for the one merge instance: " + opens, 1, mapped.size());++ merging.finishMerge();+ assertTrue("released by the only merge instance: " + opens, mapped.get(0).closed());+ }+ }+ }++ private static float[] vector() {+ float[] v = new float[DIM];+ for (int i = 0; i < DIM; i++) {+ v[i] = random().nextFloat() + 0.01f;+ }+ return v;+ }++ /** The opens a merge made for itself: the vector data, read front to back and once. */+ private static List<Open> sequentialOpens(Opens opens) {+ List<Open> sequential = new ArrayList<>();+ for (Open open : opens.all()) {+ // integrity checks read a file once, front to back, and say so with READONCE+ if (open.name().endsWith(".vec")+ && open.hint() == DataAccessHint.SEQUENTIAL+ && open.hints().contains(ReadOnceHint.INSTANCE) == false) {+ assertTrue(+ "a merge reads the vectors once and does not come back: " + open,+ open.hints().contains(NoReuseHint.INSTANCE));+ assertSame(+ "the open says a merge is reading, so a directory can route it: " + open,+ IOContext.Context.MERGE,+ open.context());+ sequential.add(open);+ }+ }+ return sequential;+ }++ /** One {@link Directory#openInput} call. */+ private static final class Open {+ private final String name;+ private final IOContext context;+ private volatile boolean closed;++ Open(String name, IOContext context) {+ this.name = name;+ this.context = context;+ }++ String name() {+ return name;+ }++ Set<IOContext.FileOpenHint> hints() {+ return context.hints();+ }++ DataAccessHint hint() {+ return context.hints(DataAccessHint.class).findFirst().orElse(null);+ }++ IOContext.Context context() {+ return context.context();+ }++ boolean closed() {+ return closed;+ }++ @Override+ public String toString() {+ return name + " [hint=" + hint() + " closed=" + closed + "]";+ }+ }++ private static final class Opens {+ private final List<Open> opens = new ArrayList<>();+ private final List<String> advised = new ArrayList<>();++ synchronized Open record(String name, IOContext context) {+ Open open = new Open(name, context);+ opens.add(open);+ return open;+ }++ /** Files whose advice was changed after they were opened. */+ synchronized void recordAdvice(String name) {+ advised.add(name);+ }++ synchronized List<Open> all() {+ return List.copyOf(opens);+ }++ synchronized List<String> advised() {+ return List.copyOf(advised);+ }++ synchronized void clear() {+ opens.clear();+ advised.clear();+ }++ @Override+ public synchronized String toString() {+ return "opens: " + opens + ", advised: " + advised;+ }+ }++ private static class RecordingDirectory extends FilterDirectory {+ private final Opens opens;++ RecordingDirectory(Directory in, Opens opens) {+ super(in);+ this.opens = opens;+ }++ @Override+ public IndexInput openInput(String name, IOContext context) throws IOException {+ Open open = opens.record(name, context);+ return new RecordingIndexInput(super.openInput(name, context), name, open, opens);+ }+ }++ private static final class RecordingIndexInput extends FilterIndexInput {+ private final String name;+ private final Open open;+ private final Opens opens;++ RecordingIndexInput(IndexInput in, String name, Open open, Opens opens) {+ super("Recording(" + name + ")", in);+ this.name = name;+ this.open = open;+ this.opens = opens;+ }++ @Override+ public void updateIOContext(IOContext context) throws IOException {+ opens.recordAdvice(name);+ in.updateIOContext(context);+ }++ @Override+ public void close() throws IOException {+ open.closed = true;+ in.close();+ }++ @Override+ public IndexInput clone() {+ return new RecordingIndexInput(in.clone(), name, open, opens);+ }++ @Override+ public IndexInput slice(String sliceDescription, long offset, long length) throws IOException {+ return new RecordingIndexInput(in.slice(sliceDescription, offset, length), name, open, opens);+ }+ }+}diff --git a/lucene/core/src/test/org/apache/lucene/store/TestIOContext.java b/lucene/core/src/test/org/apache/lucene/store/TestIOContext.javaindex 7a717ed1851..6ba3fff4590 100644--- a/lucene/core/src/test/org/apache/lucene/store/TestIOContext.java+++ b/lucene/core/src/test/org/apache/lucene/store/TestIOContext.java@@ -51,11 +51,26 @@ public class TestIOContext extends LuceneTestCase {}}+ /** A merge context with no MergeInfo, which is all a reader reopening a file can say. */+ public void testMergeWithoutMergeInfo() {+ IOContext context = IOContext.merge();+ assertEquals(IOContext.Context.MERGE, context.context());+ assertNull(context.mergeInfo());+ assertNull(context.flushInfo());+ assertEquals(Set.of(), context.hints());++ IOContext withHint = context.withHints(DataAccessHint.SEQUENTIAL);+ assertEquals(IOContext.Context.MERGE, withHint.context());+ assertNull(withHint.mergeInfo());+ assertEquals(Set.of(DataAccessHint.SEQUENTIAL), withHint.hints());+ }+protected List<IOContext> getContexts() {return List.of(IOContext.DEFAULT,IOContext.READONCE,IOContext.flush(new FlushInfo(1, 2)),+ IOContext.merge(),IOContext.merge(new MergeInfo(1, 2, true, 4)));}diff --git a/lucene/misc/src/java/org/apache/lucene/misc/store/DirectIODirectory.java b/lucene/misc/src/java/org/apache/lucene/misc/store/DirectIODirectory.javaindex f76bda39eac..018a86f07e7 100644--- a/lucene/misc/src/java/org/apache/lucene/misc/store/DirectIODirectory.java+++ b/lucene/misc/src/java/org/apache/lucene/misc/store/DirectIODirectory.java@@ -154,9 +154,9 @@ public class DirectIODirectory extends FilterDirectory {/*** Determines if direct IO should be used for a file. By default this tests if it is a merge- * context and if the merge or file length exceeds the minimum size (see {@link- * #DEFAULT_MIN_BYTES_DIRECT}). Subclasses may override method to enforce direct IO for specific- * file types.+ * context and if the merge, when its size is known, or the file length exceeds the minimum size+ * (see {@link #DEFAULT_MIN_BYTES_DIRECT}). Subclasses may override method to enforce direct IO+ * for specific file types.** @param name file name (unused by default implementation)* @param context information about merge size@@ -167,7 +167,8 @@ public class DirectIODirectory extends FilterDirectory {*/protected boolean useDirectIO(String name, IOContext context, OptionalLong fileLength) {return context.context() == Context.MERGE- && context.mergeInfo().estimatedMergeBytes() >= minBytesDirect+ && (context.mergeInfo() == null+ || context.mergeInfo().estimatedMergeBytes() >= minBytesDirect)&& fileLength.orElse(minBytesDirect) >= minBytesDirect;}diff --git a/lucene/misc/src/test/org/apache/lucene/misc/store/TestDirectIODirectory.java b/lucene/misc/src/test/org/apache/lucene/misc/store/TestDirectIODirectory.javaindex 6b533bca257..0da63c80cc5 100644--- a/lucene/misc/src/test/org/apache/lucene/misc/store/TestDirectIODirectory.java+++ b/lucene/misc/src/test/org/apache/lucene/misc/store/TestDirectIODirectory.java@@ -207,6 +207,10 @@ public class TestDirectIODirectory extends BaseDirectoryTestCase {IOContext.merge(new MergeInfo(numDocs, largeSize, true, -1)),OptionalLong.of(smallSize)));+ // a merge that does not say how large it is leaves the decision to the file length+ assertTrue(dir.useDirectIO("dummy", IOContext.merge(), OptionalLong.of(largeSize)));+ assertFalse(dir.useDirectIO("dummy", IOContext.merge(), OptionalLong.of(smallSize)));+assertFalse(dir.useDirectIO("dummy", IOContext.flush(new FlushInfo(numDocs, largeSize)), OptionalLong.empty()));