You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@iotdb.apache.org by "hongzhi-gao (via GitHub)" <gi...@apache.org> on 2026/10/13 07:14:39 UTC

[PR] Refactor write memory accounting into named memory blocks [iotdb]

hongzhi-gao opened a new pull request, #18848:
URL: https://github.com/apache/iotdb/pull/18848

   ## Description
   
   Write-memory accounting is spread across MemTables, TsFileProcessors and DataRegions, requiring callers to update several counters together. This change introduces named, categorized owner blocks that propagate usage to their accounting scope and tie rollback/release to the owner's lifecycle.
   
   ### Accounting and lifecycle
   
   - Add `WriteMemoryBlock` and `WriteMemoryManager` for MemTable arrays, Binary values, recovered totals, TsFile metadata and flush temporary reservations. Pending reservations count toward admission but become used MemTable memory only after admission succeeds. WAL failures roll back the admitted deltas.
   - Replace positional write-memory deltas with named fields across row, mixed-row and split-tablet paths. MemTable release closes its blocks and updates the region total once; query-held TVLists retain their existing resource ownership.
   - Preserve the WAL snapshot's aggregate memory field. Recovery places that aggregate in a separate category rather than guessing an array/Binary breakdown.
   - Scope flush reservations to actual worker lifetime: propagate worker failures, cancel and await both workers, clear temporary references, then release the reservation. Budget reload retains outstanding reservations.
   - Store each WAL queue entry's original charge and refund it on dequeue or interrupted enqueue.
   
   ### Array-pool accounting and hot paths
   
   Count idle arrays by actual shallow size under the existing per-type queue locks. A new `ReadOnlyMemoryBlock` exposes an exact snapshot to the existing memory-manager tree; readers acquire queue locks in a fixed order. This avoids an additional global atomic update on each array borrow/return. `WriteMemoryBlock` uses a monitor-guarded `long`; region totals remain atomic. Zero-delta writes skip reservation creation while retaining pressure checks.
   
   SQL, configured memory limits, file/WAL formats and the existing admission policy are unchanged. Accounting follows write ownership, not total JVM heap liveness. New exception messages are provided in both English and Chinese.
   
   ### Verification
   
   Executed remotely on Linux with JDK 21 (production compilation targets Java 17), against the exact submitted source:
   
   - Spotless and focused Maven tests: **122 passed**, zero failures/errors/skips (7 Node Commons, 115 DataNode).
   - Full-reactor `mvn test-compile -DskipTests` and `mvn test-compile -DskipTests -P with-zh-locale`: passed. Packaging prerequisites were built with `mvn install -DskipTests -pl iotdb-core/datanode,iotdb-core/confignode,iotdb-client/cli -am`.
   - **4 lifecycle ITs passed**, using the repository's real 1C1D fixtures through JUnitCore, rather than Maven Failsafe. Coverage includes 63/64/65 array boundaries, sparse/new aligned columns, repeated flush/unsequence overwrite, oversized-WAL row/tablet rejection and retry, forced DataNode restart/recovery, and table writes split across devices/time partitions. Tests verify query results and live database write-memory metrics.
   - Targeted tests also cover concurrent reservations/snapshots, query-held TVList ownership, interrupted WAL enqueue, and flush failure/interruption cleanup.
   
   The focused Maven test selection was:
   
   ```sh
   mvn test -pl iotdb-core/node-commons,iotdb-core/datanode \
     -Dtest=MemoryBlockTest,MemoryManagerTest,ReadOnlyMemoryBlockTest,WriteMemoryBlockTest,WriteMemoryLifecycleTest,MemTableMemoryBlockTest,TsFileProcessorTest,MemTableFlushTaskTest,PrimitiveArrayManagerTest,BooleanTVListTest,IntTVListTest,LongTVListTest,FloatTVListTest,DoubleTVListTest,BinaryTVListTest,AlignedTVListTest \
     -Dsurefire.failIfNoSpecifiedTests=false
   ```
   
   Initial environment failures were resolved before reporting these results: missing distribution ZIP prerequisites, and JMX port collisions during IT node startup. The unchanged ITs passed after rerunning with free ports.
   
   ### Performance observations
   
   Compared with `eb0e3f1f2080e34bf5593bfd1cf63b62ecdba2e0`, using the same workload/configuration and three interleaved runs per version:
   
   | Workload (4 writers) | Median throughput | P50 RPC latency | P99 RPC latency |
   | --- | ---: | ---: | ---: |
   | Non-aligned Tablet, 1024 rows | -0.24% | +3.88% | +0.10% |
   | Aligned single row | +0.50% | -0.73% | +3.19% |
   | Aligned Tablet, 1024 rows | +4.36% | -4.60% | -3.58% |
   
   Environment: shared Xeon Gold 6130 KVM host, 32 vCPUs, JDK 21, 1C1D/SimpleConsensus, ASYNC WAL, memory control enabled, 2 GiB DataNode heap, array size 64, MemTable threshold 32 MiB, compaction and timed flush disabled. Fixed per-writer warmup/measurement calls were 50k/100k for non-aligned Tablet, 125k/250k for aligned rows, and 20k/40k for aligned Tablet. Each run checked acknowledged row counts through queries after a final FLUSH.
   
   These are controlled class-overlay comparisons, not two independent clean distribution builds. The throughput window excludes the final FLUSH; it does not measure synchronous durability throughput. Shared-host variability and existing QueryId waits affect single-row results. The repeated throughput regression observed during development did not recur in the final comparisons, but the latency increases above remain review considerations; these measurements do not establish a universal speedup.
   
   <hr>
   
   This PR has:
   - [x] been self-reviewed, including concurrent reads, writes and read/write interaction.
   - [x] added comments explaining accounting ownership, reservation ordering and snapshot lock ordering.
   - [x] added unit/component tests for lifecycle and failure paths.
   - [x] added integration tests and run them against a real 1C1D environment.
   
   ##### Key changed/added classes
   
   `WriteMemoryBlock`, `WriteMemoryManager`, `AbstractMemTable`, `TsFileProcessor`, `DataRegionInfo`, `TsFileProcessorInfo`, `MemTableFlushTask`, `SystemInfo`, `MemoryControlledWALEntryQueue`, `PrimitiveArrayManager`, `ReadOnlyMemoryBlock`, `MemoryManager`.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@iotdb.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Refactor write memory accounting into named memory blocks [iotdb]

Posted by "hongzhi-gao (via GitHub)" <gi...@apache.org>.
hongzhi-gao commented on code in PR #18848:
URL: https://github.com/apache/iotdb/pull/18848#discussion_r4290366591


##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/flush/MemTableFlushTask.java:
##########
@@ -382,6 +407,68 @@ public static void recordFlushPointsMetricInternal(
         WRITING_METRICS.recordFlushCost(WritingMetrics.FLUSH_STAGE_IO, ioTime);
       };
 
+  /** Tracks actual worker exit, including cancellation before the executor starts it. */
+  private final class FlushSubTask implements Runnable {
+    private final Runnable task;
+    private final CompletableFuture<Void> finished = new CompletableFuture<>();
+    private Thread runner;
+    private boolean cancelled;
+
+    private FlushSubTask(Runnable task) {
+      this.task = task;
+    }
+
+    @Override
+    public void run() {
+      synchronized (this) {
+        if (cancelled) {
+          return;
+        }
+        runner = Thread.currentThread();
+      }
+      try {
+        task.run();
+      } catch (Throwable failure) {
+        subTaskFailure.completeExceptionally(
+            failure instanceof CompletionException || failure instanceof UncheckedIOException
+                ? failure.getCause()
+                : failure);
+      } finally {
+        synchronized (this) {
+          runner = null;
+          finished.complete(null);
+        }
+      }
+    }
+
+    private synchronized boolean isCancelled() {
+      return cancelled;
+    }
+
+    private synchronized void cancel() {
+      cancelled = true;
+      if (runner != null) {
+        runner.interrupt();
+      } else {
+        finished.complete(null);
+      }
+    }
+
+    private boolean awaitExit() {
+      boolean interrupted = false;
+      while (true) {
+        try {
+          finished.get();
+          return interrupted;
+        } catch (InterruptedException e) {
+          interrupted = true;
+        } catch (ExecutionException e) {
+          throw new AssertionError(e);
+        }
+      }
+    }

Review Comment:
   Replaced the exit wait with a CountDownLatch, so worker failures are propagated through subTaskFailure to syncFlushMemTable rather than being represented as an AssertionError in cleanup. The caller still has to wait after interruption: cancellation only requests worker interruption, and the worker may still be using the writer/buffers. Returning here would release its flush-memory reservation before those resources stop being used. Cleanup waits for both workers to exit, then restores the caller's interrupt flag and propagates the original failure/interruption. The regression now also interrupts the caller again during cancellation and checks that the reservation remains live until the I/O worker exits.
   
   Implemented in [f1945e5201](https://github.com/apache/iotdb/pull/18848/commits/f1945e52015f4d3b99ffc036b9c903592feb3f82).
   
   Validation: 87 focused tests passed; full-reactor test compilation passed for both the default and Chinese locales; all 4 IoTDBWriteMemoryLifecycleIT cases passed in 1 ConfigNode + 1 DataNode, including forced-restart WAL recovery. Independent Codex review found no actionable issues.



##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/memtable/IMemTable.java:
##########
@@ -77,7 +79,13 @@ void writeAlignedRow(
    */
   long memSize();
 
-  /** only used when mem control enabled */
+  void setWriteMemoryManager(WriteMemoryManager manager);
+
+  WriteMemoryBlock getArrayMemoryBlock();
+
+  WriteMemoryBlock getBinaryMemoryBlock();
+
+  /** Adds array/TVList structural memory; Binary payload has a separate block. */
   void addTVListRamCost(long cost);

Review Comment:
   Added getStructureMemoryBlock() and the MEMTABLE_STRUCTURE category. Aligned TVList container estimates are now accounted separately from arrays/bitmaps and Binary payloads, using the existing before/after reconciliation for working and sorted TVLists. This keeps the aggregate estimate unchanged rather than adding a second charge. The block participates in attach, clear and release; WAL snapshots retain the existing aggregate field and recover it into the recovered-total block. Extended coverage checks category totals, WAL-failure rollback, clear/release, and both old/current snapshot readers.
   
   Implemented in [f1945e5201](https://github.com/apache/iotdb/pull/18848/commits/f1945e52015f4d3b99ffc036b9c903592feb3f82).



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@iotdb.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Refactor write memory accounting into named memory blocks [iotdb]

Posted by "jt2594838 (via GitHub)" <gi...@apache.org>.
jt2594838 commented on code in PR #18848:
URL: https://github.com/apache/iotdb/pull/18848#discussion_r4269611732


##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/flush/MemTableFlushTask.java:
##########
@@ -382,6 +407,68 @@ public static void recordFlushPointsMetricInternal(
         WRITING_METRICS.recordFlushCost(WritingMetrics.FLUSH_STAGE_IO, ioTime);
       };
 
+  /** Tracks actual worker exit, including cancellation before the executor starts it. */
+  private final class FlushSubTask implements Runnable {
+    private final Runnable task;
+    private final CompletableFuture<Void> finished = new CompletableFuture<>();
+    private Thread runner;
+    private boolean cancelled;
+
+    private FlushSubTask(Runnable task) {
+      this.task = task;
+    }
+
+    @Override
+    public void run() {
+      synchronized (this) {
+        if (cancelled) {
+          return;
+        }
+        runner = Thread.currentThread();
+      }
+      try {
+        task.run();
+      } catch (Throwable failure) {
+        subTaskFailure.completeExceptionally(
+            failure instanceof CompletionException || failure instanceof UncheckedIOException
+                ? failure.getCause()
+                : failure);
+      } finally {
+        synchronized (this) {
+          runner = null;
+          finished.complete(null);
+        }
+      }
+    }
+
+    private synchronized boolean isCancelled() {
+      return cancelled;
+    }
+
+    private synchronized void cancel() {
+      cancelled = true;
+      if (runner != null) {
+        runner.interrupt();
+      } else {
+        finished.complete(null);
+      }
+    }
+
+    private boolean awaitExit() {
+      boolean interrupted = false;
+      while (true) {
+        try {
+          finished.get();
+          return interrupted;
+        } catch (InterruptedException e) {
+          interrupted = true;
+        } catch (ExecutionException e) {
+          throw new AssertionError(e);
+        }
+      }
+    }

Review Comment:
   Why does the interruption not exit?
   And why is the ExecutionException wrapped with AssertionError?



##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/memtable/IMemTable.java:
##########
@@ -77,7 +79,13 @@ void writeAlignedRow(
    */
   long memSize();
 
-  /** only used when mem control enabled */
+  void setWriteMemoryManager(WriteMemoryManager manager);
+
+  WriteMemoryBlock getArrayMemoryBlock();
+
+  WriteMemoryBlock getBinaryMemoryBlock();
+
+  /** Adds array/TVList structural memory; Binary payload has a separate block. */
   void addTVListRamCost(long cost);

Review Comment:
   Add a structureMemoryBlock?



##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/rescon/memory/SystemInfo.java:
##########
@@ -369,8 +371,10 @@ public long getMemorySizeForCompaction() {
     return compactionMemoryBlock.getTotalMemorySizeInBytes();
   }
 
-  public void loadWriteMemory() {
-    memorySizeForMemtable = memoryConfig.getMemtableMemoryManager().getTotalMemorySizeInBytes();
+  public synchronized void loadWriteMemory() {
+    memorySizeForMemtable =
+        memoryConfig.getMemtableMemoryManager().getTotalMemorySizeInBytes()
+            - flushMemoryManager.getMemoryUsageInBytes();

Review Comment:
   explain the change



##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/rescon/memory/PrimitiveArrayManager.java:
##########
@@ -268,12 +283,45 @@ public static void release(Object array) {
       ArrayDeque<Object> arrays = POOLED_ARRAYS[order];
       if (arrays.size() < LIMITS[order]) {
         arrays.add(array);
+        POOLED_ARRAY_BYTES[order] += arraySize(array);
       } else {
         StorageEngineMemoryMetrics.getInstance().incPamReleaseFailure();
       }
     }
   }
 
+  public static IMemoryBlock getMemoryBlock() {
+    return POOLED_ARRAYS_MEMORY_BLOCK;
+  }
+
+  private static long getPooledArrayMemoryInBytes(int order) {
+    if (order == POOLED_ARRAYS.length) {
+      return 0;
+    }
+    // Hold every queue lock in ascending order for a linearizable total. Borrow/return paths
+    // hold only one queue lock and never call this method or the memory manager.
+    synchronized (POOLED_ARRAYS[order]) {
+      return POOLED_ARRAY_BYTES[order] + getPooledArrayMemoryInBytes(order + 1);
+    }
+  }
+
+  private static long arraySize(Object array) {
+    // Use typed array lengths on this hot path instead of reflective shallowSizeOf(Object).
+    if (array instanceof long[]) {
+      return RamUsageEstimator.sizeOf((long[]) array);
+    } else if (array instanceof int[]) {
+      return RamUsageEstimator.sizeOf((int[]) array);
+    } else if (array instanceof boolean[]) {
+      return RamUsageEstimator.sizeOf((boolean[]) array);
+    } else if (array instanceof float[]) {
+      return RamUsageEstimator.sizeOf((float[]) array);
+    } else if (array instanceof double[]) {
+      return RamUsageEstimator.sizeOf((double[]) array);
+    }
+    // Binary[] entries have been cleared; only the shallow reference array belongs to the pool.
+    return RamUsageEstimator.shallowSizeOf((Binary[]) array);
+  }

Review Comment:
   How about caching the size calculators in an array consistent with POOLED_ARRAYS to reduce unnecessary type judgement.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@iotdb.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Refactor write memory accounting into named memory blocks [iotdb]

Posted by "hongzhi-gao (via GitHub)" <gi...@apache.org>.
hongzhi-gao commented on code in PR #18848:
URL: https://github.com/apache/iotdb/pull/18848#discussion_r4290368146


##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/rescon/memory/PrimitiveArrayManager.java:
##########
@@ -268,12 +283,45 @@ public static void release(Object array) {
       ArrayDeque<Object> arrays = POOLED_ARRAYS[order];
       if (arrays.size() < LIMITS[order]) {
         arrays.add(array);
+        POOLED_ARRAY_BYTES[order] += arraySize(array);
       } else {
         StorageEngineMemoryMetrics.getInstance().incPamReleaseFailure();
       }
     }
   }
 
+  public static IMemoryBlock getMemoryBlock() {
+    return POOLED_ARRAYS_MEMORY_BLOCK;
+  }
+
+  private static long getPooledArrayMemoryInBytes(int order) {
+    if (order == POOLED_ARRAYS.length) {
+      return 0;
+    }
+    // Hold every queue lock in ascending order for a linearizable total. Borrow/return paths
+    // hold only one queue lock and never call this method or the memory manager.
+    synchronized (POOLED_ARRAYS[order]) {
+      return POOLED_ARRAY_BYTES[order] + getPooledArrayMemoryInBytes(order + 1);
+    }
+  }
+
+  private static long arraySize(Object array) {
+    // Use typed array lengths on this hot path instead of reflective shallowSizeOf(Object).
+    if (array instanceof long[]) {
+      return RamUsageEstimator.sizeOf((long[]) array);
+    } else if (array instanceof int[]) {
+      return RamUsageEstimator.sizeOf((int[]) array);
+    } else if (array instanceof boolean[]) {
+      return RamUsageEstimator.sizeOf((boolean[]) array);
+    } else if (array instanceof float[]) {
+      return RamUsageEstimator.sizeOf((float[]) array);
+    } else if (array instanceof double[]) {
+      return RamUsageEstimator.sizeOf((double[]) array);
+    }
+    // Binary[] entries have been cleared; only the shallow reference array belongs to the pool.
+    return RamUsageEstimator.shallowSizeOf((Binary[]) array);
+  }

Review Comment:
   Added cached typed size calculators indexed by TSDataType.serialize(), matching POOLED_ARRAYS. Borrow/return now use the calculator for the selected pool instead of repeating the instanceof chain to calculate its size. The calculators still use the actual array length, and Binary[] accounting remains shallow after clearing its elements. Added coverage for the supported types and their primitive/Binary pool aliases; existing variable-length and concurrent pool-accounting regressions also pass.
   
   Implemented in [f1945e5201](https://github.com/apache/iotdb/pull/18848/commits/f1945e52015f4d3b99ffc036b9c903592feb3f82).



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@iotdb.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Refactor write memory accounting into named memory blocks [iotdb]

Posted by "jt2594838 (via GitHub)" <gi...@apache.org>.
jt2594838 commented on code in PR #18848:
URL: https://github.com/apache/iotdb/pull/18848#discussion_r4280052303


##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/rescon/memory/SystemInfo.java:
##########
@@ -369,8 +371,10 @@ public long getMemorySizeForCompaction() {
     return compactionMemoryBlock.getTotalMemorySizeInBytes();
   }
 
-  public void loadWriteMemory() {
-    memorySizeForMemtable = memoryConfig.getMemtableMemoryManager().getTotalMemorySizeInBytes();
+  public synchronized void loadWriteMemory() {
+    memorySizeForMemtable =
+        memoryConfig.getMemtableMemoryManager().getTotalMemorySizeInBytes()
+            - flushMemoryManager.getMemoryUsageInBytes();

Review Comment:
   explain the change



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@iotdb.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Refactor write memory accounting into named memory blocks [iotdb]

Posted by "jt2594838 (via GitHub)" <gi...@apache.org>.
jt2594838 merged PR #18848:
URL: https://github.com/apache/iotdb/pull/18848


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@iotdb.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org