diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/scan/AlignedSinglePageWholeChunkReader.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/scan/AlignedSinglePageWholeChunkReader.java deleted file mode 100644 index 376e275888036..0000000000000 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/scan/AlignedSinglePageWholeChunkReader.java +++ /dev/null @@ -1,380 +0,0 @@ -/* - * 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.iotdb.db.pipe.event.common.tsfile.parser.scan; - -import org.apache.tsfile.compress.IUnCompressor; -import org.apache.tsfile.encoding.decoder.Decoder; -import org.apache.tsfile.encrypt.EncryptParameter; -import org.apache.tsfile.encrypt.IDecryptor; -import org.apache.tsfile.enums.TSDataType; -import org.apache.tsfile.file.header.ChunkHeader; -import org.apache.tsfile.file.header.PageHeader; -import org.apache.tsfile.file.metadata.statistics.Statistics; -import org.apache.tsfile.read.common.Chunk; -import org.apache.tsfile.read.common.TimeRange; -import org.apache.tsfile.read.reader.chunk.AbstractChunkReader; -import org.apache.tsfile.read.reader.chunk.ChunkReader; -import org.apache.tsfile.read.reader.page.AlignedPageReader; -import org.apache.tsfile.read.reader.page.LazyLoadPageData; - -import java.io.IOException; -import java.io.Serializable; -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; -import java.util.function.LongConsumer; - -/** - * The {@link AlignedSinglePageWholeChunkReader} is used to read a whole single page aligned chunk - * with need to pass in the statistics. - */ -public class AlignedSinglePageWholeChunkReader extends AbstractChunkReader - implements EstimatedMemoryChunkReader { - - // chunk header of the time column - private final ChunkHeader timeChunkHeader; - // chunk data of the time column - private final ByteBuffer timeChunkDataBuffer; - - private final EncryptParameter encryptParam; - - // chunk headers of all the sub sensors - private final List valueChunkHeaderList = new ArrayList<>(); - // chunk data of all the sub sensors - private final List valueChunkDataBufferList = new ArrayList<>(); - // deleted intervals of all the sub sensors - private final List> valueDeleteIntervalsList = new ArrayList<>(); - private final long pageEstimatedMemoryUsageInBytes; - private final Chunk ownedTimeChunk; - private final List ownedValueChunks; - - public AlignedSinglePageWholeChunkReader( - Chunk timeChunk, List valueChunkList, LongConsumer filteredRowsRecord) - throws IOException { - super(Long.MIN_VALUE, null, filteredRowsRecord); - ownedTimeChunk = timeChunk; - ownedValueChunks = new ArrayList<>(valueChunkList); - this.timeChunkHeader = timeChunk.getHeader(); - this.timeChunkDataBuffer = timeChunk.getData(); - this.encryptParam = timeChunk.getEncryptParam(); - try { - this.pageEstimatedMemoryUsageInBytes = - calculateMaxPageEstimatedMemoryUsageInBytesWithBatchData(timeChunk, valueChunkList); - - valueChunkList.forEach( - chunk -> { - this.valueChunkHeaderList.add(chunk == null ? null : chunk.getHeader()); - this.valueChunkDataBufferList.add(chunk == null ? null : chunk.getData()); - this.valueDeleteIntervalsList.add(chunk == null ? null : chunk.getDeleteIntervalList()); - }); - - initAllPageReaders(); - } catch (IOException | RuntimeException | Error e) { - try { - close(); - } catch (RuntimeException failure) { - e.addSuppressed(failure); - } - throw e; - } - } - - @Override - public void close() { - ownedTimeChunk.close(); - for (Chunk chunk : ownedValueChunks) { - if (chunk != null) { - chunk.close(); - } - } - } - - private void initAllPageReaders() throws IOException { - int pageIndex = 0; - while (timeChunkDataBuffer.remaining() > 0) { - AlignedPageReader alignedPageReader = deserializeFromSinglePageChunk(pageIndex++); - if (alignedPageReader != null) { - pageReaderList.add(alignedPageReader); - } - } - } - - private AlignedPageReader deserializeFromSinglePageChunk(int pageIndex) throws IOException { - PageHeader timePageHeader = - PageHeader.deserializeFrom(timeChunkDataBuffer, (Statistics) null); - List valuePageHeaderList = new ArrayList<>(); - - boolean isAllNull = true; - for (ByteBuffer byteBuffer : valueChunkDataBufferList) { - if (byteBuffer != null) { - isAllNull = false; - valuePageHeaderList.add( - PageHeader.deserializeFrom(byteBuffer, (Statistics) null)); - } else { - valuePageHeaderList.add(null); - } - } - - if (isAllNull) { - // when there is only one page in the chunk, the page statistic is the same as the chunk, so - // we needn't filter the page again - skipCurrentPage(timePageHeader, valuePageHeaderList); - return null; - } - return constructAlignedPageReader(timePageHeader, valuePageHeaderList, pageIndex); - } - - private void skipCurrentPage(PageHeader timePageHeader, List valuePageHeader) { - timeChunkDataBuffer.position( - timeChunkDataBuffer.position() + timePageHeader.getCompressedSize()); - for (int i = 0; i < valuePageHeader.size(); i++) { - if (valuePageHeader.get(i) != null) { - valueChunkDataBufferList - .get(i) - .position( - valueChunkDataBufferList.get(i).position() - + valuePageHeader.get(i).getCompressedSize()); - } - } - } - - private AlignedPageReader constructAlignedPageReader( - PageHeader timePageHeader, List rawValuePageHeaderList, int pageIndex) - throws IOException { - IDecryptor decryptor = IDecryptor.getDecryptor(encryptParam); - ByteBuffer timePageData = - ChunkReader.deserializePageData( - timePageHeader, - timeChunkDataBuffer, - timeChunkHeader, - decryptor, - encryptParam, - pageIndex); - - List valuePageHeaderList = new ArrayList<>(); - LazyLoadPageData[] valuePageDataArray = new LazyLoadPageData[rawValuePageHeaderList.size()]; - List valueDataTypeList = new ArrayList<>(); - List valueDecoderList = new ArrayList<>(); - - boolean isAllNull = true; - for (int i = 0; i < rawValuePageHeaderList.size(); i++) { - PageHeader valuePageHeader = rawValuePageHeaderList.get(i); - - if (valuePageHeader == null || valuePageHeader.getUncompressedSize() == 0) { - // Empty Page - valuePageHeaderList.add(null); - valuePageDataArray[i] = null; - valueDataTypeList.add(null); - valueDecoderList.add(null); - } else { - ChunkHeader valueChunkHeader = valueChunkHeaderList.get(i); - int currentPagePosition = valueChunkDataBufferList.get(i).position(); - valueChunkDataBufferList - .get(i) - .position(currentPagePosition + valuePageHeader.getCompressedSize()); - valuePageHeaderList.add(valuePageHeader); - valuePageDataArray[i] = - new LazyLoadPageData( - valueChunkDataBufferList.get(i).array(), - currentPagePosition, - IUnCompressor.getUnCompressor(valueChunkHeader.getCompressionType()), - encryptParam, - pageIndex, - valueChunkHeader.getChunkOrdinal()); - valueDataTypeList.add(valueChunkHeader.getDataType()); - valueDecoderList.add( - Decoder.getDecoderByType( - valueChunkHeader.getEncodingType(), valueChunkHeader.getDataType())); - isAllNull = false; - } - } - if (isAllNull) { - return null; - } - AlignedPageReader alignedPageReader = - new AlignedPageReader( - timePageHeader, - timePageData, - getTimeDecoder(timeChunkHeader.getEncodingType()), - valuePageHeaderList, - valuePageDataArray, - valueDataTypeList, - valueDecoderList, - queryFilter); - alignedPageReader.setDeleteIntervalList(valueDeleteIntervalsList); - return alignedPageReader; - } - - @Override - public long getCurrentPageEstimatedMemoryUsageInBytes() { - return pageEstimatedMemoryUsageInBytes; - } - - public static long calculatePageEstimatedMemoryUsageInBytes( - final Chunk timeChunk, final List valueChunkList) throws IOException { - final ByteBuffer timeChunkDataBuffer = timeChunk.getData().duplicate(); - long estimatedMemoryUsageInBytes = - PageHeader.deserializeFrom(timeChunkDataBuffer, (Statistics) null) - .getUncompressedSize(); - - for (final Chunk valueChunk : valueChunkList) { - if (valueChunk == null) { - continue; - } - - final ByteBuffer valueChunkDataBuffer = valueChunk.getData().duplicate(); - estimatedMemoryUsageInBytes += - PageHeader.deserializeFrom( - valueChunkDataBuffer, (Statistics) null) - .getUncompressedSize(); - } - - return estimatedMemoryUsageInBytes; - } - - public static long calculateMaxPageEstimatedMemoryUsageInBytesWithBatchData( - final Chunk timeChunk, final List valueChunkList) throws IOException { - final List pageEstimatedMemoryUsageInBytesList = - calculatePageEstimatedMemoryUsageInBytesWithBatchDataList(timeChunk, valueChunkList); - return pageEstimatedMemoryUsageInBytesList.isEmpty() - ? 0 - : pageEstimatedMemoryUsageInBytesList.get(0); - } - - public static List calculatePageEstimatedMemoryUsageInBytesWithBatchDataList( - final Chunk timeChunk, final List valueChunkList) throws IOException { - final PageMemoryUsageEstimator estimator = new PageMemoryUsageEstimator(timeChunk); - for (final Chunk valueChunk : valueChunkList) { - estimator.addValueChunk(valueChunk); - } - return estimator.getPageEstimatedMemoryUsageInBytesList(); - } - - static final class PageMemoryUsageEstimator { - - private final List pageUncompressedSizeInBytesList = new ArrayList<>(); - private final List pageRowCountList = new ArrayList<>(); - private List pageEstimatedMemoryUsageInBytesList = new ArrayList<>(); - - private int valueCount; - private TSDataType singleValueDataType; - private long vectorValueMemoryUsageInBytes; - - PageMemoryUsageEstimator(final Chunk timeChunk) throws IOException { - final ByteBuffer timeChunkDataBuffer = timeChunk.getData().duplicate(); - timeChunkDataBuffer.rewind(); - while (timeChunkDataBuffer.remaining() > 0) { - final PageHeader timePageHeader = - SinglePageWholeChunkReader.deserializePageHeader( - timeChunkDataBuffer, timeChunk.getHeader()); - pageUncompressedSizeInBytesList.add((long) timePageHeader.getUncompressedSize()); - pageRowCountList.add(SinglePageWholeChunkReader.getPageRowCount(timePageHeader, timeChunk)); - SinglePageWholeChunkReader.skipCompressedPageData(timeChunkDataBuffer, timePageHeader); - } - pageEstimatedMemoryUsageInBytesList = calculatePageEstimatedMemoryUsageInBytesList(); - } - - long calculateMaxPageEstimatedMemoryUsageInBytesWithValueChunk(final Chunk valueChunk) - throws IOException { - final List pageEstimatedMemoryUsageInBytesList = - calculatePageEstimatedMemoryUsageInBytesList(valueChunk, false); - return pageEstimatedMemoryUsageInBytesList.isEmpty() - ? 0 - : pageEstimatedMemoryUsageInBytesList.get(0); - } - - void addValueChunk(final Chunk valueChunk) throws IOException { - pageEstimatedMemoryUsageInBytesList = - calculatePageEstimatedMemoryUsageInBytesList(valueChunk, true); - } - - List getPageEstimatedMemoryUsageInBytesList() { - return pageEstimatedMemoryUsageInBytesList; - } - - private List calculatePageEstimatedMemoryUsageInBytesList() { - final List pageEstimatedMemoryUsageInBytesList = - new ArrayList<>(pageUncompressedSizeInBytesList.size()); - for (int i = 0; i < pageUncompressedSizeInBytesList.size(); ++i) { - pageEstimatedMemoryUsageInBytesList.add( - SinglePageWholeChunkReader.estimatePageMemoryUsageInBytesWithBatchData( - pageUncompressedSizeInBytesList.get(i), - pageRowCountList.get(i), - valueCount, - singleValueDataType, - vectorValueMemoryUsageInBytes)); - } - return SinglePageWholeChunkReader.toSuffixMaxList(pageEstimatedMemoryUsageInBytesList); - } - - private List calculatePageEstimatedMemoryUsageInBytesList( - final Chunk valueChunk, final boolean commit) throws IOException { - final ByteBuffer valueChunkDataBuffer; - final TSDataType valueDataType; - if (Objects.isNull(valueChunk)) { - valueChunkDataBuffer = null; - valueDataType = null; - } else { - valueChunkDataBuffer = valueChunk.getData().duplicate(); - valueChunkDataBuffer.rewind(); - valueDataType = valueChunk.getHeader().getDataType(); - } - - final int newValueCount = valueCount + 1; - final TSDataType newSingleValueDataType = valueCount == 0 ? valueDataType : null; - final long newVectorValueMemoryUsageInBytes = - vectorValueMemoryUsageInBytes - + SinglePageWholeChunkReader.estimateVectorValueMemoryUsageInBytes(valueDataType); - final List newPageUncompressedSizeInBytesList = - new ArrayList<>(pageUncompressedSizeInBytesList); - final List pageEstimatedMemoryUsageInBytesList = - new ArrayList<>(pageUncompressedSizeInBytesList.size()); - - for (int i = 0; i < newPageUncompressedSizeInBytesList.size(); ++i) { - if (Objects.nonNull(valueChunkDataBuffer)) { - final PageHeader valuePageHeader = - SinglePageWholeChunkReader.deserializePageHeader( - valueChunkDataBuffer, valueChunk.getHeader()); - newPageUncompressedSizeInBytesList.set( - i, newPageUncompressedSizeInBytesList.get(i) + valuePageHeader.getUncompressedSize()); - SinglePageWholeChunkReader.skipCompressedPageData(valueChunkDataBuffer, valuePageHeader); - } - pageEstimatedMemoryUsageInBytesList.add( - SinglePageWholeChunkReader.estimatePageMemoryUsageInBytesWithBatchData( - newPageUncompressedSizeInBytesList.get(i), - pageRowCountList.get(i), - newValueCount, - newSingleValueDataType, - newVectorValueMemoryUsageInBytes)); - } - - if (commit) { - pageUncompressedSizeInBytesList.clear(); - pageUncompressedSizeInBytesList.addAll(newPageUncompressedSizeInBytesList); - valueCount = newValueCount; - singleValueDataType = newSingleValueDataType; - vectorValueMemoryUsageInBytes = newVectorValueMemoryUsageInBytes; - } - - return SinglePageWholeChunkReader.toSuffixMaxList(pageEstimatedMemoryUsageInBytesList); - } - } -} diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/scan/EstimatedMemoryChunkReader.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/scan/EstimatedMemoryChunkReader.java deleted file mode 100644 index 1d455744db25c..0000000000000 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/scan/EstimatedMemoryChunkReader.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * 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.iotdb.db.pipe.event.common.tsfile.parser.scan; - -interface EstimatedMemoryChunkReader { - - long getCurrentPageEstimatedMemoryUsageInBytes(); -} diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/scan/MemoryControlledChunkReader.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/scan/MemoryControlledChunkReader.java deleted file mode 100644 index 105bd5e8e33c8..0000000000000 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/scan/MemoryControlledChunkReader.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * 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.iotdb.db.pipe.event.common.tsfile.parser.scan; - -import org.apache.tsfile.read.common.BatchData; -import org.apache.tsfile.read.reader.IChunkReader; -import org.apache.tsfile.read.reader.IPageReader; - -import java.io.IOException; -import java.util.List; - -class MemoryControlledChunkReader implements IChunkReader, EstimatedMemoryChunkReader { - - private final IChunkReader delegate; - private final List pageEstimatedMemoryUsageInBytesList; - private int pageIndex; - - MemoryControlledChunkReader( - final IChunkReader delegate, final List pageEstimatedMemoryUsageInBytesList) { - this.delegate = delegate; - this.pageEstimatedMemoryUsageInBytesList = pageEstimatedMemoryUsageInBytesList; - } - - @Override - public long getCurrentPageEstimatedMemoryUsageInBytes() { - return pageIndex < pageEstimatedMemoryUsageInBytesList.size() - ? pageEstimatedMemoryUsageInBytesList.get(pageIndex) - : 0; - } - - @Override - public boolean hasNextSatisfiedPage() throws IOException { - return delegate.hasNextSatisfiedPage(); - } - - @Override - public BatchData nextPageData() throws IOException { - try { - return delegate.nextPageData(); - } finally { - ++pageIndex; - } - } - - @Override - public void close() throws IOException { - delegate.close(); - } - - @Override - public void markDataTypeModifiedAndCannotUseStatistics() { - delegate.markDataTypeModifiedAndCannotUseStatistics(); - } - - @Override - public List loadPageReaderList() throws IOException { - return delegate.loadPageReaderList(); - } -} diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/scan/SinglePageWholeChunkReader.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/scan/SinglePageWholeChunkReader.java deleted file mode 100644 index 1c1a30f4d0e0e..0000000000000 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/scan/SinglePageWholeChunkReader.java +++ /dev/null @@ -1,397 +0,0 @@ -/* - * 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.iotdb.db.pipe.event.common.tsfile.parser.scan; - -import org.apache.iotdb.db.i18n.DataNodePipeMessages; - -import org.apache.tsfile.common.constant.TsFileConstant; -import org.apache.tsfile.compress.IUnCompressor; -import org.apache.tsfile.encoding.decoder.Decoder; -import org.apache.tsfile.encrypt.EncryptParameter; -import org.apache.tsfile.encrypt.IDecryptor; -import org.apache.tsfile.enums.TSDataType; -import org.apache.tsfile.file.MetaMarker; -import org.apache.tsfile.file.header.ChunkHeader; -import org.apache.tsfile.file.header.PageHeader; -import org.apache.tsfile.file.metadata.enums.EncryptionType; -import org.apache.tsfile.file.metadata.statistics.Statistics; -import org.apache.tsfile.read.common.Chunk; -import org.apache.tsfile.read.common.type.Type; -import org.apache.tsfile.read.reader.chunk.AbstractChunkReader; -import org.apache.tsfile.read.reader.chunk.ChunkReader; -import org.apache.tsfile.read.reader.page.LazyLoadPageData; -import org.apache.tsfile.read.reader.page.PageReader; -import org.apache.tsfile.utils.RamUsageEstimator; - -import java.io.IOException; -import java.io.Serializable; -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Objects; - -import static org.apache.tsfile.file.metadata.enums.CompressionType.UNCOMPRESSED; - -public class SinglePageWholeChunkReader extends AbstractChunkReader - implements EstimatedMemoryChunkReader { - private final ChunkHeader chunkHeader; - private final ByteBuffer chunkDataBuffer; - private final EncryptParameter encryptParam; - private final long pageEstimatedMemoryUsageInBytes; - private final Chunk ownedChunk; - - public SinglePageWholeChunkReader(Chunk chunk) throws IOException { - super(Long.MIN_VALUE, null, null); - ownedChunk = chunk; - - this.chunkHeader = chunk.getHeader(); - this.chunkDataBuffer = chunk.getData(); - this.encryptParam = chunk.getEncryptParam(); - try { - this.pageEstimatedMemoryUsageInBytes = - calculateMaxPageEstimatedMemoryUsageInBytesWithBatchData(chunk); - initAllPageReaders(); - } catch (IOException | RuntimeException | Error e) { - try { - chunk.close(); - } catch (RuntimeException failure) { - e.addSuppressed(failure); - } - throw e; - } - } - - @Override - public void close() { - ownedChunk.close(); - } - - private void initAllPageReaders() throws IOException { - int pageIndex = 0; - // construct next satisfied page header - while (chunkDataBuffer.remaining() > 0) { - pageReaderList.add( - constructPageReader( - PageHeader.deserializeFrom( - chunkDataBuffer, (Statistics) null), - pageIndex++)); - } - } - - private PageReader constructPageReader(PageHeader pageHeader, int pageIndex) throws IOException { - final int currentPagePosition = chunkDataBuffer.position(); - chunkDataBuffer.position(currentPagePosition + pageHeader.getCompressedSize()); - return new PageReader( - pageHeader, - new LazyLoadPageData( - chunkDataBuffer.array(), - currentPagePosition, - IUnCompressor.getUnCompressor(chunkHeader.getCompressionType()), - encryptParam, - pageIndex, - chunkHeader.getChunkOrdinal()), - chunkHeader.getDataType(), - Decoder.getDecoderByType(chunkHeader.getEncodingType(), chunkHeader.getDataType()), - getConfiguredTimeDecoder(), - null); - } - - @Override - public long getCurrentPageEstimatedMemoryUsageInBytes() { - return pageEstimatedMemoryUsageInBytes; - } - - public static long calculatePageEstimatedMemoryUsageInBytes(final Chunk chunk) - throws IOException { - final ByteBuffer chunkDataBuffer = chunk.getData().duplicate(); - final PageHeader pageHeader = deserializePageHeader(chunkDataBuffer, chunk.getHeader()); - return pageHeader.getUncompressedSize(); - } - - public static long calculateMaxPageEstimatedMemoryUsageInBytes(final Chunk chunk) - throws IOException { - final ByteBuffer chunkDataBuffer = chunk.getData().duplicate(); - long maxPageEstimatedMemoryUsageInBytes = 0; - while (chunkDataBuffer.remaining() > 0) { - final PageHeader pageHeader = deserializePageHeader(chunkDataBuffer, chunk.getHeader()); - maxPageEstimatedMemoryUsageInBytes = - Math.max(maxPageEstimatedMemoryUsageInBytes, pageHeader.getUncompressedSize()); - skipCompressedPageData(chunkDataBuffer, pageHeader); - } - return maxPageEstimatedMemoryUsageInBytes; - } - - public static long calculateMaxPageEstimatedMemoryUsageInBytesWithBatchData(final Chunk chunk) - throws IOException { - final List pageEstimatedMemoryUsageInBytesList = - calculatePageEstimatedMemoryUsageInBytesWithBatchDataList(chunk); - return pageEstimatedMemoryUsageInBytesList.isEmpty() - ? 0 - : pageEstimatedMemoryUsageInBytesList.get(0); - } - - public static List calculatePageEstimatedMemoryUsageInBytesWithBatchDataList( - final Chunk chunk) throws IOException { - final ByteBuffer chunkDataBuffer = chunk.getData().duplicate(); - final List pageEstimatedMemoryUsageInBytesList = new ArrayList<>(); - while (chunkDataBuffer.remaining() > 0) { - final PageHeader pageHeader = deserializePageHeader(chunkDataBuffer, chunk.getHeader()); - pageEstimatedMemoryUsageInBytesList.add( - estimatePageMemoryUsageInBytesWithBatchData( - pageHeader, chunk, Collections.singletonList(chunk.getHeader().getDataType()))); - skipCompressedPageData(chunkDataBuffer, pageHeader); - } - return toSuffixMaxList(pageEstimatedMemoryUsageInBytesList); - } - - static PageHeader deserializePageHeader( - final ByteBuffer chunkDataBuffer, final ChunkHeader chunkHeader) throws IOException { - return isSinglePageChunk(chunkHeader) - ? PageHeader.deserializeFrom(chunkDataBuffer, (Statistics) null) - : PageHeader.deserializeFrom(chunkDataBuffer, chunkHeader.getDataType()); - } - - static boolean isSinglePageChunk(final ChunkHeader chunkHeader) { - return (chunkHeader.getChunkType() & 0x3F) == MetaMarker.ONLY_ONE_PAGE_CHUNK_HEADER; - } - - static void skipCompressedPageData( - final ByteBuffer chunkDataBuffer, final PageHeader pageHeader) { - chunkDataBuffer.position(chunkDataBuffer.position() + pageHeader.getCompressedSize()); - } - - static List toSuffixMaxList(final List pageEstimatedMemoryUsageInBytesList) { - long suffixMaxPageEstimatedMemoryUsageInBytes = 0; - for (int i = pageEstimatedMemoryUsageInBytesList.size() - 1; i >= 0; --i) { - suffixMaxPageEstimatedMemoryUsageInBytes = - Math.max( - suffixMaxPageEstimatedMemoryUsageInBytes, pageEstimatedMemoryUsageInBytesList.get(i)); - pageEstimatedMemoryUsageInBytesList.set(i, suffixMaxPageEstimatedMemoryUsageInBytes); - } - return pageEstimatedMemoryUsageInBytesList; - } - - static long estimatePageMemoryUsageInBytesWithBatchData( - final PageHeader timePageHeader, - final Chunk timeChunk, - final List valueDataTypeList) - throws IOException { - return estimatePageMemoryUsageInBytesWithBatchData( - timePageHeader.getUncompressedSize(), - getPageRowCount(timePageHeader, timeChunk), - valueDataTypeList); - } - - static int getPageRowCount(final PageHeader pageHeader, final Chunk chunk) throws IOException { - if (isSinglePageChunk(chunk.getHeader())) { - if (Objects.nonNull(chunk.getChunkStatistic())) { - return saturateToInt(chunk.getChunkStatistic().getCount()); - } - return isTimeChunk(chunk.getHeader()) ? countSinglePageTimeValues(chunk) : 0; - } - return saturateToInt(pageHeader.getNumOfValues()); - } - - private static int countSinglePageTimeValues(final Chunk chunk) throws IOException { - final ByteBuffer chunkDataBuffer = chunk.getData().duplicate(); - chunkDataBuffer.rewind(); - final PageHeader pageHeader = deserializePageHeader(chunkDataBuffer, chunk.getHeader()); - final ByteBuffer pageData = - ChunkReader.deserializePageData( - pageHeader, - chunkDataBuffer, - chunk.getHeader(), - IDecryptor.getDecryptor(chunk.getEncryptParam()), - chunk.getEncryptParam(), - 0); - final Decoder decoder = - Decoder.getDecoderByType(chunk.getHeader().getEncodingType(), TSDataType.INT64); - - int rowCount = 0; - while (decoder.hasNext(pageData)) { - decoder.readLong(pageData); - ++rowCount; - } - return rowCount; - } - - private static boolean isTimeChunk(final ChunkHeader chunkHeader) { - return (chunkHeader.getChunkType() & TsFileConstant.TIME_COLUMN_MASK) - == TsFileConstant.TIME_COLUMN_MASK; - } - - private static int saturateToInt(final long value) { - return (int) Math.min(Integer.MAX_VALUE, value); - } - - static long estimatePageMemoryUsageInBytesWithBatchData( - final long pageUncompressedSizeInBytes, - final int rowCount, - final List valueDataTypeList) { - final int valueCount = valueDataTypeList.size(); - return estimatePageMemoryUsageInBytesWithBatchData( - pageUncompressedSizeInBytes, - rowCount, - valueCount, - valueCount == 1 ? valueDataTypeList.get(0) : null, - estimateVectorValueMemoryUsageInBytes(valueDataTypeList)); - } - - static long estimatePageMemoryUsageInBytesWithBatchData( - final long pageUncompressedSizeInBytes, - final int rowCount, - final int valueCount, - final TSDataType singleValueDataType, - final long vectorValueMemoryUsageInBytes) { - return pageUncompressedSizeInBytes - + estimateBatchDataMemoryUsageInBytes( - rowCount, valueCount, singleValueDataType, vectorValueMemoryUsageInBytes); - } - - private static long estimateBatchDataMemoryUsageInBytes( - final int rowCount, - final int valueCount, - final TSDataType singleValueDataType, - final long vectorValueMemoryUsageInBytes) { - final long segmentCount = Math.max(1, (rowCount + 15L) / 16); - long estimatedMemoryUsageInBytes = RamUsageEstimator.sizeOfLongArray(16) * segmentCount; - - if (valueCount == 1) { - estimatedMemoryUsageInBytes += - estimateSingleValueArrayMemoryUsageInBytes(rowCount, singleValueDataType); - } else if (valueCount > 1) { - estimatedMemoryUsageInBytes += RamUsageEstimator.sizeOfObjectArray(16) * segmentCount; - estimatedMemoryUsageInBytes += - (long) rowCount - * (RamUsageEstimator.sizeOfObjectArray(valueCount) + vectorValueMemoryUsageInBytes); - } - - return estimatedMemoryUsageInBytes; - } - - private static long estimateSingleValueArrayMemoryUsageInBytes( - final int rowCount, final TSDataType dataType) { - final long segmentCount = Math.max(1, (rowCount + 15L) / 16); - if (Objects.isNull(dataType)) { - return 0; - } - - return Type.fromTsDataType(dataType).estimateArraySize(16) * segmentCount; - } - - private static long estimateVectorValueMemoryUsageInBytes( - final List valueDataTypeList) { - long estimatedMemoryUsageInBytes = 0; - for (final TSDataType dataType : valueDataTypeList) { - estimatedMemoryUsageInBytes += estimateVectorValueMemoryUsageInBytes(dataType); - } - return estimatedMemoryUsageInBytes; - } - - static long estimateVectorValueMemoryUsageInBytes(final TSDataType dataType) { - if (Objects.isNull(dataType)) { - return 0; - } - - return RamUsageEstimator.alignObjectSize( - RamUsageEstimator.NUM_BYTES_OBJECT_HEADER - + estimateTsPrimitiveTypeValueMemoryUsageInBytes(dataType)); - } - - private static long estimateTsPrimitiveTypeValueMemoryUsageInBytes(final TSDataType dataType) { - return Type.fromTsDataType(dataType).estimateValueSize(); - } - - ///////////////////////////////////////////////////////////////////////////////////////////////// - // util methods - ///////////////////////////////////////////////////////////////////////////////////////////////// - - public static ByteBuffer readCompressedPageData(PageHeader pageHeader, ByteBuffer chunkBuffer) - throws IOException { - int compressedPageBodyLength = pageHeader.getCompressedSize(); - byte[] compressedPageBody = new byte[compressedPageBodyLength]; - // doesn't have a complete page body - if (compressedPageBodyLength > chunkBuffer.remaining()) { - throw new IOException( - String.format( - DataNodePipeMessages.COMPLETE_PAGE_BODY_EXPECTED_ACTUAL_FMT, - compressedPageBodyLength, - chunkBuffer.remaining())); - } - chunkBuffer.get(compressedPageBody); - return ByteBuffer.wrap(compressedPageBody); - } - - public static ByteBuffer uncompressPageData( - PageHeader pageHeader, IUnCompressor unCompressor, ByteBuffer compressedPageData) - throws IOException { - if (unCompressor.getCodecName() == UNCOMPRESSED) { - return compressedPageData; - } - int compressedPageBodyLength = pageHeader.getCompressedSize(); - ByteBuffer uncompressedPageData = ByteBuffer.allocate(pageHeader.getUncompressedSize()); - try { - unCompressor.uncompress( - compressedPageData.array(), 0, compressedPageBodyLength, uncompressedPageData.array(), 0); - } catch (Exception e) { - throw new IOException( - String.format( - DataNodePipeMessages.UNCOMPRESS_PAGE_DATA_FAILED_FMT, - pageHeader.getUncompressedSize(), - pageHeader.getCompressedSize(), - pageHeader, - e.getMessage()), - e); - } - - return uncompressedPageData; - } - - public static ByteBuffer decrypt(IDecryptor decryptor, ByteBuffer buffer) { - if (decryptor == null || decryptor.getEncryptionType() == EncryptionType.UNENCRYPTED) { - return buffer; - } - return ByteBuffer.wrap( - decryptor.decrypt( - buffer.array(), buffer.arrayOffset() + buffer.position(), buffer.remaining())); - } - - public static ByteBuffer decryptAndUncompressPageData( - PageHeader pageHeader, - IUnCompressor unCompressor, - ByteBuffer compressedPageData, - IDecryptor decryptor) - throws IOException { - return uncompressPageData(pageHeader, unCompressor, decrypt(decryptor, compressedPageData)); - } - - public static ByteBuffer deserializePageData( - PageHeader pageHeader, ByteBuffer chunkBuffer, ChunkHeader chunkHeader, IDecryptor decryptor) - throws IOException { - IUnCompressor unCompressor = IUnCompressor.getUnCompressor(chunkHeader.getCompressionType()); - ByteBuffer compressedPageBody = readCompressedPageData(pageHeader, chunkBuffer); - if (decryptor == null || decryptor.getEncryptionType() == EncryptionType.UNENCRYPTED) { - return uncompressPageData(pageHeader, unCompressor, compressedPageBody); - } else { - return decryptAndUncompressPageData(pageHeader, unCompressor, compressedPageBody, decryptor); - } - } -} diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/scan/TsFileInsertionEventScanParser.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/scan/TsFileInsertionEventScanParser.java index a2c964f6406d1..cbfce6c39720b 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/scan/TsFileInsertionEventScanParser.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/scan/TsFileInsertionEventScanParser.java @@ -41,8 +41,10 @@ import org.apache.iotdb.db.pipe.event.common.tsfile.parser.TsFileInsertionEventParserMemoryBlock; import org.apache.iotdb.db.pipe.event.common.tsfile.parser.TsFileInsertionEventParserMemoryManager; import org.apache.iotdb.db.pipe.event.common.tsfile.parser.util.ModsOperationUtil; +import org.apache.iotdb.db.pipe.event.common.tsfile.parser.util.tablet.ChunkDirectTabletReader; +import org.apache.iotdb.db.pipe.event.common.tsfile.parser.util.tablet.SeriesChunkDirectTabletReader; +import org.apache.iotdb.db.pipe.event.common.tsfile.parser.util.tablet.TabletPageReader; import org.apache.iotdb.db.pipe.resource.memory.PipeMemoryWeightUtil; -import org.apache.iotdb.db.utils.TypeServices; import org.apache.iotdb.db.utils.datastructure.PatternTreeMapFactory; import org.apache.iotdb.pipe.api.event.dml.insertion.TabletInsertionEvent; import org.apache.iotdb.pipe.api.exception.PipeException; @@ -57,17 +59,9 @@ import org.apache.tsfile.file.metadata.IDeviceID; import org.apache.tsfile.file.metadata.statistics.Statistics; import org.apache.tsfile.read.TsFileSequenceReader; -import org.apache.tsfile.read.common.BatchData; import org.apache.tsfile.read.common.Chunk; -import org.apache.tsfile.read.common.type.Type; -import org.apache.tsfile.read.filter.basic.Filter; import org.apache.tsfile.read.reader.BufferedTsFileInput; -import org.apache.tsfile.read.reader.IChunkReader; -import org.apache.tsfile.read.reader.chunk.AlignedChunkReader; -import org.apache.tsfile.read.reader.chunk.ChunkReader; -import org.apache.tsfile.utils.Binary; import org.apache.tsfile.utils.Pair; -import org.apache.tsfile.utils.TsPrimitiveType; import org.apache.tsfile.write.record.Tablet; import org.apache.tsfile.write.schema.IMeasurementSchema; import org.apache.tsfile.write.schema.MeasurementSchema; @@ -111,20 +105,17 @@ public record ScanOptions( private final long startTime; private final long endTime; - private final Filter filter; private final boolean trackPointCounts; private final Map> parsedPointCountsByDevice = new HashMap<>(); private final Map> expectedPointCountsByDevice = new HashMap<>(); - private IChunkReader chunkReader; - private BatchData data; - private BatchData pendingPageDataAfterMemoryPressure; + private TabletPageReader reader; + private boolean pageCountsReported; private Tablet pendingTabletAfterMemoryPressure; private final TsFileInsertionEventParserMemoryBlock allocatedMemoryBlockForBatchData; private final TsFileInsertionEventParserMemoryBlock allocatedMemoryBlockForChunk; private TsFileInsertionEventParserMemoryBlock allocatedMemoryBlockForTsFileInput; - private boolean currentIsMultiPage; private IDeviceID currentDevice; private String currentDeviceString; private boolean currentIsAligned; @@ -134,7 +125,6 @@ public record ScanOptions( private final List modsInfos = new ArrayList<>(); // Cached time chunk private final List timeChunkList = new ArrayList<>(); - private final List isMultiPageList = new ArrayList<>(); private final Map measurementIndexMap = new HashMap<>(); private final List pendingAlignedChunkGroups = new ArrayList<>(); @@ -219,8 +209,6 @@ private TsFileInsertionEventScanParser(final ParserContext parserContext) this.trackPointCounts = scanOptions.trackPointCounts(); this.startTime = scanOptions.startTime(); this.endTime = scanOptions.endTime(); - filter = Objects.nonNull(timeFilterExpression) ? timeFilterExpression.getFilter() : null; - this.allocatedMemoryBlockForBatchData = allocateTabletMemory( TsFileInsertionEventScanParser.class.getSimpleName() + "#batchData", 0); @@ -243,8 +231,8 @@ private TsFileInsertionEventScanParser(final ParserContext parserContext) createTsFileSequenceReader(parserContext.tsFile(), !currentModifications.isEmpty()); tsFileSequenceReader.position(tsFileSequenceReader.getDataStartOffset()); - prepareData(); - if (Objects.isNull(chunkReader)) { + prepareNextChunkReader(); + if (Objects.isNull(reader)) { close(); } } catch (final Exception e) { @@ -339,7 +327,7 @@ public Iterable toTabletInsertionEvents() { public boolean hasNext() { throwIfDeferredException(); retryChunkHeaderAfterMemoryPressureIfNecessary(); - final boolean hasNext = Objects.nonNull(chunkReader); + final boolean hasNext = Objects.nonNull(reader); if (hasNext && !parseStartTimeRecorded) { // Record start time on first hasNext() that returns true recordParseStartTime(); @@ -422,7 +410,7 @@ public Iterable> toTabletWithIsAligneds() { public boolean hasNext() { throwIfDeferredException(); retryChunkHeaderAfterMemoryPressureIfNecessary(); - return Objects.nonNull(chunkReader); + return Objects.nonNull(reader); } @Override @@ -480,59 +468,47 @@ public Map> getExpectedPointCounts() { } private Tablet getNextTablet() { - Tablet tablet = null; - boolean tabletMemoryReserved = false; + Tablet tablet = pendingTabletAfterMemoryPressure; + pendingTabletAfterMemoryPressure = null; + boolean tabletMemoryReserved = tablet != null; try { - if (data != null && !data.hasCurrent() && pendingPageDataAfterMemoryPressure != null) { - data = nextPageData(); - } - tablet = pendingTabletAfterMemoryPressure; - tabletMemoryReserved = tablet != null; - pendingTabletAfterMemoryPressure = null; - - if (!data.hasCurrent()) { - if (tablet != null) { - PipeTabletUtils.compactBitMaps(tablet); - return tablet; - } + if (Objects.isNull(reader)) { return new Tablet(currentDeviceString, currentMeasurements, 1); } boolean isFirstRow = tablet == null; - while (data.hasCurrent()) { - if (currentIsMultiPage - || data.currentTime() >= startTime && data.currentTime() <= endTime) { - if (isFirstRow) { - // Calculate row count and memory size of the tablet based on the first row - Pair rowCountAndMemorySize = - PipeMemoryWeightUtil.calculateTabletRowCountAndMemory(data); - tablet = - new Tablet( - currentDeviceString, currentMeasurements, rowCountAndMemorySize.getLeft()); - if (allocatedMemoryBlockForTablet.getMemoryUsageInBytes() - < rowCountAndMemorySize.getRight()) { - allocatedMemoryBlockForTablet.forceResize(rowCountAndMemorySize.getRight()); - } - tabletMemoryReserved = true; - pendingTabletAfterMemoryPressure = tablet; - isFirstRow = false; - } - - final int rowIndex = tablet.getRowSize(); - - recordParsedPointCounts(data); - recordExpectedPointCounts(data); - if (putValueToColumns(data, tablet, rowIndex)) { - PipeTabletUtils.putTimestamp(tablet, rowIndex, data.currentTime()); - } + while (true) { + // After an out-of-memory error the pending tablet is restored with the current page already + // consumed: load the page whose reservation failed before deciding that the chunk is over, + // otherwise the retry would release the reader and drop the rest of the chunk. + if (!reader.hasCurrentRow() && !loadNextPageWithMemory(reader)) { + // The chunk is exhausted. Its measurements cannot continue in the same tablet. + break; } - - data.next(); - while (!data.hasCurrent() && chunkReader.hasNextSatisfiedPage()) { - data = nextPageData(); + if (isFirstRow) { + final Pair rowCountAndMemorySize = + PipeMemoryWeightUtil.calculateTabletRowCountAndMemory( + currentDataTypes(), + 0, + reader.binaryValueBytes(), + reader.pageRowCount(), + reader.remainingRows()); + tablet = + new Tablet(currentDeviceString, currentMeasurements, rowCountAndMemorySize.getLeft()); + if (allocatedMemoryBlockForTablet.getMemoryUsageInBytes() + < rowCountAndMemorySize.getRight()) { + allocatedMemoryBlockForTablet.forceResize(rowCountAndMemorySize.getRight()); + } + tabletMemoryReserved = true; + pendingTabletAfterMemoryPressure = tablet; + isFirstRow = false; } - if (tablet != null && tablet.getRowSize() == tablet.getMaxRowNumber()) { + recordPagePointCounts(); + reader.fillTablet( + tablet, + Math.min(reader.remainingRows(), tablet.getMaxRowNumber() - tablet.getRowSize())); + if (tablet.getRowSize() >= tablet.getMaxRowNumber()) { break; } } @@ -541,10 +517,13 @@ private Tablet getNextTablet() { tablet = new Tablet(currentDeviceString, currentMeasurements, 1); } - // Switch chunk reader iff current chunk is all consumed - if (!data.hasCurrent()) { + // Switch chunk reader iff the current chunk is all consumed. A tablet that becomes full at a + // page boundary leaves the next page of the same chunk unread, so the chunk is only over when + // it has no page left either. The next chunk may have another measurement set, so it can + // never continue the tablet that is returned here. + if (!reader.hasCurrentRow() && !reader.hasNextPage()) { try { - prepareData(); + prepareNextChunkReader(); } catch (final Exception e) { deferredException = e; } @@ -563,6 +542,15 @@ private Tablet getNextTablet() { } } + /** The data types of the measurements of the chunk that is being parsed. */ + private List currentDataTypes() { + final List dataTypes = new ArrayList<>(currentMeasurements.size()); + for (final IMeasurementSchema schema : currentMeasurements) { + dataTypes.add(schema.getType()); + } + return dataTypes; + } + private void throwIfDeferredException() { if (Objects.isNull(deferredException)) { return; @@ -580,7 +568,7 @@ private void retryChunkHeaderAfterMemoryPressureIfNecessary() { return; } try { - prepareData(); + prepareNextChunkReader(); shouldRetryChunkHeaderAfterMemoryPressure = false; } catch (final PipeRuntimeOutOfMemoryCriticalException | LoadRuntimeOutOfMemoryException e) { throw e; @@ -591,7 +579,7 @@ private void retryChunkHeaderAfterMemoryPressureIfNecessary() { } private boolean isLastTabletWithoutDeferredException() { - return Objects.isNull(deferredException) && Objects.isNull(chunkReader); + return Objects.isNull(deferredException) && Objects.isNull(reader); } private void recordParseEndTimeIfNecessary() { @@ -600,53 +588,42 @@ private void recordParseEndTimeIfNecessary() { } } - private void prepareData() throws IOException, IllegalPathException { - do { - do { - moveToNextChunkReader(); - } while (Objects.nonNull(chunkReader) && !chunkReader.hasNextSatisfiedPage()); - - if (Objects.isNull(chunkReader)) { + /** + * Advances to the next chunk that has a page with a row in the time range. The readers are + * created by {@link #moveToNextChunkReader()}; a chunk whose pages are all out of range is + * released without decoding a value. + */ + private void prepareNextChunkReader() throws IOException, IllegalPathException { + while (true) { + moveToNextChunkReader(); + if (Objects.isNull(reader)) { // Let the caller release the last tablet's memory before closing the parser. - break; + return; } - - do { - data = nextPageData(); - } while (!data.hasCurrent() && chunkReader.hasNextSatisfiedPage()); - } while (!data.hasCurrent()); - } - - private BatchData nextPageData() throws IOException { - if (pendingPageDataAfterMemoryPressure != null) { - resizePageDataMemoryIfNeeded( - PipeMemoryWeightUtil.calculateBatchDataRamBytesUsed(pendingPageDataAfterMemoryPressure)); - final BatchData pendingPageData = pendingPageDataAfterMemoryPressure; - pendingPageDataAfterMemoryPressure = null; - return pendingPageData; - } - - resizePageDataMemoryForCurrentPageIfNeeded(); - final BatchData nextData = chunkReader.nextPageData(); - try { - resizePageDataMemoryIfNeeded(PipeMemoryWeightUtil.calculateBatchDataRamBytesUsed(nextData)); - } catch (final PipeRuntimeOutOfMemoryCriticalException | LoadRuntimeOutOfMemoryException e) { - // The chunk reader has already advanced. Retain the decoded page until its memory can be - // accounted for instead of advancing to the following page on retry. - pendingPageDataAfterMemoryPressure = nextData; - throw e; + if (loadNextPageWithMemory(reader)) { + return; + } + // The chunk has no page in the range: move on to the next one. + releaseReader(); } - return nextData; } - private void resizePageDataMemoryForCurrentPageIfNeeded() { - if (!(chunkReader instanceof EstimatedMemoryChunkReader)) { - return; + /** + * Loads the next page of the reader that has a row in the time range, after reserving the memory + * of the page. The reservation happens before the page is decompressed and consumes nothing, so a + * parser that has to yield its memory can retry the same page. + * + * @return whether a page with a row in the range was loaded + */ + private boolean loadNextPageWithMemory(final TabletPageReader pageReader) throws IOException { + while (pageReader.hasNextPage()) { + resizePageDataMemoryIfNeeded(pageReader.peekNextPageBytes()); + if (pageReader.loadNextPage()) { + pageCountsReported = false; + return true; + } } - - final long estimatedMemoryUsageInBytes = - ((EstimatedMemoryChunkReader) chunkReader).getCurrentPageEstimatedMemoryUsageInBytes(); - resizePageDataMemoryIfNeeded(estimatedMemoryUsageInBytes); + return false; } private void resizePageDataMemoryIfNeeded(final long estimatedMemoryUsageInBytes) { @@ -655,80 +632,25 @@ private void resizePageDataMemoryIfNeeded(final long estimatedMemoryUsageInBytes } } - private boolean putValueToColumns(final BatchData data, final Tablet tablet, final int rowIndex) { - boolean isNeedFillTime = false; - if (data.getDataType() == TSDataType.VECTOR) { - for (int i = 0; i < tablet.getSchemas().size(); ++i) { - final TsPrimitiveType primitiveType = data.getVector()[i]; - final TSDataType dataType = tablet.getSchemas().get(i).getType(); - if (Objects.isNull(primitiveType) - || ModsOperationUtil.isDelete(data.currentTime(), modsInfos.get(i))) { - if (dataType.isBinary()) { - ((Binary[]) tablet.getValues()[i])[rowIndex] = Binary.EMPTY_VALUE; - } - PipeTabletUtils.markNullValue(tablet, rowIndex, i); - continue; - } - - isNeedFillTime = true; - TypeServices.Pipe.PIPE_TS_PRIMITIVE_TABLET_VALUE_WRITER_SERVICE - .call(Type.fromTsDataType(dataType)) - .write(primitiveType, tablet.getValues()[i], rowIndex); - PipeTabletUtils.unmarkNullValue(tablet, rowIndex, i); - } - } else { - if (!modsInfos.isEmpty() - && ModsOperationUtil.isDelete(data.currentTime(), modsInfos.get(0))) { - return false; - } - - isNeedFillTime = true; - final TSDataType dataType = tablet.getSchemas().get(0).getType(); - TypeServices.Pipe.PIPE_BATCH_DATA_TABLET_VALUE_WRITER_SERVICE - .call(Type.fromTsDataType(dataType)) - .write(data, tablet.getValues()[0], rowIndex); - PipeTabletUtils.unmarkNullValue(tablet, rowIndex, 0); - } - return isNeedFillTime; - } - - private void recordParsedPointCounts(final BatchData batchData) { - if (!trackPointCounts) { - return; - } - - if (batchData.getDataType() == TSDataType.VECTOR) { - final TsPrimitiveType[] values = batchData.getVector(); - for (int column = 0; column < values.length; column++) { - if (values[column] != null) { - addParsedPointCount(currentMeasurements.get(column).getMeasurementName(), 1); - } - } + /** + * Reports the point counts of the current page, once per page, so that a page that is split + * across several tablets is not counted several times. + */ + private void recordPagePointCounts() { + if (pageCountsReported || !trackPointCounts) { return; } - - addParsedPointCount(currentMeasurements.get(0).getMeasurementName(), 1); - } - - private void recordExpectedPointCounts(final BatchData batchData) { - if (!trackPointCounts || currentModifications.isEmpty()) { + pageCountsReported = true; + final long[] parsedCounts = reader.parsedCounts(); + if (parsedCounts == null) { return; } - - if (batchData.getDataType() == TSDataType.VECTOR) { - final TsPrimitiveType[] values = batchData.getVector(); - for (int column = 0; column < values.length; column++) { - if (values[column] != null - && !ModsOperationUtil.isDelete(batchData.currentTime(), modsInfos.get(column))) { - addExpectedPointCount(currentMeasurements.get(column).getMeasurementName()); - } + final long[] expectedCounts = reader.expectedCounts(); + for (int i = 0; i < currentMeasurements.size(); ++i) { + addParsedPointCount(currentMeasurements.get(i).getMeasurementName(), parsedCounts[i]); + if (!currentModifications.isEmpty()) { + addExpectedPointCount(currentMeasurements.get(i).getMeasurementName(), expectedCounts[i]); } - return; - } - - if (modsInfos.isEmpty() - || !ModsOperationUtil.isDelete(batchData.currentTime(), modsInfos.get(0))) { - addExpectedPointCount(currentMeasurements.get(0).getMeasurementName()); } } @@ -741,15 +663,18 @@ private void addParsedPointCount(final String measurement, final long pointCount .merge(measurement, pointCount, Long::sum); } - private void addExpectedPointCount(final String measurement) { + private void addExpectedPointCount(final String measurement, final long pointCount) { + if (!trackPointCounts || pointCount == 0) { + return; + } expectedPointCountsByDevice .computeIfAbsent(currentDevice, key -> new HashMap<>()) - .merge(measurement, 1L, Long::sum); + .merge(measurement, pointCount, Long::sum); } private void moveToNextChunkReader() throws IOException, IllegalStateException, IllegalPathException { - releaseChunkReader(); + releaseReader(); ChunkHeader chunkHeader; currentMeasurements.clear(); modsInfos.clear(); @@ -757,7 +682,7 @@ private void moveToNextChunkReader() if (lastMarker == MetaMarker.SEPARATOR) { if (!useNextPendingAlignedChunk(lastMarker)) { clearCachedAlignedChunkData(); - chunkReader = null; + reader = null; } return; } @@ -779,7 +704,6 @@ private void moveToNextChunkReader() { // Notice that the data in one chunk group is either aligned or non-aligned // There is no need to consider non-aligned chunks when there are value chunks - currentIsMultiPage = marker == MetaMarker.CHUNK_HEADER; final long currentChunkHeaderOffset = tsFileSequenceReader.position() - 1; chunkHeader = tsFileSequenceReader.readChunkHeader(marker); @@ -798,7 +722,7 @@ private void moveToNextChunkReader() // the marker so a retry does not interpret header bytes as a marker. tsFileSequenceReader.position(currentChunkHeaderOffset + 1); lastMarker = marker; - chunkReader = null; + reader = null; shouldRetryChunkHeaderAfterMemoryPressure = true; throw e; } @@ -808,15 +732,6 @@ private void moveToNextChunkReader() chunkHeader, tsFileSequenceReader.readChunk(-1, chunkHeader.getDataSize()), tsFileSequenceReader.getEncryptParam()); - final List pageEstimatedMemoryUsageInBytesList = - SinglePageWholeChunkReader - .calculatePageEstimatedMemoryUsageInBytesWithBatchDataList(chunk); - - chunkReader = - currentIsMultiPage - ? new MemoryControlledChunkReader( - new ChunkReader(chunk, filter), pageEstimatedMemoryUsageInBytesList) - : new SinglePageWholeChunkReader(chunk); currentIsAligned = false; final String measurementID = tabletStringInternPool.intern(chunkHeader.getMeasurementID()); @@ -832,6 +747,15 @@ private void moveToNextChunkReader() Collections.singletonList(measurementID), currentModifications, false)); + reader = + new SeriesChunkDirectTabletReader( + chunk, + chunkHeader.getDataType(), + startTime, + endTime, + !currentModifications.isEmpty(), + modsInfos.isEmpty() ? null : modsInfos.get(0), + trackPointCounts); return; } case MetaMarker.VALUE_CHUNK_HEADER: @@ -911,7 +835,7 @@ private void moveToNextChunkReader() lastMarker = marker; if (!useNextPendingAlignedChunk(marker)) { clearCachedAlignedChunkData(); - chunkReader = null; + reader = null; } } @@ -945,8 +869,6 @@ private boolean filterChunk( tsFileSequenceReader.readChunk(-1, chunkHeader.getDataSize()), tsFileSequenceReader.getEncryptParam()); timeChunkList.add(timeChunk); - final boolean isMultiPage = marker == MetaMarker.TIME_CHUNK_HEADER; - isMultiPageList.add(isMultiPage); return true; } } @@ -1016,37 +938,32 @@ private boolean useNextPendingAlignedChunk(final byte marker) throws IOException final Chunk timeChunk = timeChunkList.get(pendingAlignedChunkGroup.timeChunkIndex); timeChunk.getData().rewind(); for (final Chunk valueChunk : pendingAlignedChunkGroup.valueChunkList) { - valueChunk.getData().rewind(); + if (valueChunk != null) { + valueChunk.getData().rewind(); + } } - final boolean nextIsMultiPage = - isMultiPageList.get(pendingAlignedChunkGroup.timeChunkIndex); - if (!nextIsMultiPage) { - resizePageDataMemoryIfNeeded( - AlignedSinglePageWholeChunkReader.calculatePageEstimatedMemoryUsageInBytes( - timeChunk, pendingAlignedChunkGroup.valueChunkList)); + final List fieldDataTypes = + new ArrayList<>(pendingAlignedChunkGroup.measurements.size()); + for (final IMeasurementSchema schema : pendingAlignedChunkGroup.measurements) { + fieldDataTypes.add(schema.getType()); } - final List pageEstimatedMemoryUsageInBytesList = - nextIsMultiPage - ? pendingAlignedChunkGroup.pageMemoryUsageEstimator - .getPageEstimatedMemoryUsageInBytesList() - : Collections.emptyList(); - final long maxPageEstimatedMemoryUsageInBytes = - pageEstimatedMemoryUsageInBytesList.isEmpty() - ? 0 - : pageEstimatedMemoryUsageInBytesList.get(0); - resizePageDataMemoryIfNeeded(maxPageEstimatedMemoryUsageInBytes); - final IChunkReader nextChunkReader = - createAlignedChunkReader( + + final TabletPageReader nextReader = + createAlignedReader( timeChunk, pendingAlignedChunkGroup.valueChunkList, - nextIsMultiPage, - pageEstimatedMemoryUsageInBytesList); - - // Publish the state transition only after all memory reservations and reader construction - // succeed. Otherwise a retry would lose the already-read aligned chunk group. + fieldDataTypes, + pendingAlignedChunkGroup.modsInfos, + startTime, + endTime, + !currentModifications.isEmpty(), + trackPointCounts); + + // Publish the state transition only after the reader construction succeeds. Otherwise a + // retry would lose the already-read aligned chunk group. pendingAlignedChunkGroups.remove(0); - for (Chunk valueChunk : pendingAlignedChunkGroup.valueChunkList) { + for (final Chunk valueChunk : pendingAlignedChunkGroup.valueChunkList) { if (valueChunk != null) { valueChunk.close(); } @@ -1057,8 +974,7 @@ private boolean useNextPendingAlignedChunk(final byte marker) throws IOException currentMeasurements.addAll(pendingAlignedChunkGroup.measurements); modsInfos.clear(); modsInfos.addAll(pendingAlignedChunkGroup.modsInfos); - currentIsMultiPage = nextIsMultiPage; - chunkReader = nextChunkReader; + reader = nextReader; currentIsAligned = true; if (marker != Byte.MIN_VALUE) { lastMarker = marker; @@ -1072,31 +988,43 @@ private boolean useNextPendingAlignedChunk(final byte marker) throws IOException return false; } - IChunkReader createAlignedChunkReader( - Chunk timeChunk, - List valueChunks, - boolean multiPage, - List pageEstimatedMemoryUsageInBytesList) - throws IOException { - // Pending chunks must survive a failed constructor so the same group can be retried. + /** + * Builds the reader of an aligned chunk group from retained views of its chunks, so that the + * reader owns its buffers and a failure leaves the pending group intact for a retry. + */ + TabletPageReader createAlignedReader( + final Chunk timeChunk, + final List valueChunks, + final List fieldDataTypes, + final List modsInfos, + final long startTime, + final long endTime, + final boolean hasMods, + final boolean trackPointCounts) { Chunk retainedTimeChunk = null; - List retainedValueChunks = new ArrayList<>(valueChunks.size()); + final List retainedValueChunks = new ArrayList<>(valueChunks.size()); try { retainedTimeChunk = retainChunk(timeChunk); - for (Chunk valueChunk : valueChunks) { + for (final Chunk valueChunk : valueChunks) { retainedValueChunks.add(valueChunk == null ? null : retainChunk(valueChunk)); } - return multiPage - ? new MemoryControlledChunkReader( - new AlignedChunkReader(retainedTimeChunk, retainedValueChunks, filter), - pageEstimatedMemoryUsageInBytesList) - : new AlignedSinglePageWholeChunkReader(retainedTimeChunk, retainedValueChunks, null); - } catch (IOException | RuntimeException | Error failure) { - // Chunk.close() is idempotent, including when constructor cleanup has already run. + return new ChunkDirectTabletReader( + retainedTimeChunk, + retainedValueChunks, + fieldDataTypes, + 0, + startTime, + endTime, + hasMods, + modsInfos, + null, + ChunkDirectTabletReader.RowRetention.DROP_ROWS_WITHOUT_KEPT_CELL, + trackPointCounts); + } catch (final RuntimeException | Error failure) { if (retainedTimeChunk != null) { retainedTimeChunk.close(); } - for (Chunk valueChunk : retainedValueChunks) { + for (final Chunk valueChunk : retainedValueChunks) { if (valueChunk != null) { valueChunk.close(); } @@ -1137,9 +1065,13 @@ && chunkSizeAfterCaching > getChunkMemoryLimitInBytes()) { return true; } + final long pageBytesBeforeCaching = + Objects.isNull(pendingAlignedChunkGroup) + ? ChunkDirectTabletReader.estimatePageBytes( + timeChunkList.get(valueChunk.timeChunkIndex)) + : pendingAlignedChunkGroup.pageBytes; final long pageMemorySizeAfterCaching = - calculateMaxAlignedPageMemorySizeWithBatchData( - valueChunk.timeChunkIndex, pendingAlignedChunkGroup, valueChunk); + pageBytesBeforeCaching + ChunkDirectTabletReader.estimatePageBytes(valueChunk.chunk); return pageMemorySizeAfterCaching > getPageDataMemoryLimitInBytes() && (!isFirstValueChunkInGroup || !pendingAlignedChunkGroups.isEmpty()); } @@ -1166,8 +1098,9 @@ private void cacheAlignedValueChunk(final CachedAlignedValueChunk valueChunk) th resizeChunkMemoryBlockIfFirstValueChunkExceedsLimit(pendingAlignedChunkGroup, valueChunk); resizePageDataMemoryBlockIfFirstValueChunkExceedsLimit(pendingAlignedChunkGroup, valueChunk); - pendingAlignedChunkGroup.pageMemoryUsageEstimator.addValueChunk(valueChunk.chunk); pendingAlignedChunkGroup.valueChunkList.add(valueChunk.chunk); + pendingAlignedChunkGroup.pageBytes += + ChunkDirectTabletReader.estimatePageBytes(valueChunk.chunk); pendingAlignedChunkGroup.chunkSize += valueChunk.valueChunkSize; pendingAlignedChunkSize += valueChunk.valueChunkSize; @@ -1192,11 +1125,10 @@ private PendingAlignedChunkGroup getOrCreatePendingAlignedChunkGroup(final int t return pendingAlignedChunkGroup; } + final Chunk timeChunk = timeChunkList.get(timeChunkIndex); final PendingAlignedChunkGroup newPendingAlignedChunkGroup = new PendingAlignedChunkGroup( - timeChunkIndex, - PipeMemoryWeightUtil.calculateChunkRamBytesUsed(timeChunkList.get(timeChunkIndex)), - timeChunkList.get(timeChunkIndex)); + timeChunkIndex, PipeMemoryWeightUtil.calculateChunkRamBytesUsed(timeChunk), timeChunk); pendingAlignedChunkSize += newPendingAlignedChunkGroup.chunkSize; for (int i = 0; i < pendingAlignedChunkGroups.size(); ++i) { @@ -1246,7 +1178,6 @@ private void clearCachedAlignedChunkData() { pendingAlignedChunkSize = 0; cachedAlignedValueChunk = null; timeChunkList.clear(); - isMultiPageList.clear(); measurementIndexMap.clear(); } @@ -1272,26 +1203,13 @@ private void resizePageDataMemoryBlockIfFirstValueChunkExceedsLimit( } final long pageMemorySize = - calculateMaxAlignedPageMemorySizeWithBatchData( - pendingAlignedChunkGroup.timeChunkIndex, pendingAlignedChunkGroup, valueChunk); + pendingAlignedChunkGroup.pageBytes + + ChunkDirectTabletReader.estimatePageBytes(valueChunk.chunk); if (pageMemorySize > getPageDataMemoryLimitInBytes()) { allocatedMemoryBlockForBatchData.forceResize(pageMemorySize); } } - private long calculateMaxAlignedPageMemorySizeWithBatchData( - final int timeChunkIndex, - final PendingAlignedChunkGroup pendingAlignedChunkGroup, - final CachedAlignedValueChunk valueChunk) - throws IOException { - final Chunk timeChunk = timeChunkList.get(timeChunkIndex); - final AlignedSinglePageWholeChunkReader.PageMemoryUsageEstimator estimator = - Objects.isNull(pendingAlignedChunkGroup) - ? new AlignedSinglePageWholeChunkReader.PageMemoryUsageEstimator(timeChunk) - : pendingAlignedChunkGroup.pageMemoryUsageEstimator; - return estimator.calculateMaxPageEstimatedMemoryUsageInBytesWithValueChunk(valueChunk.chunk); - } - private boolean isSinglePageValueChunk(final ChunkHeader chunkHeader) { return (chunkHeader.getChunkType() & 0x3F) == MetaMarker.ONLY_ONE_PAGE_CHUNK_HEADER; } @@ -1305,13 +1223,12 @@ private byte toValueChunkMarker(final ChunkHeader chunkHeader) { @Override public void close() { try { - releaseChunkReader(); + releaseReader(); } catch (IOException e) { LOGGER.warn(DataNodeQueryMessages.LOG_FAILED_TO_RELEASE_QUERY_CHUNK_RESOURCES_91573FE5, e); } clearCachedAlignedChunkData(); super.close(); - pendingPageDataAfterMemoryPressure = null; pendingTabletAfterMemoryPressure = null; cachedAlignedValueChunk = null; pendingAlignedChunkGroups.clear(); @@ -1330,9 +1247,9 @@ public void close() { } } - private void releaseChunkReader() throws IOException { - IChunkReader current = chunkReader; - chunkReader = null; + private void releaseReader() throws IOException { + final TabletPageReader current = reader; + reader = null; if (current != null) { current.close(); } @@ -1378,20 +1295,23 @@ private Statistics findNonAlignedChunkStatistics( private static class PendingAlignedChunkGroup { private final int timeChunkIndex; - private final AlignedSinglePageWholeChunkReader.PageMemoryUsageEstimator - pageMemoryUsageEstimator; private final List valueChunkList = new ArrayList<>(); private final List measurements = new ArrayList<>(); private final List modsInfos = new ArrayList<>(); private long chunkSize; + /** + * The sum of the largest page of the time chunk and of every cached value chunk, kept + * incrementally so that testing a candidate value chunk does not walk the headers of the + * already cached ones again. + */ + private long pageBytes; + private PendingAlignedChunkGroup( - final int timeChunkIndex, final long timeChunkSize, final Chunk timeChunk) - throws IOException { + final int timeChunkIndex, final long timeChunkSize, final Chunk timeChunk) { this.timeChunkIndex = timeChunkIndex; this.chunkSize = timeChunkSize; - this.pageMemoryUsageEstimator = - new AlignedSinglePageWholeChunkReader.PageMemoryUsageEstimator(timeChunk); + this.pageBytes = ChunkDirectTabletReader.estimatePageBytes(timeChunk); } } diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/table/TsFileInsertionEventTableParserTabletIterator.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/table/TsFileInsertionEventTableParserTabletIterator.java index ce65379260794..b50a863af24a0 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/table/TsFileInsertionEventTableParserTabletIterator.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/table/TsFileInsertionEventTableParserTabletIterator.java @@ -28,6 +28,7 @@ import org.apache.iotdb.db.pipe.event.common.tablet.PipeTabletUtils.TabletStringInternPool; import org.apache.iotdb.db.pipe.event.common.tsfile.parser.TsFileInsertionEventParserMemoryBlock; import org.apache.iotdb.db.pipe.event.common.tsfile.parser.util.ModsOperationUtil; +import org.apache.iotdb.db.pipe.event.common.tsfile.parser.util.tablet.ChunkDirectTabletReader; import org.apache.iotdb.db.pipe.resource.memory.PipeMemoryWeightUtil; import org.apache.iotdb.db.storageengine.dataregion.modification.ModEntry; import org.apache.iotdb.db.utils.datastructure.PatternTreeMapFactory; @@ -69,7 +70,7 @@ *

The iterator only drives the traversal: it walks the table schemas, the devices and the chunk * groups, reserves the memory of the chunks and of the decoded pages, and creates a tablet whenever * the table, the device or the chunk group changes. Reading the pages and filling the tablets is - * delegated to {@link TableChunkDirectTabletReader}. + * delegated to {@link ChunkDirectTabletReader}. */ public class TsFileInsertionEventTableParserTabletIterator implements Iterator, AutoCloseable { @@ -98,7 +99,7 @@ public class TsFileInsertionEventTableParserTabletIterator private final PatternTreeMap modifications; // Reads the pages of the current chunk group and decodes them straight into the tablet arrays - private TableChunkDirectTabletReader directReader; + private ChunkDirectTabletReader directReader; // The time that the last tablet took to be produced, reported as the cost of one tablet private long lastTabletBuildTimeNanos = -1; @@ -437,8 +438,7 @@ private Tablet buildNextTabletInternal() { pendingTablet = tablet; // The device id columns are identical for all the rows of the tablet, so they are filled // once instead of row by row - TableChunkDirectTabletReader.fillDeviceIdColumns( - deviceID, tablet, dataTypeList, deviceIdSize); + ChunkDirectTabletReader.fillDeviceIdColumns(deviceID, tablet, dataTypeList, deviceIdSize); } final int capacity = tablet.getMaxRowNumber() - tablet.getRowSize(); @@ -576,7 +576,7 @@ private void initChunkReader(final AbstractAlignedChunkMetadata alignedChunkMeta final long maxReaderChunkSize = Math.max(0L, PipeConfig.getInstance().getPipeMaxReaderChunkSize()); // The decoded time page is held next to the value pages, so it is part of the page budget - long estimatedPageBytes = TableChunkDirectTabletReader.estimatePageBytes(timeChunk); + long estimatedPageBytes = ChunkDirectTabletReader.estimatePageBytes(timeChunk); try { for (; offset < fieldSchemaList.size(); ++offset) { final IMeasurementSchema schema = fieldSchemaList.get(offset); @@ -607,7 +607,7 @@ private void initChunkReader(final AbstractAlignedChunkMetadata alignedChunkMeta chunk = reader.readMemChunk((ChunkMetadata) metadata); } final long chunkBytes = PipeMemoryWeightUtil.calculateChunkRamBytesUsed(chunk); - final long pageBytes = TableChunkDirectTabletReader.estimatePageBytes(chunk); + final long pageBytes = ChunkDirectTabletReader.estimatePageBytes(chunk); if (hasSelectedNonNullChunk && isOverReaderChunkSize( size + chunkBytes, estimatedPageBytes + pageBytes, maxReaderChunkSize)) { @@ -703,7 +703,7 @@ && reserveChunkMemory(size + chunkBytes, true)) { // The reader prunes the pages that do not overlap the time range before decompressing them, // and decodes the pages that are kept straight into the tablet arrays this.directReader = - new TableChunkDirectTabletReader( + new ChunkDirectTabletReader( retainedTimeChunk, valueChunkList, new ArrayList<>(dataTypeList.subList(deviceIdSize, dataTypeList.size())), @@ -712,7 +712,9 @@ && reserveChunkMemory(size + chunkBytes, true)) { endTime, hasMods, modsInfoList, - timeModsInfo); + timeModsInfo, + ChunkDirectTabletReader.RowRetention.KEEP_ALL_NULL_ROWS, + false); } catch (final RuntimeException | Error failure) { // The subset is not owned by a reader yet: a column type that a tablet cannot hold, or a // failure while the modifications are prepared, must not abandon the chunk buffers that the @@ -795,7 +797,7 @@ private static void closeChunks(final List chunks) { } private void closeDirectReader() { - final TableChunkDirectTabletReader previous = directReader; + final ChunkDirectTabletReader previous = directReader; directReader = null; if (previous != null) { previous.close(); diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/util/ModsOperationUtil.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/util/ModsOperationUtil.java index 0ed8aded23a17..eebc8d2a5312a 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/util/ModsOperationUtil.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/util/ModsOperationUtil.java @@ -261,7 +261,7 @@ public static boolean isDelete(long time, ModsInfo modsInfo) { } } else { // Current index is beyond array bounds, all mods have been processed - clearModsAndReset(modsInfo); + markModsProcessed(modsInfo); return false; } } @@ -279,8 +279,8 @@ private static boolean searchAndCheckMod( List mods, long time, int startIndex, ModsInfo modsInfo) { int searchIndex = binarySearchMods(mods, time, startIndex); if (searchIndex >= mods.size()) { - // All mods checked, clear mods list and reset index to 0 - clearModsAndReset(modsInfo); + // All mods checked + markModsProcessed(modsInfo); return false; } @@ -296,11 +296,6 @@ private static boolean searchAndCheckMod( return true; } - /** - * Clear mods list and reset index to 0 - * - * @param modsInfo mods information to update - */ /** * Sorts the modifications that were filtered for one cell by time and merges the ranges that * overlap or touch. {@link ModificationUtils#sortAndMerge} keeps the ranges apart when their @@ -328,9 +323,17 @@ private static List sortAndMergeByTime(final List modificati return merged; } - private static void clearModsAndReset(ModsInfo modsInfo) { - modsInfo.setMods(Collections.emptyList()); - modsInfo.setCurrentIndex(0); + /** + * Marks every modification as processed by moving the cursor past the end. + * + *

The list is deliberately kept: the same page is walked several times (the row retention + * pass, the point counts and the decode pass), and a later pass must still see the modifications. + * The cursor at the end keeps the lookups that follow O(1) without dropping the data. + * + * @param modsInfo mods information to update + */ + private static void markModsProcessed(final ModsInfo modsInfo) { + modsInfo.setCurrentIndex(modsInfo.getMods().size()); } /** diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/util/tablet/AbstractDirectTabletReader.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/util/tablet/AbstractDirectTabletReader.java new file mode 100644 index 0000000000000..87145893797ca --- /dev/null +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/util/tablet/AbstractDirectTabletReader.java @@ -0,0 +1,327 @@ +/* + * 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.iotdb.db.pipe.event.common.tsfile.parser.util.tablet; + +import org.apache.tsfile.encoding.decoder.Decoder; +import org.apache.tsfile.write.record.Tablet; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.util.Arrays; + +/** + * The page loop and the row handling shared by the direct tablet readers. + * + *

The two layouts differ in how the body of a page is decoded and in what makes a row belong to + * the tablet, but the surrounding loop is the same: decode the time page, clip it to the parsed + * range, compute the rows that are dropped, then copy the kept rows into the tablet one segment at + * a time. Only the parts that really differ are left to a subclass: + * + *

    + *
  • how the page is read and split ({@link #loadNextPage()}, {@link #peekNextPageBytes()}); + *
  • what makes a row survive ({@link #rowSurvives(int)}, {@link #mayDropRows()}); + *
  • how a segment of kept rows is decoded ({@link #fillSegment(Tablet, int, int)}) and how the + * values of a dropped segment are consumed ({@link #skipSegment(int)}); + *
  • how the delete interval and modification cursors are rewound ({@link #resetScanCursors()}). + *
+ */ +abstract class AbstractDirectTabletReader implements TabletPageReader { + + protected final long startTime; + protected final long endTime; + + /** The decoded times of the current page. It starts empty and is grown by the first page. */ + protected long[] times = new long[0]; + + protected int pageRowCount; + protected int cursor; + protected int endRow; + protected long currentPageRamBytes; + protected int pageIndex; + + /** The rows of the current page that are dropped as a whole, or null when every row is kept. */ + protected boolean[] rowDropped; + + private final boolean trackPointCounts; + private long[] parsedCounts; + private long[] expectedCounts; + + protected AbstractDirectTabletReader( + final long startTime, final long endTime, final boolean trackPointCounts) { + this.startTime = startTime; + this.endTime = endTime; + this.trackPointCounts = trackPointCounts; + } + + @Override + public final boolean hasCurrentRow() { + return cursor < endRow; + } + + @Override + public final int remainingRows() { + return endRow - cursor; + } + + @Override + public final int pageRowCount() { + return pageRowCount; + } + + @Override + public final long currentPageRamBytes() { + return currentPageRamBytes; + } + + @Override + public final long[] parsedCounts() { + return parsedCounts; + } + + @Override + public final long[] expectedCounts() { + return expectedCounts; + } + + /** + * Decodes all the times of the page into the reusable time array. + * + * @param expectedCount the row count the page declares, or 0 when its header has no statistics + */ + protected final void decodeTimes( + final ByteBuffer timePageData, final Decoder timeDecoder, final int expectedCount) + throws IOException { + if (expectedCount > times.length) { + times = new long[expectedCount]; + } + int count = 0; + while (timeDecoder.hasNext(timePageData)) { + if (count == times.length) { + times = Arrays.copyOf(times, Math.max(1024, times.length << 1)); + } + times[count++] = timeDecoder.readLong(timePageData); + } + pageRowCount = count; + } + + /** + * Intersects the current page with {@code [startTime, endTime]}. The times of a page are sorted, + * so the rows in the range are contiguous. + * + * @return whether the page contains at least one row in the range + */ + protected final boolean clipPageToRange() { + final int from = firstRowAtOrAfter(startTime); + final int to = firstRowAfter(endTime); + if (from >= to) { + return false; + } + cursor = from; + endRow = to; + return true; + } + + /** + * Finishes the load of a page: applies the row retention and computes the point counts of the + * page. The delete interval and modification cursors are rewound before and after the pass, + * because the retention check and the decode pass both start from the first row of the page. + */ + protected final void finishPageLoad() { + resetScanCursors(); + rowDropped = mayDropRows() ? computeRowDropped() : null; + // The retention pass advanced the cursors to the end of the page, and the counts below must + // see the modifications of the page from its first row again. + resetScanCursors(); + if (trackPointCounts) { + countPagePoints(); + } else { + parsedCounts = null; + expectedCounts = null; + } + resetScanCursors(); + } + + @Override + public final void fillTablet(final Tablet tablet, final int maxRows) { + if (!hasRowDrops()) { + final int count = Math.min(endRow - cursor, maxRows); + if (count <= 0) { + return; + } + fillSegment(tablet, cursor, count); + cursor += count; + return; + } + + // The dropped rows break the page into segments of consecutive rows that are kept. Each segment + // is still filled with one sequential decode per column, and the decoders are advanced over the + // dropped rows, which are not written to the tablet at all. + int remainingRows = maxRows; + while (cursor < endRow && remainingRows > 0) { + final int segmentStart = nextKeptRow(cursor); + if (segmentStart > cursor) { + skipSegment(segmentStart - cursor); + cursor = segmentStart; + } + if (cursor >= endRow) { + break; + } + final int segmentEnd = nextDroppedRow(cursor, Math.min(endRow, cursor + remainingRows)); + fillSegment(tablet, cursor, segmentEnd - cursor); + remainingRows -= segmentEnd - cursor; + cursor = segmentEnd; + } + } + + /** Whether some row of the current page must not be written to the tablet. */ + protected abstract boolean hasRowDrops(); + + /** Whether the model can drop rows of this page at all, so that the bulk path can be kept. */ + protected abstract boolean mayDropRows(); + + /** Whether the whole row does not belong to the tablet. */ + protected abstract boolean isRowDropped(int row); + + /** Whether the row has at least one cell that survives the modifications and delete intervals. */ + protected abstract boolean rowSurvives(int row); + + /** Decodes the values of the kept rows {@code [from, from + count)} into the tablet. */ + protected abstract void fillSegment(Tablet tablet, int from, int count); + + /** + * Consumes the values of {@code count} dropped rows, starting at the current decoder position, + * without writing them. + */ + protected abstract void skipSegment(int count); + + /** Rewinds the delete interval and modification cursors to the first interval. */ + protected abstract void resetScanCursors(); + + /** Number of value columns of the current chunk, used by the point counts. */ + protected abstract int fieldCount(); + + /** Whether the cell of the current page is present (not null). */ + protected abstract boolean isCellPresent(int field, int row); + + /** Whether the cell is hidden by a modification or by a delete interval. */ + protected abstract boolean isCellDeleted(int field, long time); + + /** Releases the decoded value pages of the current page. */ + protected abstract void clearPageValues(); + + protected final void clearPage() { + pageRowCount = 0; + cursor = 0; + endRow = 0; + currentPageRamBytes = 0; + rowDropped = null; + parsedCounts = null; + expectedCounts = null; + clearPageValues(); + } + + /** + * Counts, per column, the values that the point metrics report for the current page: the present + * values, and those that neither a modification nor a delete interval hides. + */ + private void countPagePoints() { + final int fields = fieldCount(); + parsedCounts = new long[fields]; + expectedCounts = new long[fields]; + for (int field = 0; field < fields; ++field) { + for (int row = cursor; row < endRow; ++row) { + if (!isCellPresent(field, row)) { + continue; + } + ++parsedCounts[field]; + if (!isCellDeleted(field, times[row])) { + ++expectedCounts[field]; + } + } + } + } + + /** + * The rows of the page without a surviving cell, or null when every row of the page is kept. The + * rows are visited in ascending time order so that the forward cursors of the delete intervals + * stay valid. + */ + private boolean[] computeRowDropped() { + boolean[] dropped = null; + for (int row = 0; row < pageRowCount; ++row) { + if (!rowSurvives(row)) { + if (dropped == null) { + dropped = new boolean[pageRowCount]; + } + dropped[row] = true; + } + } + return dropped; + } + + /** + * The first row in the current page that is not dropped, starting from the given row, or the end + * of the page if every one of them is dropped. + */ + private int nextKeptRow(final int from) { + int row = from; + while (row < endRow && isRowDropped(row)) { + ++row; + } + return row; + } + + /** The first dropped row in [from, limit), or limit if every row of the range is kept. */ + private int nextDroppedRow(final int from, final int limit) { + int row = from + 1; + while (row < limit && !isRowDropped(row)) { + ++row; + } + return row; + } + + private int firstRowAtOrAfter(final long time) { + int low = 0; + int high = pageRowCount; + while (low < high) { + final int middle = (low + high) >>> 1; + if (times[middle] < time) { + low = middle + 1; + } else { + high = middle; + } + } + return low; + } + + private int firstRowAfter(final long time) { + int low = 0; + int high = pageRowCount; + while (low < high) { + final int middle = (low + high) >>> 1; + if (times[middle] <= time) { + low = middle + 1; + } else { + high = middle; + } + } + return low; + } +} diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/table/TableValuePage.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/util/tablet/AlignedValuePage.java similarity index 73% rename from iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/table/TableValuePage.java rename to iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/util/tablet/AlignedValuePage.java index e298ef66cbe77..99f26972a10d4 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/table/TableValuePage.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/util/tablet/AlignedValuePage.java @@ -17,18 +17,19 @@ * under the License. */ -package org.apache.iotdb.db.pipe.event.common.tsfile.parser.table; +package org.apache.iotdb.db.pipe.event.common.tsfile.parser.util.tablet; import org.apache.tsfile.encoding.decoder.Decoder; import org.apache.tsfile.utils.ReadWriteIOUtils; import java.nio.ByteBuffer; +import java.util.Arrays; /** * The decoded state of the value page of one column: the page buffer, its decoder, the null bitmap * that the page writer stores in front of the values, and the position of the next value to read. */ -final class TableValuePage { +final class AlignedValuePage { // The fields are read and advanced by the column kinds of the same package, which decode the // values of the page straight into the arrays of a tablet @@ -62,6 +63,35 @@ void setEmpty() { position = 0; } + /** + * Sets the state of a value page of a non-aligned chunk, whose body is the raw encoded values + * only: it has neither the value count nor the null bitmap of an aligned value page, because a + * non-aligned series stores no null at all. + */ + void initSeries(final ByteBuffer pageData, final Decoder decoder, final int valueCount) { + if (pageData == null || valueCount <= 0) { + setEmpty(); + return; + } + // The page has no bitmap of its own, but the skip loops of the column kinds look a value up + // through the bitmap: a bitmap with every bit present keeps them correct without a branch. + final int bitmapBytes = (valueCount + 7) >>> 3; + if (nullBitmap.length < bitmapBytes) { + nullBitmap = new byte[bitmapBytes]; + } + Arrays.fill(nullBitmap, 0, bitmapBytes, (byte) 0xFF); + if ((valueCount & 7) != 0) { + nullBitmap[bitmapBytes - 1] = (byte) ((0xFF << (8 - (valueCount & 7))) & 0xFF); + } + this.buffer = pageData; + this.decoder = decoder; + this.valueCount = valueCount; + this.valueBytes = pageData.remaining(); + this.position = 0; + this.empty = false; + this.hasNulls = false; + } + /** * Splits a decompressed value page into the null bitmap and the encoded values, which is the * layout the page writer uses. diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/table/TableChunkDirectTabletReader.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/util/tablet/ChunkDirectTabletReader.java similarity index 57% rename from iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/table/TableChunkDirectTabletReader.java rename to iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/util/tablet/ChunkDirectTabletReader.java index 2aec83cd10d1b..09cf8bb26b37e 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/table/TableChunkDirectTabletReader.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/util/tablet/ChunkDirectTabletReader.java @@ -17,7 +17,7 @@ * under the License. */ -package org.apache.iotdb.db.pipe.event.common.tsfile.parser.table; +package org.apache.iotdb.db.pipe.event.common.tsfile.parser.util.tablet; import org.apache.iotdb.db.pipe.event.common.tablet.PipeTabletUtils; import org.apache.iotdb.db.pipe.event.common.tsfile.parser.util.ModsOperationUtil; @@ -25,15 +25,12 @@ import org.apache.tsfile.encoding.decoder.Decoder; import org.apache.tsfile.encrypt.EncryptParameter; -import org.apache.tsfile.encrypt.IDecryptor; import org.apache.tsfile.enums.TSDataType; -import org.apache.tsfile.file.MetaMarker; import org.apache.tsfile.file.header.ChunkHeader; import org.apache.tsfile.file.header.PageHeader; import org.apache.tsfile.file.metadata.IDeviceID; import org.apache.tsfile.file.metadata.statistics.Statistics; import org.apache.tsfile.read.common.Chunk; -import org.apache.tsfile.read.reader.chunk.ChunkReader; import org.apache.tsfile.utils.Binary; import org.apache.tsfile.utils.BitMap; import org.apache.tsfile.write.record.Tablet; @@ -44,55 +41,58 @@ import java.util.List; /** - * Reads the pages of an aligned chunk group of a table-model TsFile and decodes them straight into - * the typed arrays of a {@link Tablet}. + * Reads the pages of an aligned chunk group of a TsFile and decodes them straight into the typed + * arrays of a {@link Tablet}. + * + *

It serves both models: the table model reads a chunk group whose tag columns are filled once + * per tablet, while the tree model reads one of the aligned chunk groups of a device, where the + * measurement columns are the only value columns and a row exists only if one of them survives. * *

Unlike a plain chunk reader, no {@code TsBlock} is materialized in between: the page body is * decompressed into one buffer, the null bitmap of the page is read from its head, and every value * is decoded by a type-specialized loop that stores it at its final position in the tablet array. A * value is therefore written once instead of twice, and the page sized column arrays of a {@code * TsBlock} are not allocated at all. - * - *

The reader also owns the time range pruning of the pages and the merging of the modifications - * into the null marks of the tablet, so that the iterator that drives it only has to decide which - * tablet to create. */ -final class TableChunkDirectTabletReader implements AutoCloseable { +public final class ChunkDirectTabletReader extends AbstractDirectTabletReader { + + /** How the reader decides whether a row of the page belongs to the tablet. */ + public enum RowRetention { + /** + * Keep a row whose cells are all null, as a table query does: the row of a table is defined by + * its timestamp and its tags. + */ + KEEP_ALL_NULL_ROWS, + /** + * Drop a row without a single surviving cell, as the tree model does: a row exists only if at + * least one measurement has a value that is neither null nor deleted. + */ + DROP_ROWS_WITHOUT_KEPT_CELL + } + + private final RowRetention rowRetention; private final Chunk timeChunk; private final List valueChunks; private final List fieldDataTypes; - private final TableColumnKind[] columnKinds; + private final ColumnKind[] columnKinds; private final int fieldCount; private final int deviceIdSize; - private final long startTime; - private final long endTime; - private final ChunkHeader timeChunkHeader; private final ChunkHeader[] valueChunkHeaders; private final EncryptParameter encryptParam; - private final boolean singlePageChunk; - private final TableDeleteIntervals timeTableDeleteIntervals; - private final TableDeleteIntervals[] valueTableDeleteIntervals; + private final DeleteIntervals timeDeleteIntervals; + private final DeleteIntervals[] valueDeleteIntervals; - private final TableValuePage[] pageStates; + private final AlignedValuePage[] pageStates; private final PageHeader[] valuePageHeaders; - /** The decoded times of the current page. It starts empty and is grown by the first page. */ - private long[] times = new long[0]; - - private int pageRowCount; - private int cursor; - private int endRow; - private long currentPageRamBytes; - private int pageIndex; - private final boolean hasMods; private final List modsInfoList; private final ModsOperationUtil.ModsInfo timeModsInfo; - TableChunkDirectTabletReader( + public ChunkDirectTabletReader( final Chunk timeChunk, final List valueChunks, final List fieldDataTypes, @@ -101,112 +101,86 @@ final class TableChunkDirectTabletReader implements AutoCloseable { final long endTime, final boolean hasMods, final List modsInfoList, - final ModsOperationUtil.ModsInfo timeModsInfo) { + final ModsOperationUtil.ModsInfo timeModsInfo, + final RowRetention rowRetention, + final boolean trackPointCounts) { + super(startTime, endTime, trackPointCounts); this.timeChunk = timeChunk; this.valueChunks = valueChunks; this.fieldDataTypes = fieldDataTypes; this.fieldCount = fieldDataTypes.size(); this.deviceIdSize = deviceIdSize; - this.startTime = startTime; - this.endTime = endTime; this.hasMods = hasMods; this.modsInfoList = modsInfoList; this.timeModsInfo = timeModsInfo; + this.rowRetention = rowRetention; this.timeChunkHeader = timeChunk.getHeader(); - this.singlePageChunk = - (timeChunkHeader.getChunkType() & 0x3F) == MetaMarker.ONLY_ONE_PAGE_CHUNK_HEADER; this.encryptParam = timeChunk.getEncryptParam(); - this.timeTableDeleteIntervals = new TableDeleteIntervals(timeChunk.getDeleteIntervalList()); + this.timeDeleteIntervals = new DeleteIntervals(timeChunk.getDeleteIntervalList()); this.valueChunkHeaders = new ChunkHeader[fieldCount]; - this.valueTableDeleteIntervals = new TableDeleteIntervals[fieldCount]; - this.pageStates = new TableValuePage[fieldCount]; + this.valueDeleteIntervals = new DeleteIntervals[fieldCount]; + this.pageStates = new AlignedValuePage[fieldCount]; this.valuePageHeaders = new PageHeader[fieldCount]; - this.columnKinds = new TableColumnKind[fieldCount]; + this.columnKinds = new ColumnKind[fieldCount]; for (int i = 0; i < fieldCount; ++i) { final Chunk valueChunk = valueChunks.get(i); valueChunkHeaders[i] = valueChunk == null ? null : valueChunk.getHeader(); - valueTableDeleteIntervals[i] = - new TableDeleteIntervals(valueChunk == null ? null : valueChunk.getDeleteIntervalList()); - pageStates[i] = new TableValuePage(); - columnKinds[i] = TableColumnKind.of(fieldDataTypes.get(i)); + valueDeleteIntervals[i] = + new DeleteIntervals(valueChunk == null ? null : valueChunk.getDeleteIntervalList()); + pageStates[i] = new AlignedValuePage(); + columnKinds[i] = ColumnKind.of(fieldDataTypes.get(i)); } } - /** Whether the current page still has a row that is not parsed. */ - boolean hasCurrentRow() { - return cursor < endRow; - } - - /** The number of rows of the current page that are not parsed. */ - int remainingRows() { - return endRow - cursor; - } - - /** The memory the decoded pages of the current page group occupy. */ - long currentPageRamBytes() { - return currentPageRamBytes; - } - - /** - * The uncompressed size of the variable length values of the current page, which is used to - * estimate the memory cost of the tablet that will be built from it. - */ - long binaryValueBytes() { + @Override + public long binaryValueBytes() { long bytes = 0; for (int i = 0; i < fieldCount; ++i) { - if (columnKinds[i] == TableColumnKind.BINARY) { + if (columnKinds[i] == ColumnKind.BINARY) { bytes += pageStates[i].valueBytes; } } return bytes; } - /** The number of rows the current page holds, whatever the time range of the parser is. */ - int pageRowCount() { - return pageRowCount; + @Override + public boolean hasNextPage() { + return timeChunk.getData().hasRemaining(); } - /** - * Estimates the memory the pages of a chunk occupy once decompressed, by peeking the header of - * its first page. The page is not decompressed and the data of the chunk is not consumed, so the - * estimate costs one header parse per column. - */ - static long estimatePageBytes(final Chunk chunk) { - final ByteBuffer buffer = chunk.getData().duplicate(); - buffer.rewind(); - if (!buffer.hasRemaining()) { - return 0; - } - try { - final ChunkHeader header = chunk.getHeader(); - final boolean singlePageChunk = - (header.getChunkType() & 0x3F) == MetaMarker.ONLY_ONE_PAGE_CHUNK_HEADER; - // The pages of the column are decoded one at a time, so its peak is the largest page and not - // the first one: the pages that follow are skipped by their headers without decompression - long maxPageBytes = 0; - while (buffer.hasRemaining()) { - final PageHeader pageHeader = - singlePageChunk - ? PageHeader.deserializeFrom(buffer, chunk.getChunkStatistic()) - : PageHeader.deserializeFrom(buffer, header.getDataType()); - maxPageBytes = Math.max(maxPageBytes, pageHeader.getUncompressedSize()); - final int compressedSize = pageHeader.getCompressedSize(); - if (singlePageChunk || compressedSize < 0 || compressedSize > buffer.remaining()) { - break; - } - // An all-null page is stored as a header without a body (compressedSize == 0), so the next - // header follows immediately and the walk must not stop at it: the largest page may be - // stored after an empty one - buffer.position(buffer.position() + compressedSize); + @Override + public long peekNextPageBytes() { + final ByteBuffer timeBuffer = timeChunk.getData().duplicate(); + if (!timeBuffer.hasRemaining()) { + return 0L; + } + long bytes = + PageIo.readPageHeader(timeBuffer, timeChunkHeader, timeChunk.getChunkStatistic()) + .getUncompressedSize(); + for (int i = 0; i < fieldCount; ++i) { + final Chunk valueChunk = valueChunks.get(i); + if (valueChunk == null) { + continue; } - return maxPageBytes > 0 ? maxPageBytes : chunk.getData().remaining(); - } catch (final RuntimeException e) { - // A chunk whose pages cannot be parsed is not expected here; the compressed size is the best - // remaining upper bound of what the chunk costs before it is decompressed - return chunk.getData().remaining(); + final ByteBuffer valueBuffer = valueChunk.getData().duplicate(); + if (!valueBuffer.hasRemaining()) { + continue; + } + bytes += + PageIo.readPageHeader(valueBuffer, valueChunkHeaders[i], valueChunk.getChunkStatistic()) + .getUncompressedSize(); } + return bytes; + } + + /** + * Estimates the memory the pages of a chunk occupy once decompressed, by walking their headers. + * The pages are not decompressed and the data of the chunk is not consumed. + */ + public static long estimatePageBytes(final Chunk chunk) { + return PageIo.estimatePageBytes(chunk); } /** @@ -216,14 +190,13 @@ static long estimatePageBytes(final Chunk chunk) { * * @return whether such a page exists */ - boolean loadNextPage() throws IOException { + @Override + public boolean loadNextPage() throws IOException { final ByteBuffer timeBuffer = timeChunk.getData(); while (timeBuffer.hasRemaining()) { final int currentPageIndex = pageIndex++; final PageHeader timePageHeader = - singlePageChunk - ? PageHeader.deserializeFrom(timeBuffer, timeChunk.getChunkStatistic()) - : PageHeader.deserializeFrom(timeBuffer, timeChunkHeader.getDataType()); + PageIo.readPageHeader(timeBuffer, timeChunkHeader, timeChunk.getChunkStatistic()); // The header of every value page of the group is read as well, so that the page bodies of the // time column and of the value columns are consumed in lockstep @@ -236,10 +209,8 @@ boolean loadNextPage() throws IOException { // Every chunk carries its own page marker: a value chunk may hold several pages although // the time chunk of the same group holds one, and the other way round valuePageHeaders[i] = - (valueChunkHeaders[i].getChunkType() & 0x3F) == MetaMarker.ONLY_ONE_PAGE_CHUNK_HEADER - ? PageHeader.deserializeFrom(valueChunk.getData(), valueChunk.getChunkStatistic()) - : PageHeader.deserializeFrom( - valueChunk.getData(), valueChunkHeaders[i].getDataType()); + PageIo.readPageHeader( + valueChunk.getData(), valueChunkHeaders[i], valueChunk.getChunkStatistic()); } if (!isTimePageNeeded(timePageHeader)) { @@ -248,62 +219,51 @@ boolean loadNextPage() throws IOException { continue; } - // The decryptor is created for the page group, exactly like the aligned chunk reader does - final IDecryptor decryptor = IDecryptor.getDecryptor(encryptParam); final ByteBuffer timePageData = - ChunkReader.deserializePageData( - timePageHeader, - timeBuffer, - timeChunkHeader, - decryptor, - encryptParam, - currentPageIndex); - decodeTimes(timePageData, timePageHeader); - - final int from = firstRowAtOrAfter(startTime); - final int to = firstRowAfter(endTime); - if (from >= to) { + PageIo.decompress( + timePageHeader, timeBuffer, timeChunkHeader, encryptParam, currentPageIndex); + decodeTimes( + timePageData, + Decoder.getDecoderByType(timeChunkHeader.getEncodingType(), TSDataType.INT64), + PageIo.expectedRows(timePageHeader)); + + if (!clipPageToRange()) { skipValuePageData(); clearPage(); continue; } + final int from = cursor; long ramBytes = (long) pageRowCount * Long.BYTES; for (int i = 0; i < fieldCount; ++i) { - final TableValuePage state = pageStates[i]; + final AlignedValuePage state = pageStates[i]; final PageHeader valuePageHeader = valuePageHeaders[i]; final Chunk valueChunk = valueChunks.get(i); if (valuePageHeader == null || valueChunk == null || valuePageHeader.getUncompressedSize() == 0) { // The column has no chunk in this group, or an empty page: every cell is null. The body - // is - // normally absent, but a page that carries one has to be consumed, otherwise the next + // is normally absent, but a page that carries one has to be consumed, otherwise the next // header is read from the middle of its body if (valueChunk != null && valuePageHeader != null && valuePageHeader.getCompressedSize() > 0) { - valueChunk - .getData() - .position(valueChunk.getData().position() + valuePageHeader.getCompressedSize()); + PageIo.skipBody(valuePageHeader, valueChunk.getData()); } state.setEmpty(); continue; } - if (isPageDeleted(valuePageHeader, valueTableDeleteIntervals[i])) { - valueChunk - .getData() - .position(valueChunk.getData().position() + valuePageHeader.getCompressedSize()); + if (isPageDeleted(valuePageHeader, valueDeleteIntervals[i])) { + PageIo.skipBody(valuePageHeader, valueChunk.getData()); state.setEmpty(); continue; } final ByteBuffer valuePageData = - ChunkReader.deserializePageData( + PageIo.decompress( valuePageHeader, valueChunk.getData(), valueChunkHeaders[i], - decryptor, encryptParam, currentPageIndex); ramBytes += valuePageData.remaining(); @@ -313,9 +273,8 @@ boolean loadNextPage() throws IOException { } } - cursor = from; - endRow = to; currentPageRamBytes = ramBytes; + finishPageLoad(); return true; } @@ -323,96 +282,164 @@ boolean loadNextPage() throws IOException { return false; } - /** - * Decodes the rows of the current page into the given tablet, starting at its current row. - * - *

The rows that are deleted as a whole, which are the rows in the deleted intervals of the - * time column or in a modification that affects every measurement, are skipped, because a query - * on the TsFile does not return them either. The rows that only lose some of their cells are - * kept, with the deleted cells marked null. - * - * @param maxRows the number of rows the tablet can still hold - */ - void fillTablet(final Tablet tablet, final int maxRows) { - if (!hasRowDeletions()) { - final int count = Math.min(endRow - cursor, maxRows); - if (count <= 0) { - return; + @Override + public void close() { + timeChunk.close(); + for (final Chunk valueChunk : valueChunks) { + if (valueChunk != null) { + valueChunk.close(); } - fillTabletInBulk(tablet, tablet.getRowSize(), cursor, count); - cursor += count; - return; } + } + + // ------------------------------------------------------------------------- + // Row retention and point counts + // ------------------------------------------------------------------------- + + @Override + protected boolean hasRowDrops() { + return rowDropped != null || hasTimeRowDeletions(); + } + + @Override + protected boolean mayDropRows() { + return rowRetention == RowRetention.DROP_ROWS_WITHOUT_KEPT_CELL + && (hasMods || hasTimeRowDeletions() || anyValuePageHasNulls() || allValuePagesEmpty()); + } + + @Override + protected boolean isRowDropped(final int row) { + if (rowDropped != null) { + return rowDropped[row]; + } + return isTimeRowDeleted(times[row]); + } + + @Override + protected boolean rowSurvives(final int row) { + final long time = times[row]; + if (isTimeRowDeleted(time)) { + return false; + } + for (int i = 0; i < fieldCount; ++i) { + if (cellSurvives(i, row, time)) { + return true; + } + } + return false; + } + + @Override + protected int fieldCount() { + return fieldCount; + } + + @Override + protected boolean isCellPresent(final int field, final int row) { + final AlignedValuePage state = pageStates[field]; + // A value page may hold fewer values than the time page: the rows behind its value count have + // no cell, and must not index the bitmap of the page. + return !state.empty + && row < state.valueCount + && (!state.hasNulls || AlignedValuePage.isValuePresent(state.nullBitmap, row)); + } + + @Override + protected boolean isCellDeleted(final int field, final long time) { + if (hasMods && ModsOperationUtil.isDelete(time, modsInfoList.get(deviceIdSize + field))) { + return true; + } + return !valueDeleteIntervals[field].isEmpty() && valueDeleteIntervals[field].contains(time); + } - // The deleted rows break the page into segments of consecutive rows that are kept, and each - // segment is still filled with one sequential decode per column. The decoders of the columns - // are advanced over the deleted rows, which are not written to the tablet at all. - int remainingRows = maxRows; - while (cursor < endRow && remainingRows > 0) { - final int segmentStart = nextKeptRow(cursor); - if (segmentStart > cursor) { - skipRows(segmentStart - cursor); - cursor = segmentStart; + @Override + protected void clearPageValues() { + // The page bodies of the columns are not part of the reported page memory anymore, so the + // buffers must not stay reachable while the reader skips pages + for (final AlignedValuePage state : pageStates) { + state.setEmpty(); + } + } + + @Override + protected void resetScanCursors() { + timeDeleteIntervals.reset(); + for (final DeleteIntervals intervals : valueDeleteIntervals) { + if (intervals != null) { + intervals.reset(); } - if (cursor >= endRow) { - break; + } + if (modsInfoList != null) { + for (final ModsOperationUtil.ModsInfo modsInfo : modsInfoList) { + if (modsInfo != null) { + modsInfo.setCurrentIndex(0); + } } - final int segmentEnd = nextDeletedRow(cursor, Math.min(endRow, cursor + remainingRows)); - fillTabletInBulk(tablet, tablet.getRowSize(), cursor, segmentEnd - cursor); - remainingRows -= segmentEnd - cursor; - cursor = segmentEnd; + } + if (timeModsInfo != null) { + timeModsInfo.setCurrentIndex(0); } } - /** Whether the time column deletes the rows as a whole. */ - private boolean hasRowDeletions() { - return !timeTableDeleteIntervals.isEmpty() + private boolean hasTimeRowDeletions() { + return !timeDeleteIntervals.isEmpty() || (timeModsInfo != null && !timeModsInfo.getMods().isEmpty()); } - /** Whether the row does not exist for a query, i.e. the time column deletes the whole row. */ - private boolean isRowDeleted(final long time) { - return (!timeTableDeleteIntervals.isEmpty() && timeTableDeleteIntervals.contains(time)) + /** Whether the time column deletes the whole row, whatever the model of the file is. */ + private boolean isTimeRowDeleted(final long time) { + return (!timeDeleteIntervals.isEmpty() && timeDeleteIntervals.contains(time)) || ModsOperationUtil.isDelete(time, timeModsInfo); } - /** - * The first row in the current page that is not deleted, starting from the given row, or the end - * of the page if every one of them is deleted. The times are visited in ascending order. - */ - private int nextKeptRow(final int from) { - int row = from; - while (row < endRow && isRowDeleted(times[row])) { - ++row; + private boolean cellSurvives(final int field, final int row, final long time) { + final AlignedValuePage state = pageStates[field]; + if (state.empty || row >= state.valueCount) { + return false; } - return row; + if (state.hasNulls && !AlignedValuePage.isValuePresent(state.nullBitmap, row)) { + return false; + } + if (hasMods && ModsOperationUtil.isDelete(time, modsInfoList.get(deviceIdSize + field))) { + return false; + } + return valueDeleteIntervals[field].isEmpty() || !valueDeleteIntervals[field].contains(time); } - /** The first deleted row in [from, limit), or limit if every row of the range is kept. */ - private int nextDeletedRow(final int from, final int limit) { - int row = from + 1; - while (row < limit && !isRowDeleted(times[row])) { - ++row; + private boolean anyValuePageHasNulls() { + for (final AlignedValuePage state : pageStates) { + if (!state.empty && state.hasNulls) { + return true; + } } - return row; + return false; } - /** Skips the values of the given number of rows, which are deleted, in every column decoder. */ - private void skipRows(final int count) { - for (int i = 0; i < fieldCount; ++i) { - final TableValuePage state = pageStates[i]; + /** + * Whether every value page of the current page is empty, which makes every cell of the page null. + * A table keeps such rows, but the tree model has no row to keep and must drop them, exactly like + * the BatchData path did. + */ + private boolean allValuePagesEmpty() { + for (final AlignedValuePage state : pageStates) { if (!state.empty) { - columnKinds[i].skip(state, Math.min(count, state.valuesLeft())); + return false; } } + return true; } + // ------------------------------------------------------------------------- + // Tablet filling + // ------------------------------------------------------------------------- + /** * Copies a contiguous segment of the current page into the tablet, one sequential decode per * column, so that the values are written only once and no intermediate array is created. */ - private void fillTabletInBulk( - final Tablet tablet, final int destRowIndex, final int from, final int count) { + @Override + protected void fillSegment(final Tablet tablet, final int from, final int count) { + final int destRowIndex = tablet.getRowSize(); System.arraycopy(times, from, tablet.getTimestamps(), destRowIndex, count); final Object[] tabletValues = tablet.getValues(); @@ -422,7 +449,7 @@ private void fillTabletInBulk( for (int i = 0; i < fieldCount; ++i) { final int columnIndex = deviceIdSize + i; final Object columnValues = tabletValues[columnIndex]; - final TableValuePage state = pageStates[i]; + final AlignedValuePage state = pageStates[i]; if (state.empty) { markRangeNull(tablet, columnValues, columnIndex, destRowIndex, count); continue; @@ -436,7 +463,7 @@ private void fillTabletInBulk( tablet, columnValues, columnIndex, destRowIndex + decodable, count - decodable); } if (decodable > 0) { - final TableColumnKind kind = columnKinds[i]; + final ColumnKind kind = columnKinds[i]; if (state.hasNulls) { kind.decodeWithNulls( state, columnValues, destRowIndex, decodable, nullMarks(tablet, columnIndex)); @@ -451,21 +478,25 @@ private void fillTabletInBulk( markDeletedCells(tablet, columnValues, columnIndex, from, destRowIndex, count, modsInfo); } } - if (!valueTableDeleteIntervals[i].isEmpty()) { + if (!valueDeleteIntervals[i].isEmpty()) { markDeletedCells( - tablet, - columnValues, - columnIndex, - from, - destRowIndex, - count, - valueTableDeleteIntervals[i]); + tablet, columnValues, columnIndex, from, destRowIndex, count, valueDeleteIntervals[i]); } } tablet.setRowSize(destRowIndex + count); } + @Override + protected void skipSegment(final int count) { + for (int i = 0; i < fieldCount; ++i) { + final AlignedValuePage state = pageStates[i]; + if (!state.empty) { + columnKinds[i].skip(state, Math.min(count, state.valuesLeft())); + } + } + } + /** Marks the cells of the segment that the modifications of the column deleted as null. */ private void markDeletedCells( final Tablet tablet, @@ -500,7 +531,7 @@ private void markDeletedCells( final int from, final int destRowIndex, final int count, - final TableDeleteIntervals deleteIntervals) { + final DeleteIntervals deleteIntervals) { final BitMap marks = nullMarks(tablet, columnIndex); final Binary[] binaries = columnValues instanceof Binary[] ? (Binary[]) columnValues : null; for (int row = 0; row < count; ++row) { @@ -513,11 +544,77 @@ private void markDeletedCells( } } + // ------------------------------------------------------------------------- + // Page decoding + // ------------------------------------------------------------------------- + + private boolean isTimePageNeeded(final PageHeader pageHeader) { + return PageIo.isPageInRange(pageHeader, startTime, endTime) + && !isPageDeleted(pageHeader, timeDeleteIntervals); + } + + /** Whether the page is entirely contained in the deleted intervals of the column. */ + private static boolean isPageDeleted( + final PageHeader pageHeader, final DeleteIntervals deleteIntervals) { + if (deleteIntervals.isEmpty()) { + return false; + } + final Statistics statistics = pageHeader.getStatistics(); + // An all-null page has no time range (its count is 0, so the default range is the whole long + // domain), and a page without statistics has none either. Deciding on that range would advance + // the cursor of the intervals to the end and would disable the deletions of the following + // pages. + if (statistics == null || statistics.getCount() == 0) { + return false; + } + return deleteIntervals.coversPage(statistics.getStartTime(), statistics.getEndTime()); + } + + /** Skips the bodies of the page of the time column and of the value columns. */ + private void skipPageData(final PageHeader timePageHeader) { + PageIo.skipBody(timePageHeader, timeChunk.getData()); + skipValuePageData(); + } + + private void skipValuePageData() { + for (int i = 0; i < fieldCount; ++i) { + final PageHeader valuePageHeader = valuePageHeaders[i]; + if (valuePageHeader != null) { + PageIo.skipBody(valuePageHeader, valueChunks.get(i).getData()); + } + } + } + + /** Whether some row of {@code [fromTime, toTime]} is deleted by the mods of the given column. */ + private static boolean hasDeletionsInRange( + final ModsOperationUtil.ModsInfo modsInfo, final long fromTime, final long toTime) { + if (modsInfo == null) { + return false; + } + final List mods = modsInfo.getMods(); + if (mods == null || mods.isEmpty()) { + return false; + } + // The mods are sorted and disjoint, and the parser always moves forward in time, so the search + // can start from the cursor of the mods info + for (int i = Math.max(0, modsInfo.getCurrentIndex()); i < mods.size(); ++i) { + if (mods.get(i).getTimeRange().getMax() < fromTime) { + continue; + } + return mods.get(i).getTimeRange().getMin() <= toTime; + } + return false; + } + + // ------------------------------------------------------------------------- + // Device id columns + // ------------------------------------------------------------------------- + /** * Fills all the rows of the device id columns at once, because the device id is identical for all * the rows of a tablet. */ - static void fillDeviceIdColumns( + public static void fillDeviceIdColumns( final IDeviceID deviceID, final Tablet tablet, final List dataTypeList, @@ -589,160 +686,9 @@ private static void fillDeviceIdValue( } } - ///////////////////////////////////////////////////////////////////////////////////////////////// - // Page decoding - ///////////////////////////////////////////////////////////////////////////////////////////////// - - private boolean isTimePageNeeded(final PageHeader pageHeader) { - if (pageHeader.getUncompressedSize() == 0) { - // Empty page, there is no row to read - return false; - } - final Statistics statistics = pageHeader.getStatistics(); - if (statistics == null) { - // A page without statistics has no time range to prune with, so it has to be read - return true; - } - if (statistics.getCount() == 0) { - return false; - } - if (statistics.getEndTime() < startTime || statistics.getStartTime() > endTime) { - return false; - } - return !isPageDeleted(pageHeader, timeTableDeleteIntervals); - } - - /** Whether the page is entirely contained in the deleted intervals of the column. */ - private static boolean isPageDeleted( - final PageHeader pageHeader, final TableDeleteIntervals deleteIntervals) { - if (deleteIntervals.isEmpty()) { - return false; - } - final Statistics statistics = pageHeader.getStatistics(); - // An all-null page has no time range (its count is 0, so the default range is the whole long - // domain), and a page without statistics has none either. Deciding on that range would advance - // the cursor of the intervals to the end and would disable the deletions of the following - // pages. - if (statistics == null || statistics.getCount() == 0) { - return false; - } - return deleteIntervals.coversPage(statistics.getStartTime(), statistics.getEndTime()); - } - - /** Skips the bodies of the page of the time column and of the value columns. */ - private void skipPageData(final PageHeader timePageHeader) { - final ByteBuffer timeBuffer = timeChunk.getData(); - timeBuffer.position(timeBuffer.position() + timePageHeader.getCompressedSize()); - skipValuePageData(); - } - - private void skipValuePageData() { - for (int i = 0; i < fieldCount; ++i) { - final PageHeader valuePageHeader = valuePageHeaders[i]; - if (valuePageHeader != null) { - final ByteBuffer valueBuffer = valueChunks.get(i).getData(); - valueBuffer.position(valueBuffer.position() + valuePageHeader.getCompressedSize()); - } - } - } - - /** Decodes all the times of the page into the reusable time array. */ - private void decodeTimes(final ByteBuffer timePageData, final PageHeader timePageHeader) - throws IOException { - final Decoder timeDecoder = - Decoder.getDecoderByType(timeChunkHeader.getEncodingType(), TSDataType.INT64); - - if (timePageHeader.getStatistics() != null) { - final int expected = (int) timePageHeader.getStatistics().getCount(); - if (times.length < expected) { - times = new long[expected]; - } - } - - int count = 0; - while (timeDecoder.hasNext(timePageData)) { - if (count == times.length) { - times = Arrays.copyOf(times, Math.max(1024, times.length << 1)); - } - times[count++] = timeDecoder.readLong(timePageData); - } - pageRowCount = count; - } - - private void clearPage() { - pageRowCount = 0; - cursor = 0; - endRow = 0; - currentPageRamBytes = 0; - // The page bodies of the columns are not part of the reported page memory anymore, so the - // buffers must not stay reachable while the reader skips pages - for (final TableValuePage state : pageStates) { - state.setEmpty(); - } - } - - private int firstRowAtOrAfter(final long time) { - int low = 0; - int high = pageRowCount; - while (low < high) { - final int middle = (low + high) >>> 1; - if (times[middle] < time) { - low = middle + 1; - } else { - high = middle; - } - } - return low; - } - - private int firstRowAfter(final long time) { - int low = 0; - int high = pageRowCount; - while (low < high) { - final int middle = (low + high) >>> 1; - if (times[middle] <= time) { - low = middle + 1; - } else { - high = middle; - } - } - return low; - } - - /** Whether some row of {@code [fromTime, toTime]} is deleted by the mods of the given column. */ - private static boolean hasDeletionsInRange( - final ModsOperationUtil.ModsInfo modsInfo, final long fromTime, final long toTime) { - if (modsInfo == null) { - return false; - } - final List mods = modsInfo.getMods(); - if (mods == null || mods.isEmpty()) { - return false; - } - // The mods are sorted and disjoint, and the parser always moves forward in time, so the search - // can start from the cursor of the mods info - for (int i = Math.max(0, modsInfo.getCurrentIndex()); i < mods.size(); ++i) { - if (mods.get(i).getTimeRange().getMax() < fromTime) { - continue; - } - return mods.get(i).getTimeRange().getMin() <= toTime; - } - return false; - } - - @Override - public void close() { - timeChunk.close(); - for (final Chunk valueChunk : valueChunks) { - if (valueChunk != null) { - valueChunk.close(); - } - } - } - - ///////////////////////////////////////////////////////////////////////////////////////////////// + // ------------------------------------------------------------------------- // Tablet helpers - ///////////////////////////////////////////////////////////////////////////////////////////////// + // ------------------------------------------------------------------------- private static BitMap nullMarks(final Tablet tablet, final int columnIndex) { BitMap[] bitMaps = tablet.getBitMaps(); diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/table/TableColumnKind.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/util/tablet/ColumnKind.java similarity index 81% rename from iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/table/TableColumnKind.java rename to iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/util/tablet/ColumnKind.java index 2524274fb022b..783041c741d55 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/table/TableColumnKind.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/util/tablet/ColumnKind.java @@ -17,7 +17,7 @@ * under the License. */ -package org.apache.iotdb.db.pipe.event.common.tsfile.parser.table; +package org.apache.iotdb.db.pipe.event.common.tsfile.parser.util.tablet; import org.apache.iotdb.db.i18n.DataNodeQueryMessages; @@ -37,11 +37,11 @@ * over the array of the tablet. The kind of a column is derived from its data type once, when the * reader is created, so that no check is needed while decoding. */ -enum TableColumnKind { +enum ColumnKind { LONG { @Override void decode( - final TableValuePage state, final Object values, final int offset, final int count) { + final AlignedValuePage state, final Object values, final int offset, final int count) { final long[] target = (long[]) values; final Decoder decoder = state.decoder; final ByteBuffer buffer = state.buffer; @@ -53,7 +53,7 @@ void decode( @Override void decodeWithNulls( - final TableValuePage state, + final AlignedValuePage state, final Object values, final int offset, final int count, @@ -64,7 +64,7 @@ void decodeWithNulls( final byte[] nullBitmap = state.nullBitmap; int position = state.position; for (int row = 0; row < count; ++row, ++position) { - if (TableValuePage.isValuePresent(nullBitmap, position)) { + if (AlignedValuePage.isValuePresent(nullBitmap, position)) { target[offset + row] = decoder.readLong(buffer); } else { nullMarks.mark(offset + row); @@ -74,13 +74,13 @@ void decodeWithNulls( } @Override - void skip(final TableValuePage state, final int count) { + void skip(final AlignedValuePage state, final int count) { final Decoder decoder = state.decoder; final ByteBuffer buffer = state.buffer; final byte[] nullBitmap = state.nullBitmap; int position = state.position; for (int row = 0; row < count; ++row, ++position) { - if (TableValuePage.isValuePresent(nullBitmap, position)) { + if (AlignedValuePage.isValuePresent(nullBitmap, position)) { decoder.readLong(buffer); } } @@ -90,7 +90,7 @@ void skip(final TableValuePage state, final int count) { INT { @Override void decode( - final TableValuePage state, final Object values, final int offset, final int count) { + final AlignedValuePage state, final Object values, final int offset, final int count) { final int[] target = (int[]) values; final Decoder decoder = state.decoder; final ByteBuffer buffer = state.buffer; @@ -102,7 +102,7 @@ void decode( @Override void decodeWithNulls( - final TableValuePage state, + final AlignedValuePage state, final Object values, final int offset, final int count, @@ -113,7 +113,7 @@ void decodeWithNulls( final byte[] nullBitmap = state.nullBitmap; int position = state.position; for (int row = 0; row < count; ++row, ++position) { - if (TableValuePage.isValuePresent(nullBitmap, position)) { + if (AlignedValuePage.isValuePresent(nullBitmap, position)) { target[offset + row] = decoder.readInt(buffer); } else { nullMarks.mark(offset + row); @@ -123,13 +123,13 @@ void decodeWithNulls( } @Override - void skip(final TableValuePage state, final int count) { + void skip(final AlignedValuePage state, final int count) { final Decoder decoder = state.decoder; final ByteBuffer buffer = state.buffer; final byte[] nullBitmap = state.nullBitmap; int position = state.position; for (int row = 0; row < count; ++row, ++position) { - if (TableValuePage.isValuePresent(nullBitmap, position)) { + if (AlignedValuePage.isValuePresent(nullBitmap, position)) { decoder.readInt(buffer); } } @@ -139,7 +139,7 @@ void skip(final TableValuePage state, final int count) { FLOAT { @Override void decode( - final TableValuePage state, final Object values, final int offset, final int count) { + final AlignedValuePage state, final Object values, final int offset, final int count) { final float[] target = (float[]) values; final Decoder decoder = state.decoder; final ByteBuffer buffer = state.buffer; @@ -151,7 +151,7 @@ void decode( @Override void decodeWithNulls( - final TableValuePage state, + final AlignedValuePage state, final Object values, final int offset, final int count, @@ -162,7 +162,7 @@ void decodeWithNulls( final byte[] nullBitmap = state.nullBitmap; int position = state.position; for (int row = 0; row < count; ++row, ++position) { - if (TableValuePage.isValuePresent(nullBitmap, position)) { + if (AlignedValuePage.isValuePresent(nullBitmap, position)) { target[offset + row] = decoder.readFloat(buffer); } else { nullMarks.mark(offset + row); @@ -172,13 +172,13 @@ void decodeWithNulls( } @Override - void skip(final TableValuePage state, final int count) { + void skip(final AlignedValuePage state, final int count) { final Decoder decoder = state.decoder; final ByteBuffer buffer = state.buffer; final byte[] nullBitmap = state.nullBitmap; int position = state.position; for (int row = 0; row < count; ++row, ++position) { - if (TableValuePage.isValuePresent(nullBitmap, position)) { + if (AlignedValuePage.isValuePresent(nullBitmap, position)) { decoder.readFloat(buffer); } } @@ -188,7 +188,7 @@ void skip(final TableValuePage state, final int count) { DOUBLE { @Override void decode( - final TableValuePage state, final Object values, final int offset, final int count) { + final AlignedValuePage state, final Object values, final int offset, final int count) { final double[] target = (double[]) values; final Decoder decoder = state.decoder; final ByteBuffer buffer = state.buffer; @@ -200,7 +200,7 @@ void decode( @Override void decodeWithNulls( - final TableValuePage state, + final AlignedValuePage state, final Object values, final int offset, final int count, @@ -211,7 +211,7 @@ void decodeWithNulls( final byte[] nullBitmap = state.nullBitmap; int position = state.position; for (int row = 0; row < count; ++row, ++position) { - if (TableValuePage.isValuePresent(nullBitmap, position)) { + if (AlignedValuePage.isValuePresent(nullBitmap, position)) { target[offset + row] = decoder.readDouble(buffer); } else { nullMarks.mark(offset + row); @@ -221,13 +221,13 @@ void decodeWithNulls( } @Override - void skip(final TableValuePage state, final int count) { + void skip(final AlignedValuePage state, final int count) { final Decoder decoder = state.decoder; final ByteBuffer buffer = state.buffer; final byte[] nullBitmap = state.nullBitmap; int position = state.position; for (int row = 0; row < count; ++row, ++position) { - if (TableValuePage.isValuePresent(nullBitmap, position)) { + if (AlignedValuePage.isValuePresent(nullBitmap, position)) { decoder.readDouble(buffer); } } @@ -237,7 +237,7 @@ void skip(final TableValuePage state, final int count) { BOOLEAN { @Override void decode( - final TableValuePage state, final Object values, final int offset, final int count) { + final AlignedValuePage state, final Object values, final int offset, final int count) { final boolean[] target = (boolean[]) values; final Decoder decoder = state.decoder; final ByteBuffer buffer = state.buffer; @@ -249,7 +249,7 @@ void decode( @Override void decodeWithNulls( - final TableValuePage state, + final AlignedValuePage state, final Object values, final int offset, final int count, @@ -260,7 +260,7 @@ void decodeWithNulls( final byte[] nullBitmap = state.nullBitmap; int position = state.position; for (int row = 0; row < count; ++row, ++position) { - if (TableValuePage.isValuePresent(nullBitmap, position)) { + if (AlignedValuePage.isValuePresent(nullBitmap, position)) { target[offset + row] = decoder.readBoolean(buffer); } else { nullMarks.mark(offset + row); @@ -270,13 +270,13 @@ void decodeWithNulls( } @Override - void skip(final TableValuePage state, final int count) { + void skip(final AlignedValuePage state, final int count) { final Decoder decoder = state.decoder; final ByteBuffer buffer = state.buffer; final byte[] nullBitmap = state.nullBitmap; int position = state.position; for (int row = 0; row < count; ++row, ++position) { - if (TableValuePage.isValuePresent(nullBitmap, position)) { + if (AlignedValuePage.isValuePresent(nullBitmap, position)) { decoder.readBoolean(buffer); } } @@ -286,7 +286,7 @@ void skip(final TableValuePage state, final int count) { BINARY { @Override void decode( - final TableValuePage state, final Object values, final int offset, final int count) { + final AlignedValuePage state, final Object values, final int offset, final int count) { final Binary[] target = (Binary[]) values; final Decoder decoder = state.decoder; final ByteBuffer buffer = state.buffer; @@ -298,7 +298,7 @@ void decode( @Override void decodeWithNulls( - final TableValuePage state, + final AlignedValuePage state, final Object values, final int offset, final int count, @@ -309,7 +309,7 @@ void decodeWithNulls( final byte[] nullBitmap = state.nullBitmap; int position = state.position; for (int row = 0; row < count; ++row, ++position) { - if (TableValuePage.isValuePresent(nullBitmap, position)) { + if (AlignedValuePage.isValuePresent(nullBitmap, position)) { target[offset + row] = decoder.readBinary(buffer); } else { target[offset + row] = Binary.EMPTY_VALUE; @@ -320,13 +320,13 @@ void decodeWithNulls( } @Override - void skip(final TableValuePage state, final int count) { + void skip(final AlignedValuePage state, final int count) { final Decoder decoder = state.decoder; final ByteBuffer buffer = state.buffer; final byte[] nullBitmap = state.nullBitmap; int position = state.position; for (int row = 0; row < count; ++row, ++position) { - if (TableValuePage.isValuePresent(nullBitmap, position)) { + if (AlignedValuePage.isValuePresent(nullBitmap, position)) { decoder.readBinary(buffer); } } @@ -336,7 +336,7 @@ void skip(final TableValuePage state, final int count) { DATE { @Override void decode( - final TableValuePage state, final Object values, final int offset, final int count) { + final AlignedValuePage state, final Object values, final int offset, final int count) { final LocalDate[] target = (LocalDate[]) values; final Decoder decoder = state.decoder; final ByteBuffer buffer = state.buffer; @@ -348,7 +348,7 @@ void decode( @Override void decodeWithNulls( - final TableValuePage state, + final AlignedValuePage state, final Object values, final int offset, final int count, @@ -359,7 +359,7 @@ void decodeWithNulls( final byte[] nullBitmap = state.nullBitmap; int position = state.position; for (int row = 0; row < count; ++row, ++position) { - if (TableValuePage.isValuePresent(nullBitmap, position)) { + if (AlignedValuePage.isValuePresent(nullBitmap, position)) { target[offset + row] = DateUtils.parseIntToLocalDate(decoder.readInt(buffer)); } else { nullMarks.mark(offset + row); @@ -369,13 +369,13 @@ void decodeWithNulls( } @Override - void skip(final TableValuePage state, final int count) { + void skip(final AlignedValuePage state, final int count) { final Decoder decoder = state.decoder; final ByteBuffer buffer = state.buffer; final byte[] nullBitmap = state.nullBitmap; int position = state.position; for (int row = 0; row < count; ++row, ++position) { - if (TableValuePage.isValuePresent(nullBitmap, position)) { + if (AlignedValuePage.isValuePresent(nullBitmap, position)) { decoder.readInt(buffer); } } @@ -383,16 +383,16 @@ void skip(final TableValuePage state, final int count) { } }; - abstract void decode(TableValuePage state, Object values, int offset, int count); + abstract void decode(AlignedValuePage state, Object values, int offset, int count); abstract void decodeWithNulls( - TableValuePage state, Object values, int offset, int count, BitMap nullMarks); + AlignedValuePage state, Object values, int offset, int count, BitMap nullMarks); - abstract void skip(TableValuePage state, int count); + abstract void skip(AlignedValuePage state, int count); // The arch rule forbids switching on TSDataType outside TypeService, so the dispatch on the // column type goes through a TypeService, which is also exhaustive on the type enum. - private static final TypeService SERVICE = + private static final TypeService SERVICE = type -> switch (type.getTypeEnum()) { case INT64, TIMESTAMP -> LONG; @@ -413,7 +413,7 @@ abstract void decodeWithNulls( type.getTypeEnum())); }; - static TableColumnKind of(final TSDataType dataType) { + static ColumnKind of(final TSDataType dataType) { return dataType == null ? BINARY : SERVICE.call(Type.fromTsDataType(dataType)); } } diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/table/TableDeleteIntervals.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/util/tablet/DeleteIntervals.java similarity index 90% rename from iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/table/TableDeleteIntervals.java rename to iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/util/tablet/DeleteIntervals.java index 681d9c5fa7816..f21c29a11b74a 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/table/TableDeleteIntervals.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/util/tablet/DeleteIntervals.java @@ -17,7 +17,7 @@ * under the License. */ -package org.apache.iotdb.db.pipe.event.common.tsfile.parser.table; +package org.apache.iotdb.db.pipe.event.common.tsfile.parser.util.tablet; import org.apache.tsfile.read.common.TimeRange; @@ -31,12 +31,12 @@ * so the cursor only moves forward and every query starts from it, which makes the lookup of a row * and the check whether a whole page is deleted O(1) amortized. */ -final class TableDeleteIntervals { +final class DeleteIntervals { private final List intervals; private int cursor; - TableDeleteIntervals(final List intervals) { + DeleteIntervals(final List intervals) { this.intervals = sortedAndMerged(intervals); } @@ -75,6 +75,14 @@ boolean isEmpty() { return intervals == null || intervals.isEmpty(); } + /** + * Rewinds the forward cursor, so that another pass over the rows of a page (the retention pass + * before the decode, for instance) can start from its first row again. + */ + void reset() { + cursor = 0; + } + /** Whether a single interval covers the whole page. */ boolean coversPage(final long startTime, final long endTime) { if (isEmpty()) { diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/util/tablet/PageIo.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/util/tablet/PageIo.java new file mode 100644 index 0000000000000..c51945d7a9095 --- /dev/null +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/util/tablet/PageIo.java @@ -0,0 +1,145 @@ +/* + * 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.iotdb.db.pipe.event.common.tsfile.parser.util.tablet; + +import org.apache.tsfile.encrypt.EncryptParameter; +import org.apache.tsfile.encrypt.IDecryptor; +import org.apache.tsfile.file.MetaMarker; +import org.apache.tsfile.file.header.ChunkHeader; +import org.apache.tsfile.file.header.PageHeader; +import org.apache.tsfile.file.metadata.statistics.Statistics; +import org.apache.tsfile.read.common.Chunk; +import org.apache.tsfile.read.reader.chunk.ChunkReader; + +import java.io.IOException; +import java.nio.ByteBuffer; + +/** + * The page header, decompression and page size helpers shared by the direct tablet readers. + * + *

An aligned chunk and a non-aligned chunk store their pages with the same header, so reading a + * page, deciding whether it overlaps the parsed range, skipping its body and estimating its memory + * are the same for the two layouts; only the body of a page differs. + */ +final class PageIo { + + private PageIo() {} + + static boolean isSinglePageChunk(final ChunkHeader chunkHeader) { + return (chunkHeader.getChunkType() & 0x3F) == MetaMarker.ONLY_ONE_PAGE_CHUNK_HEADER; + } + + /** + * Reads the next page header of the chunk. A chunk that holds a single page stores the page + * statistics in the chunk statistics instead of the header, so the header has to be read with the + * chunk statistics in that case. + */ + static PageHeader readPageHeader( + final ByteBuffer buffer, final ChunkHeader chunkHeader, final Statistics chunkStatistics) { + return isSinglePageChunk(chunkHeader) + ? PageHeader.deserializeFrom(buffer, chunkStatistics) + : PageHeader.deserializeFrom(buffer, chunkHeader.getDataType()); + } + + /** The number of rows the page declares, or 0 when its header carries no statistics. */ + static int expectedRows(final PageHeader pageHeader) { + final Statistics statistics = pageHeader.getStatistics(); + return statistics == null ? 0 : (int) statistics.getCount(); + } + + /** + * Whether the page has at least one row in {@code [startTime, endTime]}. A page without + * statistics, or with an empty body, cannot be pruned by its header and is kept so that the + * caller decodes it and clips its rows. + */ + static boolean isPageInRange( + final PageHeader pageHeader, final long startTime, final long endTime) { + if (pageHeader.getUncompressedSize() == 0) { + // Empty page, there is no row to read + return false; + } + final Statistics statistics = pageHeader.getStatistics(); + if (statistics == null) { + // A page without statistics has no time range to prune with, so it has to be read + return true; + } + if (statistics.getCount() == 0) { + return false; + } + return statistics.getEndTime() >= startTime && statistics.getStartTime() <= endTime; + } + + /** Decompresses the body of a page that the caller is about to decode. */ + static ByteBuffer decompress( + final PageHeader pageHeader, + final ByteBuffer buffer, + final ChunkHeader chunkHeader, + final EncryptParameter encryptParam, + final int pageIndex) + throws IOException { + return ChunkReader.deserializePageData( + pageHeader, + buffer, + chunkHeader, + IDecryptor.getDecryptor(encryptParam), + encryptParam, + pageIndex); + } + + /** Skips the compressed body of a page without decompressing it. */ + static void skipBody(final PageHeader pageHeader, final ByteBuffer buffer) { + buffer.position(buffer.position() + pageHeader.getCompressedSize()); + } + + /** + * The memory the pages of a chunk occupy once decompressed, which is the largest page of the + * chunk: the pages are decoded one at a time, so the peak is not their sum. The pages are walked + * by their headers only, without decompressing any of them, and the chunk data is not consumed. + */ + static long estimatePageBytes(final Chunk chunk) { + final ByteBuffer buffer = chunk.getData().duplicate(); + buffer.rewind(); + if (!buffer.hasRemaining()) { + return 0; + } + try { + final ChunkHeader header = chunk.getHeader(); + final boolean singlePageChunk = isSinglePageChunk(header); + long maxPageBytes = 0; + while (buffer.hasRemaining()) { + final PageHeader pageHeader = readPageHeader(buffer, header, chunk.getChunkStatistic()); + maxPageBytes = Math.max(maxPageBytes, pageHeader.getUncompressedSize()); + final int compressedSize = pageHeader.getCompressedSize(); + if (singlePageChunk || compressedSize < 0 || compressedSize > buffer.remaining()) { + break; + } + // An all-null page is stored as a header without a body (compressedSize == 0), so the next + // header follows immediately and the walk must not stop at it: the largest page may be + // stored after an empty one + buffer.position(buffer.position() + compressedSize); + } + return maxPageBytes > 0 ? maxPageBytes : chunk.getData().remaining(); + } catch (final RuntimeException e) { + // A chunk whose pages cannot be parsed is not expected here; the compressed size is the best + // remaining upper bound of what the chunk costs before it is decompressed + return chunk.getData().remaining(); + } + } +} diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/util/tablet/SeriesChunkDirectTabletReader.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/util/tablet/SeriesChunkDirectTabletReader.java new file mode 100644 index 0000000000000..91acac12076bf --- /dev/null +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/util/tablet/SeriesChunkDirectTabletReader.java @@ -0,0 +1,230 @@ +/* + * 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.iotdb.db.pipe.event.common.tsfile.parser.util.tablet; + +import org.apache.iotdb.db.pipe.event.common.tsfile.parser.util.ModsOperationUtil; + +import org.apache.tsfile.common.conf.TSFileConfig; +import org.apache.tsfile.common.conf.TSFileDescriptor; +import org.apache.tsfile.encoding.decoder.Decoder; +import org.apache.tsfile.encrypt.EncryptParameter; +import org.apache.tsfile.enums.TSDataType; +import org.apache.tsfile.file.header.ChunkHeader; +import org.apache.tsfile.file.header.PageHeader; +import org.apache.tsfile.file.metadata.enums.TSEncoding; +import org.apache.tsfile.read.common.Chunk; +import org.apache.tsfile.utils.ReadWriteForEncodingUtils; +import org.apache.tsfile.write.record.Tablet; + +import java.io.IOException; +import java.nio.ByteBuffer; + +/** + * Reads the pages of a non-aligned series chunk of a tree-model TsFile and decodes them straight + * into the single value column of a {@link Tablet}. + * + *

A page of a non-aligned chunk holds the time values and the value values in one body: an + * unsigned varint gives the length of the time part, which is followed by the encoded values. There + * is no null bitmap, because a non-aligned series stores no null: a point either exists or it does + * not, and the points deleted by the modifications or by the delete intervals of the chunk are + * dropped from the tablet instead of being marked null. + */ +public final class SeriesChunkDirectTabletReader extends AbstractDirectTabletReader { + + private static final TSFileConfig CONFIG = TSFileDescriptor.getInstance().getConfig(); + + private final Chunk chunk; + private final TSDataType dataType; + private final ColumnKind columnKind; + + private final boolean hasMods; + private final ModsOperationUtil.ModsInfo modsInfo; + private final DeleteIntervals deleteIntervals; + + private final ChunkHeader chunkHeader; + private final EncryptParameter encryptParam; + + private final AlignedValuePage valuePage = new AlignedValuePage(); + + public SeriesChunkDirectTabletReader( + final Chunk chunk, + final TSDataType dataType, + final long startTime, + final long endTime, + final boolean hasMods, + final ModsOperationUtil.ModsInfo modsInfo, + final boolean trackPointCounts) { + super(startTime, endTime, trackPointCounts); + this.chunk = chunk; + this.dataType = dataType; + this.columnKind = ColumnKind.of(dataType); + this.hasMods = hasMods; + this.modsInfo = modsInfo; + this.deleteIntervals = new DeleteIntervals(chunk.getDeleteIntervalList()); + this.chunkHeader = chunk.getHeader(); + this.encryptParam = chunk.getEncryptParam(); + } + + @Override + public long binaryValueBytes() { + return dataType.isBinary() ? valuePage.valueBytes : 0L; + } + + @Override + public boolean hasNextPage() { + return chunk.getData().hasRemaining(); + } + + @Override + public long peekNextPageBytes() { + final ByteBuffer buffer = chunk.getData().duplicate(); + if (!buffer.hasRemaining()) { + return 0L; + } + return PageIo.readPageHeader(buffer, chunkHeader, chunk.getChunkStatistic()) + .getUncompressedSize(); + } + + @Override + public boolean loadNextPage() throws IOException { + final ByteBuffer buffer = chunk.getData(); + while (buffer.hasRemaining()) { + final int currentPageIndex = pageIndex++; + final PageHeader pageHeader = + PageIo.readPageHeader(buffer, chunkHeader, chunk.getChunkStatistic()); + + if (!PageIo.isPageInRange(pageHeader, startTime, endTime)) { + PageIo.skipBody(pageHeader, buffer); + clearPage(); + continue; + } + + final ByteBuffer pageData = + PageIo.decompress(pageHeader, buffer, chunkHeader, encryptParam, currentPageIndex); + + // A non-aligned page starts with the length of its time part, then the times, then the + // values. The time part is decoded in full so that the rows outside the parser range can be + // clipped without touching the values before them. + final int timeLength = ReadWriteForEncodingUtils.readUnsignedVarInt(pageData); + final ByteBuffer timeBuffer = pageData.slice(); + timeBuffer.limit(timeLength); + final ByteBuffer valueBuffer = pageData.slice(); + valueBuffer.position(timeLength); + + decodeTimes( + timeBuffer, + Decoder.getDecoderByType(TSEncoding.valueOf(CONFIG.getTimeEncoder()), TSDataType.INT64), + PageIo.expectedRows(pageHeader)); + + if (!clipPageToRange()) { + clearPage(); + continue; + } + + valuePage.initSeries( + valueBuffer, chunkHeader.calculateDecoderForNonTimeChunk(), pageRowCount); + if (cursor > 0) { + columnKind.skip(valuePage, Math.min(cursor, valuePage.valuesLeft())); + } + + currentPageRamBytes = (long) pageRowCount * Long.BYTES + pageData.remaining(); + finishPageLoad(); + return true; + } + + clearPage(); + return false; + } + + @Override + public void close() { + chunk.close(); + } + + // ------------------------------------------------------------------------- + // Row retention and point counts + // ------------------------------------------------------------------------- + + @Override + protected boolean hasRowDrops() { + return rowDropped != null; + } + + @Override + protected boolean mayDropRows() { + return hasMods || !deleteIntervals.isEmpty(); + } + + @Override + protected boolean isRowDropped(final int row) { + return rowDropped != null && rowDropped[row]; + } + + @Override + protected boolean rowSurvives(final int row) { + return !isCellDeleted(0, times[row]); + } + + @Override + protected int fieldCount() { + return 1; + } + + @Override + protected boolean isCellPresent(final int field, final int row) { + return !valuePage.empty; + } + + @Override + protected boolean isCellDeleted(final int field, final long time) { + return (hasMods && ModsOperationUtil.isDelete(time, modsInfo)) + || (!deleteIntervals.isEmpty() && deleteIntervals.contains(time)); + } + + @Override + protected void clearPageValues() { + valuePage.setEmpty(); + } + + @Override + protected void resetScanCursors() { + deleteIntervals.reset(); + if (modsInfo != null) { + modsInfo.setCurrentIndex(0); + } + } + + // ------------------------------------------------------------------------- + // Tablet filling + // ------------------------------------------------------------------------- + + @Override + protected void fillSegment(final Tablet tablet, final int from, final int count) { + final int rowIndex = tablet.getRowSize(); + System.arraycopy(times, from, tablet.getTimestamps(), rowIndex, count); + columnKind.decode(valuePage, tablet.getValues()[0], rowIndex, count); + tablet.setRowSize(rowIndex + count); + } + + @Override + protected void skipSegment(final int count) { + columnKind.skip(valuePage, Math.min(count, valuePage.valuesLeft())); + } +} diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/util/tablet/TabletPageReader.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/util/tablet/TabletPageReader.java new file mode 100644 index 0000000000000..588cc9d3d899f --- /dev/null +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/util/tablet/TabletPageReader.java @@ -0,0 +1,86 @@ +/* + * 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.iotdb.db.pipe.event.common.tsfile.parser.util.tablet; + +import org.apache.tsfile.write.record.Tablet; + +import java.io.IOException; + +/** + * A reader that decodes the pages of one chunk (or of one aligned chunk group) straight into the + * typed arrays of a {@link Tablet}, with no {@code BatchData} or {@code TsBlock} in between. + * + *

It is the common contract of the aligned chunk group reader, which serves both models, and of + * the non-aligned series reader of the tree model, so that the TsFile parser of a pipe only has to + * drive pages and tablets. + */ +public interface TabletPageReader extends AutoCloseable { + + /** Whether the current page still has a row that is not parsed. */ + boolean hasCurrentRow(); + + /** The number of rows of the current page that are not parsed. */ + int remainingRows(); + + /** The number of rows the current page holds, whatever the time range of the parser is. */ + int pageRowCount(); + + /** + * The uncompressed size of the variable length values of the current page, used to estimate the + * memory cost of the tablet that will be built from it. + */ + long binaryValueBytes(); + + /** The memory the decoded pages of the current page group occupy. */ + long currentPageRamBytes(); + + /** Whether the chunk has a page that is not parsed yet. */ + boolean hasNextPage(); + + /** + * The uncompressed bytes of the next page, used to reserve its memory before it is decompressed. + * The peek costs one header parse per column and consumes nothing, so a retry after an + * out-of-memory error can reserve the same page again. + */ + long peekNextPageBytes(); + + /** + * Moves to the next page that has a row in the time range of the parser. + * + * @return whether such a page exists + */ + boolean loadNextPage() throws IOException; + + /** + * Decodes the rows of the current page into the given tablet, starting at its current row. + * + * @param maxRows the number of rows the tablet can still hold + */ + void fillTablet(Tablet tablet, int maxRows); + + /** The present values of the current page per column, or null when they are not tracked. */ + long[] parsedCounts(); + + /** The values of the current page that survive per column, or null when they are not tracked. */ + long[] expectedCounts(); + + @Override + void close(); +} diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/event/TsFileInsertionEventParserTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/event/TsFileInsertionEventParserTest.java index 21eba2beaacb1..51d6aeb836fa0 100644 --- a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/event/TsFileInsertionEventParserTest.java +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/event/TsFileInsertionEventParserTest.java @@ -34,10 +34,9 @@ import org.apache.iotdb.db.pipe.event.common.tsfile.parser.TsFileInsertionEventParserMemoryManager; import org.apache.iotdb.db.pipe.event.common.tsfile.parser.TsFileInsertionEventParserProvider; import org.apache.iotdb.db.pipe.event.common.tsfile.parser.query.TsFileInsertionEventQueryParser; -import org.apache.iotdb.db.pipe.event.common.tsfile.parser.scan.AlignedSinglePageWholeChunkReader; -import org.apache.iotdb.db.pipe.event.common.tsfile.parser.scan.SinglePageWholeChunkReader; import org.apache.iotdb.db.pipe.event.common.tsfile.parser.scan.TsFileInsertionEventScanParser; import org.apache.iotdb.db.pipe.event.common.tsfile.parser.table.TsFileInsertionEventTableParser; +import org.apache.iotdb.db.pipe.event.common.tsfile.parser.util.tablet.ChunkDirectTabletReader; import org.apache.iotdb.db.pipe.resource.memory.PipeMemoryWeightUtil; import org.apache.iotdb.db.storageengine.dataregion.compaction.io.CompactionTsFileWriter; import org.apache.iotdb.db.storageengine.dataregion.compaction.schedule.constant.CompactionType; @@ -4413,9 +4412,10 @@ private long calculatePipeMaxReaderChunkSizeForSinglePageAlignedChunk(final File chunkSizeLimit += valueChunk.getHeader().getDataSize(); } - final long estimatedPageMemorySize = - AlignedSinglePageWholeChunkReader.calculatePageEstimatedMemoryUsageInBytes( - timeChunk, valueChunkList); + long estimatedPageMemorySize = ChunkDirectTabletReader.estimatePageBytes(timeChunk); + for (final Chunk valueChunk : valueChunkList) { + estimatedPageMemorySize += ChunkDirectTabletReader.estimatePageBytes(valueChunk); + } Assert.assertTrue(estimatedPageMemorySize > chunkSizeLimit); return chunkSizeLimit; } @@ -4439,9 +4439,7 @@ private long calculatePipeMaxReaderChunkSizeForSinglePageNonAlignedChunk(final F Assert.assertEquals( MetaMarker.ONLY_ONE_PAGE_CHUNK_HEADER, chunk.getHeader().getChunkType() & 0x3F); chunkSizeLimit += chunk.getHeader().getDataSize(); - estimatedPageMemorySize += - SinglePageWholeChunkReader.calculateMaxPageEstimatedMemoryUsageInBytesWithBatchData( - chunk); + estimatedPageMemorySize += ChunkDirectTabletReader.estimatePageBytes(chunk); } Assert.assertTrue(estimatedPageMemorySize > chunkSizeLimit); @@ -4463,15 +4461,13 @@ private long calculatePipeMaxReaderChunkSizeForMultiPageAlignedChunk(final File Assert.assertEquals(MetaMarker.CHUNK_HEADER, timeChunk.getHeader().getChunkType() & 0x3F); long chunkSizeLimit = PipeMemoryWeightUtil.calculateChunkRamBytesUsed(timeChunk); - long estimatedMaxPageMemorySize = - SinglePageWholeChunkReader.calculateMaxPageEstimatedMemoryUsageInBytes(timeChunk); + long estimatedMaxPageMemorySize = ChunkDirectTabletReader.estimatePageBytes(timeChunk); for (final IChunkMetadata valueChunkMetadata : alignedChunkMetadata.getValueChunkMetadataList()) { final Chunk valueChunk = reader.readMemChunk((ChunkMetadata) valueChunkMetadata); Assert.assertEquals(MetaMarker.CHUNK_HEADER, valueChunk.getHeader().getChunkType() & 0x3F); chunkSizeLimit += valueChunk.getHeader().getDataSize(); - estimatedMaxPageMemorySize += - SinglePageWholeChunkReader.calculateMaxPageEstimatedMemoryUsageInBytes(valueChunk); + estimatedMaxPageMemorySize += ChunkDirectTabletReader.estimatePageBytes(valueChunk); } Assert.assertTrue(estimatedMaxPageMemorySize > chunkSizeLimit); @@ -4509,14 +4505,14 @@ private long calculateFirstBatchedAlignedValueChunkGroupMemoryLimit( firstTwoBatchChunkSize += valueChunk.getHeader().getDataSize(); } - final long firstBatchPageMemorySize = - AlignedSinglePageWholeChunkReader - .calculateMaxPageEstimatedMemoryUsageInBytesWithBatchData( - timeChunk, firstValueChunkBatch); - final long firstTwoBatchPageMemorySize = - AlignedSinglePageWholeChunkReader - .calculateMaxPageEstimatedMemoryUsageInBytesWithBatchData( - timeChunk, firstTwoValueChunkBatches); + long firstBatchPageMemorySize = ChunkDirectTabletReader.estimatePageBytes(timeChunk); + for (final Chunk valueChunk : firstValueChunkBatch) { + firstBatchPageMemorySize += ChunkDirectTabletReader.estimatePageBytes(valueChunk); + } + long firstTwoBatchPageMemorySize = ChunkDirectTabletReader.estimatePageBytes(timeChunk); + for (final Chunk valueChunk : firstTwoValueChunkBatches) { + firstTwoBatchPageMemorySize += ChunkDirectTabletReader.estimatePageBytes(valueChunk); + } Assert.assertTrue(firstTwoBatchChunkSize > firstBatchChunkSize); Assert.assertTrue(firstTwoBatchPageMemorySize > firstBatchPageMemorySize); return Math.max(firstBatchChunkSize, firstBatchPageMemorySize); diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/scan/AlignedPageMemoryUsageEstimatorTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/scan/AlignedPageMemoryUsageEstimatorTest.java deleted file mode 100644 index 22ba15742fe4f..0000000000000 --- a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/scan/AlignedPageMemoryUsageEstimatorTest.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * 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.iotdb.db.pipe.event.common.tsfile.parser.scan; - -import org.apache.iotdb.commons.path.PartialPath; - -import org.apache.tsfile.common.conf.TSFileDescriptor; -import org.apache.tsfile.enums.TSDataType; -import org.apache.tsfile.file.MetaMarker; -import org.apache.tsfile.file.metadata.AbstractAlignedChunkMetadata; -import org.apache.tsfile.file.metadata.ChunkMetadata; -import org.apache.tsfile.file.metadata.IChunkMetadata; -import org.apache.tsfile.file.metadata.IDeviceID; -import org.apache.tsfile.file.metadata.enums.CompressionType; -import org.apache.tsfile.file.metadata.enums.TSEncoding; -import org.apache.tsfile.read.TsFileSequenceReader; -import org.apache.tsfile.read.common.Chunk; -import org.apache.tsfile.write.TsFileWriter; -import org.apache.tsfile.write.record.Tablet; -import org.apache.tsfile.write.schema.IMeasurementSchema; -import org.apache.tsfile.write.schema.MeasurementSchema; -import org.junit.Assert; -import org.junit.Test; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -public class AlignedPageMemoryUsageEstimatorTest { - - @Test - public void testIncrementalEstimatesMatchFullEstimates() throws Exception { - final int originalMaxNumberOfPointsInPage = - TSFileDescriptor.getInstance().getConfig().getMaxNumberOfPointsInPage(); - final File tsFile = new File("aligned-page-memory-estimator.tsfile"); - - try { - TSFileDescriptor.getInstance().getConfig().setMaxNumberOfPointsInPage(2); - if (tsFile.exists()) { - Assert.assertTrue(tsFile.delete()); - } - - final List schemas = new ArrayList<>(); - for (int i = 0; i < 4; ++i) { - schemas.add( - new MeasurementSchema( - "s" + i, TSDataType.INT64, TSEncoding.PLAIN, CompressionType.LZ4)); - } - final Tablet tablet = new Tablet("root.sg.d", schemas, 8); - for (int row = 0; row < 8; ++row) { - tablet.addTimestamp(row, row); - for (int measurement = 0; measurement < schemas.size(); ++measurement) { - tablet.addValue("s" + measurement, row, (long) row + measurement); - } - } - - try (final TsFileWriter writer = new TsFileWriter(tsFile)) { - writer.registerAlignedTimeseries(new PartialPath("root.sg.d"), schemas); - writer.writeAligned(tablet); - } - - try (final TsFileSequenceReader reader = new TsFileSequenceReader(tsFile.getAbsolutePath())) { - final IDeviceID deviceID = reader.getDeviceMeasurementsMap().keySet().iterator().next(); - final List alignedChunkMetadataList = - reader.getAlignedChunkMetadata(deviceID, true); - Assert.assertEquals(1, alignedChunkMetadataList.size()); - final AbstractAlignedChunkMetadata alignedChunkMetadata = alignedChunkMetadataList.get(0); - final Chunk timeChunk = - reader.readMemChunk((ChunkMetadata) alignedChunkMetadata.getTimeChunkMetadata()); - Assert.assertEquals(MetaMarker.CHUNK_HEADER, timeChunk.getHeader().getChunkType() & 0x3F); - - final List prefix = new ArrayList<>(); - final AlignedSinglePageWholeChunkReader.PageMemoryUsageEstimator estimator = - new AlignedSinglePageWholeChunkReader.PageMemoryUsageEstimator(timeChunk); - for (final IChunkMetadata valueChunkMetadata : - alignedChunkMetadata.getValueChunkMetadataList()) { - final Chunk valueChunk = reader.readMemChunk((ChunkMetadata) valueChunkMetadata); - Assert.assertEquals( - MetaMarker.CHUNK_HEADER, valueChunk.getHeader().getChunkType() & 0x3F); - - final long expectedWithCandidate = - AlignedSinglePageWholeChunkReader - .calculateMaxPageEstimatedMemoryUsageInBytesWithBatchData( - timeChunk, appendAndCopy(prefix, valueChunk)); - Assert.assertEquals( - expectedWithCandidate, - estimator.calculateMaxPageEstimatedMemoryUsageInBytesWithValueChunk(valueChunk)); - - estimator.addValueChunk(valueChunk); - prefix.add(valueChunk); - final List expectedPageMemoryUsage = - AlignedSinglePageWholeChunkReader - .calculatePageEstimatedMemoryUsageInBytesWithBatchDataList(timeChunk, prefix); - Assert.assertEquals( - expectedPageMemoryUsage, estimator.getPageEstimatedMemoryUsageInBytesList()); - } - } - } finally { - TSFileDescriptor.getInstance() - .getConfig() - .setMaxNumberOfPointsInPage(originalMaxNumberOfPointsInPage); - if (tsFile.exists()) { - Assert.assertTrue(tsFile.delete()); - } - } - } - - private List appendAndCopy(final List chunks, final Chunk chunk) { - final List copy = new ArrayList<>(chunks); - copy.add(chunk); - return copy; - } -} diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/scan/TreeScanPageBoundaryTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/scan/TreeScanPageBoundaryTest.java new file mode 100644 index 0000000000000..6e8c6148ee56b --- /dev/null +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/scan/TreeScanPageBoundaryTest.java @@ -0,0 +1,115 @@ +/* + * 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.iotdb.db.pipe.event.common.tsfile.parser.scan; + +import org.apache.iotdb.commons.conf.CommonDescriptor; +import org.apache.iotdb.commons.path.PartialPath; +import org.apache.iotdb.commons.pipe.datastructure.pattern.PrefixTreePattern; + +import org.apache.tsfile.common.conf.TSFileDescriptor; +import org.apache.tsfile.enums.TSDataType; +import org.apache.tsfile.file.metadata.enums.CompressionType; +import org.apache.tsfile.file.metadata.enums.TSEncoding; +import org.apache.tsfile.utils.Pair; +import org.apache.tsfile.write.TsFileWriter; +import org.apache.tsfile.write.record.Tablet; +import org.apache.tsfile.write.schema.IMeasurementSchema; +import org.apache.tsfile.write.schema.MeasurementSchema; +import org.junit.Assert; +import org.junit.Test; + +import java.io.File; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +/** + * A tablet that becomes full exactly at the boundary of a page of a multi-page chunk must not make + * the parser release the chunk: the next page of the chunk still holds rows. + */ +public class TreeScanPageBoundaryTest { + + private static final String DEVICE = "root.sg.d0"; + private static final int ROWS_PER_PAGE = 2048; + private static final int PAGE_COUNT = 3; + + @Test + public void testTabletFullAtAPageBoundaryKeepsTheRestOfTheChunk() throws Exception { + final int originalPointsInPage = + TSFileDescriptor.getInstance().getConfig().getMaxNumberOfPointsInPage(); + final int originalTabletRowSize = + CommonDescriptor.getInstance().getConfig().getPipeDataStructureTabletRowSize(); + final File file = File.createTempFile("tree-scan-page-boundary-", ".tsfile"); + try { + TSFileDescriptor.getInstance().getConfig().setMaxNumberOfPointsInPage(ROWS_PER_PAGE); + CommonDescriptor.getInstance().getConfig().setPipeDataStructureTabletRowSize(ROWS_PER_PAGE); + + final List schemas = + Collections.singletonList( + new MeasurementSchema("s0", TSDataType.INT64, TSEncoding.PLAIN, CompressionType.LZ4)); + final int rows = ROWS_PER_PAGE * PAGE_COUNT; + try (final TsFileWriter writer = new TsFileWriter(file)) { + writer.registerAlignedTimeseries(new PartialPath(DEVICE), schemas); + final Tablet tablet = new Tablet(DEVICE, schemas, rows); + for (int row = 0; row < rows; ++row) { + tablet.addTimestamp(row, row); + tablet.addValue("s0", row, (long) row); + } + writer.writeAligned(tablet); + } + + final Set timestamps = new HashSet<>(); + int firstTabletRows = -1; + try (final TsFileInsertionEventScanParser parser = + new TsFileInsertionEventScanParser( + file, + new PrefixTreePattern("root"), + Long.MIN_VALUE, + Long.MAX_VALUE, + null, + null, + false)) { + for (final Pair tabletWithIsAligned : parser.toTabletWithIsAligneds()) { + final Tablet parsedTablet = tabletWithIsAligned.getLeft(); + if (firstTabletRows < 0) { + firstTabletRows = parsedTablet.getRowSize(); + } + for (int row = 0; row < parsedTablet.getRowSize(); ++row) { + if (!parsedTablet.isNull(row, 0)) { + timestamps.add(parsedTablet.getTimestamp(row)); + } + } + } + } + + Assert.assertEquals(ROWS_PER_PAGE, firstTabletRows); + Assert.assertEquals(rows, timestamps.size()); + Assert.assertTrue(timestamps.contains(0L)); + Assert.assertTrue(timestamps.contains((long) rows - 1)); + } finally { + TSFileDescriptor.getInstance().getConfig().setMaxNumberOfPointsInPage(originalPointsInPage); + CommonDescriptor.getInstance() + .getConfig() + .setPipeDataStructureTabletRowSize(originalTabletRowSize); + Assert.assertTrue(file.delete()); + } + } +} diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/scan/TsFileInsertionEventScanParserContextTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/scan/TsFileInsertionEventScanParserContextTest.java index 7481329196c00..2433958b89991 100644 --- a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/scan/TsFileInsertionEventScanParserContextTest.java +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/scan/TsFileInsertionEventScanParserContextTest.java @@ -20,21 +20,20 @@ package org.apache.iotdb.db.pipe.event.common.tsfile.parser.scan; import org.apache.iotdb.commons.exception.pipe.PipeRuntimeOutOfMemoryCriticalException; +import org.apache.iotdb.db.pipe.event.common.tsfile.parser.util.tablet.TabletPageReader; import org.apache.iotdb.db.utils.TestFileEncryptionParameterProvider; import org.apache.tsfile.encrypt.EncryptParameter; import org.apache.tsfile.enums.TSDataType; -import org.apache.tsfile.file.header.ChunkHeader; import org.apache.tsfile.file.metadata.AbstractAlignedChunkMetadata; import org.apache.tsfile.file.metadata.ChunkMetadata; import org.apache.tsfile.file.metadata.IDeviceID; import org.apache.tsfile.file.metadata.enums.CompressionType; import org.apache.tsfile.file.metadata.enums.TSEncoding; import org.apache.tsfile.read.TsFileSequenceReader; -import org.apache.tsfile.read.common.BatchData; import org.apache.tsfile.read.common.Chunk; -import org.apache.tsfile.read.reader.IChunkReader; import org.apache.tsfile.write.chunk.AlignedChunkWriterImpl; +import org.apache.tsfile.write.record.Tablet; import org.apache.tsfile.write.schema.MeasurementSchema; import org.apache.tsfile.write.writer.TsFileIOWriter; import org.junit.After; @@ -93,26 +92,26 @@ public void testMultiPageConstructorFailureCanRetry() throws Exception { assertConstructorFailureCanRetry(true); } - private void assertConstructorFailureCanRetry(boolean multiPage) throws Exception { + private void assertConstructorFailureCanRetry(final boolean multiPage) throws Exception { TsFileInsertionEventScanParser parser = mock(TsFileInsertionEventScanParser.class, CALLS_REAL_METHODS); List chunks = readChunks(multiPage); try { Chunk time = chunks.get(0); Chunk originalValue = chunks.get(1); - ChunkHeader valueHeader = spy(originalValue.getHeader()); Chunk value = - new Chunk( - valueHeader, - originalValue.getData().duplicate(), - originalValue.getDeleteIntervalList(), - originalValue.getChunkStatistic(), - originalValue.getEncryptParam()); + spy( + new Chunk( + originalValue.getHeader(), + originalValue.getData().duplicate(), + originalValue.getDeleteIntervalList(), + originalValue.getChunkStatistic(), + originalValue.getEncryptParam())); chunks.set(1, value); originalValue.close(); AtomicBoolean fail = new AtomicBoolean(true); PipeRuntimeOutOfMemoryCriticalException expected = - new PipeRuntimeOutOfMemoryCriticalException("test constructor memory pressure"); + new PipeRuntimeOutOfMemoryCriticalException("test retaining memory pressure"); Answer failOnce = call -> { if (fail.getAndSet(false)) { @@ -120,46 +119,50 @@ private void assertConstructorFailureCanRetry(boolean multiPage) throws Exceptio } return call.callRealMethod(); }; - if (multiPage) { - doAnswer(failOnce).when(valueHeader).calculateDecoderForNonTimeChunk(); - } else { - doAnswer(failOnce).when(valueHeader).getEncodingType(); - } + doAnswer(failOnce).when(value).getData(); assertSame( expected, assertThrows( PipeRuntimeOutOfMemoryCriticalException.class, - () -> { - try (IChunkReader ignored = - parser.createAlignedChunkReader( - time, - Collections.singletonList(value), - multiPage, - Collections.emptyList())) { - // Unexpected success must not leak a reader while reporting the assertion. - } - })); + () -> + parser.createAlignedReader( + time, + Collections.singletonList(value), + Collections.singletonList(TSDataType.INT64), + Collections.emptyList(), + Long.MIN_VALUE, + Long.MAX_VALUE, + false, + false))); assertFalse(time.getEncryptParam().isDestroyed()); assertFalse(value.getEncryptParam().isDestroyed()); assertEquals(0, time.getData().position()); assertEquals(0, value.getData().position()); - try (IChunkReader reader = - parser.createAlignedChunkReader( - time, Collections.singletonList(value), multiPage, Collections.emptyList())) { + try (TabletPageReader reader = + parser.createAlignedReader( + time, + Collections.singletonList(value), + Collections.singletonList(TSDataType.INT64), + Collections.emptyList(), + Long.MIN_VALUE, + Long.MAX_VALUE, + false, + false)) { // Once construction succeeds, the pending group can release its original value chunks. value.close(); - int row = 0; - while (reader.hasNextSatisfiedPage()) { - BatchData data = reader.nextPageData(); - while (data.hasCurrent()) { - assertEquals(row, data.currentTime()); - assertEquals(row * 10L, data.getVector()[0].getLong()); - row++; - data.next(); + final Tablet tablet = new Tablet(DEVICE.toString(), Collections.singletonList(SCHEMA), 20); + while (reader.hasNextPage()) { + reader.loadNextPage(); + while (reader.hasCurrentRow()) { + reader.fillTablet(tablet, tablet.getMaxRowNumber() - tablet.getRowSize()); } } - assertEquals(20, row); + assertEquals(20, tablet.getRowSize()); + for (int row = 0; row < 20; row++) { + assertEquals(row, tablet.getTimestamps()[row]); + assertEquals(row * 10L, ((long[]) tablet.getValues()[0])[row]); + } } assertFalse(time.getEncryptParam().isDestroyed()); } finally { @@ -181,11 +184,15 @@ public void testPartialRetainFailureReleasesAttemptOnly() throws Exception { assertThrows( IllegalStateException.class, () -> - parser.createAlignedChunkReader( + parser.createAlignedReader( chunks.get(0), Arrays.asList(chunks.get(1), broken), + Collections.singletonList(TSDataType.INT64), + Collections.emptyList(), + Long.MIN_VALUE, + Long.MAX_VALUE, false, - Collections.emptyList()))); + false))); for (Chunk chunk : chunks) { assertFalse(chunk.getEncryptParam().isDestroyed()); } diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/util/ModsOperationUtilTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/util/ModsOperationUtilTest.java index 7eb09bbab41a3..a81e9fa48dca8 100644 --- a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/util/ModsOperationUtilTest.java +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/util/ModsOperationUtilTest.java @@ -74,10 +74,15 @@ public void testIsDeleteWithBinarySearch() { assertTrue(ModsOperationUtil.isDelete(75, modsInfo)); assertEquals(3, modsInfo.getCurrentIndex()); - // Time 85: after last mod, should return false and clear mods + // Time 85: after last mod, should return false and move the cursor past the end; the list is + // kept so that a later pass over the same page still sees the modifications assertFalse(ModsOperationUtil.isDelete(85, modsInfo)); - assertTrue(modsInfo.getMods().isEmpty()); - assertEquals(0, modsInfo.getCurrentIndex()); + assertEquals(4, modsInfo.getMods().size()); + assertEquals(4, modsInfo.getCurrentIndex()); + + // Rewinding the cursor makes the same modifications visible again + modsInfo.setCurrentIndex(0); + assertTrue(ModsOperationUtil.isDelete(15, modsInfo)); } @Test @@ -118,8 +123,8 @@ public void testIsDeleteWithSingleMod() { // Time after mod assertFalse(ModsOperationUtil.isDelete(25, modsInfo)); - assertTrue(modsInfo.getMods().isEmpty()); - assertEquals(0, modsInfo.getCurrentIndex()); + assertEquals(1, modsInfo.getMods().size()); + assertEquals(1, modsInfo.getCurrentIndex()); } @Test diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/table/TableChunkDirectTabletReaderDeleteIntervalTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/util/tablet/ChunkDirectTabletReaderDeleteIntervalTest.java similarity index 94% rename from iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/table/TableChunkDirectTabletReaderDeleteIntervalTest.java rename to iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/util/tablet/ChunkDirectTabletReaderDeleteIntervalTest.java index 7f00a4a9e29fc..7efd06a70df39 100644 --- a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/table/TableChunkDirectTabletReaderDeleteIntervalTest.java +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/util/tablet/ChunkDirectTabletReaderDeleteIntervalTest.java @@ -17,7 +17,7 @@ * under the License. */ -package org.apache.iotdb.db.pipe.event.common.tsfile.parser.table; +package org.apache.iotdb.db.pipe.event.common.tsfile.parser.util.tablet; import org.apache.tsfile.enums.ColumnCategory; import org.apache.tsfile.enums.TSDataType; @@ -50,7 +50,7 @@ * path, so they are reproduced here by wrapping the chunks read from a TsFile instead of being * written into one. */ -public class TableChunkDirectTabletReaderDeleteIntervalTest { +public class ChunkDirectTabletReaderDeleteIntervalTest { private static final String TABLE_NAME = "delete_interval_table"; private static final String TAG_COLUMN = "tag0"; @@ -103,9 +103,9 @@ public void testChunkDeleteIntervalsDropRowsAndNullCells() throws Exception { withDeleteIntervals( reader.readMemChunk((ChunkMetadata) valueChunkMetadataList.get(1)), null)); - TableChunkDirectTabletReader.fillDeviceIdColumns(deviceID, tablet, columnDataTypes, 1); - try (final TableChunkDirectTabletReader directReader = - new TableChunkDirectTabletReader( + ChunkDirectTabletReader.fillDeviceIdColumns(deviceID, tablet, columnDataTypes, 1); + try (final ChunkDirectTabletReader directReader = + new ChunkDirectTabletReader( timeChunk, valueChunks, fieldDataTypes, @@ -114,7 +114,9 @@ public void testChunkDeleteIntervalsDropRowsAndNullCells() throws Exception { Long.MAX_VALUE, false, null, - null)) { + null, + ChunkDirectTabletReader.RowRetention.KEEP_ALL_NULL_ROWS, + false)) { while (directReader.loadNextPage()) { while (directReader.hasCurrentRow()) { directReader.fillTablet(tablet, tablet.getMaxRowNumber() - tablet.getRowSize()); diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/table/TableChunkDirectTabletReaderTypeTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/util/tablet/ChunkDirectTabletReaderTypeTest.java similarity index 84% rename from iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/table/TableChunkDirectTabletReaderTypeTest.java rename to iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/util/tablet/ChunkDirectTabletReaderTypeTest.java index e84adf4d8af5c..903c35738cdbe 100644 --- a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/table/TableChunkDirectTabletReaderTypeTest.java +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/util/tablet/ChunkDirectTabletReaderTypeTest.java @@ -17,7 +17,7 @@ * under the License. */ -package org.apache.iotdb.db.pipe.event.common.tsfile.parser.table; +package org.apache.iotdb.db.pipe.event.common.tsfile.parser.util.tablet; import org.apache.iotdb.db.i18n.DataNodeQueryMessages; @@ -33,7 +33,7 @@ import java.util.Arrays; import java.util.Collections; -public class TableChunkDirectTabletReaderTypeTest { +public class ChunkDirectTabletReaderTypeTest { @Test public void testReaderAcceptsTheDataTypesOfTheTableModel() throws Exception { @@ -49,7 +49,7 @@ public void testReaderAcceptsTheDataTypesOfTheTableModel() throws Exception { TSDataType.STRING, TSDataType.BLOB, TSDataType.OBJECT)) { - try (final TableChunkDirectTabletReader reader = createReader(dataType)) { + try (final ChunkDirectTabletReader reader = createReader(dataType)) { Assert.assertFalse(reader.hasCurrentRow()); } } @@ -58,7 +58,7 @@ public void testReaderAcceptsTheDataTypesOfTheTableModel() throws Exception { @Test public void testReaderRejectsTheDataTypesWithoutATabletCell() throws Exception { for (final TSDataType dataType : Arrays.asList(TSDataType.VECTOR, TSDataType.UNKNOWN)) { - try (final TableChunkDirectTabletReader ignored = createReader(dataType)) { + try (final ChunkDirectTabletReader ignored = createReader(dataType)) { Assert.fail("the reader must reject the column of type " + dataType); } catch (final UnsupportedOperationException e) { Assert.assertEquals( @@ -69,11 +69,11 @@ public void testReaderRejectsTheDataTypesWithoutATabletCell() throws Exception { } } - private static TableChunkDirectTabletReader createReader(final TSDataType dataType) { + private static ChunkDirectTabletReader createReader(final TSDataType dataType) { final ChunkHeader timeHeader = new ChunkHeader( "time", 0, TSDataType.INT64, CompressionType.UNCOMPRESSED, TSEncoding.PLAIN, 0); - return new TableChunkDirectTabletReader( + return new ChunkDirectTabletReader( new Chunk(timeHeader, ByteBuffer.allocate(0)), Collections.singletonList(null), Collections.singletonList(dataType), @@ -82,6 +82,8 @@ private static TableChunkDirectTabletReader createReader(final TSDataType dataTy Long.MAX_VALUE, false, null, - null); + null, + ChunkDirectTabletReader.RowRetention.KEEP_ALL_NULL_ROWS, + false); } }