Repository navigation
Conversation
| return 0; | ||
| } | ||
| long retainedSize = RamUsageEstimator.shallowSizeOf(output); | ||
| if (output instanceof PublicBAOS publicOutput) { |
There was a problem hiding this comment.
major java/tsfile/src/main/java/org/apache/tsfile/encoding/encoder/Encoder.java:154 — estimateByteArrayOutputStreamRetainedSize ignores PublicBAOS capacity growth
RleEncoder and SprintzEncoder now create new PublicBAOS() (RleEncoder.java:121, SprintzEncoder.java:65). PublicBAOS grows by doubling from the 32-byte default, so after a flush that wrote e.g. 1 MB the buffer stays ~1 MB while size() is 0. The helper returns sizeOf(publicOutput.getBuf()) only for the PublicBAOS branch, which is correct, but the plain-BAOS fallback branch (used when a subclass swaps in a ByteArrayOutputStream, as the new tests do) estimates capacity from `max(size, maximumO
…[truncated]
Fix: Track the maximum observed size at flush time (before byteCache.reset()) in RleEncoder.flush/SprintzEncoder.flush, not only in reset(), so the estimate reflects the peak capacity actually retained.
There was a problem hiding this comment.
Thanks for flagging this. No additional change is needed: the PublicBAOS branch estimates the backing array directly, and both RleEncoder.reset() and SprintzEncoder.reset() record byteCache.size() before calling byteCache.reset(). Their flush() methods invoke reset() after writing, so the fallback retains the observed high-water mark.
| + RamUsageEstimator.shallowSizeOf(entryIndex) | ||
| + (long) entryIndex.size() * RamUsageEstimator.SHALLOW_SIZE_OF_HASHMAP_ENTRY | ||
| + dictionaryEntriesRetainedSize | ||
| + estimateHashMapTableSize(maximumDictionarySize) |
There was a problem hiding this comment.
major java/tsfile/src/main/java/org/apache/tsfile/encoding/encoder/DictionaryEncoder.java:117 — HashMap table size estimated from stale maximumDictionarySize
maximumDictionarySize is only updated inside the computeIfAbsent lambda, i.e. only when a new entry is inserted. After reset() the map is cleared but maximumDictionarySize keeps the previous peak, so estimateHashMapTableSize(maximumDictionarySize) reports a full-size table for an empty map; conversely, while entries are being added the value lags by one insert. Trigger: encode N distinct values, flush, then call getRetainedSizeInBytes() — the estimate still charges a table sized for
…[truncated]
Fix: Base the table estimate on the live map (entryIndex.size()), or reset maximumDictionarySize in reset() and update it before/after insertion outside the lambda.
There was a problem hiding this comment.
Thanks for the suggestion. No change is needed: maximumDictionarySize is updated after indexEntry.add(v), and HashMap.clear()/ArrayList.clear() retain their backing arrays. Keeping the peak is necessary to estimate capacity after reset; using the live map size would undercount it.
| : retainedMeasurementNames.put(measurementName, Boolean.TRUE) == null | ||
| ? 0 | ||
| : RamUsageEstimator.sizeOf(measurementName); | ||
| totalSizeInBytes += measurementSchema.ramBytesUsed() - measurementNameSize; |
There was a problem hiding this comment.
major java/tsfile/src/main/java/org/apache/tsfile/write/record/Tablet.java:1368 — Tablet subtracts measurement-name size that VectorMeasurementSchema never counted
totalSizeInBytes += measurementSchema.ramBytesUsed() - measurementNameSize; assumes every schema's ramBytesUsed() includes sizeOf(getMeasurementName()). MeasurementSchema does, but VectorMeasurementSchema.ramBytesUsed() (VectorMeasurementSchema.java:526) adds sizeOf(deviceId) and getMeasurementName() returns deviceId, so the subtraction is valid there; however for any IMeasurementSchema implementation whose ramBytesUsed() does not include the name (or where getMeasurementName() returns a d
…[truncated]
Fix: Clamp the per-column contribution at 0 (Math.max(0, schema.ramBytesUsed() - measurementNameSize)) or only subtract when the schema type is known to include the name.
There was a problem hiding this comment.
Fixed in 6c3d421d: the per-schema contribution is clamped to zero, so implementations whose ramBytesUsed() omits the measurement name cannot make the tablet estimate negative for that entry.
| + RamUsageEstimator.sizeOf(timeOut.getBuf()) | ||
| + RamUsageEstimator.shallowSizeOf(valueOut) | ||
| + RamUsageEstimator.sizeOf(valueOut.getBuf()) | ||
| + timeEncoder.getRetainedSizeInBytes() |
There was a problem hiding this comment.
major java/tsfile/src/main/java/org/apache/tsfile/write/page/PageWriter.java:287 — estimateRetainedMemSize NPEs when encoders/statistics are null
PageWriter() and PageWriter(EncryptParameter) leave timeEncoder, valueEncoder and statistics null (only set later via setTimeEncoder/setValueEncoder/initStatistics). estimateRetainedMemSize() dereferences all three unconditionally, so calling it on a freshly constructed PageWriter throws NullPointerException. Trigger: any caller that computes the estimate before encoders are configured (the existing estimateMaxMemSize() has the same shape but is only called after configuration; the new met
…[truncated]
Fix: Null-guard each component: (timeEncoder == null ? 0 : timeEncoder.getRetainedSizeInBytes()) etc., and same for statistics.
There was a problem hiding this comment.
Fixed in 6c3d421d: estimateRetainedMemSize() now treats time/value encoders and statistics as optional until configured. Added a regression test for a fresh PageWriter.
| for (Object value : values) { | ||
| if (value instanceof Integer integerValue) { | ||
| if (integerValue < -128 || integerValue > 127) { | ||
| retainedValuesSize += RamUsageEstimator.shallowSizeOfInstance(valueType); |
There was a problem hiding this comment.
minor java/tsfile/src/main/java/org/apache/tsfile/encoding/encoder/SprintzEncoder.java:93 — getVectorRetainedSize charges boxed size for Float/Double values that are never boxed
For FloatSprintzEncoder/DoubleSprintzEncoder the else if (value != null) branch adds shallowSizeOfInstance(valueType) per element, but the Vector holds Float/Double objects created by autoboxing in encode(float/double) — those are real allocations, so the charge is correct; however the Integer/Long branches use shallowSizeOfInstance(valueType)/sizeOf(longValue) while the valueType passed is the declared class, so for a Vector holding a Long (not possible) it would be wrong.
…[truncated]
Fix: n/a
There was a problem hiding this comment.
Thanks for checking this. No code change is needed: buffered Vector entries are boxed objects and remain retained, including the autoboxed Float/Double values. The Integer/Long branches inspect the actual runtime wrapper type; these encoders cannot insert the mismatched wrapper described.
| public void encode(int value, ByteArrayOutputStream out) { | ||
| values.add(value); | ||
| maximumValuesSize = Math.max(maximumValuesSize, values.size()); | ||
| if (value < -128 || value > 127) { |
There was a problem hiding this comment.
minor java/tsfile/src/main/java/org/apache/tsfile/encoding/encoder/BitmapEncoder.java:87 — BitmapEncoder counts boxed Integer only outside the JVM cache range
if (value < -128 || value > 127) currentValuesRetainedSize += BOXED_VALUE_SIZE; assumes the Integer cache covers [-128,127]. RamUsageEstimator itself probes the actual cache range (LONG_CACHE_MIN_VALUE/MAX_VALUE) because it is JVM/flag dependent (-XX:AutoBoxCacheMax). On a JVM with a larger cache the estimate over-counts; with a smaller/disabled cache it under-counts. Same pattern in IntZigzagEncoder, LongZigzagEncoder, IntRleEncoder, LongRleEncoder and Fire.getRetainedSizeInBytes.
Fix: Reuse the JVM-probed cache bounds (expose them from RamUsageEstimator) instead of hard-coding -128/127.
There was a problem hiding this comment.
Fixed in 6c3d421d: boxed-value estimates now use the JVM-detected Integer cache maximum and the existing probed Long cache range instead of hardcoded upper bounds.
| retainedSizeInBytes += columnBuilder.getRetainedSizeInBytes(); | ||
| } | ||
| return retainedSizeInBytes; | ||
| return retainedSizeInBytes - valueColumnBuilders.length * SHARED_STATUS_SIZE; |
There was a problem hiding this comment.
major java/tsfile/src/main/java/org/apache/tsfile/read/common/block/TsBlockBuilder.java:241 — TsBlockBuilder subtracts SHARED_STATUS_SIZE per column that builders never add
Each value column builder gets its own ColumnBuilderStatus (createColumnBuilderStatus() per column), and BinaryColumnBuilder.getRetainedSizeInBytes() adds ColumnBuilderStatus.INSTANCE_SIZE (deep size incl. TsBlockBuilderStatus), not TsBlockBuilderStatus shallow size. Subtracting valueColumnBuilders.length * SHARED_STATUS_SIZE therefore under-counts: for a TEXT column the builder's status contribution (~40B) is smaller than the subtracted TsBlockBuilderStatus shallow size, so the total can be les
…[truncated]
Fix: Drop the subtraction (each column builder owns a distinct status object) or subtract only the shared TsBlockBuilderStatus once, and add tsBlockBuilderStatus itself to the estimate.
There was a problem hiding this comment.
Fixed in 6c3d421d: TsBlockBuilder now adds its TsBlockBuilderStatus once and removes the per-value-column subtraction.
| } | ||
| } | ||
|
|
||
| public long estimateMaxSeriesMemSize() { |
There was a problem hiding this comment.
major java/tsfile/src/main/java/org/apache/tsfile/write/chunk/ValueChunkWriter.java:340 — estimateMaxSeriesMemSize now counts retained capacity that never shrinks, breaking chunk sealing
estimateMaxSeriesMemSize() is used by checkIsChunkSizeOverThreshold/updateMaxGroupMemSize as a live memory gauge. It now adds RamUsageEstimator.sizeOf(pageBuffer.getBuf()) plus encoder retained capacity (PublicBAOS buffers, RLE/Sprintz value lists, statistics). After a large chunk is flushed, pageBuffer.reset() and encoder reset() keep the grown arrays, so the estimate stays above the threshold forever and every subsequent write immediately seals a new chunk, producing one-point chunks and a lar
…[truncated]
Fix: Keep the live gauge based on size()/getMaxByteSize() (as before) and expose the retained-capacity figure through a separate method used only for memory accounting.
There was a problem hiding this comment.
Fixed in 6c3d421d: estimateMaxSeriesMemSize() again uses active page/chunk sizes for threshold decisions. A separate getRetainedSizeInBytes() tracks retained capacity and feeds group memory accounting in aligned and non-aligned writers.
|
Review-comment follow-up
|
…mory-estimates-20261127 # Conflicts: # java/tsfile/src/main/java/org/apache/tsfile/encoding/encoder/DeltaBinaryEncoder.java # java/tsfile/src/test/java/org/apache/tsfile/encoding/decoder/delta/DeltaBinaryEncoderIntegerTest.java # java/tsfile/src/test/java/org/apache/tsfile/encoding/decoder/delta/DeltaBinaryEncoderLongTest.java
…mory-estimates-20261127
…mory-estimates-20261127
|
|
||
| @Override | ||
| public long getRetainedSizeInBytes() { | ||
| return RamUsageEstimator.shallowSizeOf(this) |
There was a problem hiding this comment.
May cache the shallow size if it is static.
There was a problem hiding this comment.
The boxed Integer shallow size is already cached in the static final BOXED_VALUE_SIZE field, initialized once when the class loads, so no further change was needed.
| if (index > 127) { | ||
| dictionaryEntriesRetainedSize += BOXED_INDEX_SIZE; | ||
| } |
There was a problem hiding this comment.
Fixed in 7b95a669: dictionary index accounting now uses RamUsageEstimator.INTEGER_CACHE_MAX_VALUE instead of a hard-coded 127. Added a regression test and verified it with -XX:AutoBoxCacheMax=1024.
|
Review-comment follow-up
|
| return RamUsageEstimator.shallowSizeOf(this) | ||
| + RamUsageEstimator.shallowSizeOf(pageBuffer) | ||
| + RamUsageEstimator.sizeOf(pageBuffer.getBuf()) | ||
| + pageWriter.estimateRetainedMemSize() |
There was a problem hiding this comment.
minor java/tsfile/src/main/java/org/apache/tsfile/write/chunk/ValueChunkWriter.java:351 — New chunk-writer getRetainedSizeInBytes() NPEs when pageWriter is null
clearPageWriter() (ValueChunkWriter:419, TimeChunkWriter:327, ChunkWriterImpl:430 — documented as "set the current pageWriter to null, friendly for gc", cascaded from AlignedChunkWriterImpl:494 and used by TDEPageAeadTsFileTest) sets pageWriter = null, but the new getRetainedSizeInBytes() dereferences pageWriter.estimateRetainedMemSize() unconditionally at ValueChunkWriter:351, TimeChunkWriter:299 and ChunkWriterImpl:399. Calling it after clearing the writer throws NPE, and this method is now the gauge used by updateMaxGroupMemSize() in both group writers.
Fix: Null-guard the pageWriter contribution (pageWriter == null ? 0 : pageWriter.estimateRetainedMemSize()) in all three implementations, mirroring the null guards just added to PageWriter.estimateRetainedMemSize().
There was a problem hiding this comment.
Fixed in 4ff096c1: getRetainedSizeInBytes() now treats a cleared pageWriter as contributing zero in ValueChunkWriter, TimeChunkWriter, and ChunkWriterImpl. A regression test covers clearPageWriter() for all three implementations. The focused writer tests pass.
| return size; | ||
| } | ||
|
|
||
| private long getBinaryValuesRetainedSize() { |
There was a problem hiding this comment.
minor java/tsfile/src/main/java/org/apache/tsfile/read/common/block/column/BinaryColumnBuilder.java:179 — BinaryColumnBuilder.getRetainedSizeInBytes() now scans all rows and allocates per call
getBinaryValuesRetainedSize() walks every position and allocates an IdentityHashMap holding one entry per distinct Binary and per distinct payload on each invocation, replacing the previously O(1) cached arraysRetainedSizeInBytes. TsBlockBuilder.getRetainedSizeInBytes() (line 236) calls it for every column, so one call on an N-row block with C text columns does O(N*C) work plus transient allocation proportional to block content (e.g. ~16K map entries for 8K rows), turning a cheap getter into a GC-heavy operation in read paths that poll retained size.
Fix: Accumulate the distinct Binary/payload sizes incrementally in writeBinary (and on growCapacity) so getRetainedSizeInBytes() stays O(1), or only compute the scan when the estimate is actually needed.
There was a problem hiding this comment.
Fixed across 4ff096c1 and b00cc56d: BinaryColumnBuilder now updates identity-based accounting as values are appended, so getRetainedSizeInBytes() is O(1) in steady state without per-call row scans or map allocations. Binary.setValues() advances a shared modification version; the next estimate refreshes the cached set once, preserving payload-replacement accounting. Tests cover repeated Binary references, shared payloads, payload sizing, identity-table growth, and payload replacement.
|
Review-comment follow-up
|
| } | ||
|
|
||
| private void updateBinaryValuesRetainedSizeIfNeeded() { | ||
| long currentModificationVersion = Binary.getValuesModificationVersion(); |
There was a problem hiding this comment.
minor java/tsfile/src/main/java/org/apache/tsfile/read/common/block/column/BinaryColumnBuilder.java:212 — Retained-size cache invalidation is process-global, not per builder
Binary.VALUES_MODIFICATION_VERSION is one static counter bumped by every Binary.setValues(), including PooledBinary.setValues (PooledBinary.java:153), which never touches any builder. After any unrelated mutation, the next getRetainedSizeInBytes() or writeBinary() clears the identity table and re-walks all positionCount positions, so the intended O(1) steady state is lost; if a reused Binary is appended per row, every append rescans the column (O(n^2)).
Fix: Track invalidation per builder (e.g. keep the payload reference/length seen for each position, or a per-Binary version stamp recorded at append time) instead of a JVM-wide counter.
There was a problem hiding this comment.
Implemented in 5080ffde by replacing the process-wide counter with weak per-Binary listeners. A builder is notified only when a Binary it retains changes, so unrelated mutations no longer invalidate its cached size. The regression test covers this case, and the payload-replacement test remains passing. The focused suite passed 49 tests; full Java verify passed 1,474 tests total (11 skipped). The fix is now on the PR; cross-language and sanitizer checks remain outstanding. Leaving the thread unresolved.
| /** estimate memory usage of this series. */ | ||
| long estimateMaxSeriesMemSize(); | ||
|
|
||
| long getRetainedSizeInBytes(); |
There was a problem hiding this comment.
minor java/tsfile/src/main/java/org/apache/tsfile/write/chunk/IChunkWriter.java:42 — New abstract IChunkWriter method breaks external implementors
long getRetainedSizeInBytes(); is added to the public IChunkWriter interface without a default body. Only the two in-tree implementors (ChunkWriterImpl, AlignedChunkWriterImpl) were updated, so third-party chunk writers compiled against the previous tsfile artifact fail to compile and throw AbstractMethodError when updateMaxGroupMemSize() now invokes the method.
Fix: Declare it as default long getRetainedSizeInBytes() { return estimateMaxSeriesMemSize(); } so existing implementors keep working.
There was a problem hiding this comment.
Implemented in 5080ffde: getRetainedSizeInBytes() now defaults to estimateMaxSeriesMemSize(). A legacy-style implementation without the override verifies the fallback. The focused suite passed 49 tests; full Java verify passed 1,474 tests total (11 skipped). The fix is now on the PR; cross-language and sanitizer checks remain outstanding. Leaving the thread unresolved.
|
Review-comment follow-up
|
|
major Every value appended through writeBinary registers the builder via Binary.addValuesModificationListener (Binary.java:129-145), which allocates a WeakReference[1] plus a WeakReference (~56 B) on that Binary. Binary exposes no unregister API and build() (line 162-166) hands the same Binary[] to BinaryColumn, so the bookkeeping survives for the column's lifetime, and Binary.ramBytesUsed() now reports it, inflating BinaryColumn.getRetainedSizeInBytes() by ~56 B per distinct TEXT/BLOB value on the read path (PageReader -> TsBlockBuilder). Fix: Avoid per-Binary registration for the O(1) cache, or add Binary.removeValuesModificationListener and unregister in build()/when retainedBinaryValues is cleared, so built columns do not carry accounting-only objects. |
Summary
Validation
spotless:apply -P with-integration-testspassed.Performance impact (memory-rich workload)
-Xms2g -Xmx4g.developand 155.091 ms on this PR (+0.47%), which is negligible in this run.developand 484.011 ms on this PR (3.28x; about 69.5% lower write throughput). This intentionally stresses estimation overhead and does not represent the normal adaptive path.Overall, the impact is negligible when memory is sufficient and estimation is infrequent, while estimation cost becomes significant when checks are forced at a very high frequency.