comphead commented on code in PR #7840:
URL: https://github.com/apache/datafusion-comet/pull/7840#discussion_r4788738550


##########
spark/src/main/scala/org/apache/comet/CometConf.scala:
##########
@@ -252,6 +252,16 @@ object CometConf extends ShimCometConf {
       .booleanConf
       .createWithDefault(false)
 
+  val COMET_PARQUET_PAGE_MEMORY_ENABLED: ConfigEntry[Boolean] =
+    conf("spark.comet.parquet.pageMemory.enabled")
+      .category(CATEGORY_PARQUET)
+      .doc(
+        "Reserve task memory for compressed Parquet pages and estimate the 
working memory for " +
+          "decoding fetched columns and building one batch. Cloud reads 
include fetched gaps. " +
+          "A refused reservation allows the scan to continue.")
+      .booleanConf
+      .createWithDefault(true)

Review Comment:
   This is on by default and adds unspillable bytes to every task that runs a 
native Parquet scan. Under `fair_unified` that lowers the limit of every 
consumer that can spill (`(task_share - unspillable) / num_spill` in 
`fair_pool.rs`) and the room left in `pool_size` for consumers that cannot. A 
sort's first request or a hash join build that fit before can now be refused, 
and `ExternalSorter` fails on a refused first request. Each page `try_grow` can 
also make Spark spill JVM consumers in the same task, such as a JVM shuffle 
writer fed by the scan. The only evidence is one single-partition sort on a 
debug build, and it already shows an extra spill per run. Can you post the 
SF100 TPC-H q9/q10 run the description mentions, or TPC-DS, with the flag on 
and off at a realistic off-heap size, with spill counts and any new task 
failures? Until that exists I would default this to `false`. I did not run this.



##########
native/core/src/parquet/eager_page_index_reader_factory.rs:
##########
@@ -220,8 +228,66 @@ fn ranges_bytes(ranges: &[Range<u64>]) -> usize {
     ranges.iter().map(range_bytes).sum()
 }
 
+// The owner is installed before the cloud store splits a response into 
logical pages.
+// A single surviving slice pins the complete response, including the 
coalesced gaps.
+struct ReservedPageBytes {
+    bytes: Bytes,
+    _reservation: MemoryReservation,
+}
+
+impl AsRef<[u8]> for ReservedPageBytes {
+    fn as_ref(&self) -> &[u8] {
+        &self.bytes
+    }
+}
+
+#[derive(Debug)]
+struct ScanPageMemory {
+    reservation: MemoryReservation,
+    source: ScanIoSource,
+    skip_after_refusal: AtomicUsize,
+}
+
+impl ScanPageMemory {
+    fn hold(&self, bytes: Bytes, unreserved: &Count) -> ParquetResult<Bytes> {
+        if bytes.is_empty() {
+            return Ok(bytes);
+        }
+        // A refusal can spill unrelated Spark consumers. Let several 
responses pass before
+        // asking again. Independent readers of this scan share the backoff.
+        const RESPONSES_BEFORE_RETRY: usize = 8;
+        let skip =
+            self.skip_after_refusal
+                .try_update(Ordering::Relaxed, Ordering::Relaxed, |remaining| {
+                    remaining.checked_sub(1)
+                });
+        if skip.is_err() {
+            let reservation = self.reservation.new_empty();
+            match reservation.try_grow(bytes.len()) {

Review Comment:
   Under `fair_unified` each `try_grow` here takes the pool lock, runs 
`block_in_place` and calls `acquireMemory` over JNI (`ask_spark` in 
`spark_memory.rs`). Dropping the `Bytes` then calls `releaseMemory`. For local 
and HDFS stores `get_ranges` returns one response per requested range 
(`LocalFileSystem::get_ranges` in object_store 0.13.2 reads each range 
separately), so a wide projection or a page-index-pruned read pays two JNI 
calls per column chunk or page range in each row group. Could this reserve once 
per `get_byte_ranges` call, for the sum of the response lengths, and share one 
`Arc`'d reservation owner across the responses? As far as I can tell from 
DataFusion 55.2's `push_decoder.rs`, those bytes are freed together when the 
row group's reader drops anyway. Either way, a release-build number for a wide 
file (hundreds of columns, several row groups) with the flag on and off would 
show the cost. I did not measure it.



##########
spark/src/main/scala/org/apache/spark/sql/comet/CometMetricNode.scala:
##########
@@ -468,6 +468,12 @@ object CometMetricNode {
         SQLMetrics.createMetric(sc, "Number of row groups matched by limit 
pruning (not pruned)"),
       "bytes_scanned" ->
         SQLMetrics.createSizeMetric(sc, "Number of bytes scanned"),
+      "scan_decode_reserved_bytes_total" ->
+        SQLMetrics.createSizeMetric(sc, "Cumulative granted Parquet decode 
estimates"),
+      "scan_decode_unreserved_bytes_total" ->
+        SQLMetrics.createSizeMetric(sc, "Cumulative refused Parquet decode 
estimates"),
+      "scan_io_unreserved_page_bytes_total" ->
+        SQLMetrics.createSizeMetric(sc, "Cumulative page bytes skipped after 
memory refusal"),

Review Comment:
   The bytes are not skipped. `hold` returns them unchanged and the scan 
decodes them, just without a reservation. Please match `metrics.md`, for 
example "Parquet page bytes read without a memory reservation".



##########
docs/source/contributor-guide/memory_management.md:
##########
@@ -615,6 +615,16 @@ diverge for several structural reasons:
   its estimate misses (see [Native writers](#native-writers)), `object_store` 
request buffers, and
   tokio's own machinery all allocate without reserving. Only operators that 
were explicitly written
   to reserve show up in the pool.
+  With `spark.comet.parquet.pageMemory.enabled`, the Parquet scan also 
reserves compressed
+  page buffers. For cloud stores it charges the merged range before splitting 
it into pages.
+  For local and custom stores it charges each range the store returns. A 
separate reservation
+  estimates decoder memory on the first data fetch. For each fetched leaf in 
the current row
+  group it includes up to 1 MiB of uncompressed pages and one batch of values, 
scaled to the
+  smaller of the configured batch size and the group's row count. Nested 
estimates use the leaf
+  value count and repetition and definition levels. Later fetches of other 
leaves, including
+  predicate columns, can raise this estimate. The reader retains its highest 
granted estimate
+  until close. The estimate excludes footer, page index, and Bloom filter 
allocations.
+  Set `spark.comet.parquet.pageMemory.enabled=false` to disable both 
reservations.

Review Comment:
   With this on by default, the example at line 383 of this page no longer 
holds. It describes a task that holds a native pool but no memory, "such as a 
native scan that feeds a JVM shuffle". That scan now reserves page and decode 
bytes, so Spark counts the task too. Please update or replace that example in 
this PR.



-- 
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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to