Visorgood commented on code in PR #221:
URL: https://github.com/apache/datafusion-site/pull/221#discussion_r4679726701


##########
content/blog/2026-11-22-comet-spark-comparison.md:
##########
@@ -0,0 +1,391 @@
+---
+layout: post
+title: Where Apache Spark loses time, and how Apache DataFusion Comet gets it 
back
+date: 2026-11-22
+author: Viacheslav Inozemtsev
+categories: [performance, subprojects]
+---
+
+<!--
+{% comment %}
+Licensed to the Apache Software Foundation (ASF) under one or more
+contributor license agreements.  See the NOTICE file distributed with
+this work for additional information regarding copyright ownership.
+The ASF licenses this file to you under the Apache License, Version 2.0
+(the "License"); you may not use this file except in compliance with
+the License.  You may obtain a copy of the License at
+
+http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+{% endcomment %}
+-->
+
+[TOC]
+
+## Introduction
+
+[Apache DataFusion Comet](https://datafusion.apache.org/comet/) is an 
accelerator for [Apache Spark](https://spark.apache.org/) that can also read 
and write [Apache Iceberg](https://iceberg.apache.org/) tables natively. It is 
built on top of [Apache DataFusion](https://datafusion.apache.org/), a query 
engine written in Rust on [Apache Arrow](https://arrow.apache.org/). Comet 
plugs into Spark without changes to the jobs: it takes the physical plan that 
Spark has built and executes the operators it supports in native code. The 
promise is better performance thanks to two things: Comet processes data in 
columnar Arrow batches instead of one row at a time, and it runs in native code 
outside the JVM, without JVM objects and their overhead. The project's README 
states a speedup of about 1.8 times on TPC-DS at 1 TB, which translates into 
roughly 45% lower cost.
+
+Numbers like these are useful, but they don't explain where the gain comes 
from. The usual answer – "Comet is columnar and native" – is true, but it 
explains less than it seems, because Spark's own Iceberg reader already decodes 
Parquet into Arrow vectors. If both engines start from columnar batches, where 
exactly does Spark lose time, and what does Comet do differently? I wanted to 
see this in detail, step by step, on a real job.
+
+In this post, I will take one ordinary ETL job – read an Iceberg table, filter 
it, compute a value, aggregate it, and write the result into another Iceberg 
table – and run it with plain Spark and with Spark + Comet. We will follow a 
few rows through every step of the job in both engines, look at the CPU 
profiles, and estimate how much CPU each step costs. On 8 cores, plain Spark 
took 38.7 seconds and 295 CPU-seconds, and Spark with Comet took 10.5 seconds 
and 76 CPU-seconds, with the same output. Then we will look at the opposite 
case: how one unsupported expression takes most of this gain away. I will 
finish with a practical guide on checking and tuning Comet for your own jobs.
+
+Everything in this post is reproducible with two commands, `docker build` and 
`docker run`, from the repository 
[Visorgood/spark-comet-iceberg-bench](https://github.com/Visorgood/spark-comet-iceberg-bench).
 All numbers come from Spark 4.1.3, Iceberg 1.11.0 and Comet 1.2.0.
+
+## The benchmark job
+
+For the data, I use TPC-H – a standard decision-support benchmark with a 
synthetic dataset of customers, orders, parts and suppliers, which can be 
generated at any size set by a scale factor. Its largest table is `lineitem`, 
with one row per line of a customer order: the order key, the part, the 
quantity, the price, the discount, the ship date, and other attributes. At 
scale factor 100, `lineitem` has 600 million rows.
+
+The job computes the revenue of each order from the lines shipped since 1995 – 
a typical ETL step that touches every part of the engine, from the scan to the 
write:
+
+```sql
+INSERT INTO lake.tpch.order_revenue
+SELECT l_orderkey,
+       sum(l_extendedprice * (1 - l_discount)) AS revenue,
+       count(*)                                AS lines
+FROM   lake.tpch.lineitem
+WHERE  l_shipdate >= DATE '1995-01-01'
+GROUP  BY l_orderkey
+```
+
+A few details of this setup matter for the results:
+
+- **Source.** `lineitem` at scale factor 100 is stored in an Iceberg table 
with Iceberg's defaults: Parquet data files with zstd compression, 15.1 GiB in 
206 files. The query needs only four of the 16 columns, and Comet's scan 
metrics show 3.5 GiB read from these files.
+- **Target.** An unpartitioned Iceberg table with no sort order and default 
properties. In this case, Iceberg asks Spark for no extra shuffle or sort 
before the write, and the write stays eligible for Comet's native Iceberg 
writer.
+- **Shape.** An order has about four lines, so the partial aggregate shrinks 
the data only about four times, and the shuffle still carries 87 million rows. 
A query with few groups, like TPC-H Q1, would hide the shuffle.
+- **Types.** The money columns are `decimal(15,2)`. The product 
`l_extendedprice * (1 - l_discount)` is `decimal(32,4)`, and the sum is 
`decimal(38,4)`, both wider than 18 digits. As we will see later, this matters 
more than anything else in this job.
+- **`INSERT INTO` rather than `CREATE TABLE AS SELECT`.** Comet's native 
Iceberg write covers append, overwrite and copy-on-write DML, but not CTAS.
+
+Here are the physical plans of both runs:
+
+| Step | Spark | Spark + Comet |
+| --- | --- | --- |
+| Read | `BatchScan` (Iceberg) → `ColumnarToRow` | `CometIcebergNativeScan` |
+| Filter, compute | `Filter`, `Project` (whole-stage codegen) | `CometFilter`, 
`CometProject` |
+| Partial aggregate | `HashAggregate` (partial) | `CometHashAggregate` 
(partial) |
+| Shuffle | `Exchange hashpartitioning(l_orderkey, 200)` | `CometExchange` 
(native shuffle) |
+| Final aggregate | `HashAggregate` (final) | `CometHashAggregate` (final) |
+| Write | `AppendData`: iceberg-java writes rows | `CometIcebergWrite` under 
`IcebergCommit` |
+
+The Comet plan requires `spark.comet.write.iceberg.enabled=true`. The native 
write is off by default in Comet 1.2, and without it the plan ends with 
`CometColumnarToRow` → `AppendData`. Reading a Comet plan comes down to one 
rule: every `Comet*` node is accelerated, a node without the prefix is plain 
Spark, and `CometColumnarToRow` marks the place where Arrow batches become rows.
+
+## How Spark executes the job
+
+Spark on Iceberg is not row-based from the disk up. Iceberg's reader decodes 
Parquet into Arrow vectors on the JVM, and only at the first operator does the 
batch become a stream of rows. From there on, filtering, decimal math, hashing, 
hash map updates, partitioning and serialization all run once per row, until 
the Iceberg writer turns the rows back into columns.
+
+<figure>
+<a href="/blog/images/comet-spark-comparison/01-spark-plan.png">
+<img
+src="/blog/images/comet-spark-comparison/01-spark-plan.png"
+width="100%"
+class="img-fluid"
+alt="Plain Spark, Iceberg to Iceberg: columnar at both ends, rows in between. 
From ColumnarToRow to the Iceberg writer, every highlighted step runs once per 
row."
+/>
+</a>
+<figcaption><b>Figure 1</b>: Plain Spark, Iceberg to Iceberg: columnar at both 
ends, rows in between. From <code>ColumnarToRow</code> to the Iceberg writer, 
every highlighted step runs once per row.</figcaption>
+</figure>
+
+<figure>
+<a href="/blog/images/comet-spark-comparison/02-spark-ui-spark.png">
+<img
+src="/blog/images/comet-spark-comparison/02-spark-ui-spark.png"
+width="100%"
+class="img-fluid"
+alt="The Spark run in the Spark UI, SQL tab. Read the left column top to 
bottom, then the right one: 600 million rows go into ColumnarToRow, 342 million 
come out of the Filter, and 87 million go into the shuffle and into the output 
table."
+/>
+</a>
+<figcaption><b>Figure 2</b>: The Spark run in the Spark UI, SQL tab. Read the 
left column top to bottom, then the right one: 600 million rows go into 
<code>ColumnarToRow</code>, 342 million come out of the <code>Filter</code>, 
and 87 million go into the shuffle and into the output table.</figcaption>
+</figure>
+
+Let's go through the steps one by one:
+
+1. **Scan: `BatchScan` with Iceberg's vectorized reader.** Iceberg Java plans 
the scan on the driver, i.e., decides which data files to read. On each 
executor, its vectorized Parquet reader decompresses and decodes the needed 
column chunks into Arrow vectors on the JVM, 5,000 rows per batch 
(`read.parquet.vectorization.batch-size`), and hands them to Spark as a 
`ColumnarBatch` of `IcebergArrowColumnVector`s. The `WHERE` predicate is pushed 
down too, but Iceberg's reader uses it only to skip data files and Parquet row 
groups whose statistics rule them out. In this table, ship dates are spread 
over every file and row group, so nothing is skipped: the reader hands Spark 
every row, and all 600,037,902 rows go into `ColumnarToRow`, in 120,098 
batches. The rows themselves are filtered later, by Spark's `Filter`.
+2. **`ColumnarToRow` inside whole-stage codegen.** Spark generates one Java 
loop per stage. In the map stage, the loop walks the batch row by row, reads 
each value from its vector into a local variable, and runs `Filter`, `Project` 
and the partial aggregate in the same loop body. The filter and the projection 
create no row objects – this is what codegen buys – but every row still goes 
through the loop on its own.
+3. **Filter and compute.** The filter drops the rows shipped before 1995, and 
341,948,854 rows remain. For each of them, Spark's `Decimal` subtraction and 
multiplication go through `java.math.BigDecimal`, and the 32-digit result stays 
a `BigDecimal`, because Spark keeps a decimal in a `long` only up to 18 digits.
+4. **Partial aggregate.** For each row, Spark builds the grouping key as an 
`UnsafeRow`, hashes it, probes `UnsafeFixedWidthAggregationMap` (a 
`BytesToBytesMap` in Tungsten memory pages), and updates the aggregation buffer 
in place. The buffer holds the sum, the `isEmpty` flag that Spark keeps for 
decimal sums, and the count. The sum is `decimal(38,4)`, too wide for an 8-byte 
slot, so it is stored as bytes in the variable-length part of the row and has 
to be decoded and encoded again on every update.
+5. **Shuffle write.** For each row that the partial aggregate emits, Spark 
computes the partition id as `Pmod(Murmur3Hash(l_orderkey), 200)` and 
serializes the row with `UnsafeRowSerializer`. With 200 partitions, at the 
`spark.shuffle.sort.bypassMergeThreshold` of 200, Spark picks 
`BypassMergeSortShuffleWriter`: one lz4-compressed stream per reducer, 
concatenated into one data file plus an index file.
+6. **Shuffle read.** The reduce task fetches the blocks, decompresses them, 
and hands out `UnsafeRow`s that point into the buffer.
+7. **Final aggregate.** Once per row again: probe the map, merge the partial 
sums and counts.
+8. **Write: `AppendData` with Iceberg's writer.** Iceberg's Spark writer is a 
`DataWriter<InternalRow>`: it takes one row at a time and hands each value to a 
per-column value writer, which buffers it into that column's pages. The turn 
from rows back to columns happens inside the writer, not as a plan node, which 
is why the plan shows no `RowToColumnar`. The pages are encoded and 
zstd-compressed, and the driver commits the written files as a new snapshot of 
the table.
+
+Now let's look at the same data as it is stored at each step. Four `lineitem` 
rows go in, one of them fails the filter, and two orders come out.
+
+<figure>
+<a href="/blog/images/comet-spark-comparison/03-spark-data-journey.png">
+<img
+src="/blog/images/comet-spark-comparison/03-spark-data-journey.png"
+width="100%"
+class="img-fluid"
+alt="Four rows through the job without Comet. The file on each end is 
columnar, and so is the reader&#x27;s batch; everything in the highlighted 
middle is processed one row at a time."
+/>
+</a>
+<figcaption><b>Figure 3</b>: Four rows through the job without Comet. The file 
on each end is columnar, and so is the reader's batch; everything in the 
highlighted middle is processed one row at a time.</figcaption>
+</figure>
+
+## How Comet executes the job
+
+Comet keeps Spark's stages, tasks and shuffle files. What changes is the unit 
of work. The data stays an Arrow batch of up to 8,192 rows 
(`spark.comet.batchSize`) from the Parquet decoder to the shuffle file and 
back, and each operator makes one pass per column in Rust. With the native 
Iceberg write turned on, the data stays in Arrow all the way into the output 
Parquet file.
+
+1. **Scan: `CometIcebergNativeScan`.** Iceberg Java still plans the scan on 
the driver. Comet takes the planned `FileScanTask`s and puts them into its 
native plan, where iceberg-rust's `ArrowReader` decodes the Parquet column 
chunks into Arrow arrays in Rust. This is the integration that Matt Butrovich 
describes on the [Apache Iceberg 
blog](https://iceberg.apache.org/blog/accelerating-iceberg-rust-development-with-datafusion-comet/).
 Like Iceberg's Java reader, it skips row groups by their statistics, but it 
goes one step further and filters the rows themselves while decoding. So only 
the 341,948,854 matching rows leave the scan, not 600 million.
+2. **Filter and compute: `CometFilter`, `CometProject`.** A predicate runs 
over a whole column and yields a boolean array, and a filter kernel then copies 
the surviving values column by column. In this job, the scan has already done 
this work: `CometFilter` receives 342 million rows, keeps all of them, and 
takes 0.3 seconds across all tasks. The decimal math works column in, column 
out, on `Decimal128` arrays – one 16-byte integer per value, with no objects.
+3. **Partial aggregate: `CometHashAggregate`.** DataFusion hashes the key 
column of the whole batch, maps the hashes to group indices, and updates the 
accumulators for the whole batch at once. Comet's decimal sum accumulates into 
one `Decimal128` value per group.
+4. **Shuffle write: `CometExchange`.** The shuffle writer is part of the same 
native plan as the scan, the filter and the aggregate, so in this stage the 
column data never enters the JVM. The writer computes Spark-compatible Murmur3 
hashes for the whole batch, takes `pmod` to get the partition ids, and gathers 
each partition's rows with `interleave_record_batch`. Each block is a 
self-contained Arrow IPC stream compressed with lz4 and written in Spark's 
data-plus-index file layout, so Spark's block manager serves it as usual.
+5. **Shuffle read.** Native code decompresses and decodes the IPC blocks. With 
`spark.comet.shuffle.directRead.enabled` (on by default), the final aggregate 
reads them directly in native code.
+6. **Final aggregate: `CometHashAggregate`.** Merges the partial sums and 
counts, batch by batch.
+7. **Write: `CometIcebergWrite` and `IcebergCommit`.** With the native write 
enabled, Comet splits the write into `IcebergWrite` on the executors and 
`IcebergCommit` on the driver. When the write is eligible – its input plan is 
fully native, and every table setting is on Comet's allowlist – the executor 
side becomes `CometIcebergWrite`, and iceberg-rust writes the Parquet files 
straight from the Arrow batches. Iceberg Java still does the commit. An 
ineligible write keeps iceberg-java's writer and reports the reason in extended 
`EXPLAIN`.
+
+<figure>
+<a href="/blog/images/comet-spark-comparison/04-comet-plan.png">
+<img
+src="/blog/images/comet-spark-comparison/04-comet-plan.png"
+width="100%"
+class="img-fluid"
+alt="Spark + Comet: the same stages and the same shuffle files as in Figure 1, 
with Arrow batches from the source file to the target file. With the native 
Iceberg write turned on, no step runs once per row."
+/>
+</a>
+<figcaption><b>Figure 4</b>: Spark + Comet: the same stages and the same 
shuffle files as in Figure 1, with Arrow batches from the source file to the 
target file. With the native Iceberg write turned on, no step runs once per 
row.</figcaption>
+</figure>
+
+<figure>
+<a href="/blog/images/comet-spark-comparison/05-spark-ui-comet.png">
+<img
+src="/blog/images/comet-spark-comparison/05-spark-ui-comet.png"
+width="100%"
+class="img-fluid"
+alt="The Comet run in the Spark UI, SQL tab: the scan already returns only the 
342 million matching rows, and every node down to the write is a Comet node 
with its native metrics."
+/>
+</a>
+<figcaption><b>Figure 5</b>: The Comet run in the Spark UI, SQL tab: the scan 
already returns only the 342 million matching rows, and every node down to the 
write is a Comet node with its native metrics.</figcaption>
+</figure>
+
+Here are the same four rows, step by step:
+
+<figure>
+<a href="/blog/images/comet-spark-comparison/06-comet-data-journey.png">
+<img
+src="/blog/images/comet-spark-comparison/06-comet-data-journey.png"
+width="100%"
+class="img-fluid"
+alt="The same four rows with Comet: the same values at every step as in Figure 
3, but every middle panel holds arrays instead of rows, including the 
aggregation state and the shuffle blocks."
+/>
+</a>
+<figcaption><b>Figure 6</b>: The same four rows with Comet: the same values at 
every step as in Figure 3, but every middle panel holds arrays instead of rows, 
including the aggregation state and the shuffle blocks.</figcaption>
+</figure>
+
+When batches do cross between the JVM and Rust, they go through the Arrow C 
Data and C Stream interfaces. From the JVM to Rust, Comet imports the buffers 
without a copy, and ownership moves by reference count. From Rust to the JVM, 
the batch is exported into structures that the JVM has allocated. In this job, 
that happens only on the reduce side, between the final aggregate and the 
native writer. Either way, the cost of crossing is paid once per batch, not 
once per row.
+
+## Where the time goes
+
+Here are the totals for the whole job, as medians of five iterations, with the 
fastest and the slowest iteration in brackets:
+
+| Run | Wall time | CPU time | GC time | Shuffle written |
+| --- | --- | --- | --- | --- |
+| Spark | 38.7 s (35.4-39.0) | 295 s | 7.9 s | 1,698 MiB |
+| Spark + Comet | 10.5 s (9.2-11.4) | 76 s | 0.3 s | 1,197 MiB |
+
+With Comet, the job ran 3.7 times faster and used 3.9 times less CPU; even its 
slowest iteration beat Spark's fastest by 3.1 times. Both engines kept most of 
the 8 cores busy (7.6 and 7.2 cores on average), so the gain comes from 
removing CPU work, not from removing waiting.
+
+One warning if you measure this yourself: Spark's own executor CPU metric 
counts only task threads. Comet runs a native plan with no JVM input on its own 
threads while the Spark task waits, so Spark's metric shows Comet using far 
less CPU than it does: 24 CPU-seconds per iteration, against the 76 that the 
container used. For plain Spark, the two numbers are close: 277 and 295. The 
CPU times above come from the container's own counter, which also covers the 
driver.
+
+To find out which steps the CPU time goes to, I ran the job once more under 
async-profiler – a sampling profiler for the JVM that also sees native code – 
and built a CPU flame graph of the executor for each engine. If you haven't 
worked with flame graphs before, here is how to read them:
+
+- Each box is a function, and the boxes on top of it are the functions it 
called. The bottom box (`all`) is the whole profile, and each tower above it is 
a set of call stacks, from a thread's entry point at the bottom to the code 
that was running on the CPU at the top.
+- The width of a box is proportional to the number of samples in which the 
function was on the stack, either running itself or calling something above it. 
The horizontal axis is not time: the boxes on each level are sorted by name, so 
the order from left to right means nothing.
+- The top edge shows where the CPU spent its time. A wide box with nothing 
above it is a hot function.
+- The colour shows the type of code: green is Java, aqua is Java inlined into 
its caller, yellow is C++ (the JVM itself), red is other native code, such as 
libc or zstd, and orange is the kernel. Rust frames show up in yellow, like C++.
+
+<figure>
+<a href="/blog/images/comet-spark-comparison/07-flamegraph-spark.png">
+<img
+src="/blog/images/comet-spark-comparison/07-flamegraph-spark.png"
+width="100%"
+class="img-fluid"
+alt="CPU flame graph of Spark&#x27;s executor: the map stage on the right, the 
reduce stage and the Iceberg writer on the left, JVM service threads at the far 
left."
+/>
+</a>
+<figcaption><b>Figure 7</b>: CPU flame graph of Spark's executor: the map 
stage on the right, the reduce stage and the Iceberg writer on the left, JVM 
service threads at the far left.</figcaption>
+</figure>
+
+In Spark's flame graph (Figure 7), almost everything grows out of 
`java/lang/Thread.run`, i.e., the executor's task threads. Above 
`Executor$TaskRunner.run`, the graph splits into two towers, one per stage:
+
+- The wide tower on the right, about 63% of the samples, is the map stage: 
`ShuffleMapTask` → `BypassMergeSortShuffleWriter.write` → the generated class 
`GeneratedIteratorForCodegenStage1`. About 80% of the stage runs inside one 
generated method, `hashAgg_doAggregateWithKeys` – this is whole-stage codegen 
fusing the scan loop, the filter, the projection and the partial aggregate into 
one loop. On top of it sit the decimal frames (Spark's `Decimal`, Java's 
`BigDecimal` and `BigInteger`, `UnsafeRow.getDecimal`), the hash map 
(`BytesToBytesMap`, whose `safeLookup` has more samples of its own than any 
other function in the graph), and Iceberg's vectorized reader with zstd 
decompression.
+- The tower on the left, about 31%, is the reduce stage: `ResultTask` → 
`WritingSparkTask`, with the shuffle read, the final aggregate – again with 
decimal and hash map frames on top – and Iceberg's Parquet writer with zstd 
compression.
+- The thin towers at the far left, about 5%, are JVM threads that don't run 
tasks: the JIT compiler and the garbage collector.
+
+If we convert each step's share of the samples into CPU-seconds, using the 
measured CPU time, the biggest cost in Spark is decimal math: about a third of 
the CPU, or 100 seconds, of which 79 are in the map stage and 21 in the final 
aggregate. This includes the subtraction and multiplication, the precision 
checks, and moving the `decimal(38,4)` sum in and out of the aggregation buffer 
as bytes (`UnsafeRow.getDecimal` and `setDecimal`). Garbage collection took 
only 7.9 seconds; the cost is in computing with objects. The hash maps of the 
two aggregates take another 55 seconds. The table below has every step.

Review Comment:
   Thanks for checking this. The 55 s was 35 s for the partial aggregate plus 
about 20 s for the final aggregate's hash map; the other 8 s of the final 
aggregate's 49 go to its per-row loop and to building the output rows, and the 
text didn't say so. And you're right about the 7%: it was Comet's map stage 
only. Across both stages, Comet's decimal work is about 9% of its samples, or 7 
s, against Spark's 100 s. Both fixed in c8142cb.



##########
content/blog/2026-11-22-comet-spark-comparison.md:
##########
@@ -0,0 +1,391 @@
+---
+layout: post
+title: Where Apache Spark loses time, and how Apache DataFusion Comet gets it 
back
+date: 2026-11-22
+author: Viacheslav Inozemtsev
+categories: [performance, subprojects]
+---
+
+<!--
+{% comment %}
+Licensed to the Apache Software Foundation (ASF) under one or more
+contributor license agreements.  See the NOTICE file distributed with
+this work for additional information regarding copyright ownership.
+The ASF licenses this file to you under the Apache License, Version 2.0
+(the "License"); you may not use this file except in compliance with
+the License.  You may obtain a copy of the License at
+
+http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+{% endcomment %}
+-->
+
+[TOC]
+
+## Introduction
+
+[Apache DataFusion Comet](https://datafusion.apache.org/comet/) is an 
accelerator for [Apache Spark](https://spark.apache.org/) that can also read 
and write [Apache Iceberg](https://iceberg.apache.org/) tables natively. It is 
built on top of [Apache DataFusion](https://datafusion.apache.org/), a query 
engine written in Rust on [Apache Arrow](https://arrow.apache.org/). Comet 
plugs into Spark without changes to the jobs: it takes the physical plan that 
Spark has built and executes the operators it supports in native code. The 
promise is better performance thanks to two things: Comet processes data in 
columnar Arrow batches instead of one row at a time, and it runs in native code 
outside the JVM, without JVM objects and their overhead. The project's README 
states a speedup of about 1.8 times on TPC-DS at 1 TB, which translates into 
roughly 45% lower cost.
+
+Numbers like these are useful, but they don't explain where the gain comes 
from. The usual answer – "Comet is columnar and native" – is true, but it 
explains less than it seems, because Spark's own Iceberg reader already decodes 
Parquet into Arrow vectors. If both engines start from columnar batches, where 
exactly does Spark lose time, and what does Comet do differently? I wanted to 
see this in detail, step by step, on a real job.
+
+In this post, I will take one ordinary ETL job – read an Iceberg table, filter 
it, compute a value, aggregate it, and write the result into another Iceberg 
table – and run it with plain Spark and with Spark + Comet. We will follow a 
few rows through every step of the job in both engines, look at the CPU 
profiles, and estimate how much CPU each step costs. On 8 cores, plain Spark 
took 38.7 seconds and 295 CPU-seconds, and Spark with Comet took 10.5 seconds 
and 76 CPU-seconds, with the same output. Then we will look at the opposite 
case: how one unsupported expression takes most of this gain away. I will 
finish with a practical guide on checking and tuning Comet for your own jobs.
+
+Everything in this post is reproducible with two commands, `docker build` and 
`docker run`, from the repository 
[Visorgood/spark-comet-iceberg-bench](https://github.com/Visorgood/spark-comet-iceberg-bench).
 All numbers come from Spark 4.1.3, Iceberg 1.11.0 and Comet 1.2.0.
+
+## The benchmark job
+
+For the data, I use TPC-H – a standard decision-support benchmark with a 
synthetic dataset of customers, orders, parts and suppliers, which can be 
generated at any size set by a scale factor. Its largest table is `lineitem`, 
with one row per line of a customer order: the order key, the part, the 
quantity, the price, the discount, the ship date, and other attributes. At 
scale factor 100, `lineitem` has 600 million rows.
+
+The job computes the revenue of each order from the lines shipped since 1995 – 
a typical ETL step that touches every part of the engine, from the scan to the 
write:
+
+```sql
+INSERT INTO lake.tpch.order_revenue
+SELECT l_orderkey,
+       sum(l_extendedprice * (1 - l_discount)) AS revenue,
+       count(*)                                AS lines
+FROM   lake.tpch.lineitem
+WHERE  l_shipdate >= DATE '1995-01-01'
+GROUP  BY l_orderkey
+```
+
+A few details of this setup matter for the results:
+
+- **Source.** `lineitem` at scale factor 100 is stored in an Iceberg table 
with Iceberg's defaults: Parquet data files with zstd compression, 15.1 GiB in 
206 files. The query needs only four of the 16 columns, and Comet's scan 
metrics show 3.5 GiB read from these files.
+- **Target.** An unpartitioned Iceberg table with no sort order and default 
properties. In this case, Iceberg asks Spark for no extra shuffle or sort 
before the write, and the write stays eligible for Comet's native Iceberg 
writer.
+- **Shape.** An order has about four lines, so the partial aggregate shrinks 
the data only about four times, and the shuffle still carries 87 million rows. 
A query with few groups, like TPC-H Q1, would hide the shuffle.
+- **Types.** The money columns are `decimal(15,2)`. The product 
`l_extendedprice * (1 - l_discount)` is `decimal(32,4)`, and the sum is 
`decimal(38,4)`, both wider than 18 digits. As we will see later, this matters 
more than anything else in this job.
+- **`INSERT INTO` rather than `CREATE TABLE AS SELECT`.** Comet's native 
Iceberg write covers append, overwrite and copy-on-write DML, but not CTAS.
+
+Here are the physical plans of both runs:
+
+| Step | Spark | Spark + Comet |
+| --- | --- | --- |
+| Read | `BatchScan` (Iceberg) → `ColumnarToRow` | `CometIcebergNativeScan` |
+| Filter, compute | `Filter`, `Project` (whole-stage codegen) | `CometFilter`, 
`CometProject` |
+| Partial aggregate | `HashAggregate` (partial) | `CometHashAggregate` 
(partial) |
+| Shuffle | `Exchange hashpartitioning(l_orderkey, 200)` | `CometExchange` 
(native shuffle) |
+| Final aggregate | `HashAggregate` (final) | `CometHashAggregate` (final) |
+| Write | `AppendData`: iceberg-java writes rows | `CometIcebergWrite` under 
`IcebergCommit` |
+
+The Comet plan requires `spark.comet.write.iceberg.enabled=true`. The native 
write is off by default in Comet 1.2, and without it the plan ends with 
`CometColumnarToRow` → `AppendData`. Reading a Comet plan comes down to one 
rule: every `Comet*` node is accelerated, a node without the prefix is plain 
Spark, and `CometColumnarToRow` marks the place where Arrow batches become rows.
+
+## How Spark executes the job
+
+Spark on Iceberg is not row-based from the disk up. Iceberg's reader decodes 
Parquet into Arrow vectors on the JVM, and only at the first operator does the 
batch become a stream of rows. From there on, filtering, decimal math, hashing, 
hash map updates, partitioning and serialization all run once per row, until 
the Iceberg writer turns the rows back into columns.
+
+<figure>
+<a href="/blog/images/comet-spark-comparison/01-spark-plan.png">
+<img
+src="/blog/images/comet-spark-comparison/01-spark-plan.png"
+width="100%"
+class="img-fluid"
+alt="Plain Spark, Iceberg to Iceberg: columnar at both ends, rows in between. 
From ColumnarToRow to the Iceberg writer, every highlighted step runs once per 
row."
+/>
+</a>
+<figcaption><b>Figure 1</b>: Plain Spark, Iceberg to Iceberg: columnar at both 
ends, rows in between. From <code>ColumnarToRow</code> to the Iceberg writer, 
every highlighted step runs once per row.</figcaption>
+</figure>
+
+<figure>
+<a href="/blog/images/comet-spark-comparison/02-spark-ui-spark.png">
+<img
+src="/blog/images/comet-spark-comparison/02-spark-ui-spark.png"
+width="100%"
+class="img-fluid"
+alt="The Spark run in the Spark UI, SQL tab. Read the left column top to 
bottom, then the right one: 600 million rows go into ColumnarToRow, 342 million 
come out of the Filter, and 87 million go into the shuffle and into the output 
table."
+/>
+</a>
+<figcaption><b>Figure 2</b>: The Spark run in the Spark UI, SQL tab. Read the 
left column top to bottom, then the right one: 600 million rows go into 
<code>ColumnarToRow</code>, 342 million come out of the <code>Filter</code>, 
and 87 million go into the shuffle and into the output table.</figcaption>
+</figure>
+
+Let's go through the steps one by one:
+
+1. **Scan: `BatchScan` with Iceberg's vectorized reader.** Iceberg Java plans 
the scan on the driver, i.e., decides which data files to read. On each 
executor, its vectorized Parquet reader decompresses and decodes the needed 
column chunks into Arrow vectors on the JVM, 5,000 rows per batch 
(`read.parquet.vectorization.batch-size`), and hands them to Spark as a 
`ColumnarBatch` of `IcebergArrowColumnVector`s. The `WHERE` predicate is pushed 
down too, but Iceberg's reader uses it only to skip data files and Parquet row 
groups whose statistics rule them out. In this table, ship dates are spread 
over every file and row group, so nothing is skipped: the reader hands Spark 
every row, and all 600,037,902 rows go into `ColumnarToRow`, in 120,098 
batches. The rows themselves are filtered later, by Spark's `Filter`.
+2. **`ColumnarToRow` inside whole-stage codegen.** Spark generates one Java 
loop per stage. In the map stage, the loop walks the batch row by row, reads 
each value from its vector into a local variable, and runs `Filter`, `Project` 
and the partial aggregate in the same loop body. The filter and the projection 
create no row objects – this is what codegen buys – but every row still goes 
through the loop on its own.
+3. **Filter and compute.** The filter drops the rows shipped before 1995, and 
341,948,854 rows remain. For each of them, Spark's `Decimal` subtraction and 
multiplication go through `java.math.BigDecimal`, and the 32-digit result stays 
a `BigDecimal`, because Spark keeps a decimal in a `long` only up to 18 digits.
+4. **Partial aggregate.** For each row, Spark builds the grouping key as an 
`UnsafeRow`, hashes it, probes `UnsafeFixedWidthAggregationMap` (a 
`BytesToBytesMap` in Tungsten memory pages), and updates the aggregation buffer 
in place. The buffer holds the sum, the `isEmpty` flag that Spark keeps for 
decimal sums, and the count. The sum is `decimal(38,4)`, too wide for an 8-byte 
slot, so it is stored as bytes in the variable-length part of the row and has 
to be decoded and encoded again on every update.
+5. **Shuffle write.** For each row that the partial aggregate emits, Spark 
computes the partition id as `Pmod(Murmur3Hash(l_orderkey), 200)` and 
serializes the row with `UnsafeRowSerializer`. With 200 partitions, at the 
`spark.shuffle.sort.bypassMergeThreshold` of 200, Spark picks 
`BypassMergeSortShuffleWriter`: one lz4-compressed stream per reducer, 
concatenated into one data file plus an index file.
+6. **Shuffle read.** The reduce task fetches the blocks, decompresses them, 
and hands out `UnsafeRow`s that point into the buffer.
+7. **Final aggregate.** Once per row again: probe the map, merge the partial 
sums and counts.
+8. **Write: `AppendData` with Iceberg's writer.** Iceberg's Spark writer is a 
`DataWriter<InternalRow>`: it takes one row at a time and hands each value to a 
per-column value writer, which buffers it into that column's pages. The turn 
from rows back to columns happens inside the writer, not as a plan node, which 
is why the plan shows no `RowToColumnar`. The pages are encoded and 
zstd-compressed, and the driver commits the written files as a new snapshot of 
the table.
+
+Now let's look at the same data as it is stored at each step. Four `lineitem` 
rows go in, one of them fails the filter, and two orders come out.
+
+<figure>
+<a href="/blog/images/comet-spark-comparison/03-spark-data-journey.png">
+<img
+src="/blog/images/comet-spark-comparison/03-spark-data-journey.png"
+width="100%"
+class="img-fluid"
+alt="Four rows through the job without Comet. The file on each end is 
columnar, and so is the reader&#x27;s batch; everything in the highlighted 
middle is processed one row at a time."
+/>
+</a>
+<figcaption><b>Figure 3</b>: Four rows through the job without Comet. The file 
on each end is columnar, and so is the reader's batch; everything in the 
highlighted middle is processed one row at a time.</figcaption>
+</figure>
+
+## How Comet executes the job
+
+Comet keeps Spark's stages, tasks and shuffle files. What changes is the unit 
of work. The data stays an Arrow batch of up to 8,192 rows 
(`spark.comet.batchSize`) from the Parquet decoder to the shuffle file and 
back, and each operator makes one pass per column in Rust. With the native 
Iceberg write turned on, the data stays in Arrow all the way into the output 
Parquet file.
+
+1. **Scan: `CometIcebergNativeScan`.** Iceberg Java still plans the scan on 
the driver. Comet takes the planned `FileScanTask`s and puts them into its 
native plan, where iceberg-rust's `ArrowReader` decodes the Parquet column 
chunks into Arrow arrays in Rust. This is the integration that Matt Butrovich 
describes on the [Apache Iceberg 
blog](https://iceberg.apache.org/blog/accelerating-iceberg-rust-development-with-datafusion-comet/).
 Like Iceberg's Java reader, it skips row groups by their statistics, but it 
goes one step further and filters the rows themselves while decoding. So only 
the 341,948,854 matching rows leave the scan, not 600 million.
+2. **Filter and compute: `CometFilter`, `CometProject`.** A predicate runs 
over a whole column and yields a boolean array, and a filter kernel then copies 
the surviving values column by column. In this job, the scan has already done 
this work: `CometFilter` receives 342 million rows, keeps all of them, and 
takes 0.3 seconds across all tasks. The decimal math works column in, column 
out, on `Decimal128` arrays – one 16-byte integer per value, with no objects.
+3. **Partial aggregate: `CometHashAggregate`.** DataFusion hashes the key 
column of the whole batch, maps the hashes to group indices, and updates the 
accumulators for the whole batch at once. Comet's decimal sum accumulates into 
one `Decimal128` value per group.
+4. **Shuffle write: `CometExchange`.** The shuffle writer is part of the same 
native plan as the scan, the filter and the aggregate, so in this stage the 
column data never enters the JVM. The writer computes Spark-compatible Murmur3 
hashes for the whole batch, takes `pmod` to get the partition ids, and gathers 
each partition's rows with `interleave_record_batch`. Each block is a 
self-contained Arrow IPC stream compressed with lz4 and written in Spark's 
data-plus-index file layout, so Spark's block manager serves it as usual.
+5. **Shuffle read.** Native code decompresses and decodes the IPC blocks. With 
`spark.comet.shuffle.directRead.enabled` (on by default), the final aggregate 
reads them directly in native code.
+6. **Final aggregate: `CometHashAggregate`.** Merges the partial sums and 
counts, batch by batch.
+7. **Write: `CometIcebergWrite` and `IcebergCommit`.** With the native write 
enabled, Comet splits the write into `IcebergWrite` on the executors and 
`IcebergCommit` on the driver. When the write is eligible – its input plan is 
fully native, and every table setting is on Comet's allowlist – the executor 
side becomes `CometIcebergWrite`, and iceberg-rust writes the Parquet files 
straight from the Arrow batches. Iceberg Java still does the commit. An 
ineligible write keeps iceberg-java's writer and reports the reason in extended 
`EXPLAIN`.
+
+<figure>
+<a href="/blog/images/comet-spark-comparison/04-comet-plan.png">
+<img
+src="/blog/images/comet-spark-comparison/04-comet-plan.png"
+width="100%"
+class="img-fluid"
+alt="Spark + Comet: the same stages and the same shuffle files as in Figure 1, 
with Arrow batches from the source file to the target file. With the native 
Iceberg write turned on, no step runs once per row."
+/>
+</a>
+<figcaption><b>Figure 4</b>: Spark + Comet: the same stages and the same 
shuffle files as in Figure 1, with Arrow batches from the source file to the 
target file. With the native Iceberg write turned on, no step runs once per 
row.</figcaption>
+</figure>
+
+<figure>
+<a href="/blog/images/comet-spark-comparison/05-spark-ui-comet.png">
+<img
+src="/blog/images/comet-spark-comparison/05-spark-ui-comet.png"
+width="100%"
+class="img-fluid"
+alt="The Comet run in the Spark UI, SQL tab: the scan already returns only the 
342 million matching rows, and every node down to the write is a Comet node 
with its native metrics."
+/>
+</a>
+<figcaption><b>Figure 5</b>: The Comet run in the Spark UI, SQL tab: the scan 
already returns only the 342 million matching rows, and every node down to the 
write is a Comet node with its native metrics.</figcaption>
+</figure>
+
+Here are the same four rows, step by step:
+
+<figure>
+<a href="/blog/images/comet-spark-comparison/06-comet-data-journey.png">
+<img
+src="/blog/images/comet-spark-comparison/06-comet-data-journey.png"
+width="100%"
+class="img-fluid"
+alt="The same four rows with Comet: the same values at every step as in Figure 
3, but every middle panel holds arrays instead of rows, including the 
aggregation state and the shuffle blocks."
+/>
+</a>
+<figcaption><b>Figure 6</b>: The same four rows with Comet: the same values at 
every step as in Figure 3, but every middle panel holds arrays instead of rows, 
including the aggregation state and the shuffle blocks.</figcaption>
+</figure>
+
+When batches do cross between the JVM and Rust, they go through the Arrow C 
Data and C Stream interfaces. From the JVM to Rust, Comet imports the buffers 
without a copy, and ownership moves by reference count. From Rust to the JVM, 
the batch is exported into structures that the JVM has allocated. In this job, 
that happens only on the reduce side, between the final aggregate and the 
native writer. Either way, the cost of crossing is paid once per batch, not 
once per row.
+
+## Where the time goes
+
+Here are the totals for the whole job, as medians of five iterations, with the 
fastest and the slowest iteration in brackets:
+
+| Run | Wall time | CPU time | GC time | Shuffle written |
+| --- | --- | --- | --- | --- |
+| Spark | 38.7 s (35.4-39.0) | 295 s | 7.9 s | 1,698 MiB |
+| Spark + Comet | 10.5 s (9.2-11.4) | 76 s | 0.3 s | 1,197 MiB |
+
+With Comet, the job ran 3.7 times faster and used 3.9 times less CPU; even its 
slowest iteration beat Spark's fastest by 3.1 times. Both engines kept most of 
the 8 cores busy (7.6 and 7.2 cores on average), so the gain comes from 
removing CPU work, not from removing waiting.
+
+One warning if you measure this yourself: Spark's own executor CPU metric 
counts only task threads. Comet runs a native plan with no JVM input on its own 
threads while the Spark task waits, so Spark's metric shows Comet using far 
less CPU than it does: 24 CPU-seconds per iteration, against the 76 that the 
container used. For plain Spark, the two numbers are close: 277 and 295. The 
CPU times above come from the container's own counter, which also covers the 
driver.
+
+To find out which steps the CPU time goes to, I ran the job once more under 
async-profiler – a sampling profiler for the JVM that also sees native code – 
and built a CPU flame graph of the executor for each engine. If you haven't 
worked with flame graphs before, here is how to read them:
+
+- Each box is a function, and the boxes on top of it are the functions it 
called. The bottom box (`all`) is the whole profile, and each tower above it is 
a set of call stacks, from a thread's entry point at the bottom to the code 
that was running on the CPU at the top.
+- The width of a box is proportional to the number of samples in which the 
function was on the stack, either running itself or calling something above it. 
The horizontal axis is not time: the boxes on each level are sorted by name, so 
the order from left to right means nothing.
+- The top edge shows where the CPU spent its time. A wide box with nothing 
above it is a hot function.
+- The colour shows the type of code: green is Java, aqua is Java inlined into 
its caller, yellow is C++ (the JVM itself), red is other native code, such as 
libc or zstd, and orange is the kernel. Rust frames show up in yellow, like C++.
+
+<figure>
+<a href="/blog/images/comet-spark-comparison/07-flamegraph-spark.png">
+<img
+src="/blog/images/comet-spark-comparison/07-flamegraph-spark.png"
+width="100%"
+class="img-fluid"
+alt="CPU flame graph of Spark&#x27;s executor: the map stage on the right, the 
reduce stage and the Iceberg writer on the left, JVM service threads at the far 
left."
+/>
+</a>
+<figcaption><b>Figure 7</b>: CPU flame graph of Spark's executor: the map 
stage on the right, the reduce stage and the Iceberg writer on the left, JVM 
service threads at the far left.</figcaption>
+</figure>
+
+In Spark's flame graph (Figure 7), almost everything grows out of 
`java/lang/Thread.run`, i.e., the executor's task threads. Above 
`Executor$TaskRunner.run`, the graph splits into two towers, one per stage:
+
+- The wide tower on the right, about 63% of the samples, is the map stage: 
`ShuffleMapTask` → `BypassMergeSortShuffleWriter.write` → the generated class 
`GeneratedIteratorForCodegenStage1`. About 80% of the stage runs inside one 
generated method, `hashAgg_doAggregateWithKeys` – this is whole-stage codegen 
fusing the scan loop, the filter, the projection and the partial aggregate into 
one loop. On top of it sit the decimal frames (Spark's `Decimal`, Java's 
`BigDecimal` and `BigInteger`, `UnsafeRow.getDecimal`), the hash map 
(`BytesToBytesMap`, whose `safeLookup` has more samples of its own than any 
other function in the graph), and Iceberg's vectorized reader with zstd 
decompression.
+- The tower on the left, about 31%, is the reduce stage: `ResultTask` → 
`WritingSparkTask`, with the shuffle read, the final aggregate – again with 
decimal and hash map frames on top – and Iceberg's Parquet writer with zstd 
compression.
+- The thin towers at the far left, about 5%, are JVM threads that don't run 
tasks: the JIT compiler and the garbage collector.
+
+If we convert each step's share of the samples into CPU-seconds, using the 
measured CPU time, the biggest cost in Spark is decimal math: about a third of 
the CPU, or 100 seconds, of which 79 are in the map stage and 21 in the final 
aggregate. This includes the subtraction and multiplication, the precision 
checks, and moving the `decimal(38,4)` sum in and out of the aggregation buffer 
as bytes (`UnsafeRow.getDecimal` and `setDecimal`). Garbage collection took 
only 7.9 seconds; the cost is in computing with objects. The hash maps of the 
two aggregates take another 55 seconds. The table below has every step.

Review Comment:
   The 55 s was 35 s for the partial aggregate plus about 20 s for the final 
aggregate's hash map; the other 8 s of the final aggregate's 49 go to its 
per-row loop and to building the output rows, and the text didn't say so. And 
you're right about the 7%: it was Comet's map stage only. Across both stages, 
Comet's decimal work is about 9% of its samples, or 7 s, against Spark's 100 s. 
Both fixed in c8142cb.



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