Skip to content
Merged
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,10 @@
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.apache.iotdb.db.utils.constant.TestConstant.avg;
Expand Down Expand Up @@ -3695,4 +3698,59 @@ public void negativeOrZeroTimeIntervalTest() {
.contains("The second parameter time interval should be a positive integer."));
}
}

/** Regression test for #19392: partial updates across flushes merge in strict priority order. */
@Test
public void partialUpdateMergeAcrossMultipleFlushesTest() throws SQLException {
try (Connection conn = EnvFactory.getEnv().getTableConnection();
Statement s = conn.createStatement()) {
s.execute(USE_DB);
s.execute("DROP TABLE IF EXISTS merge_lookahead_bug");
s.execute("CREATE TABLE merge_lookahead_bug (d STRING TAG, x INT64 FIELD, y INT64 FIELD)");
try {
// Ascending-scan scenario (#19392) on d1: verify before and after 3rd flush
s.execute("INSERT INTO merge_lookahead_bug(time,d,y) VALUES (10,'d1',100),(20,'d1',200)");
s.execute("FLUSH");
s.execute("INSERT INTO merge_lookahead_bug(time,d,y) VALUES (20,'d1',220)");
s.execute("FLUSH");
s.execute("INSERT INTO merge_lookahead_bug(time,d,x) VALUES (10,'d1',110),(20,'d1',120)");
for (int i = 0; i < 2; i++) {
if (i == 1) {
s.execute("FLUSH");
}
assertMergeRows(s, "d='d1' AND time=20", "20,120,220");
assertMergeRows(s, "d='d1' ORDER BY time", "10,110,100", "20,120,220");
assertMergeRows(s, "d='d1' ORDER BY time DESC", "20,120,220", "10,110,100");
assertMergeRows(s, "x=120 AND y=220 ORDER BY time", "20,120,220");
}

// Symmetric descending-scan scenario on d2: verify before and after 3rd flush
s.execute("INSERT INTO merge_lookahead_bug(time,d,y) VALUES (10,'d2',100),(20,'d2',200)");
s.execute("FLUSH");
s.execute("INSERT INTO merge_lookahead_bug(time,d,y) VALUES (10,'d2',120)");
s.execute("FLUSH");
s.execute("INSERT INTO merge_lookahead_bug(time,d,x) VALUES (10,'d2',110),(20,'d2',210)");
for (int i = 0; i < 2; i++) {
if (i == 1) {
s.execute("FLUSH");
}
assertMergeRows(s, "d='d2' ORDER BY time DESC", "20,210,200", "10,110,120");
assertMergeRows(s, "d='d2' AND x=110 AND y=120 ORDER BY time DESC", "10,110,120");
}
} finally {
s.execute("DROP TABLE IF EXISTS merge_lookahead_bug");
}
}
}

private void assertMergeRows(Statement s, String where, String... expected) throws SQLException {
String sql = "SELECT time, x, y FROM merge_lookahead_bug WHERE " + where;
List<String> actual = new ArrayList<>();
try (ResultSet rs = s.executeQuery(sql)) {
while (rs.next()) {
actual.add(rs.getLong(1) + "," + rs.getString(2) + "," + rs.getString(3));
}
}
assertEquals("Mismatch for query: " + sql, Arrays.asList(expected), actual);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,12 @@ public class AlignedDescPriorityMergeReader extends DescPriorityMergeReader {
* @param c TimeValuePair with low priority is used to fill the v
*/
@Override
protected void fillNullValue(TimeValuePair v, TimeValuePair c) {
AlignedPriorityMergeReader.fillNullValueInAligned(v, c);
protected boolean fillNullValue(TimeValuePair v, TimeValuePair c) {
return AlignedPriorityMergeReader.fillNullValueInAligned(v, c);
}

@Override
protected boolean canSkipOverwrittenNext(TimeValuePair topNext) {
return AlignedPriorityMergeReader.hasNoNullFields(topNext);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -35,18 +35,41 @@ public class AlignedPriorityMergeReader extends PriorityMergeReader {
* @param c TimeValuePair with low priority is used to fill the v
*/
@Override
protected void fillNullValue(TimeValuePair v, TimeValuePair c) {
fillNullValueInAligned(v, c);
protected boolean fillNullValue(TimeValuePair v, TimeValuePair c) {
return fillNullValueInAligned(v, c);
}

static void fillNullValueInAligned(TimeValuePair to, TimeValuePair from) {
@Override
protected boolean canSkipOverwrittenNext(TimeValuePair topNext) {
return hasNoNullFields(topNext);
}

static boolean hasNoNullFields(TimeValuePair pair) {
TsPrimitiveType value = pair.getValue();
if (value == null) {
return false;
}
for (TsPrimitiveType field : value.getVector()) {
if (field == null || field.getValue() == null) {
return false;
}
}
return true;
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have a performance concern here for wide rows. If only the last field is null, hasNoNullFields() scans the entire vector just to determine that the lower-priority point must stay in the heap. fillNullValueInAligned() then scans the row again when the points are merged. In an in-memory microbenchmark with 256 fields and two readers whose timestamps fully overlapped, this case took about 210 ns per output row, compared with 130 ns with look-ahead skipping disabled. Could we track whether the row is complete while building the vector and check that flag here? That would preserve the fast path for complete rows while avoiding the extra scan.

@samyak-jain-dev samyak-jain-dev Nov 26, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes total sense, thanks for benchmarking that! I removed hasNoNullFields() in 304bf2c and instead tracked completeness while building each row via a small AlignedPointReader interface across the TsBlock and AlignedTVList iterators (since TsVector is in tsfile). PriorityMergeReader now just checks that cached boolean in O(1), and all unit tests + the table IT pass locally. Ready for another look whenever you get a chance!


static boolean fillNullValueInAligned(TimeValuePair to, TimeValuePair from) {
TsPrimitiveType[] toArray = to.getValue().getVector();
TsPrimitiveType[] fromArray = from.getValue().getVector();
boolean allFilled = true;
for (int i = 0, size = toArray.length; i < size; i++) {
if ((toArray[i] == null || toArray[i].getValue() == null)
&& (fromArray[i] != null && fromArray[i].getValue() != null)) {
toArray[i] = fromArray[i];
if (toArray[i] == null || toArray[i].getValue() == null) {
if (fromArray[i] != null && fromArray[i].getValue() != null) {
toArray[i] = fromArray[i];
} else {
allFilled = false;
}
}
}
return allFilled;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -123,44 +123,54 @@ public TimeValuePair currentTimeValuePair() throws IOException {
*/
protected void updateHeap(TimeValuePair ret, TimeValuePair topNext) throws IOException {
long topTime = ret.getTimestamp();
long topNextTime = (topNext == null ? Long.MAX_VALUE : topNext.getTimestamp());
long topNextTime = topNext == null ? 0L : topNext.getTimestamp();
int canSkipNext = topNext == null ? 0 : -1;
boolean retComplete = false;
while (!heap.isEmpty() && heap.peek().currTime() == topTime) {
Element e = heap.poll();
fillNullValue(ret, e.getTimeValuePair());
if (!retComplete) {
retComplete = fillNullValue(ret, e.getTimeValuePair());
}
if (!e.hasNext()) {
long size = e.getReader().getUsedMemorySize();
usedMemorySize -= size;
if (memoryReservationManager != null) {
memoryReservationManager.releaseMemoryCumulatively(size);
}
e.getReader().close();
releaseAndCloseElement(e);
continue;
}
e.next();
if (e.currTime() == topNextTime) {
// if the next value of the peek will be overwritten by the next of the top, skip it
fillNullValue(topNext, e.getTimeValuePair());
if (e.hasNext()) {
e.next();
heap.add(e);
} else {
long size = e.getReader().getUsedMemorySize();
usedMemorySize -= size;
if (memoryReservationManager != null) {
memoryReservationManager.releaseMemoryCumulatively(size);
if (canSkipNext != 0 && e.currTime() == topNextTime) {
if (canSkipNext < 0) {
canSkipNext = canSkipOverwrittenNext(topNext) ? 1 : 0;
}
if (canSkipNext == 1) {
// if the next value of the peek will be overwritten by the next of the top, skip it
if (!e.hasNext()) {
// the chunk is end
releaseAndCloseElement(e);
continue;
}
// the chunk is end
e.close();
e.next();
}
} else {
heap.add(e);
}
heap.add(e);
}
}

/** this method only take effect for aligned time series, so the override version. */
protected void fillNullValue(TimeValuePair v, TimeValuePair c) {
// do nothing for non-aligned time series
private void releaseAndCloseElement(Element e) throws IOException {
long size = e.getReader().getUsedMemorySize();
usedMemorySize -= size;
if (memoryReservationManager != null) {
memoryReservationManager.releaseMemoryCumulatively(size);
}
e.close();
}

/** Whether {@code topNext} completely overwrites lower-priority points at its timestamp. */
protected boolean canSkipOverwrittenNext(TimeValuePair topNext) {
return true;
}

/** Fills null sub-sensor slots in {@code v} from {@code c}; returns true when none remain. */
protected boolean fillNullValue(TimeValuePair v, TimeValuePair c) {
return true;
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,22 @@
*/
package org.apache.iotdb.db.storageengine.dataregion.read.reader.common;

import org.apache.tsfile.enums.TSDataType;
import org.apache.tsfile.read.TimeValuePair;
import org.apache.tsfile.read.common.BatchData;
import org.apache.tsfile.utils.Binary;
import org.apache.tsfile.utils.TsPrimitiveType;
import org.apache.tsfile.utils.TsPrimitiveType.TsBinary;
import org.apache.tsfile.utils.TsPrimitiveType.TsInt;
import org.apache.tsfile.utils.TsPrimitiveType.TsLong;
import org.apache.tsfile.utils.TsPrimitiveType.TsVector;
import org.junit.Test;

import java.io.IOException;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

public class AlignedPriorityMergeReaderTest {

Expand Down Expand Up @@ -87,4 +96,115 @@ public void test3() {
assertEquals(20, v.getValue().getVector()[1].getInt());
assertEquals(30, v.getValue().getVector()[2].getInt());
}

@Test
public void testAscScanMergesMiddlePriorityReaderAtNextTimestamp() throws IOException {
assertMiddlePriorityMerge(new AlignedPriorityMergeReader(), 10L, 20L);
}

@Test
public void testDescScanMergesMiddlePriorityReaderAtNextTimestamp() throws IOException {
assertMiddlePriorityMerge(new AlignedDescPriorityMergeReader(), 20L, 10L);
}

private void assertMiddlePriorityMerge(PriorityMergeReader reader, long t1, long t2)
throws IOException {
addBatch(reader, 1, t2, batch(t1, vec(null, 100L), t2, vec(null, 200L)));
addBatch(reader, 2, t2, batch(t2, vec(null, 220L)));
addBatch(reader, 3, t2, batch(t1, vec(110L, null), t2, vec(120L, null)));

assertLongRow(reader.nextTimeValuePair(), t1, 110L, 100L);
assertLongRow(reader.nextTimeValuePair(), t2, 120L, 220L);
assertFalse(reader.hasNextTimeValuePair());
}

@Test
public void testAscScanPreservesOlderColumnsWhileMiddleOverridesOverlappingColumn()
throws IOException {
AlignedPriorityMergeReader reader = new AlignedPriorityMergeReader();
addBatch(reader, 1, 20L, batch(10L, vec(null, 100L, 1000L), 20L, vec(null, 200L, 2000L)));
addBatch(reader, 2, 20L, batch(20L, vec(null, 220L, null)));
addBatch(reader, 3, 20L, batch(10L, vec(110L, null, null), 20L, vec(120L, null, null)));

assertLongRow(reader.nextTimeValuePair(), 10L, 110L, 100L, 1000L);
assertLongRow(reader.nextTimeValuePair(), 20L, 120L, 220L, 2000L);
assertFalse(reader.hasNextTimeValuePair());
}

@Test
public void testSkipOlderReaderOnlyWhenNextAlignedRowIsComplete() throws IOException {
assertFalse(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we also add direct unit tests covering isLastRowComplete() on AlignedTVListIterator and MultiAlignedTVListIterator (OrderedMultiAlignedTVListIterator and MergeSortMultiAlignedTVListIterator) for complete vs. incomplete rows (including null TsBinary / deleted column cases)? Right now unit tests only exercise TsBlockAlignedRowPointReader and the non-AlignedPointReader fallback directly.

AlignedPriorityMergeReader.fillNullValueInAligned(
new TimeValuePair(1, new TsVector(vec(10L, null, null))),
new TimeValuePair(1, new TsVector(vec(null, 20L, null)))));
assertTrue(
AlignedPriorityMergeReader.fillNullValueInAligned(
new TimeValuePair(1, new TsVector(vec(10L, null))),
new TimeValuePair(1, new TsVector(vec(null, 20L)))));

assertCompleteRowSkip(new AlignedPriorityMergeReader(), 10L, 20L, 30L);
assertCompleteRowSkip(new AlignedDescPriorityMergeReader(), 30L, 20L, 10L);
}

private void assertCompleteRowSkip(PriorityMergeReader reader, long t1, long t2, long t3)
throws IOException {
TsBinary oldVal = new TsBinary(new Binary(new byte[] {1}));
TsBinary emptyVal = new TsBinary(Binary.EMPTY_VALUE);

BatchData older = new BatchData(TSDataType.VECTOR);
for (long t : new long[] {t1, t2, t3}) {
older.putVector(t, new TsPrimitiveType[] {null, oldVal});
}
BatchData newer = new BatchData(TSDataType.VECTOR);
newer.putVector(t1, new TsPrimitiveType[] {new TsLong(10L), emptyVal});
newer.putVector(t2, new TsPrimitiveType[] {new TsLong(20L), new TsBinary()});
newer.putVector(t3, new TsPrimitiveType[] {new TsLong(30L), emptyVal});

addBatch(reader, 1, t3, older);
addBatch(reader, 2, t3, newer);

// topNext (t2) has a null-valued TsBinary, so older stays in the heap; at t2, topNext (t3) is
// complete, so older is skipped and closed immediately.
assertEquals(emptyVal, reader.nextTimeValuePair().getValue().getVector()[1]);
assertEquals(2, reader.heap.size());
assertEquals(oldVal, reader.nextTimeValuePair().getValue().getVector()[1]);
assertEquals(1, reader.heap.size());
assertEquals(emptyVal, reader.nextTimeValuePair().getValue().getVector()[1]);
assertFalse(reader.hasNextTimeValuePair());
}

private static void addBatch(PriorityMergeReader reader, int prio, long endTime, BatchData data)
throws IOException {
reader.addReader(
data.getBatchDataIterator(), new MergeReaderPriority(prio, 1, 0, false), endTime);
}

private static BatchData batch(long t1, TsPrimitiveType[] v1) {
BatchData b = new BatchData(TSDataType.VECTOR);
b.putVector(t1, v1);
return b;
}

private static BatchData batch(long t1, TsPrimitiveType[] v1, long t2, TsPrimitiveType[] v2) {
BatchData b = batch(t1, v1);
b.putVector(t2, v2);
return b;
}

private static TsPrimitiveType[] vec(Long... values) {
TsPrimitiveType[] v = new TsPrimitiveType[values.length];
for (int i = 0; i < values.length; i++) {
if (values[i] != null) {
v[i] = new TsLong(values[i]);
}
}
return v;
}

private static void assertLongRow(TimeValuePair row, long expectedTime, long... expectedValues) {
assertEquals(expectedTime, row.getTimestamp());
for (int i = 0; i < expectedValues.length; i++) {
assertEquals(expectedValues[i], row.getValue().getVector()[i].getLong());
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,15 @@ public void test1() throws IOException {
new long[] {4, 6});
}

@Test
public void testPointAtLongMaxValueNotSkippedWhenTopEnds() throws IOException {
testAscAndDescPriorityMergeReader(
new long[] {10, Long.MAX_VALUE},
new long[] {2, 1},
new long[] {10, Long.MAX_VALUE},
new long[] {10});
}

private void testAscAndDescPriorityMergeReader(
long[] retTimestamp, long[] retValue, long[]... sourceTimestamps) throws IOException {
testAsc(retTimestamp, retValue, sourceTimestamps);
Expand Down Expand Up @@ -100,6 +109,7 @@ private void testAsc(long[] retTimestamp, long[] retValue, long[]... sourceTimes
assertEquals(retValue[i], timeValuePair.getValue().getValue());
i++;
}
assertEquals(retTimestamp.length, i);
}

private void testDesc(long[] retTimestamp, long[] retValue, long[]... sourceTimestamps)
Expand Down Expand Up @@ -129,6 +139,7 @@ private void testDesc(long[] retTimestamp, long[] retValue, long[]... sourceTime
assertEquals(retValue[i], timeValuePair.getValue().getValue());
i--;
}
assertEquals(-1, i);
}

@Test
Expand Down
Loading