Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
247 changes: 134 additions & 113 deletions java/tsfile/src/main/java/org/apache/tsfile/write/record/Tablet.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -91,10 +92,21 @@ 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 {
/** 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
}
Comment on lines +95 to +105

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.

Better to add some comments explaining the behavior of each mode.


private BitMapMode bitMapMode = BitMapMode.DIRECT;
// All columns have writable bitmaps with null flags initialized through maxRowNumber.
private boolean bitMapsReady;

private int rowSize;

Expand Down Expand Up @@ -231,17 +243,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
Expand All @@ -259,6 +268,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;
Expand Down Expand Up @@ -286,15 +296,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;
}

@TsFileApi
public void addTimestamp(int rowIndex, long timestamp) {
timestamps[rowIndex] = timestamp;
if (!bitMapsReady && (bitMapMode != BitMapMode.AUTO || rowIndex >= rowSize)) {
initializeBitMapsForWrite();
}
this.rowSize = Math.max(this.rowSize, rowIndex + 1);
initBitMapsWithApiUsage();
}

public void addValue(final String measurementId, final int rowIndex, final Object value) {

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.

[P2] Mark null bitmaps in the @TsFileApi reference-typed addValue and addObjectPathValue overloads when val == null. addValue(String, int, Object) handles null via updateBitMap(rowIndex, indexOfSchema, value == null), but the @TsFileApi typed overloads—addValue(int, int, String) (L437), addObjectPathValue(int, int, String) (L459), addObjectPathValue(int, int, byte[]) (L478), addValue(int, int, byte[]) (L493), and addValue(int, int, LocalDate) (L513)—all do if (val == null) { return; }.

That early return only worked on fresh tablets whose bitmaps had already been marked all-null. On a deserialized or populated Tablet (including table-model callers using @TsFileApi), calling e.g. copy.addValue(0, 0, (String) null) or copy.addValue(0, 0, (LocalDate) null) neither transitions POPULATED → AUTO nor marks the cell null, silently retaining the old non-null value in row 0. When val == null (after validating the column type, including in addObjectPathValue(int, int, String)), please clear the slot (Binary.EMPTY_VALUE / DateType.EMPTY_DATE) and call updateBitMap(rowIndex, columnIndex, true).

Expand Down Expand Up @@ -415,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
Expand All @@ -437,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
Expand All @@ -456,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
Expand All @@ -471,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
Expand All @@ -491,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) {
Expand Down Expand Up @@ -527,24 +531,60 @@ 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() {
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 initializeBitMapsForWrite() {
if (bitMaps == null) {
initBitMaps();
bitMaps = new BitMap[schemas.size()];
}
if (!autoUpdateBitMaps) {
autoUpdateBitMaps = true;
for (BitMap bitMap : bitMaps) {
bitMap.markAll();
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();
} else {
bitMaps[i].markRange(firstNullRow, maxRowNumber - firstNullRow);

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.

[P2] Handle bitmaps trimmed to the active row count. I deserialized a 64-row tablet, called setRowSize(2), and replaced the bitmap for its single column with oldMap.getRegion(0, 2). This tablet serializes successfully. On the base commit, addValue("s", 0, 71) produces [71, null]. Here the same edit calls markRange(2, 62) on a two-bit bitmap and throws IndexOutOfBoundsException while updating row 0.

Please extend an existing bitmap before marking beyond its size, or defer marking until the reserved rows are used. A test that trims both the row count and the bitmap before the first edit would cover this case.

}
}
bitMapMode = BitMapMode.AUTO;
bitMapsReady = true;
}

public List<IMeasurementSchema> getSchemas() {
Expand All @@ -559,12 +599,19 @@ 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.POPULATED) {
// No API writes yet. Allow the caller to refill the arrays directly.
bitMapMode = BitMapMode.DIRECT;
}
bitMapsReady = bitMapMode == BitMapMode.AUTO && bitMaps != null;
if (bitMaps != null) {
for (BitMap bitMap : bitMaps) {
if (bitMap == null) {
bitMapsReady = false;
continue;
}
if (autoUpdateBitMaps) {
if (bitMapMode == BitMapMode.AUTO) {
bitMap.extend(maxRowNumber);
bitMap.markAll();
} else {
bitMap.reset();
Expand Down Expand Up @@ -875,10 +922,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.constructMeasurementIndexMap();
return tablet;
return new Tablet(deviceId, schemas, columnCategories, times, values, bitMaps, rowSize);
}

/** deserialize bitmaps */
Expand Down Expand Up @@ -1126,12 +1170,18 @@ 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() {
bitMapsReady = false;
return bitMaps;
}

public void setBitMaps(BitMap[] bitMaps) {
this.bitMaps = bitMaps;
bitMapsReady = false;
}

/**
Expand Down Expand Up @@ -1218,10 +1268,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 newRowSize = rowSize + another.rowSize;
int newCapacity = Math.max(preferredCapacity, Math.max(maxRowNumber, newRowSize));
appendBitMaps(another, newRowSize, newCapacity);
rowSize = newRowSize;
maxRowNumber = newCapacity;
return true;
}

Expand Down Expand Up @@ -1268,68 +1319,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);
}
}
}
Expand Down
Loading