Skip to content

feat(java): add retained memory estimates - #1161

Open
Caideyipi wants to merge 10 commits into
apache:developfrom
Caideyipi:feat/retained-memory-estimates-20261127
Open

Caideyipi wants to merge 10 commits into
apache:developfrom
Caideyipi:feat/retained-memory-estimates-20261127

Conversation

@Caideyipi

@Caideyipi Caideyipi commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Add retained-memory estimates for Java encoders, page/chunk writers, statistics, tablets, and column builders.
  • Add regression coverage for identity de-duplication, buffer reuse, and DeltaBinary boundaries and round trips.

Validation

  • Focused local Java tests: 8 test classes, 114 tests passed.
  • spotless:apply -P with-integration-tests passed.
  • Full cross-language Maven verification, C++ ASan, Python ASan/LSan, compatibility checks, and static analysis have not been run locally; please review the CI results for the checks that this change triggers.

Performance impact (memory-rich workload)

  • Environment: dedicated host with 16 CPUs and about 30 GB available memory; Java 17.0.9; benchmark JVM configured with -Xms2g -Xmx4g.
  • Workload: 524,288 rows across 64 devices, with 8 INT64 measurements per device; a 1.5 GB memory threshold was configured. No flushes occurred during the measured write phase, and both versions produced a 34,153,533-byte file.
  • With the normal adaptive check (1 estimate per benchmark), median write time across 10 iterations was 154.358 ms on develop and 155.091 ms on this PR (+0.47%), which is negligible in this run.
  • In a forced high-frequency scenario (one estimate per tablet; 1,024 estimates per benchmark), median write time was 147.635 ms on develop and 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.

return 0;
}
long retainedSize = RamUsageEstimator.shallowSizeOf(output);
if (output instanceof PublicBAOS publicOutput) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

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.

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)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

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.

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;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

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.

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()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

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.

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);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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

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.

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) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

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.

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.

@Caideyipi
Caideyipi marked this pull request as draft November 27, 2026 10:40
@Caideyipi
Caideyipi marked this pull request as ready for review November 27, 2026 11:38
retainedSizeInBytes += columnBuilder.getRetainedSizeInBytes();
}
return retainedSizeInBytes;
return retainedSizeInBytes - valueColumnBuilders.length * SHARED_STATUS_SIZE;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

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.

Fixed in 6c3d421d: TsBlockBuilder now adds its TsBlockBuilderStatus once and removes the per-value-column subtraction.

}
}

public long estimateMaxSeriesMemSize() {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

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.

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.

@Caideyipi

Copy link
Copy Markdown
Contributor Author

Review-comment follow-up

  • Fixed the actionable findings: runtime-aware boxed-value cache accounting, nonnegative schema-name accounting, null-safe PageWriter estimates, correct TsBlockBuilderStatus accounting, and separate live chunk-size versus retained-capacity estimates.
  • No code change was needed for the PublicBAOS high-water estimate, dictionary backing-capacity estimate, or Sprintz boxed-value accounting; the current implementation already handles those cases.
  • Verification: spotless:apply -P with-java -pl java/tsfile -am passed; focused Maven tests passed with 107 tests across six classes, including a run with -XX:AutoBoxCacheMax=1024.
  • Reviewed SHA: 632677ea553015427036b35ac615bafcd4a780f8.
  • Final local and confirmed remote SHA: 6c3d421d29a80550e35d807937887c3ac427efd8.
  • Remote CI: Python analysis passed; other checks remain pending; CodeQL and Codecov are skipped. The PR remains open and non-draft, with no update steps incomplete.

@Caideyipi
Caideyipi marked this pull request as draft November 30, 2026 02:57
…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
@Caideyipi
Caideyipi marked this pull request as ready for review December 1, 2026 03:00

@Override
public long getRetainedSizeInBytes() {
return RamUsageEstimator.shallowSizeOf(this)

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.

May cache the shallow size if it is static.

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.

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.

Comment on lines +79 to +81
if (index > 127) {
dictionaryEntriesRetainedSize += BOXED_INDEX_SIZE;
}

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.

Use the cache bound?

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.

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.

@Caideyipi

Copy link
Copy Markdown
Contributor Author

Review-comment follow-up

  • Confirmed BitmapEncoder already caches the boxed Integer shallow size in a static final field; no code change was needed.
  • Updated DictionaryEncoder to use the JVM-detected Integer cache upper bound instead of hard-coded 127; added a regression test.
  • Verification: scoped Spotless formatting completed successfully. EncoderMemoryEstimateTest passed all 21 tests with -XX:AutoBoxCacheMax=1024.
  • Reviewed SHA: a6fe2b1c21c944ad08d70cf66baca46d1af1cff2.
  • Final local and confirmed remote SHA: 7b95a6697f98464fb5f51f0d57c346a63b525158.
  • Remote CI: checks are queued/in progress; Codecov is skipped.
  • The PR remains open and non-draft.

return RamUsageEstimator.shallowSizeOf(this)
+ RamUsageEstimator.shallowSizeOf(pageBuffer)
+ RamUsageEstimator.sizeOf(pageBuffer.getBuf())
+ pageWriter.estimateRetainedMemSize()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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().

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.

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() {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

@Caideyipi Caideyipi Dec 2, 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.

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.

@Caideyipi

Caideyipi commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor Author

Review-comment follow-up

  • Fixed both findings in 4ff096c1 and b00cc56d: null-safe retained-size estimates after clearPageWriter() and incremental identity-based BinaryColumnBuilder accounting.
  • Binary.setValues() invalidates the cache; the next estimate refreshes it once, while repeated reads remain O(1) in steady state.
  • Verification: mvnw.cmd spotless:apply -P with-java -pl java/tsfile -am; mvnw.cmd test -P with-java -pl java/tsfile -am -Dtest=ColumnTest,ValueChunkWriterTest -Dsurefire.failIfNoSpecifiedTests=false -DforkCount=1 -DreuseForks=false -DargLine=-Xmx1g passed (47 tests, 0 failures).
  • Reviewed SHA: 7b95a6697f98464fb5f51f0d57c346a63b525158.
  • Final local and confirmed remote SHA: b00cc56d782974742b48321f892a91a23aad1540.
  • Remote CI for the latest SHA is queued or in progress; Codecov is skipped.
  • The PR remains open and non-draft; discussions remain unresolved.

}

private void updateBinaryValuesRetainedSizeIfNeeded() {
long currentModificationVersion = Binary.getValuesModificationVersion();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

@Caideyipi Caideyipi Dec 2, 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.

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();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

@Caideyipi Caideyipi Dec 2, 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.

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.

@Caideyipi

Caideyipi commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor Author

Review-comment follow-up

  • Scoped Binary cache invalidation to weak listeners on values retained by each builder; unrelated mutations no longer trigger column rescans.
  • Made IChunkWriter.getRetainedSizeInBytes() default to estimateMaxSeriesMemSize() for compatibility with existing implementors.
  • Added regression tests for unrelated Binary mutation and a legacy-style IChunkWriter implementation.
  • Verification: focused tests passed (49/49); full Java verify -P with-java passed (1,474 tests total, 1,463 executed, 11 skipped).
  • Remaining required checks: full cross-language formatting, the combined Java/C++/Python suite, and C++/Python sanitizer checks have not passed or run; they remain outstanding. PR CI checks are pending.
  • Reviewed base SHA: b00cc56d782974742b48321f892a91a23aad1540.
  • Final local and confirmed remote SHA: 5080ffdea706a286670444799fd94c3fef559567.
  • The commit is now pushed to the PR branch. The PR remains open and non-draft; discussions remain unresolved.

@luoluoyuyu

Copy link
Copy Markdown
Member

major java/tsfile/src/main/java/org/apache/tsfile/read/common/block/column/BinaryColumnBuilder.java:238 — Listener bookkeeping is attached permanently to every read Binary, inflating TEXT block memory

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants