From 10cca83981b84ba0371cf43e4ea0d2072fe9b7e3 Mon Sep 17 00:00:00 2001 From: DaZuiZui Date: Fri, 4 Dec 2026 11:03:11 +0800 Subject: [PATCH 1/5] fix(java): preserve null bitmaps when editing deserialized tablets --- .../apache/tsfile/write/record/Tablet.java | 32 +++++--- .../tsfile/write/record/TabletTest.java | 77 +++++++++++++++++++ skills/tsfile/references/advanced-apis.md | 2 + 3 files changed, 102 insertions(+), 9 deletions(-) diff --git a/java/tsfile/src/main/java/org/apache/tsfile/write/record/Tablet.java b/java/tsfile/src/main/java/org/apache/tsfile/write/record/Tablet.java index 1b1010c01..ce243456c 100644 --- a/java/tsfile/src/main/java/org/apache/tsfile/write/record/Tablet.java +++ b/java/tsfile/src/main/java/org/apache/tsfile/write/record/Tablet.java @@ -91,10 +91,13 @@ public class Tablet implements Accountable { private BitMap[] bitMaps; - /** - * For compatibility with the usage of directly modifying Tablet content through public fields. - */ - private boolean autoUpdateBitMaps = false; + private enum BitMapMode { + DIRECT, + DESERIALIZED, + AUTO + } + + private BitMapMode bitMapMode = BitMapMode.DIRECT; private int rowSize; @@ -539,11 +542,17 @@ private void initBitMapsWithApiUsage() { if (bitMaps == null) { initBitMaps(); } - if (!autoUpdateBitMaps) { - autoUpdateBitMaps = true; - for (BitMap bitMap : bitMaps) { - bitMap.markAll(); + if (bitMapMode != BitMapMode.AUTO) { + for (int i = 0; i < bitMaps.length; i++) { + if (bitMaps[i] == null) { + // A serialized column without nulls has no bitmap. + bitMaps[i] = new BitMap(maxRowNumber); + } + if (bitMapMode == BitMapMode.DIRECT) { + bitMaps[i].markAll(); + } } + bitMapMode = BitMapMode.AUTO; } } @@ -559,12 +568,16 @@ public int getMaxRowNumber() { /** Reset Tablet to the default state - set the rowSize to 0 and reset bitMaps */ public void reset() { this.rowSize = 0; + if (bitMapMode == BitMapMode.DESERIALIZED) { + // No API writes yet. Allow the caller to refill the arrays directly. + bitMapMode = BitMapMode.DIRECT; + } if (bitMaps != null) { for (BitMap bitMap : bitMaps) { if (bitMap == null) { continue; } - if (autoUpdateBitMaps) { + if (bitMapMode == BitMapMode.AUTO) { bitMap.markAll(); } else { bitMap.reset(); @@ -877,6 +890,7 @@ public static Tablet deserialize(ByteBuffer byteBuffer) { Tablet tablet = new Tablet(deviceId, schemas, columnCategories, times, values, bitMaps, rowSize); + tablet.bitMapMode = BitMapMode.DESERIALIZED; tablet.constructMeasurementIndexMap(); return tablet; } diff --git a/java/tsfile/src/test/java/org/apache/tsfile/write/record/TabletTest.java b/java/tsfile/src/test/java/org/apache/tsfile/write/record/TabletTest.java index 358f2d85f..f0b3dcea6 100644 --- a/java/tsfile/src/test/java/org/apache/tsfile/write/record/TabletTest.java +++ b/java/tsfile/src/test/java/org/apache/tsfile/write/record/TabletTest.java @@ -195,6 +195,83 @@ public void testAddValue() { Assert.assertTrue(tablet.getBitMaps()[0].isAllMarked()); } + @Test + public void testEditDeserializedTabletPreservesOtherRows() throws IOException { + Tablet tablet = + new Tablet("root.sg.d1", List.of(new MeasurementSchema("s", TSDataType.INT32)), 3); + tablet.addTimestamp(0, 10); + tablet.addValue(0, 0, 70); + tablet.addTimestamp(1, 20); + tablet.addValue(1, 0, 80); + tablet.addTimestamp(2, 30); + + Tablet copy = Tablet.deserialize(tablet.serialize()); + copy.addValue(0, 0, 71); + Tablet reread = Tablet.deserialize(copy.serialize()); + assertEquals(71, reread.getValue(0, 0)); + assertEquals(80, reread.getValue(1, 0)); + assertNull(reread.getValue(2, 0)); + + copy.reset(); + copy.addTimestamp(0, 40); + assertNull(copy.getValue(0, 0)); + } + + @Test + public void testEditDeserializedTabletWithOmittedColumnBitMap() throws IOException { + Tablet tablet = + new Tablet("root.sg.d1", List.of(new MeasurementSchema("s", TSDataType.INT32)), 2); + tablet.addTimestamp(0, 10); + tablet.addValue(0, 0, 70); + tablet.addTimestamp(1, 20); + tablet.addValue(1, 0, 80); + + Tablet copy = Tablet.deserialize(tablet.serialize()); + copy.addValue("s", 0, null); + assertNull(copy.getValue(0, 0)); + assertEquals(80, copy.getValue(1, 0)); + } + + @Test + public void testEditDeserializedTabletWithoutBitMaps() throws IOException { + Tablet tablet = + new Tablet( + "root.sg.d1", + List.of(new MeasurementSchema("s", TSDataType.INT32)), + new long[] {10, 20}, + new Object[] {new int[] {70, 80}}, + null, + 2); + + Tablet copy = Tablet.deserialize(tablet.serialize()); + copy.addTimestamp(0, 11); + assertEquals(70, copy.getValue(0, 0)); + assertEquals(80, copy.getValue(1, 0)); + copy.addValue("s", 0, null); + assertNull(copy.getValue(0, 0)); + assertEquals(80, copy.getValue(1, 0)); + } + + @Test + public void testResetDeserializedTabletBeforeFirstEdit() throws IOException { + Tablet tablet = + new Tablet("root.sg.d1", List.of(new MeasurementSchema("s", TSDataType.INT32)), 2); + tablet.addTimestamp(0, 10); + tablet.addTimestamp(1, 20); + tablet.addValue(1, 0, 80); + + Tablet copy = Tablet.deserialize(tablet.serialize()); + copy.reset(); + copy.getTimestamps()[0] = 30; + ((int[]) copy.getValues()[0])[0] = 90; + copy.setRowSize(1); + assertEquals(90, copy.getValue(0, 0)); + + copy.reset(); + copy.addTimestamp(0, 40); + assertNull(copy.getValue(0, 0)); + } + @Test public void testSerializationAndDeSerialization() { final String deviceId = "root.sg"; diff --git a/skills/tsfile/references/advanced-apis.md b/skills/tsfile/references/advanced-apis.md index 23005997f..6f1d44e4b 100644 --- a/skills/tsfile/references/advanced-apis.md +++ b/skills/tsfile/references/advanced-apis.md @@ -91,6 +91,8 @@ the current `TableSchema`; do not infer constructor positions from memory. a measurement name or column index and a `String` or `byte[]` path. - Use `Tablet.serializedSize()` to allocate or validate the serialized Tablet payload. Do not replace it with a RAM-size estimate. +- After `Tablet.deserialize(...)`, use `addValue` or `addTimestamp` to edit + an existing row. Other cells retain their values and null flags. ## Custom and Buffered Input From b9838afc92e042208fb2c2907a36bba84598ae63 Mon Sep 17 00:00:00 2001 From: DaZuiZui Date: Fri, 4 Dec 2026 11:43:51 +0800 Subject: [PATCH 2/5] Preserve populated tablet cells and initialize reserved rows as null --- .../apache/tsfile/write/record/Tablet.java | 61 ++++++++++--------- .../tsfile/write/record/TabletTest.java | 60 ++++++++++++++++++ skills/tsfile/references/advanced-apis.md | 8 ++- 3 files changed, 98 insertions(+), 31 deletions(-) diff --git a/java/tsfile/src/main/java/org/apache/tsfile/write/record/Tablet.java b/java/tsfile/src/main/java/org/apache/tsfile/write/record/Tablet.java index ce243456c..6c3483115 100644 --- a/java/tsfile/src/main/java/org/apache/tsfile/write/record/Tablet.java +++ b/java/tsfile/src/main/java/org/apache/tsfile/write/record/Tablet.java @@ -93,7 +93,7 @@ public class Tablet implements Accountable { private enum BitMapMode { DIRECT, - DESERIALIZED, + POPULATED, AUTO } @@ -234,17 +234,14 @@ public Tablet( Object[] values, BitMap[] bitMaps, int maxRowNumber) { - this.insertTargetName = deviceId; - this.schemas = schemas; - setColumnCategories(ColumnCategory.nCopy(ColumnCategory.FIELD, schemas.size())); - this.timestamps = timestamps; - this.values = values; - this.bitMaps = bitMaps; - this.maxRowNumber = maxRowNumber; - // rowSize == maxRowNumber in this case - this.rowSize = maxRowNumber; - measurementIndex = new HashMap<>(); - constructMeasurementIndexMap(); + this( + deviceId, + schemas, + ColumnCategory.nCopy(ColumnCategory.FIELD, schemas.size()), + timestamps, + values, + bitMaps, + maxRowNumber); } @TableModel @@ -262,6 +259,7 @@ public Tablet( this.timestamps = timestamps; this.values = values; this.bitMaps = bitMaps; + this.bitMapMode = BitMapMode.POPULATED; this.maxRowNumber = maxRowNumber; // rowSize == maxRowNumber in this case this.rowSize = maxRowNumber; @@ -296,8 +294,8 @@ public void initBitMaps() { @TsFileApi public void addTimestamp(int rowIndex, long timestamp) { timestamps[rowIndex] = timestamp; - this.rowSize = Math.max(this.rowSize, rowIndex + 1); initBitMapsWithApiUsage(); + this.rowSize = Math.max(this.rowSize, rowIndex + 1); } public void addValue(final String measurementId, final int rowIndex, final Object value) { @@ -539,20 +537,25 @@ private void updateBitMap(int rowIndex, int columnIndex, boolean mark) { } private void initBitMapsWithApiUsage() { + if (bitMapMode != BitMapMode.AUTO || bitMaps == null) { + initializeBitMapsFromRow(bitMapMode == BitMapMode.DIRECT ? 0 : rowSize); + bitMapMode = BitMapMode.AUTO; + } + } + + private void initializeBitMapsFromRow(int firstNullRow) { if (bitMaps == null) { initBitMaps(); } - if (bitMapMode != BitMapMode.AUTO) { - for (int i = 0; i < bitMaps.length; i++) { - if (bitMaps[i] == null) { - // A serialized column without nulls has no bitmap. - bitMaps[i] = new BitMap(maxRowNumber); - } - if (bitMapMode == BitMapMode.DIRECT) { - bitMaps[i].markAll(); - } + for (int i = 0; i < bitMaps.length; i++) { + if (bitMaps[i] == null) { + bitMaps[i] = new BitMap(maxRowNumber); + } + if (firstNullRow == 0) { + bitMaps[i].markAll(); + } else { + bitMaps[i].markRange(firstNullRow, maxRowNumber - firstNullRow); } - bitMapMode = BitMapMode.AUTO; } } @@ -568,7 +571,7 @@ public int getMaxRowNumber() { /** Reset Tablet to the default state - set the rowSize to 0 and reset bitMaps */ public void reset() { this.rowSize = 0; - if (bitMapMode == BitMapMode.DESERIALIZED) { + if (bitMapMode == BitMapMode.POPULATED) { // No API writes yet. Allow the caller to refill the arrays directly. bitMapMode = BitMapMode.DIRECT; } @@ -888,11 +891,7 @@ public static Tablet deserialize(ByteBuffer byteBuffer) { values = readvaluesFromBuffer(byteBuffer, dataTypes, columnCategories, schemaSize, rowSize); } - Tablet tablet = - new Tablet(deviceId, schemas, columnCategories, times, values, bitMaps, rowSize); - tablet.bitMapMode = BitMapMode.DESERIALIZED; - tablet.constructMeasurementIndexMap(); - return tablet; + return new Tablet(deviceId, schemas, columnCategories, times, values, bitMaps, rowSize); } /** deserialize bitmaps */ @@ -1236,6 +1235,10 @@ public boolean append(Tablet another, int preferredCapacity) { maxRowNumber = Math.max(preferredCapacity, Math.max(maxRowNumber, rowSize + another.rowSize)); rowSize = rowSize + another.rowSize; + int firstReservedRow = Math.max(prevCapacity, rowSize); + if (bitMapMode == BitMapMode.AUTO && firstReservedRow < maxRowNumber) { + initializeBitMapsFromRow(firstReservedRow); + } return true; } diff --git a/java/tsfile/src/test/java/org/apache/tsfile/write/record/TabletTest.java b/java/tsfile/src/test/java/org/apache/tsfile/write/record/TabletTest.java index f0b3dcea6..1a01effaa 100644 --- a/java/tsfile/src/test/java/org/apache/tsfile/write/record/TabletTest.java +++ b/java/tsfile/src/test/java/org/apache/tsfile/write/record/TabletTest.java @@ -252,6 +252,66 @@ public void testEditDeserializedTabletWithoutBitMaps() throws IOException { assertEquals(80, copy.getValue(1, 0)); } + @Test + public void testEditTabletWithSuppliedColumns() { + List schemas = + List.of( + new MeasurementSchema("a", TSDataType.INT32), + new MeasurementSchema("b", TSDataType.INT32)); + for (boolean tableModel : new boolean[] {false, true}) { + long[] timestamps = {10, 20}; + Object[] values = {new int[] {1, 2}, new int[] {3, 4}}; + BitMap[] bitMaps = {null, new BitMap(2)}; + bitMaps[1].mark(0); + Tablet tablet = + tableModel + ? new Tablet( + "t", + schemas, + List.of(ColumnCategory.FIELD, ColumnCategory.FIELD), + timestamps, + values, + bitMaps, + 2) + : new Tablet("root.sg.d1", schemas, timestamps, values, bitMaps, 2); + + tablet.addTimestamp(0, 11); + assertEquals(2, tablet.getValue(1, 0)); + tablet.addValue("a", 1, null); + assertEquals(1, tablet.getValue(0, 0)); + assertNull(tablet.getValue(1, 0)); + assertNull(tablet.getValue(0, 1)); + assertEquals(4, tablet.getValue(1, 1)); + } + } + + @Test + public void testTimestampOnlyRowsAfterAppendingToDeserializedTablet() throws IOException { + List schemas = + List.of( + new MeasurementSchema("a", TSDataType.INT32), + new MeasurementSchema("b", TSDataType.INT32)); + Tablet source = new Tablet("root.sg.d1", schemas, 1); + source.addTimestamp(0, 10); + source.addValue(0, 0, 1); + Tablet target = Tablet.deserialize(source.serialize()); + + assertTrue(target.append(source, 4)); + target.addTimestamp(2, 30); + assertEquals(1, target.getValue(0, 0)); + assertEquals(1, target.getValue(1, 0)); + assertNull(target.getValue(1, 1)); + assertNull(target.getValue(2, 0)); + assertNull(target.getValue(2, 1)); + + assertTrue(target.append(source, 16)); + target.addTimestamp(8, 90); + assertEquals(1, target.getValue(3, 0)); + assertNull(target.getValue(3, 1)); + assertNull(target.getValue(8, 0)); + assertNull(target.getValue(8, 1)); + } + @Test public void testResetDeserializedTabletBeforeFirstEdit() throws IOException { Tablet tablet = diff --git a/skills/tsfile/references/advanced-apis.md b/skills/tsfile/references/advanced-apis.md index 6f1d44e4b..a6641a1bc 100644 --- a/skills/tsfile/references/advanced-apis.md +++ b/skills/tsfile/references/advanced-apis.md @@ -91,8 +91,12 @@ the current `TableSchema`; do not infer constructor positions from memory. a measurement name or column index and a `String` or `byte[]` path. - Use `Tablet.serializedSize()` to allocate or validate the serialized Tablet payload. Do not replace it with a RAM-size estimate. -- After `Tablet.deserialize(...)`, use `addValue` or `addTimestamp` to edit - an existing row. Other cells retain their values and null flags. +- When a Tablet is deserialized or constructed with populated arrays, editing + an existing row with `addValue` or `addTimestamp` preserves the values and + null flags of other cells. An omitted column bitmap means its values are + all present. +- If `append(other, preferredCapacity)` reserves space beyond the last row, + use `addTimestamp` to add a row there. Its values are null until set. ## Custom and Buffered Input From 3795d25e3c80fbe82eb92493633a2073bf518472 Mon Sep 17 00:00:00 2001 From: DaZuiZui Date: Fri, 4 Dec 2026 14:44:07 +0800 Subject: [PATCH 3/5] Fix bitmap handling for reserved and compacted tablet rows Use the previous logical capacity when growing existing bitmaps. Preserve values written ahead of their timestamps and extend trimmed maps before marking new rows. Keep omitted bitmaps sparse during append and avoid bitmap preparation on the normal API write path. Cover oversized backing arrays, trimmed and partially compacted bitmaps, and timestamp-only writes. Update the Java SDK reference. CLI behavior and the wire format are unchanged. Verified with JDK 21 and ./mvnw -P with-java clean verify (27 TabletTest cases). A TsFile write/readback retained values at times 10, 20 and 30 and yielded no stale point at time 40. Single-thread JMH, Apple M4, JDK 21.0.10, median of three forks. Name-based inserts took 160.87 / 174.32 / 144.47 us per batch on base / reviewed / fixed. Compact append took 14.47 / 17.69 / 14.78 us and allocated 306576 / 343712 / 306584 bytes per batch. --- .../apache/tsfile/write/record/Tablet.java | 157 ++++++++++-------- .../tsfile/write/record/TabletTest.java | 118 +++++++++++++ skills/tsfile/references/advanced-apis.md | 6 +- 3 files changed, 207 insertions(+), 74 deletions(-) diff --git a/java/tsfile/src/main/java/org/apache/tsfile/write/record/Tablet.java b/java/tsfile/src/main/java/org/apache/tsfile/write/record/Tablet.java index 6c3483115..7447110f9 100644 --- a/java/tsfile/src/main/java/org/apache/tsfile/write/record/Tablet.java +++ b/java/tsfile/src/main/java/org/apache/tsfile/write/record/Tablet.java @@ -98,6 +98,10 @@ private enum BitMapMode { } private BitMapMode bitMapMode = BitMapMode.DIRECT; + // All columns have writable bitmaps with null flags initialized through maxRowNumber. + private boolean bitMapsReady; + // Callers can trim or remove individual bitmaps through an array they retain. + private boolean bitMapsShared; private int rowSize; @@ -259,6 +263,7 @@ public Tablet( this.timestamps = timestamps; this.values = values; this.bitMaps = bitMaps; + this.bitMapsShared = bitMaps != null; this.bitMapMode = BitMapMode.POPULATED; this.maxRowNumber = maxRowNumber; // rowSize == maxRowNumber in this case @@ -287,14 +292,21 @@ public void initBitMaps() { this.bitMaps = new BitMap[schemas.size()]; for (int column = 0; column < schemas.size(); column++) { BitMap bitMap = new BitMap(getMaxRowNumber()); + if (bitMapMode == BitMapMode.AUTO) { + bitMap.markRange(rowSize, maxRowNumber - rowSize); + } this.bitMaps[column] = bitMap; } + bitMapsReady = bitMapMode == BitMapMode.AUTO; + bitMapsShared = false; } @TsFileApi public void addTimestamp(int rowIndex, long timestamp) { timestamps[rowIndex] = timestamp; - initBitMapsWithApiUsage(); + if (!bitMapsReady && (bitMapMode != BitMapMode.AUTO || rowIndex >= rowSize)) { + initializeBitMapsForWrite(); + } this.rowSize = Math.max(this.rowSize, rowIndex + 1); } @@ -528,28 +540,51 @@ private int getColumnIndexByMeasurement(String measurement) { } private void updateBitMap(int rowIndex, int columnIndex, boolean mark) { - initBitMapsWithApiUsage(); + if (!bitMapsReady && !prepareColumnBitMap(rowIndex, columnIndex, mark)) { + return; + } + BitMap bitMap = bitMaps[columnIndex]; if (mark) { - bitMaps[columnIndex].mark(rowIndex); + bitMap.mark(rowIndex); } else { - bitMaps[columnIndex].unmark(rowIndex); + bitMap.unmark(rowIndex); } } - private void initBitMapsWithApiUsage() { - if (bitMapMode != BitMapMode.AUTO || bitMaps == null) { - initializeBitMapsFromRow(bitMapMode == BitMapMode.DIRECT ? 0 : rowSize); - bitMapMode = BitMapMode.AUTO; + private boolean prepareColumnBitMap(int rowIndex, int columnIndex, boolean mark) { + if (bitMapMode != BitMapMode.AUTO || rowIndex >= rowSize) { + initializeBitMapsForWrite(); + } else if (bitMaps == null || bitMaps[columnIndex] == null) { + // A compacted column already represents a present value in every active row. + if (!mark) { + return false; + } + if (bitMaps == null) { + bitMaps = new BitMap[schemas.size()]; + } + bitMaps[columnIndex] = new BitMap(maxRowNumber); + bitMaps[columnIndex].markRange(rowSize, maxRowNumber - rowSize); } + return true; } - private void initializeBitMapsFromRow(int firstNullRow) { + private void initializeBitMapsForWrite() { if (bitMaps == null) { - initBitMaps(); + bitMaps = new BitMap[schemas.size()]; } for (int i = 0; i < bitMaps.length; i++) { + int firstNullRow = bitMapMode == BitMapMode.DIRECT ? 0 : rowSize; if (bitMaps[i] == null) { bitMaps[i] = new BitMap(maxRowNumber); + } else { + if (bitMapMode == BitMapMode.AUTO) { + // Preserve values already written ahead of their timestamps. + firstNullRow = bitMaps[i].getSize(); + if (firstNullRow >= maxRowNumber) { + continue; + } + } + bitMaps[i].extend(maxRowNumber); } if (firstNullRow == 0) { bitMaps[i].markAll(); @@ -557,6 +592,8 @@ private void initializeBitMapsFromRow(int firstNullRow) { bitMaps[i].markRange(firstNullRow, maxRowNumber - firstNullRow); } } + bitMapMode = BitMapMode.AUTO; + bitMapsReady = !bitMapsShared; } public List getSchemas() { @@ -575,12 +612,15 @@ public void reset() { // No API writes yet. Allow the caller to refill the arrays directly. bitMapMode = BitMapMode.DIRECT; } + bitMapsReady = bitMapMode == BitMapMode.AUTO && bitMaps != null && !bitMapsShared; if (bitMaps != null) { for (BitMap bitMap : bitMaps) { if (bitMap == null) { + bitMapsReady = false; continue; } if (bitMapMode == BitMapMode.AUTO) { + bitMap.extend(maxRowNumber); bitMap.markAll(); } else { bitMap.reset(); @@ -1140,11 +1180,17 @@ public void setValues(Object[] values) { } public BitMap[] getBitMaps() { + if (bitMaps != null) { + bitMapsShared = true; + bitMapsReady = false; + } return bitMaps; } public void setBitMaps(BitMap[] bitMaps) { this.bitMaps = bitMaps; + bitMapsShared = bitMaps != null; + bitMapsReady = false; } /** @@ -1231,14 +1277,11 @@ public boolean append(Tablet another, int preferredCapacity) { int prevCapacity = timestamps.length; appendTimestamps(another, preferredCapacity); appendValues(another, prevCapacity, preferredCapacity); - appendBitMaps(another, prevCapacity, preferredCapacity); - - maxRowNumber = Math.max(preferredCapacity, Math.max(maxRowNumber, rowSize + another.rowSize)); - rowSize = rowSize + another.rowSize; - int firstReservedRow = Math.max(prevCapacity, rowSize); - if (bitMapMode == BitMapMode.AUTO && firstReservedRow < maxRowNumber) { - initializeBitMapsFromRow(firstReservedRow); - } + int newRowSize = rowSize + another.rowSize; + int newCapacity = Math.max(preferredCapacity, Math.max(maxRowNumber, newRowSize)); + appendBitMaps(another, newRowSize, newCapacity); + rowSize = newRowSize; + maxRowNumber = newCapacity; return true; } @@ -1285,68 +1328,38 @@ private void appendValue( } } - private void appendBitMaps(Tablet another, int prevCapacity, int preferredCapacity) { - if (bitMaps == null && another.bitMaps == null) { - return; - } - + private void appendBitMaps(Tablet another, int newRowSize, int newCapacity) { if (bitMaps == null) { - appendBitMapsWhenThisNull(another, prevCapacity, preferredCapacity); - } else if (another.bitMaps == null) { - appendBitMapsWhenThatNull(another, prevCapacity, preferredCapacity); - } else { - appendBitMapsWhenNoNull(another, prevCapacity, preferredCapacity); - } - } - - private void appendBitMapsWhenThisNull(Tablet another, int prevCapacity, int preferredCapacity) { - int thisSize = rowSize; - int thatSize = another.rowSize; - bitMaps = new BitMap[schemas.size()]; - int totalSize = Math.max(prevCapacity, Math.max(thisSize + thatSize, preferredCapacity)); - for (int i = 0; i < bitMaps.length; i++) { - if (another.bitMaps[i] != null) { - bitMaps[i] = new BitMap(totalSize); - bitMaps[i].append(another.bitMaps[i], thisSize, thatSize); - } - } - } - - private void appendBitMapsWhenThatNull(Tablet another, int prevCapacity, int preferredCapacity) { - int thisSize = rowSize; - int thatSize = another.rowSize; - int totalSize = Math.max(prevCapacity, Math.max(thisSize + thatSize, preferredCapacity)); - for (BitMap bitMap : bitMaps) { - if (bitMap != null) { - bitMap.extend(totalSize); - for (int j = 0; j < thatSize; j++) { - bitMap.unmark(j + thisSize); - } + if (another.bitMaps == null) { + return; } + bitMaps = new BitMap[schemas.size()]; } - } - - private void appendBitMapsWhenNoNull(Tablet another, int prevCapacity, int preferredCapacity) { - int thisSize = rowSize; - int thatSize = another.rowSize; - int totalSize = Math.max(prevCapacity, Math.max(thisSize + thatSize, preferredCapacity)); for (int i = 0; i < bitMaps.length; i++) { - if (bitMaps[i] == null && another.bitMaps[i] == null) { + BitMap source = another.bitMaps == null ? null : another.bitMaps[i]; + BitMap target = bitMaps[i]; + if (target == null && source == null) { continue; } - if (bitMaps[i] == null && another.bitMaps[i] != null) { - bitMaps[i] = new BitMap(totalSize); - bitMaps[i].append(another.bitMaps[i], thisSize, thatSize); - } else if (bitMaps[i] != null && another.bitMaps[i] == null) { - bitMaps[i].extend(totalSize); - for (int j = 0; j < thatSize; j++) { - bitMaps[i].unmark(j + thisSize); - } - } else if (bitMaps[i] != null && another.bitMaps[i] != null) { - bitMaps[i].extend(totalSize); - bitMaps[i].append(another.bitMaps[i], thisSize, thatSize); + // A new column bitmap describes only the appended rows. An existing bitmap can + // also contain values written ahead of their timestamps within the old logical capacity. + int firstReservedRow = newRowSize; + if (target == null) { + target = new BitMap(newCapacity); + bitMaps[i] = target; + } else { + firstReservedRow = Math.max(newRowSize, Math.min(maxRowNumber, target.getSize())); + target.extend(newCapacity); + } + if (source == null) { + target.unmarkRange(rowSize, another.rowSize); + } else { + target.append(source, rowSize, another.rowSize); + } + if (bitMapMode == BitMapMode.AUTO && firstReservedRow < newCapacity) { + target.markRange(firstReservedRow, newCapacity - firstReservedRow); } } } diff --git a/java/tsfile/src/test/java/org/apache/tsfile/write/record/TabletTest.java b/java/tsfile/src/test/java/org/apache/tsfile/write/record/TabletTest.java index 1a01effaa..62eaa78a4 100644 --- a/java/tsfile/src/test/java/org/apache/tsfile/write/record/TabletTest.java +++ b/java/tsfile/src/test/java/org/apache/tsfile/write/record/TabletTest.java @@ -312,6 +312,124 @@ public void testTimestampOnlyRowsAfterAppendingToDeserializedTablet() throws IOE assertNull(target.getValue(8, 1)); } + @Test + public void testAppendWithOversizedBackingArrays() throws IOException { + List schemas = List.of(new MeasurementSchema("s", TSDataType.INT32)); + Tablet target = + new Tablet( + "root.sg.d1", + schemas, + new long[] {10, 20, 0, 0, 0, 0, 0, 0}, + new Object[] {new int[] {70, 80, 0, 733, 0, 0, 0, 0}}, + null, + 2); + target.addValue("s", 0, 71); + Tablet source = + new Tablet("root.sg.d1", schemas, new long[] {30}, new Object[] {new int[] {90}}, null, 1); + + assertTrue(target.append(source, 8)); + target.addTimestamp(3, 40); + + Tablet reread = Tablet.deserialize(target.serialize()); + assertEquals(71, reread.getValue(0, 0)); + assertEquals(80, reread.getValue(1, 0)); + assertEquals(90, reread.getValue(2, 0)); + assertEquals(40, reread.getTimestamp(3)); + assertNull(reread.getValue(3, 0)); + } + + @Test + public void testEditDeserializedTabletWithTrimmedBitMap() throws IOException { + Tablet source = + new Tablet("root.sg.d1", List.of(new MeasurementSchema("s", TSDataType.INT32)), 64); + source.addTimestamp(0, 10); + source.addValue("s", 0, 70); + source.addTimestamp(63, 630); + source.addValue("s", 63, 99); + + Tablet target = Tablet.deserialize(source.serialize()); + target.setRowSize(2); + target.getBitMaps()[0] = target.getBitMaps()[0].getRegion(0, 2); + target.addValue("s", 0, 71); + assertEquals(71, target.getValue(0, 0)); + assertNull(target.getValue(1, 0)); + + target.addTimestamp(63, 640); + Tablet reread = Tablet.deserialize(target.serialize()); + assertNull(reread.getValue(2, 0)); + assertNull(reread.getValue(63, 0)); + } + + @Test + public void testAppendPreservesCompactedBitMapsUntilReservedRowsAreUsed() throws IOException { + List schemas = + List.of( + new MeasurementSchema("a", TSDataType.BOOLEAN), + new MeasurementSchema("b", TSDataType.BOOLEAN)); + Tablet target = new Tablet("root.sg.d1", schemas, 1); + target.addTimestamp(0, 10); + target.addValue(0, 0, true); + target.addValue(0, 1, true); + target.setBitMaps(null); + Tablet source = + new Tablet( + "root.sg.d1", + schemas, + new long[] {20}, + new Object[] {new boolean[] {false}, new boolean[] {true}}, + null, + 1); + + assertTrue(target.append(source, 4096)); + assertNull(target.getBitMaps()); + target.addValue(3, 1, false); + target.addTimestamp(4, 50); + + Tablet reread = Tablet.deserialize(target.serialize()); + assertEquals(true, reread.getValue(0, 0)); + assertEquals(false, reread.getValue(1, 0)); + assertEquals(true, reread.getValue(1, 1)); + assertNull(reread.getValue(2, 0)); + assertNull(reread.getValue(2, 1)); + assertNull(reread.getValue(3, 0)); + assertEquals(false, reread.getValue(3, 1)); + assertNull(reread.getValue(4, 0)); + assertNull(reread.getValue(4, 1)); + } + + @Test + public void testAppendNullIntoPartiallyCompactedTablet() throws IOException { + List schemas = + List.of( + new MeasurementSchema("a", TSDataType.INT32), + new MeasurementSchema("b", TSDataType.INT32), + new MeasurementSchema("c", TSDataType.INT32)); + Tablet target = new Tablet("root.sg.d1", schemas, 8); + target.addTimestamp(0, 10); + target.addValue(0, 0, 11); + target.addValue(0, 1, 12); + target.addValue(4, 2, 43); + target.setBitMaps(new BitMap[] {null, null, target.getBitMaps()[2]}); + + Tablet source = new Tablet("root.sg.d1", schemas, 1); + source.addTimestamp(0, 20); + source.addValue(0, 1, 22); + source.getBitMaps()[1] = null; + + assertTrue(target.append(source)); + target.addValue("b", 0, null); + target.addTimestamp(4, 50); + + Tablet reread = Tablet.deserialize(target.serialize()); + assertEquals(11, reread.getValue(0, 0)); + assertNull(reread.getValue(0, 1)); + assertNull(reread.getValue(1, 0)); + assertEquals(22, reread.getValue(1, 1)); + assertNull(reread.getValue(4, 0)); + assertNull(reread.getValue(4, 1)); + assertEquals(43, reread.getValue(4, 2)); + } + @Test public void testResetDeserializedTabletBeforeFirstEdit() throws IOException { Tablet tablet = diff --git a/skills/tsfile/references/advanced-apis.md b/skills/tsfile/references/advanced-apis.md index a6641a1bc..f6f308081 100644 --- a/skills/tsfile/references/advanced-apis.md +++ b/skills/tsfile/references/advanced-apis.md @@ -95,8 +95,10 @@ the current `TableSchema`; do not infer constructor positions from memory. an existing row with `addValue` or `addTimestamp` preserves the values and null flags of other cells. An omitted column bitmap means its values are all present. -- If `append(other, preferredCapacity)` reserves space beyond the last row, - use `addTimestamp` to add a row there. Its values are null until set. +- Appending two tablets with omitted bitmaps keeps those columns bitmap-free + while reserving capacity. When `addTimestamp` makes a reserved row active, + its unset cells and any skipped rows' unset cells are null. Values set with + `addValue` before their timestamps are preserved. ## Custom and Buffered Input From 54137b514ce0bae2276e0c5101b2b1b6edb4926d Mon Sep 17 00:00:00 2001 From: DaZuiZui Date: Fri, 4 Dec 2026 14:56:34 +0800 Subject: [PATCH 4/5] Document Tablet bitmap modes and reset behavior --- .../main/java/org/apache/tsfile/write/record/Tablet.java | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/java/tsfile/src/main/java/org/apache/tsfile/write/record/Tablet.java b/java/tsfile/src/main/java/org/apache/tsfile/write/record/Tablet.java index 7447110f9..93e558a71 100644 --- a/java/tsfile/src/main/java/org/apache/tsfile/write/record/Tablet.java +++ b/java/tsfile/src/main/java/org/apache/tsfile/write/record/Tablet.java @@ -92,8 +92,14 @@ public class Tablet implements Accountable { private BitMap[] bitMaps; private enum BitMapMode { + /** Callers can fill the arrays directly. The first API write starts with every cell null. */ DIRECT, + /** + * Supplied or deserialized rows already have null flags. The first API write preserves them. A + * reset before that write returns the tablet to direct array access. + */ POPULATED, + /** API writes maintain null flags. After a reset, cells default to null until written. */ AUTO } From 56a1cabc4e49c887494d66599e1195a47f27aefe Mon Sep 17 00:00:00 2001 From: DaZuiZui Date: Fri, 4 Dec 2026 17:50:04 +0800 Subject: [PATCH 5/5] Restore fast Tablet reuse and honor typed null writes --- .../apache/tsfile/write/record/Tablet.java | 57 +++++--------- .../tsfile/write/record/TabletTest.java | 77 +++++++++++++++++++ skills/tsfile/references/advanced-apis.md | 6 ++ 3 files changed, 104 insertions(+), 36 deletions(-) diff --git a/java/tsfile/src/main/java/org/apache/tsfile/write/record/Tablet.java b/java/tsfile/src/main/java/org/apache/tsfile/write/record/Tablet.java index 93e558a71..ff49ab570 100644 --- a/java/tsfile/src/main/java/org/apache/tsfile/write/record/Tablet.java +++ b/java/tsfile/src/main/java/org/apache/tsfile/write/record/Tablet.java @@ -28,6 +28,7 @@ import org.apache.tsfile.file.metadata.IDeviceID; import org.apache.tsfile.file.metadata.StringArrayDeviceID; import org.apache.tsfile.i18n.Messages; +import org.apache.tsfile.read.common.type.DateType; import org.apache.tsfile.read.common.type.Type; import org.apache.tsfile.utils.Accountable; import org.apache.tsfile.utils.Binary; @@ -106,8 +107,6 @@ private enum BitMapMode { private BitMapMode bitMapMode = BitMapMode.DIRECT; // All columns have writable bitmaps with null flags initialized through maxRowNumber. private boolean bitMapsReady; - // Callers can trim or remove individual bitmaps through an array they retain. - private boolean bitMapsShared; private int rowSize; @@ -269,7 +268,6 @@ public Tablet( this.timestamps = timestamps; this.values = values; this.bitMaps = bitMaps; - this.bitMapsShared = bitMaps != null; this.bitMapMode = BitMapMode.POPULATED; this.maxRowNumber = maxRowNumber; // rowSize == maxRowNumber in this case @@ -304,7 +302,6 @@ public void initBitMaps() { this.bitMaps[column] = bitMap; } bitMapsReady = bitMapMode == BitMapMode.AUTO; - bitMapsShared = false; } @TsFileApi @@ -434,12 +431,10 @@ public void addValue(int rowIndex, int columnIndex, String val) { throw new IllegalArgumentException( Messages.format("error.write.tablet_col_wrong_type", columnIndex, "TEXT/STRING/BLOB")); } - if (val == null) { - return; - } final Binary[] sensor = (Binary[]) values[columnIndex]; - sensor[rowIndex] = new Binary(val, TSFileConfig.STRING_CHARSET); - updateBitMap(rowIndex, columnIndex, false); + sensor[rowIndex] = + val == null ? Binary.EMPTY_VALUE : new Binary(val, TSFileConfig.STRING_CHARSET); + updateBitMap(rowIndex, columnIndex, val == null); } @TsFileApi @@ -456,10 +451,10 @@ public void addObjectPathValue(int rowIndex, String measurement, String objectPa @TsFileApi public void addObjectPathValue(int rowIndex, int columnIndex, String objectPath) { - if (objectPath == null) { - return; - } - addObjectPathValue(rowIndex, columnIndex, objectPath.getBytes(TSFileConfig.STRING_CHARSET)); + addObjectPathValue( + rowIndex, + columnIndex, + objectPath == null ? null : objectPath.getBytes(TSFileConfig.STRING_CHARSET)); } @TsFileApi @@ -475,12 +470,9 @@ public void addObjectPathValue(int rowIndex, int columnIndex, byte[] objectPath) throw new IllegalArgumentException( Messages.format("error.write.tablet_col_wrong_type", columnIndex, "OBJECT")); } - if (objectPath == null) { - return; - } final Binary[] sensor = (Binary[]) values[columnIndex]; - sensor[rowIndex] = new Binary(objectPath); - updateBitMap(rowIndex, columnIndex, false); + sensor[rowIndex] = objectPath == null ? Binary.EMPTY_VALUE : new Binary(objectPath); + updateBitMap(rowIndex, columnIndex, objectPath == null); } @TsFileApi @@ -490,12 +482,9 @@ public void addValue(int rowIndex, int columnIndex, byte[] val) { throw new IllegalArgumentException( Messages.format("error.write.tablet_col_wrong_type", columnIndex, "TEXT/STRING/BLOB")); } - if (val == null) { - return; - } final Binary[] sensor = (Binary[]) values[columnIndex]; - sensor[rowIndex] = new Binary(val); - updateBitMap(rowIndex, columnIndex, false); + sensor[rowIndex] = val == null ? Binary.EMPTY_VALUE : new Binary(val); + updateBitMap(rowIndex, columnIndex, val == null); } @TsFileApi @@ -510,12 +499,8 @@ public void addValue(int rowIndex, int columnIndex, LocalDate val) { throw new IllegalArgumentException( Messages.format("error.write.tablet_col_wrong_type", columnIndex, "DATE")); } - if (val == null) { - return; - } - final LocalDate[] sensor = (LocalDate[]) values[columnIndex]; - sensor[rowIndex] = val; - updateBitMap(rowIndex, columnIndex, false); + DateType.DATE.addValue(rowIndex, val, values[columnIndex]); + updateBitMap(rowIndex, columnIndex, val == null); } public void addValue(int rowIndex, int columnIndex, boolean isEOF, long offset, byte[] content) { @@ -599,7 +584,7 @@ private void initializeBitMapsForWrite() { } } bitMapMode = BitMapMode.AUTO; - bitMapsReady = !bitMapsShared; + bitMapsReady = true; } public List getSchemas() { @@ -618,7 +603,7 @@ public void reset() { // No API writes yet. Allow the caller to refill the arrays directly. bitMapMode = BitMapMode.DIRECT; } - bitMapsReady = bitMapMode == BitMapMode.AUTO && bitMaps != null && !bitMapsShared; + bitMapsReady = bitMapMode == BitMapMode.AUTO && bitMaps != null; if (bitMaps != null) { for (BitMap bitMap : bitMaps) { if (bitMap == null) { @@ -1185,17 +1170,17 @@ public void setValues(Object[] values) { this.values = values; } + /** + * Returns the live column bitmaps. Call this method before replacing entries, or pass the + * modified array to {@link #setBitMaps(BitMap[])} before the next write. + */ public BitMap[] getBitMaps() { - if (bitMaps != null) { - bitMapsShared = true; - bitMapsReady = false; - } + bitMapsReady = false; return bitMaps; } public void setBitMaps(BitMap[] bitMaps) { this.bitMaps = bitMaps; - bitMapsShared = bitMaps != null; bitMapsReady = false; } diff --git a/java/tsfile/src/test/java/org/apache/tsfile/write/record/TabletTest.java b/java/tsfile/src/test/java/org/apache/tsfile/write/record/TabletTest.java index 62eaa78a4..27f3c46e8 100644 --- a/java/tsfile/src/test/java/org/apache/tsfile/write/record/TabletTest.java +++ b/java/tsfile/src/test/java/org/apache/tsfile/write/record/TabletTest.java @@ -60,6 +60,9 @@ import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import static org.mockito.Mockito.clearInvocations; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verifyNoInteractions; public class TabletTest { @@ -217,6 +220,45 @@ public void testEditDeserializedTabletPreservesOtherRows() throws IOException { assertNull(copy.getValue(0, 0)); } + @Test + public void testTypedNullOverwritesDeserializedValues() throws IOException { + Tablet source = + new Tablet( + "root.sg.d1", + List.of( + new MeasurementSchema("text", TSDataType.TEXT), + new MeasurementSchema("blob", TSDataType.BLOB), + new MeasurementSchema("path", TSDataType.OBJECT), + new MeasurementSchema("pathBytes", TSDataType.OBJECT), + new MeasurementSchema("date", TSDataType.DATE)), + 2); + for (int row = 0; row < 2; row++) { + source.addTimestamp(row, row); + source.addValue(row, 0, "text"); + source.addValue(row, 1, new byte[] {1}); + source.addObjectPathValue(row, 2, "file"); + source.addObjectPathValue(row, 3, new byte[] {2}); + source.addValue(row, 4, LocalDate.of(2024, 1, 1)); + } + + Tablet copy = Tablet.deserialize(source.serialize()); + copy.addValue(0, "text", (String) null); + copy.addValue(0, "blob", (byte[]) null); + copy.addObjectPathValue(0, "path", (String) null); + copy.addObjectPathValue(0, "pathBytes", (byte[]) null); + copy.addValue(0, "date", (LocalDate) null); + + for (int col = 0; col < 4; col++) { + assertEquals(Binary.EMPTY_VALUE, ((Binary[]) copy.getValues()[col])[0]); + } + assertEquals(LocalDate.of(1000, 1, 1), ((LocalDate[]) copy.getValues()[4])[0]); + Tablet reread = Tablet.deserialize(copy.serialize()); + for (int col = 0; col < source.getSchemas().size(); col++) { + assertTrue(reread.isNull(0, col)); + assertEquals(source.getValue(1, col), reread.getValue(1, col)); + } + } + @Test public void testEditDeserializedTabletWithOmittedColumnBitMap() throws IOException { Tablet tablet = @@ -360,6 +402,39 @@ public void testEditDeserializedTabletWithTrimmedBitMap() throws IOException { assertNull(reread.getValue(63, 0)); } + @Test + public void testReuseAfterInspectingBitMapsDoesNotRescanOtherColumns() { + Tablet tablet = + new Tablet( + "root.sg.d1", + List.of( + new MeasurementSchema("a", TSDataType.INT32), + new MeasurementSchema("b", TSDataType.INT32)), + 4); + tablet.addTimestamp(0, 10); + tablet.addValue(0, 1, 7); + BitMap[] bitMaps = tablet.getBitMaps(); + BitMap otherColumn = spy(bitMaps[1].getRegion(0, 1)); + bitMaps[1] = otherColumn; + tablet.addTimestamp(1, 20); + assertEquals(7, tablet.getValue(0, 1)); + assertNull(tablet.getValue(1, 1)); + + clearInvocations(otherColumn); + tablet.addValue(2, 0, 30); + tablet.addTimestamp(2, 30); + verifyNoInteractions(otherColumn); + + tablet.getBitMaps(); + tablet.reset(); + clearInvocations(otherColumn); + tablet.addTimestamp(0, 40); + tablet.addValue(0, 0, 40); + tablet.addValue(1, 0, 50); + tablet.addTimestamp(1, 50); + verifyNoInteractions(otherColumn); + } + @Test public void testAppendPreservesCompactedBitMapsUntilReservedRowsAreUsed() throws IOException { List schemas = @@ -679,6 +754,8 @@ public void testWriteWrongType2() { addValueWithException2(tablet, 8, 0, "str"); addValueWithException2(tablet, 9, 0, 1L); addValueWithException2(tablet, 10, 0, "str"); + Assert.assertThrows( + IllegalArgumentException.class, () -> tablet.addObjectPathValue(0, 5, (String) null)); } private void addValueWithException2(Tablet tablet, int columnIndex, int rowIndex, Object value) { diff --git a/skills/tsfile/references/advanced-apis.md b/skills/tsfile/references/advanced-apis.md index f6f308081..d43acc94c 100644 --- a/skills/tsfile/references/advanced-apis.md +++ b/skills/tsfile/references/advanced-apis.md @@ -95,6 +95,12 @@ the current `TableSchema`; do not infer constructor positions from memory. an existing row with `addValue` or `addTimestamp` preserves the values and null flags of other cells. An omitted column bitmap means its values are all present. +- To clear a cell, pass a typed null to the matching setter. For example, + `tablet.addValue(row, "label", (String) null)` clears a `STRING` value. + The `byte[]` and `LocalDate` overloads of `addValue` and both path types of + `addObjectPathValue` also accept null for their respective column types. +- After a batch is written, `reset()` reuses full-capacity column bitmaps for + the next batch, including when the writer inspected them via `getBitMaps()`. - Appending two tablets with omitted bitmaps keeps those columns bitmap-free while reserving capacity. When `addTimestamp` makes a reserved row active, its unset cells and any skipped rows' unset cells are null. Values set with