Apache Lucene open-source search software
LUCENE-5647: fix term vectors bulk merge (same algorithm now as stored fields)
Robert Muir069ad263a50b
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txtindex e5c6b8a064d..fe1f59d5692 100644--- a/lucene/CHANGES.txt+++ b/lucene/CHANGES.txt@@ -33,10 +33,10 @@ API ChangesOptimizations-* LUCENE-6183: Avoid recompressing stored fields when merging- segments without deletions. Lucene50Codec's BEST_COMPRESSION- mode uses a higher deflate level for more compact storage.- (Robert Muir)+* LUCENE-6183, LUCENE-5647: Avoid recompressing stored fields+ and term vectors when merging segments without deletions.+ Lucene50Codec's BEST_COMPRESSION mode uses a higher deflate+ level for more compact storage. (Robert Muir)* LUCENE-6184: Make BooleanScorer only score windows that containmatches. (Adrien Grand)diff --git a/lucene/core/src/java/org/apache/lucene/codecs/compressing/CompressingTermVectorsReader.java b/lucene/core/src/java/org/apache/lucene/codecs/compressing/CompressingTermVectorsReader.javaindex e3ff6646678..5ff54fc8481 100644--- a/lucene/core/src/java/org/apache/lucene/codecs/compressing/CompressingTermVectorsReader.java+++ b/lucene/core/src/java/org/apache/lucene/codecs/compressing/CompressingTermVectorsReader.java@@ -26,6 +26,7 @@ import static org.apache.lucene.codecs.compressing.CompressingTermVectorsWriter.import static org.apache.lucene.codecs.compressing.CompressingTermVectorsWriter.POSITIONS;import static org.apache.lucene.codecs.compressing.CompressingTermVectorsWriter.VECTORS_EXTENSION;import static org.apache.lucene.codecs.compressing.CompressingTermVectorsWriter.VECTORS_INDEX_EXTENSION;+import static org.apache.lucene.codecs.compressing.CompressingTermVectorsWriter.VERSION_CHUNK_STATS;import static org.apache.lucene.codecs.compressing.CompressingTermVectorsWriter.VERSION_CURRENT;import static org.apache.lucene.codecs.compressing.CompressingTermVectorsWriter.VERSION_START;@@ -82,6 +83,9 @@ public final class CompressingTermVectorsReader extends TermVectorsReader implemprivate final int numDocs;private boolean closed;private final BlockPackedReaderIterator reader;+ private final long numChunks; // number of compressed blocks written+ private final long numDirtyChunks; // number of incomplete compressed blocks written+ private final long maxPointer; // end of the data section// used by cloneprivate CompressingTermVectorsReader(CompressingTermVectorsReader reader) {@@ -95,6 +99,9 @@ public final class CompressingTermVectorsReader extends TermVectorsReader implemthis.numDocs = reader.numDocs;this.reader = new BlockPackedReaderIterator(vectorsStream, packedIntsVersion, PACKED_BLOCK_SIZE, 0);this.version = reader.version;+ this.numChunks = reader.numChunks;+ this.numDirtyChunks = reader.numDirtyChunks;+ this.maxPointer = reader.maxPointer;this.closed = false;}@@ -109,6 +116,8 @@ public final class CompressingTermVectorsReader extends TermVectorsReader implemint version = -1;CompressingStoredFieldsIndexReader indexReader = null;+ long maxPointer = -1;+// Load the index into memoryfinal String indexName = IndexFileNames.segmentFileName(segment, segmentSuffix, VECTORS_INDEX_EXTENSION);try (ChecksumIndexInput input = d.openChecksumInput(indexName, context)) {@@ -118,7 +127,7 @@ public final class CompressingTermVectorsReader extends TermVectorsReader implemversion = CodecUtil.checkIndexHeader(input, codecNameIdx, VERSION_START, VERSION_CURRENT, si.getId(), segmentSuffix);assert CodecUtil.indexHeaderLength(codecNameIdx, segmentSuffix) == input.getFilePointer();indexReader = new CompressingStoredFieldsIndexReader(input, si);- input.readVLong(); // the end of the data file+ maxPointer = input.readVLong(); // the end of the data section} catch (Throwable exception) {priorE = exception;} finally {@@ -128,6 +137,7 @@ public final class CompressingTermVectorsReader extends TermVectorsReader implemthis.version = version;this.indexReader = indexReader;+ this.maxPointer = maxPointer;try {// Open the data file and read metadata@@ -141,6 +151,18 @@ public final class CompressingTermVectorsReader extends TermVectorsReader implemassert CodecUtil.indexHeaderLength(codecNameDat, segmentSuffix) == vectorsStream.getFilePointer();long pos = vectorsStream.getFilePointer();++ if (version >= VERSION_CHUNK_STATS) {+ vectorsStream.seek(maxPointer);+ numChunks = vectorsStream.readVLong();+ numDirtyChunks = vectorsStream.readVLong();+ if (numDirtyChunks > numChunks) {+ throw new CorruptIndexException("invalid chunk counts: dirty=" + numDirtyChunks + ", total=" + numChunks, vectorsStream);+ }+ } else {+ numChunks = numDirtyChunks = -1;+ }+// NOTE: data file is too costly to verify checksum against all the bytes on open,// but for now we at least verify proper structure of the checksum footer: which looks// for FOOTER_MAGIC + algorithmID. This is cheap and can detect some forms of corruption@@ -177,13 +199,25 @@ public final class CompressingTermVectorsReader extends TermVectorsReader implemreturn version;}- CompressingStoredFieldsIndexReader getIndex() {+ CompressingStoredFieldsIndexReader getIndexReader() {return indexReader;}IndexInput getVectorsStream() {return vectorsStream;}++ long getMaxPointer() {+ return maxPointer;+ }++ long getNumChunks() {+ return numChunks;+ }++ long getNumDirtyChunks() {+ return numDirtyChunks;+ }/*** @throws AlreadyClosedException if this TermVectorsReader is closeddiff --git a/lucene/core/src/java/org/apache/lucene/codecs/compressing/CompressingTermVectorsWriter.java b/lucene/core/src/java/org/apache/lucene/codecs/compressing/CompressingTermVectorsWriter.javaindex 9aa42c930f8..f432dd24cc7 100644--- a/lucene/core/src/java/org/apache/lucene/codecs/compressing/CompressingTermVectorsWriter.java+++ b/lucene/core/src/java/org/apache/lucene/codecs/compressing/CompressingTermVectorsWriter.java@@ -28,6 +28,7 @@ import java.util.TreeSet;import org.apache.lucene.codecs.CodecUtil;import org.apache.lucene.codecs.TermVectorsReader;import org.apache.lucene.codecs.TermVectorsWriter;+import org.apache.lucene.index.CorruptIndexException;import org.apache.lucene.index.FieldInfo;import org.apache.lucene.index.FieldInfos;import org.apache.lucene.index.Fields;@@ -66,7 +67,8 @@ public final class CompressingTermVectorsWriter extends TermVectorsWriter {static final String CODEC_SFX_DAT = "Data";static final int VERSION_START = 0;- static final int VERSION_CURRENT = VERSION_START;+ static final int VERSION_CHUNK_STATS = 1;+ static final int VERSION_CURRENT = VERSION_CHUNK_STATS;static final int PACKED_BLOCK_SIZE = 64;@@ -75,15 +77,16 @@ public final class CompressingTermVectorsWriter extends TermVectorsWriter {static final int PAYLOADS = 0x04;static final int FLAGS_BITS = PackedInts.bitsRequired(POSITIONS | OFFSETS | PAYLOADS);- private final Directory directory;private final String segment;- private final String segmentSuffix;private CompressingStoredFieldsIndexWriter indexWriter;private IndexOutput vectorsStream;private final CompressionMode compressionMode;private final Compressor compressor;private final int chunkSize;++ private long numChunks; // number of compressed blocks written+ private long numDirtyChunks; // number of incomplete compressed blocks written/** a pending doc */private class DocData {@@ -206,9 +209,7 @@ public final class CompressingTermVectorsWriter extends TermVectorsWriter {public CompressingTermVectorsWriter(Directory directory, SegmentInfo si, String segmentSuffix, IOContext context,String formatName, CompressionMode compressionMode, int chunkSize, int blockSize) throws IOException {assert directory != null;- this.directory = directory;this.segment = si.name;- this.segmentSuffix = segmentSuffix;this.compressionMode = compressionMode;this.compressor = compressionMode.newCompressor();this.chunkSize = chunkSize;@@ -365,6 +366,7 @@ public final class CompressingTermVectorsWriter extends TermVectorsWriter {curDoc = null;curField = null;termSuffixes.length = 0;+ numChunks++;}private int flushNumFields(int chunkDocs) throws IOException {@@ -647,11 +649,14 @@ public final class CompressingTermVectorsWriter extends TermVectorsWriter {public void finish(FieldInfos fis, int numDocs) throws IOException {if (!pendingDocs.isEmpty()) {flush();+ numDirtyChunks++; // incomplete: we had to force this flush}if (numDocs != this.numDocs) {throw new RuntimeException("Wrote " + this.numDocs + " docs, finish called with numDocs=" + numDocs);}indexWriter.finish(numDocs, vectorsStream.getFilePointer());+ vectorsStream.writeVLong(numChunks);+ vectorsStream.writeVLong(numDirtyChunks);CodecUtil.writeFooter(vectorsStream);}@@ -712,6 +717,19 @@ public final class CompressingTermVectorsWriter extends TermVectorsWriter {curField.totalPositions += numProx;}++ // bulk merge is scary: its caused corruption bugs in the past.+ // we try to be extra safe with this impl, but add an escape hatch to+ // have a workaround for undiscovered bugs.+ static final String BULK_MERGE_ENABLED_SYSPROP = CompressingTermVectorsWriter.class.getName() + ".enableBulkMerge";+ static final boolean BULK_MERGE_ENABLED;+ static {+ boolean v = true;+ try {+ v = Boolean.parseBoolean(System.getProperty(BULK_MERGE_ENABLED_SYSPROP, "true"));+ } catch (SecurityException ignored) {}+ BULK_MERGE_ENABLED = v;+ }@Overridepublic int merge(MergeState mergeState) throws IOException {@@ -732,17 +750,81 @@ public final class CompressingTermVectorsWriter extends TermVectorsWriter {final int maxDoc = mergeState.maxDocs[readerIndex];final Bits liveDocs = mergeState.liveDocs[readerIndex];-- if (matchingVectorsReader == null- || matchingVectorsReader.getVersion() != VERSION_CURRENT- || matchingVectorsReader.getCompressionMode() != compressionMode- || matchingVectorsReader.getChunkSize() != chunkSize- || matchingVectorsReader.getPackedIntsVersion() != PackedInts.VERSION_CURRENT) {++ if (matchingVectorsReader != null &&+ matchingVectorsReader.getCompressionMode() == compressionMode &&+ matchingVectorsReader.getChunkSize() == chunkSize &&+ matchingVectorsReader.getVersion() == VERSION_CURRENT &&+ matchingVectorsReader.getPackedIntsVersion() == PackedInts.VERSION_CURRENT &&+ BULK_MERGE_ENABLED &&+ liveDocs == null &&+ !tooDirty(matchingVectorsReader)) {+ // optimized merge, raw byte copy+ // its not worth fine-graining this if there are deletions.++ matchingVectorsReader.checkIntegrity();++ // flush any pending chunks+ if (!pendingDocs.isEmpty()) {+ flush();+ numDirtyChunks++; // incomplete: we had to force this flush+ }++ // iterate over each chunk. we use the vectors index to find chunk boundaries,+ // read the docstart + doccount from the chunk header (we write a new header, since doc numbers will change),+ // and just copy the bytes directly.+ IndexInput rawDocs = matchingVectorsReader.getVectorsStream();+ CompressingStoredFieldsIndexReader index = matchingVectorsReader.getIndexReader();+ rawDocs.seek(index.getStartPointer(0));+ int docID = 0;+ while (docID < maxDoc) {+ // read header+ int base = rawDocs.readVInt();+ if (base != docID) {+ throw new CorruptIndexException("invalid state: base=" + base + ", docID=" + docID, rawDocs);+ }+ int bufferedDocs = rawDocs.readVInt();++ // write a new index entry and new header for this chunk.+ indexWriter.writeIndex(bufferedDocs, vectorsStream.getFilePointer());+ vectorsStream.writeVInt(docCount); // rebase+ vectorsStream.writeVInt(bufferedDocs);+ docID += bufferedDocs;+ docCount += bufferedDocs;+ numDocs += bufferedDocs;++ if (docID > maxDoc) {+ throw new CorruptIndexException("invalid state: base=" + base + ", count=" + bufferedDocs + ", maxDoc=" + maxDoc, rawDocs);+ }++ // copy bytes until the next chunk boundary (or end of chunk data).+ // using the stored fields index for this isn't the most efficient, but fast enough+ // and is a source of redundancy for detecting bad things.+ final long end;+ if (docID == maxDoc) {+ end = matchingVectorsReader.getMaxPointer();+ } else {+ end = index.getStartPointer(docID);+ }+ vectorsStream.copyBytes(rawDocs, end - rawDocs.getFilePointer());+ }++ if (rawDocs.getFilePointer() != matchingVectorsReader.getMaxPointer()) {+ throw new CorruptIndexException("invalid state: pos=" + rawDocs.getFilePointer() + ", max=" + matchingVectorsReader.getMaxPointer(), rawDocs);+ }++ // since we bulk merged all chunks, we inherit any dirty ones from this segment.+ numChunks += matchingVectorsReader.getNumChunks();+ numDirtyChunks += matchingVectorsReader.getNumDirtyChunks();+ } else {// naive merge...if (vectorsReader != null) {vectorsReader.checkIntegrity();}- for (int i = nextLiveDoc(0, liveDocs, maxDoc); i < maxDoc; i = nextLiveDoc(i + 1, liveDocs, maxDoc)) {+ for (int i = 0; i < maxDoc; i++) {+ if (liveDocs != null && liveDocs.get(i) == false) {+ continue;+ }Fields vectors;if (vectorsReader == null) {vectors = null;@@ -752,86 +834,22 @@ public final class CompressingTermVectorsWriter extends TermVectorsWriter {addAllDocVectors(vectors, mergeState);++docCount;}- } else {- final CompressingStoredFieldsIndexReader index = matchingVectorsReader.getIndex();- final IndexInput vectorsStreamOrig = matchingVectorsReader.getVectorsStream();- vectorsStreamOrig.seek(0);- final ChecksumIndexInput vectorsStream = new BufferedChecksumIndexInput(vectorsStreamOrig.clone());-- for (int i = nextLiveDoc(0, liveDocs, maxDoc); i < maxDoc; ) {- // We make sure to move the checksum input in any case, otherwise the final- // integrity check might need to read the whole file a second time- final long startPointer = index.getStartPointer(i);- if (startPointer > vectorsStream.getFilePointer()) {- vectorsStream.seek(startPointer);- }- if (pendingDocs.isEmpty()- && (i == 0 || index.getStartPointer(i - 1) < startPointer)) { // start of a chunk- final int docBase = vectorsStream.readVInt();- final int chunkDocs = vectorsStream.readVInt();- assert docBase + chunkDocs <= maxDoc;- if (docBase + chunkDocs < maxDoc- && nextDeletedDoc(docBase, liveDocs, docBase + chunkDocs) == docBase + chunkDocs) {- final long chunkEnd = index.getStartPointer(docBase + chunkDocs);- final long chunkLength = chunkEnd - vectorsStream.getFilePointer();- indexWriter.writeIndex(chunkDocs, this.vectorsStream.getFilePointer());- this.vectorsStream.writeVInt(docCount);- this.vectorsStream.writeVInt(chunkDocs);- this.vectorsStream.copyBytes(vectorsStream, chunkLength);- docCount += chunkDocs;- this.numDocs += chunkDocs;- i = nextLiveDoc(docBase + chunkDocs, liveDocs, maxDoc);- } else {- for (; i < docBase + chunkDocs; i = nextLiveDoc(i + 1, liveDocs, maxDoc)) {- Fields vectors;- if (vectorsReader == null) {- vectors = null;- } else {- vectors = vectorsReader.get(i);- }- addAllDocVectors(vectors, mergeState);- ++docCount;- }- }- } else {- Fields vectors;- if (vectorsReader == null) {- vectors = null;- } else {- vectors = vectorsReader.get(i);- }- addAllDocVectors(vectors, mergeState);- ++docCount;- i = nextLiveDoc(i + 1, liveDocs, maxDoc);- }- }-- vectorsStream.seek(vectorsStream.length() - CodecUtil.footerLength());- CodecUtil.checkFooter(vectorsStream);}}finish(mergeState.mergeFieldInfos, docCount);return docCount;}- private static int nextLiveDoc(int doc, Bits liveDocs, int maxDoc) {- if (liveDocs == null) {- return doc;- }- while (doc < maxDoc && !liveDocs.get(doc)) {- ++doc;- }- return doc;- }-- private static int nextDeletedDoc(int doc, Bits liveDocs, int maxDoc) {- if (liveDocs == null) {- return maxDoc;- }- while (doc < maxDoc && liveDocs.get(doc)) {- ++doc;- }- return doc;+ /**+ * Returns true if we should recompress this reader, even though we could bulk merge compressed data+ * <p>+ * The last chunk written for a segment is typically incomplete, so without recompressing,+ * in some worst-case situations (e.g. frequent reopen with tiny flushes), over time the+ * compression ratio can degrade. This is a safety switch.+ */+ boolean tooDirty(CompressingTermVectorsReader candidate) {+ // more than 1% dirty, or more than hard limit of 1024 dirty chunks+ return candidate.getNumDirtyChunks() > 1024 ||+ candidate.getNumDirtyChunks() * 100 > candidate.getNumChunks();}-}diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene50/Lucene50TermVectorsFormat.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene50/Lucene50TermVectorsFormat.javaindex bf9465d18ec..ca627540b88 100644--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene50/Lucene50TermVectorsFormat.java+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene50/Lucene50TermVectorsFormat.java@@ -58,7 +58,7 @@ import org.apache.lucene.util.packed.PackedInts;* {@link BlockPackedWriter blocks of packed ints} for positions.</p>* <p>Here is a more detailed description of the field data file format:</p>* <ul>- * <li>VectorData (.tvd) --> <Header>, PackedIntsVersion, ChunkSize, <Chunk><sup>ChunkCount</sup>, Footer</li>+ * <li>VectorData (.tvd) --> <Header>, PackedIntsVersion, ChunkSize, <Chunk><sup>ChunkCount</sup>, ChunkCount, DirtyChunkCount, Footer</li>* <li>Header --> {@link CodecUtil#writeIndexHeader IndexHeader}</li>* <li>PackedIntsVersion --> {@link PackedInts#VERSION_CURRENT} as a {@link DataOutput#writeVInt VInt}</li>* <li>ChunkSize is the number of bytes of terms to accumulate before flushing, as a {@link DataOutput#writeVInt VInt}</li>@@ -106,6 +106,8 @@ import org.apache.lucene.util.packed.PackedInts;* <li>FieldTermsAndPayLoads --> Terms (Payloads)</li>* <li>Terms: term bytes</li>* <li>Payloads: payload bytes (if the field has payloads)</li>+ * <li>ChunkCount --> the number of chunks in this file</li>+ * <li>DirtyChunkCount --> the number of prematurely flushed chunks in this file</li>* <li>Footer --> {@link CodecUtil#writeFooter CodecFooter}</li>* </ul>* </li>diff --git a/lucene/core/src/test/org/apache/lucene/codecs/compressing/TestCompressingTermVectorsFormat.java b/lucene/core/src/test/org/apache/lucene/codecs/compressing/TestCompressingTermVectorsFormat.javaindex 46e4eced7be..18a120d89bd 100644--- a/lucene/core/src/test/org/apache/lucene/codecs/compressing/TestCompressingTermVectorsFormat.java+++ b/lucene/core/src/test/org/apache/lucene/codecs/compressing/TestCompressingTermVectorsFormat.java@@ -1,12 +1,22 @@package org.apache.lucene.codecs.compressing;+import java.io.IOException;++import org.apache.lucene.analysis.MockAnalyzer;import org.apache.lucene.codecs.Codec;import org.apache.lucene.document.Document;import org.apache.lucene.document.Field;import org.apache.lucene.document.FieldType;+import org.apache.lucene.document.StoredField;import org.apache.lucene.document.TextField;+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.LeafReader;import org.apache.lucene.index.BaseTermVectorsFormatTestCase;+import org.apache.lucene.index.LeafReaderContext;+import org.apache.lucene.index.NoMergePolicy;import org.apache.lucene.index.RandomIndexWriter;import org.apache.lucene.index.Terms;import org.apache.lucene.index.TermsEnum;@@ -69,4 +79,52 @@ public class TestCompressingTermVectorsFormat extends BaseTermVectorsFormatTestCiw.close();dir.close();}++ /**+ * writes some tiny segments with incomplete compressed blocks,+ * and ensures merge recompresses them.+ */+ public void testChunkCleanup() throws IOException {+ Directory dir = newDirectory();+ IndexWriterConfig iwConf = newIndexWriterConfig(new MockAnalyzer(random()));+ iwConf.setMergePolicy(NoMergePolicy.INSTANCE);++ // we have to enforce certain things like maxDocsPerChunk to cause dirty chunks to be created+ // by this test.+ iwConf.setCodec(CompressingCodec.randomInstance(random(), 4*1024, 100, false, 8));+ IndexWriter iw = new IndexWriter(dir, iwConf);+ DirectoryReader ir = DirectoryReader.open(iw, true);+ for (int i = 0; i < 5; i++) {+ Document doc = new Document();+ FieldType ft = new FieldType(TextField.TYPE_NOT_STORED);+ ft.setStoreTermVectors(true);+ doc.add(new Field("text", "not very long at all", ft));+ iw.addDocument(doc);+ // force flush+ DirectoryReader ir2 = DirectoryReader.openIfChanged(ir);+ assertNotNull(ir2);+ ir.close();+ ir = ir2;+ // examine dirty counts:+ for (LeafReaderContext leaf : ir2.leaves()) {+ CodecReader sr = (CodecReader) leaf.reader();+ CompressingTermVectorsReader reader = (CompressingTermVectorsReader)sr.getTermVectorsReader();+ assertEquals(1, reader.getNumChunks());+ assertEquals(1, reader.getNumDirtyChunks());+ }+ }+ iw.getConfig().setMergePolicy(newLogMergePolicy());+ iw.forceMerge(1);+ DirectoryReader ir2 = DirectoryReader.openIfChanged(ir);+ assertNotNull(ir2);+ ir.close();+ ir = ir2;+ CodecReader sr = getOnlySegmentReader(ir);+ CompressingTermVectorsReader reader = (CompressingTermVectorsReader)sr.getTermVectorsReader();+ // we could get lucky, and have zero, but typically one.+ assertTrue(reader.getNumDirtyChunks() <= 1);+ ir.close();+ iw.close();+ dir.close();+ }}