You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@spark.apache.org by "yaooqinn (via GitHub)" <gi...@apache.org> on 2026/04/20 06:38:10 UTC

[PR] [WIP][SPARK-56546][SQL] Block-chunked segment-tree window frame for non-invertible sliding aggregates [spark]

yaooqinn opened a new pull request, #55422:
URL: https://github.com/apache/spark/pull/55422

   <!-- Thanks for contributing to Spark! Please read the contribution guide. -->
   
   ## What changes were proposed in this pull request?
   
   > **WIP / Draft.** This PR is opened early for visibility and incremental review. Rebase onto current `apache/master` and a fresh 3-JDK GHA benchmark rerun will follow. Feedback on overall design/scope is very welcome in the meantime.
   
   Introduce a **block-chunked segment-tree window function frame** that evaluates sliding aggregates in `O(log W)` per output row for the non-invertible path in Spark's window operator.
   
   - New frame class `SegmentTreeWindowFunctionFrame` (sibling to the existing sliding frame), selected by `WindowFunctionFrameFactory` when **all** of the following hold:
     1. The frame is a non-invertible sliding `ROWS`/`RANGE` frame (i.e. today's full-recompute path).
     2. Every window function over that frame is an eligible `DeclarativeAggregate`: `MIN / MAX / SUM / COUNT / AVG / STDDEV_POP / STDDEV_SAMP / VAR_POP / VAR_SAMP`, with no `FILTER` clause and no `DISTINCT`.
     3. The new SQLConf `spark.sql.window.segmentTree.enabled` is `true` (default `false` — **opt-in**).
   - **Internal-only**: no public API change, no new SQL syntax, no user-visible catalog / plan surface. All other frames fall back to the existing path unchanged.
   - Partitions below `spark.sql.window.segmentTree.minPartitionRows` fall back to the existing `SlidingWindowFunctionFrame` to avoid paying build cost on small partitions.
   
   ### New SQLConfs (all `since = 4.2.0`)
   
   | Key | Default | Scope |
   |---|---|---|
   | `spark.sql.window.segmentTree.enabled` | `false` | public, boolean — master opt-in switch |
   | `spark.sql.window.segmentTree.minPartitionRows` | `64` | internal, int — min rows to activate; below → naive fallback |
   | `spark.sql.window.segmentTree.blockSize` | `65536` | public, int — rows per leaf block (≥ 16) |
   | `spark.sql.window.segmentTree.fanout` | `16` | internal, int — internal-node fanout (≥ 2) |
   
   ### New SQLMetrics on the window operator
   
   - segment-tree frame construction count
   - fallback-to-naive count (when eligibility fails at runtime)
   
   ## Why are the changes needed?
   
   Spark's current sliding-window aggregate evaluation recomputes the full frame for every output row when no inverse exists — MIN/MAX always, and SUM/AVG/STDDEV whenever the inverse is numerically unstable (see [SPARK-36844](https://issues.apache.org/jira/browse/SPARK-36844)). That path is `O(N·W)` even though `O(N log W)` algorithms are standard in the streaming-analytics literature (Leis et al. 2015; Arasu & Widom 2004).
   
   Practical symptoms: sliding `MIN/MAX/SUM/AVG/COUNT/STDDEV` over `W ≳ 1000` rows become CPU-bound, spill-sensitive on variable-width types (String/Binary), and scale poorly with `W`. At `W = 4001 / 2M rows` the current engine takes ~100 s per sliding pass on modern hardware.
   
   ## Does this PR introduce _any_ user-facing change?
   
   **No** — the feature is gated behind a new SQLConf that defaults to `false`. There are no API, SQL grammar, or plan-shape changes. When the conf is enabled, a new physical frame implementation is selected for eligible sliding frames; all other cases (invertible aggregates, non-sliding frames, ranking functions, UDFs, `FILTER`/`DISTINCT`, small partitions) take the existing path.
   
   ## How was this patch tested?
   
   ### Functional tests (all new)
   
   - `WindowSegmentTreeSuite` — unit tests for the frame implementation (14 cases): basic aggregates, frame boundaries, NULL / NaN / ±Infinity, numeric / string / date-timestamp types, small-partition fallback, unsupported-merge / DISTINCT / disabled-conf fallback.
   - `SegmentTreeWindowFunctionSuite` — end-to-end SQL-level tests (34 cases) with the conf enabled, comparing against the naive frame row-for-row as an oracle.
   - `SegmentTreeWindowMetricsSuite` — SQLMetric visibility (7 cases) asserting the new operator-level metrics propagate to the UI.
   - `WindowSegmentTreeMemorySuite` — `TaskMemoryManager` accounting (9 cases) covering build, spill-not-supported paths, and release-on-completion.
   - `WindowSegmentTreePropertySuite` — ScalaCheck property-based suite (3 generators) asserting segtree-vs-naive equivalence over random shapes.
   
   All existing window tests remain green with the conf at default `false`.
   
   ### Benchmark (`WindowBenchmark`)
   
   Rerun on GitHub Actions across **JDK 17 / 21 / 25** (Azure EPYC 9V74 80-core, Linux 6.17, OpenJDK LTS), `SPARK_GENERATE_BENCHMARK_FILES=1`, baseline resized to a 3–5 s per-iteration target.
   
   | Aggregate | W / N | JDK 17 | JDK 21 | JDK 25 |
   |---|---|---|---|---|
   | MIN (non-invertible) | 1001 / 256K | 8.9× | 9.0× | 9.0× |
   | MAX (non-invertible) | 1001 / 256K | 10.2× | 13.1× | 14.2× |
   | SUM (full recompute) | 1001 / 256K | 9.6× | 9.5× | 9.9× |
   | COUNT | 1001 / 256K | 9.4× | 9.3× | 9.3× |
   | AVG (multi-buffer) | 1001 / 192K | 10.6× | 10.6× | 10.2× |
   | STDDEV_SAMP (multi-buffer, stress) | 1001 / 2M | 18.7× | 19.3× | 18.5× |
   | SUM W-sweep (stress, cross-block) | 4001 / 2M | 32.4× | 32.6× | 29.0× |
   | MAX String spill guard (stress) | 1001 / 1M | 15.7× | 16.4× | 17.6× |
   
   N-sweep (segtree-only, `W=1001`, JDK 17): `N=2M → 1358 ns/row`, `N=8M → 1374 ns/row`, `N=16M → 1338 ns/row` — sub-linear / near-constant, matching the `O(log W)` cost model.
   
   ### Caveats (documented, not blockers)
   
   - `W ≤ 50` is a **Pareto-loss zone** where naive is ~2–3× faster than segtree (build overhead dominates). Covered by explicit `(stress)` benchmark cases at `W=11` and `W=51`. The feature is opt-in precisely so users can stay on naive for small-W workloads.
   - `W=10` pathological (~0.4×) is the same cause; documented in the design doc.
   - Segtree is a secondary path only; the naive frame is untouched and remains the default.
   
   ## Was this patch authored or co-authored using generative AI tooling?
   
   No.
   
   ---
   
   JIRA: [SPARK-56546](https://issues.apache.org/jira/browse/SPARK-56546)
   


-- 
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@spark.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [WIP][SPARK-56546][SQL] Block-chunked segment-tree window frame for non-invertible sliding aggregates [spark]

Posted by "yaooqinn (via GitHub)" <gi...@apache.org>.
yaooqinn commented on code in PR #55422:
URL: https://github.com/apache/spark/pull/55422#discussion_r3115704422


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/SegmentTreeWindowFunctionFrame.scala:
##########
@@ -0,0 +1,280 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.execution.window
+
+import org.apache.spark.TaskContext
+import org.apache.spark.memory.TaskMemoryManager
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, Expression, FrameType, MutableProjection, RangeFrame, RowFrame, UnsafeRow}
+import org.apache.spark.sql.catalyst.expressions.aggregate.DeclarativeAggregate
+import org.apache.spark.sql.execution.ExternalAppendOnlyUnsafeRowArray
+import org.apache.spark.sql.execution.metric.SQLMetric
+import org.apache.spark.sql.internal.SQLConf
+
+/**
+ * Moving-frame window function frame backed by [[WindowSegmentTree]]. Produces
+ * the same outputs as [[SlidingWindowFunctionFrame]] for RowFrame or
+ * single-column RangeFrame moving frames whose aggregate functions are all
+ * [[DeclarativeAggregate]] with no FILTER/DISTINCT. For partitions below
+ * `spark.sql.window.segmentTree.minPartitionRows`, delegates to a wrapped
+ * [[SlidingWindowFunctionFrame]].
+ *
+ * See `docs/frame-integration-contract.md` Section 1 for the full contract.
+ *
+ * RANGE support (RANGE frame support): when `frameType == RangeFrame`, the per-row
+ * driver uses two forward-only cursors (`lowerIter` / `upperIter`) over the
+ * materialized `rowArray` to advance `lowerBound` / `upperBound`. Endpoints
+ * are monotone per partition (SQL RANGE semantics + sorted input), so total
+ * cursor work is O(n). The segment tree then answers `[lowerBound,
+ * upperBound)` in O(log n).
+ *
+ * @note Not thread-safe.
+ */
+private[window] final class SegmentTreeWindowFunctionFrame(
+    target: InternalRow,
+    processor: AggregateProcessor,
+    functions: Array[DeclarativeAggregate],
+    inputSchema: Seq[Attribute],
+    frameType: FrameType,
+    lbound: BoundOrdering,
+    ubound: BoundOrdering,
+    newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
+    conf: SQLConf,
+    maxCachedBlocks: Option[Int],
+    taskMemoryManager: TaskMemoryManager,
+    numSegmentTreeFrames: Option[SQLMetric] = None,
+    numSegmentTreeFallbackFrames: Option[SQLMetric] = None)
+  extends WindowFunctionFrame with AutoCloseable {
+
+  require(frameType == RowFrame || frameType == RangeFrame,
+    s"SegmentTreeWindowFunctionFrame supports RowFrame or RangeFrame, got $frameType")
+
+  private[this] val fallback =
+    new SlidingWindowFunctionFrame(target, processor, lbound, ubound)

Review Comment:
   Lazy-allocated the fallback in `prepare()` on the small-partition path (with a `newFallback()` factory); segtree-exclusive frames no longer pay the allocation. On the segtree path we also drop the retained fallback reference so its row-copy buffer is eligible for GC.
   
   Addressed in `e97e28b3c8d`. Thank you for the advice!



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/SegmentTreeWindowFunctionFrame.scala:
##########
@@ -0,0 +1,280 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.execution.window
+
+import org.apache.spark.TaskContext
+import org.apache.spark.memory.TaskMemoryManager
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, Expression, FrameType, MutableProjection, RangeFrame, RowFrame, UnsafeRow}
+import org.apache.spark.sql.catalyst.expressions.aggregate.DeclarativeAggregate
+import org.apache.spark.sql.execution.ExternalAppendOnlyUnsafeRowArray
+import org.apache.spark.sql.execution.metric.SQLMetric
+import org.apache.spark.sql.internal.SQLConf
+
+/**
+ * Moving-frame window function frame backed by [[WindowSegmentTree]]. Produces
+ * the same outputs as [[SlidingWindowFunctionFrame]] for RowFrame or
+ * single-column RangeFrame moving frames whose aggregate functions are all
+ * [[DeclarativeAggregate]] with no FILTER/DISTINCT. For partitions below
+ * `spark.sql.window.segmentTree.minPartitionRows`, delegates to a wrapped
+ * [[SlidingWindowFunctionFrame]].
+ *
+ * See `docs/frame-integration-contract.md` Section 1 for the full contract.
+ *
+ * RANGE support (RANGE frame support): when `frameType == RangeFrame`, the per-row
+ * driver uses two forward-only cursors (`lowerIter` / `upperIter`) over the
+ * materialized `rowArray` to advance `lowerBound` / `upperBound`. Endpoints
+ * are monotone per partition (SQL RANGE semantics + sorted input), so total
+ * cursor work is O(n). The segment tree then answers `[lowerBound,
+ * upperBound)` in O(log n).
+ *
+ * @note Not thread-safe.
+ */
+private[window] final class SegmentTreeWindowFunctionFrame(
+    target: InternalRow,
+    processor: AggregateProcessor,
+    functions: Array[DeclarativeAggregate],
+    inputSchema: Seq[Attribute],
+    frameType: FrameType,
+    lbound: BoundOrdering,
+    ubound: BoundOrdering,
+    newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
+    conf: SQLConf,
+    maxCachedBlocks: Option[Int],
+    taskMemoryManager: TaskMemoryManager,
+    numSegmentTreeFrames: Option[SQLMetric] = None,
+    numSegmentTreeFallbackFrames: Option[SQLMetric] = None)
+  extends WindowFunctionFrame with AutoCloseable {
+
+  require(frameType == RowFrame || frameType == RangeFrame,
+    s"SegmentTreeWindowFunctionFrame supports RowFrame or RangeFrame, got $frameType")
+
+  private[this] val fallback =
+    new SlidingWindowFunctionFrame(target, processor, lbound, ubound)
+  private[this] var tree: WindowSegmentTree = _
+
+  // ---- RowFrame-only driver state ----
+  // `boundIter` advances `upperBound` one row at a time (sliding admit loop);
+  // the lower bound is inferred from pure index arithmetic under RowFrame.
+  private[this] var boundIter: Iterator[UnsafeRow] = _
+  private[this] var nextRow: UnsafeRow = _
+
+  // ---- RangeFrame-only driver state ----
+  // Two cursors over `rowArray`; `lowerRow` / `upperRow` hold the currently-
+  // buffered head of each cursor (pre-fetched in `prepare` -- fix so
+  // `RangeBoundOrdering.compare` is never called with a null row on round 0).
+  //
+  // Spill-safety invariant: when `rowArray` spills, its iterator reuses a
+  // single `UnsafeRow` object whose pointer is rebound on each `next()`.
+  // That is tolerated here because the cursor is **read-before-advance**:
+  // each `writeRange` loop iteration reads `lowerRow`/`upperRow` for
+  // comparison before calling `getNextOrNull(...)`. Between `write()`
+  // calls the pointer's content is stable (this frame is the sole consumer
+  // of each iterator). DO NOT cache a historical row into a separate field
+  // without an explicit `.copy()`; the shared reusable UnsafeRow would
+  // silently mutate.
+  private[this] var lowerIter: Iterator[UnsafeRow] = _
+  private[this] var upperIter: Iterator[UnsafeRow] = _
+  private[this] var lowerRow: UnsafeRow = _
+  private[this] var upperRow: UnsafeRow = _
+
+  // Shared endpoints: monotone across `write()` calls within a partition.
+  private[this] var lowerBound: Int = 0
+  private[this] var upperBound: Int = 0
+
+  /**
+   * Runtime dispatch flag: when `true`, `write()`, `currentLowerBound()`,
+   * and `currentUpperBound()` delegate to the wrapped
+   * [[SlidingWindowFunctionFrame]] (small-partition path). Set by
+   * `prepare()` based on partition size vs.
+   * `spark.sql.window.segmentTree.minPartitionRows`.
+   */
+  private[window] var fallbackUsed: Boolean = false
+
+  // Register close() once per frame instance so the tree's block cache and
+  // any open row-array iterators are released when the task completes.
+  // Keeping the registration here (vs. inside the factory closure) avoids
+  // duplicate listeners when the factory is invoked multiple times per task.
+  {
+    val tc = TaskContext.get()
+    if (tc != null) {
+      tc.addTaskCompletionListener[Unit](_ => close())
+    }
+  }
+
+  override def prepare(rows: ExternalAppendOnlyUnsafeRowArray): Unit = {
+    // First-call hygiene: release prior tree/iterators/cursors before building
+    // the new tree. `prepare` is called exactly once per (partition, frame) by
+    // `WindowPartitionEvaluator.fetchNextPartition` (the sole call site); this
+    // mirrors `SlidingWindowFunctionFrame`, which has no guard. Counters bump
+    // unconditionally on the successful branch.
+    if (tree != null) {
+      tree.close()
+      tree = null
+    }
+    closeIters()
+    nextRow = null
+    lowerRow = null
+    upperRow = null
+    lowerBound = 0
+    upperBound = 0
+    if (rows.length < conf.windowSegmentTreeMinPartitionRows) {
+      fallbackUsed = true
+      fallback.prepare(rows)
+      // Count only on the successful fallback path: if `fallback.prepare`
+      // throws, the counter is not bumped.
+      numSegmentTreeFallbackFrames.foreach(_ += 1)
+      return
+    }

Review Comment:
   Reordered `prepare()` to match `OffsetWindowFunctionFrameBase`: commit to the path first, then reset the opposite side's cached state. Small-partition branch calls `fallback.prepare(rows)` and only flips `fallbackUsed = true` after it returns; if `fallback.prepare` throws, the frame stays in its previous self-consistent state. Added a lifecycle test (`SegmentTreeWindowFunctionSuite` -> `lifecycle: small then segtree transition drops fallback reference`) that structurally witnesses this ordering.
   
   Addressed in `e97e28b3c8d`. Thank you for the advice!



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowSegmentTree.scala:
##########
@@ -0,0 +1,610 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.execution.window
+
+import java.util.{LinkedHashMap => JLinkedHashMap, Map => JMap}
+
+import scala.collection.mutable
+
+import org.apache.spark.{SparkEnv, SparkException, TaskContext}
+import org.apache.spark.memory.{MemoryConsumer, TaskMemoryManager}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.expressions.aggregate.DeclarativeAggregate
+import org.apache.spark.sql.errors.QueryExecutionErrors
+import org.apache.spark.sql.execution.ExternalAppendOnlyUnsafeRowArray
+import org.apache.spark.sql.types.DataType
+import org.apache.spark.util.ArrayImplicits._
+
+/**
+ * Block-chunked segment tree for range aggregate queries over window partitions.
+ *
+ * See `the class documentation`
+ * for the full design (API contract Section 2, block-chunked memory layout Section 3,
+ * DeclarativeAggregate binding Section 4, error handling Section 5, test hooks Section 6).
+ *
+ * initial implementation scope: correctness only. The data layer uses
+ * `ExternalAppendOnlyUnsafeRowArray` to hold input rows (spillable). Each
+ * block materializes its own small segment tree (levels 0..h). Internal
+ * nodes are cached in an LRU keyed by block index; block root aggregates
+ * (block pre-aggregates) stay resident for all blocks.
+ *
+ * Note: the design doc Section 3.3 specifies leaves are NOT materialized and
+ * recomputed from the spillable array on demand. For initial implementation simplicity
+ * we materialize leaves inside the per-block internal node arrays.
+ * // TODO(SPARK-XXXXX) re-assess after Frame integration.
+ *
+ * @note Instances are not thread-safe.
+ */
+private[window] class WindowSegmentTree(
+    functions: Array[DeclarativeAggregate],
+    inputSchema: Seq[Attribute],
+    newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
+    fanout: Int = WindowSegmentTree.DefaultFanout,
+    blockSize: Int = WindowSegmentTree.DefaultBlockSize,
+    maxCachedBlocks: Option[Int] = None,
+    spillThreshold: Int = Int.MaxValue,
+    inMemoryThreshold: Int = Int.MaxValue,
+    taskMemoryManager: TaskMemoryManager = null)
+  extends AutoCloseable {
+
+  require(fanout >= 2, s"fanout must be >= 2, got $fanout")
+  require(blockSize >= 1, s"blockSize must be >= 1, got $blockSize")
+  require(functions.nonEmpty, "WindowSegmentTree requires at least one aggregate function")
+  maxCachedBlocks.foreach { n =>
+    require(n >= 1, s"maxCachedBlocks must be >= 1 when specified, got $n")
+  }
+  require(taskMemoryManager != null,
+    "WindowSegmentTree requires a non-null TaskMemoryManager; " +
+      "in tests use `new TaskMemoryManager(new TestMemoryManager(conf), 0)`")
+
+  // ---------- Schemas & projections ----------
+
+  private val bufferAttrs: Seq[AttributeReference] =
+    functions.flatMap(_.aggBufferAttributes).toImmutableArraySeq
+  private val rightAttrs: Seq[AttributeReference] =
+    functions.flatMap(_.inputAggBufferAttributes).toImmutableArraySeq
+  private val bufferDataTypes: IndexedSeq[DataType] =
+    bufferAttrs.map(_.dataType).toIndexedSeq
+
+  private val initialValues: Seq[Expression] = functions.flatMap(_.initialValues).toIndexedSeq
+  private val updateExpressions: Seq[Expression] =
+    functions.flatMap(_.updateExpressions).toIndexedSeq
+  private val mergeExpressions: Seq[Expression] =
+    functions.flatMap(_.mergeExpressions).toIndexedSeq
+
+  private[this] val initProj: MutableProjection = newMutableProjection(initialValues, Nil)
+  private[this] val updateProj: MutableProjection =
+    newMutableProjection(updateExpressions, bufferAttrs ++ inputSchema)
+  private[this] val mergeProj: MutableProjection =
+    newMutableProjection(mergeExpressions, bufferAttrs ++ rightAttrs)
+
+  private val inputUnsafeProj: UnsafeProjection =
+    UnsafeProjection.create(inputSchema.map(_.dataType).toArray)
+
+  private[this] val joinedRow = new JoinedRow()
+
+  // ---------- State ----------
+
+  private var numRows: Int = 0
+  private var numBlocks: Int = 0
+  private var rowArray: ExternalAppendOnlyUnsafeRowArray = _
+  private var closed: Boolean = false
+
+  /** Always-resident per-block root aggregates. `blockAggregates(i)` =
+   *  merged buffer over all rows in block i. */
+  private var blockAggregates: Array[InternalRow] = Array.empty
+
+  /** Rough byte width of one aggregate buffer row. Chosen at 16 B/field as a
+   *  conservative heap-overhead-aware lower bound for a
+   *  `SpecificInternalRow` slot: primitive `MutableValue` is 8 B, boxed
+   *  references and object headers push the effective footprint higher.
+   *  Tighter per-type sizing (real boxing cost, variable-length fields) is
+   *  intentionally out of scope here; TaskMemoryManager remains the hard
+   *  backstop via spill / OOM.
+   *  TODO(SPARK-XXXXX): per-type width estimator keyed on
+   *  `bufferDataTypes` (primitive 16 B, String/Binary/Decimal wider). */
+  private val bufferWidthBytes: Long = {
+    val bytesPerField = 16L
+    math.max(1L, bufferDataTypes.size.toLong * bytesPerField)
+  }
+
+  /** Number of aggregate-buffer slots cached per block (contract I5).
+   *
+   *  Invariant: equals `sum over levels L of levels(L).length` for any
+   *  block materialized by [[buildBlockLevels]]. Level 0 holds `blockSize`
+   *  leaf buffers and each subsequent level holds `ceil(prev / fanout)`
+   *  parent buffers until a single root remains. The iterative ceiling
+   *  matches the allocation in [[buildBlockLevels]] for every
+   *  `(blockSize, fanout)` pair, including non-power-of-`fanout` cases.
+   *  For `blockSize == 1` the block is a single leaf with no parent
+   *  levels, so this returns 1.
+   *  TODO(SPARK-XXXXX): drop the leaf term when [[buildBlockLevels]]
+   *  switches to on-demand leaf recomputation. */
+  private val cachedSlotsPerBlock: Long = {
+    var n = blockSize.toLong
+    var sum = n
+    while (n > 1L) {
+      n = (n + fanout - 1) / fanout
+      sum += n
+    }
+    sum
+  }
+
+  /** Bytes accounted per cached block (contract I5). Conservative: assumes
+   *  every block is full; tail block (`numRows % blockSize != 0`) will
+   *  hold fewer leaves, giving a small headroom. */
+  private[this] val blockBytes: Long =
+    math.max(1L, cachedSlotsPerBlock * bufferWidthBytes)
+
+  /** `spans(L)` = number of leaves covered by a single node at level L. Depends
+   *  only on fanout + blockSize, so precomputed once. */
+  private val spans: Array[Int] = {
+    val maxLevel = {
+      var lvl = 0
+      var span = 1L
+      while (span < blockSize) { span *= fanout; lvl += 1 }
+      lvl
+    }
+    val arr = new Array[Int](maxLevel + 1)
+    var s = 1L
+    var i = 0
+    while (i <= maxLevel) {
+      arr(i) = if (s > Int.MaxValue) Int.MaxValue else s.toInt
+      s *= fanout
+      i += 1
+    }
+    arr
+  }
+
+  /** LRU cache of per-block internal node arrays. Key = blockIdx.
+   *  Value = `Array[Array[InternalRow]]` with levels(0..h). Auto-eviction via
+   *  `removeEldestEntry` is disabled (contract I3) -- eviction is driven
+   *  explicitly from [[ensureBlockLevels]] (capacity overflow) or
+   *  [[SegTreeSpiller.spill]] (TMM pressure). Each cache entry maps 1:1 to
+   *  one [[acquireBlockMemory]] accounting. Callers (e.g.
+   *  `SegmentTreeWindowFunctionFrame`) should pass a W-aware
+   *  value like `ceil(W / blockSize) + 2`. */
+  private val blockLevelsCache: JLinkedHashMap[Integer, Array[Array[InternalRow]]] =
+    new JLinkedHashMap[Integer, Array[Array[InternalRow]]](16, 0.75f, true) {
+      override def removeEldestEntry(
+          eldest: JMap.Entry[Integer, Array[Array[InternalRow]]]): Boolean = false
+    }
+
+  // ---------- Memory consumer (contract Section 2.2) ----------
+
+  /**
+   * Private MemoryConsumer tracking cached block levels under TMM.
+   *
+   * Heap accounting only (no Tungsten pages): uses
+   * [[MemoryConsumer.acquireMemory]] / [[MemoryConsumer.freeMemory]]. The
+   * [[MemoryConsumer]] base class records `used` via an `AtomicLong` when
+   * we call these -- so TMM's consumer-priority sort in
+   * `acquireExecutionMemory` sees our pressure accurately.
+   *
+   * @note `spill()` MUST NOT call `acquireMemory` (contract I1).
+   */
+  private final class SegTreeSpiller extends MemoryConsumer(
+      taskMemoryManager,
+      taskMemoryManager.pageSizeBytes(),
+      taskMemoryManager.getTungstenMemoryMode()) {
+    override def spill(size: Long, trigger: MemoryConsumer): Long = {
+      // I2: self-trigger short-circuit. Prevents re-entrant eviction when
+      // our own acquireMemory() triggers TMM to poll us.
+      if (trigger eq this) return 0L
+      // I8: rowArray spilled-to-disk detection. If the rowArray has already
+      // spilled, evicting our cache is counter-productive (rebuild would
+      // O(blockStart)-scan the spill file). Return 0L to let TMM fall
+      // through to the next consumer.
+      //
+      // TODO(SPARK-XXXXX) #segtree-spill-priority (contract Section 7 O4): current
+      // heuristic uses `spillSize > 0` as the "has spilled" signal. A more
+      // precise check would consult `UnsafeExternalSorter.getSpillWriters`
+      // state, but that API is not public. Re-evaluate after benchmark.
+      // FIXME(kentyao): upstream a public "hasSpilled" hook on the array.
+      if (rowArray != null && rowArray.spillSize > 0) return 0L
+      evictUntil(size)
+    }
+  }
+
+  private[this] val spiller: SegTreeSpiller = new SegTreeSpiller
+
+  // Task kill / completion fall-back: ensure cache is freed even if caller
+  // forgets close() (contract Section 2.5). Frame already registers a
+  // listener too; double close is idempotent (contract I4).
+  {
+    val tc = TaskContext.get()
+    if (tc != null) {

Review Comment:
   Dropped `WindowSegmentTree`'s self-registered `TaskCompletionListener`. The sole production caller (`SegmentTreeWindowFunctionFrame`) owns the tree lifecycle via its own `close()`, and standalone tests wrap construction in `try/finally`, so the duplicate listener is redundant.
   
   Addressed in `7226e3aa2e4`. Thank you for the advice!



-- 
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@spark.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [WIP][SPARK-56546][SQL] Block-chunked segment-tree window frame for non-invertible sliding aggregates [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #55422:
URL: https://github.com/apache/spark/pull/55422#discussion_r3109520641


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/SegmentTreeWindowFunctionFrame.scala:
##########
@@ -0,0 +1,280 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.execution.window
+
+import org.apache.spark.TaskContext
+import org.apache.spark.memory.TaskMemoryManager
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, Expression, FrameType, MutableProjection, RangeFrame, RowFrame, UnsafeRow}
+import org.apache.spark.sql.catalyst.expressions.aggregate.DeclarativeAggregate
+import org.apache.spark.sql.execution.ExternalAppendOnlyUnsafeRowArray
+import org.apache.spark.sql.execution.metric.SQLMetric
+import org.apache.spark.sql.internal.SQLConf
+
+/**
+ * Moving-frame window function frame backed by [[WindowSegmentTree]]. Produces
+ * the same outputs as [[SlidingWindowFunctionFrame]] for RowFrame or
+ * single-column RangeFrame moving frames whose aggregate functions are all
+ * [[DeclarativeAggregate]] with no FILTER/DISTINCT. For partitions below
+ * `spark.sql.window.segmentTree.minPartitionRows`, delegates to a wrapped
+ * [[SlidingWindowFunctionFrame]].
+ *
+ * See `docs/frame-integration-contract.md` Section 1 for the full contract.
+ *
+ * RANGE support (RANGE frame support): when `frameType == RangeFrame`, the per-row
+ * driver uses two forward-only cursors (`lowerIter` / `upperIter`) over the
+ * materialized `rowArray` to advance `lowerBound` / `upperBound`. Endpoints
+ * are monotone per partition (SQL RANGE semantics + sorted input), so total
+ * cursor work is O(n). The segment tree then answers `[lowerBound,
+ * upperBound)` in O(log n).
+ *
+ * @note Not thread-safe.
+ */
+private[window] final class SegmentTreeWindowFunctionFrame(
+    target: InternalRow,
+    processor: AggregateProcessor,
+    functions: Array[DeclarativeAggregate],
+    inputSchema: Seq[Attribute],
+    frameType: FrameType,
+    lbound: BoundOrdering,
+    ubound: BoundOrdering,
+    newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
+    conf: SQLConf,
+    maxCachedBlocks: Option[Int],
+    taskMemoryManager: TaskMemoryManager,
+    numSegmentTreeFrames: Option[SQLMetric] = None,
+    numSegmentTreeFallbackFrames: Option[SQLMetric] = None)
+  extends WindowFunctionFrame with AutoCloseable {
+
+  require(frameType == RowFrame || frameType == RangeFrame,
+    s"SegmentTreeWindowFunctionFrame supports RowFrame or RangeFrame, got $frameType")
+
+  private[this] val fallback =
+    new SlidingWindowFunctionFrame(target, processor, lbound, ubound)

Review Comment:
   The fallback frame is allocated in every `SegmentTreeWindowFunctionFrame` ctor call, even for partitions that will take the segtree path exclusively. For a task with many frames this is avoidable cost. Consider constructing it lazily inside `prepare()` only when `rows.length < minPartitionRows`.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/SegmentTreeWindowFunctionFrame.scala:
##########
@@ -0,0 +1,280 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.execution.window
+
+import org.apache.spark.TaskContext
+import org.apache.spark.memory.TaskMemoryManager
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, Expression, FrameType, MutableProjection, RangeFrame, RowFrame, UnsafeRow}
+import org.apache.spark.sql.catalyst.expressions.aggregate.DeclarativeAggregate
+import org.apache.spark.sql.execution.ExternalAppendOnlyUnsafeRowArray
+import org.apache.spark.sql.execution.metric.SQLMetric
+import org.apache.spark.sql.internal.SQLConf
+
+/**
+ * Moving-frame window function frame backed by [[WindowSegmentTree]]. Produces
+ * the same outputs as [[SlidingWindowFunctionFrame]] for RowFrame or
+ * single-column RangeFrame moving frames whose aggregate functions are all
+ * [[DeclarativeAggregate]] with no FILTER/DISTINCT. For partitions below
+ * `spark.sql.window.segmentTree.minPartitionRows`, delegates to a wrapped
+ * [[SlidingWindowFunctionFrame]].
+ *
+ * See `docs/frame-integration-contract.md` Section 1 for the full contract.
+ *
+ * RANGE support (RANGE frame support): when `frameType == RangeFrame`, the per-row
+ * driver uses two forward-only cursors (`lowerIter` / `upperIter`) over the
+ * materialized `rowArray` to advance `lowerBound` / `upperBound`. Endpoints
+ * are monotone per partition (SQL RANGE semantics + sorted input), so total
+ * cursor work is O(n). The segment tree then answers `[lowerBound,
+ * upperBound)` in O(log n).
+ *
+ * @note Not thread-safe.
+ */
+private[window] final class SegmentTreeWindowFunctionFrame(
+    target: InternalRow,
+    processor: AggregateProcessor,
+    functions: Array[DeclarativeAggregate],
+    inputSchema: Seq[Attribute],
+    frameType: FrameType,
+    lbound: BoundOrdering,
+    ubound: BoundOrdering,
+    newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
+    conf: SQLConf,
+    maxCachedBlocks: Option[Int],
+    taskMemoryManager: TaskMemoryManager,
+    numSegmentTreeFrames: Option[SQLMetric] = None,
+    numSegmentTreeFallbackFrames: Option[SQLMetric] = None)
+  extends WindowFunctionFrame with AutoCloseable {
+
+  require(frameType == RowFrame || frameType == RangeFrame,
+    s"SegmentTreeWindowFunctionFrame supports RowFrame or RangeFrame, got $frameType")
+
+  private[this] val fallback =
+    new SlidingWindowFunctionFrame(target, processor, lbound, ubound)
+  private[this] var tree: WindowSegmentTree = _
+
+  // ---- RowFrame-only driver state ----
+  // `boundIter` advances `upperBound` one row at a time (sliding admit loop);
+  // the lower bound is inferred from pure index arithmetic under RowFrame.
+  private[this] var boundIter: Iterator[UnsafeRow] = _
+  private[this] var nextRow: UnsafeRow = _
+
+  // ---- RangeFrame-only driver state ----
+  // Two cursors over `rowArray`; `lowerRow` / `upperRow` hold the currently-
+  // buffered head of each cursor (pre-fetched in `prepare` -- fix so
+  // `RangeBoundOrdering.compare` is never called with a null row on round 0).
+  //
+  // Spill-safety invariant: when `rowArray` spills, its iterator reuses a
+  // single `UnsafeRow` object whose pointer is rebound on each `next()`.
+  // That is tolerated here because the cursor is **read-before-advance**:
+  // each `writeRange` loop iteration reads `lowerRow`/`upperRow` for
+  // comparison before calling `getNextOrNull(...)`. Between `write()`
+  // calls the pointer's content is stable (this frame is the sole consumer
+  // of each iterator). DO NOT cache a historical row into a separate field
+  // without an explicit `.copy()`; the shared reusable UnsafeRow would
+  // silently mutate.
+  private[this] var lowerIter: Iterator[UnsafeRow] = _
+  private[this] var upperIter: Iterator[UnsafeRow] = _
+  private[this] var lowerRow: UnsafeRow = _
+  private[this] var upperRow: UnsafeRow = _
+
+  // Shared endpoints: monotone across `write()` calls within a partition.
+  private[this] var lowerBound: Int = 0
+  private[this] var upperBound: Int = 0
+
+  /**
+   * Runtime dispatch flag: when `true`, `write()`, `currentLowerBound()`,
+   * and `currentUpperBound()` delegate to the wrapped
+   * [[SlidingWindowFunctionFrame]] (small-partition path). Set by
+   * `prepare()` based on partition size vs.
+   * `spark.sql.window.segmentTree.minPartitionRows`.
+   */
+  private[window] var fallbackUsed: Boolean = false
+
+  // Register close() once per frame instance so the tree's block cache and
+  // any open row-array iterators are released when the task completes.
+  // Keeping the registration here (vs. inside the factory closure) avoids
+  // duplicate listeners when the factory is invoked multiple times per task.
+  {
+    val tc = TaskContext.get()
+    if (tc != null) {
+      tc.addTaskCompletionListener[Unit](_ => close())
+    }
+  }
+
+  override def prepare(rows: ExternalAppendOnlyUnsafeRowArray): Unit = {
+    // First-call hygiene: release prior tree/iterators/cursors before building
+    // the new tree. `prepare` is called exactly once per (partition, frame) by
+    // `WindowPartitionEvaluator.fetchNextPartition` (the sole call site); this
+    // mirrors `SlidingWindowFunctionFrame`, which has no guard. Counters bump
+    // unconditionally on the successful branch.
+    if (tree != null) {
+      tree.close()
+      tree = null
+    }
+    closeIters()
+    nextRow = null
+    lowerRow = null
+    upperRow = null
+    lowerBound = 0
+    upperBound = 0
+    if (rows.length < conf.windowSegmentTreeMinPartitionRows) {
+      fallbackUsed = true
+      fallback.prepare(rows)
+      // Count only on the successful fallback path: if `fallback.prepare`
+      // throws, the counter is not bumped.
+      numSegmentTreeFallbackFrames.foreach(_ += 1)
+      return
+    }

Review Comment:
   `prepare` resets all segtree state at the top (`tree`, iters, cursors, bounds) *before* the fallback-path branch calls `fallback.prepare(rows)`. If that `fallback.prepare` throws (e.g., OOM during listener init), the frame is left reset-but-unprepared; a subsequent `write` would dispatch with `fallbackUsed = true` against an unprepared fallback. Safer: defer the reset until after the size-check branch, or mark the frame `BROKEN` on failure so `write` fails loudly.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowSegmentTree.scala:
##########
@@ -0,0 +1,610 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.execution.window
+
+import java.util.{LinkedHashMap => JLinkedHashMap, Map => JMap}
+
+import scala.collection.mutable
+
+import org.apache.spark.{SparkEnv, SparkException, TaskContext}
+import org.apache.spark.memory.{MemoryConsumer, TaskMemoryManager}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.expressions.aggregate.DeclarativeAggregate
+import org.apache.spark.sql.errors.QueryExecutionErrors
+import org.apache.spark.sql.execution.ExternalAppendOnlyUnsafeRowArray
+import org.apache.spark.sql.types.DataType
+import org.apache.spark.util.ArrayImplicits._
+
+/**
+ * Block-chunked segment tree for range aggregate queries over window partitions.
+ *
+ * See `the class documentation`
+ * for the full design (API contract Section 2, block-chunked memory layout Section 3,
+ * DeclarativeAggregate binding Section 4, error handling Section 5, test hooks Section 6).
+ *
+ * initial implementation scope: correctness only. The data layer uses
+ * `ExternalAppendOnlyUnsafeRowArray` to hold input rows (spillable). Each
+ * block materializes its own small segment tree (levels 0..h). Internal
+ * nodes are cached in an LRU keyed by block index; block root aggregates
+ * (block pre-aggregates) stay resident for all blocks.
+ *
+ * Note: the design doc Section 3.3 specifies leaves are NOT materialized and
+ * recomputed from the spillable array on demand. For initial implementation simplicity
+ * we materialize leaves inside the per-block internal node arrays.
+ * // TODO(SPARK-XXXXX) re-assess after Frame integration.
+ *
+ * @note Instances are not thread-safe.
+ */
+private[window] class WindowSegmentTree(
+    functions: Array[DeclarativeAggregate],
+    inputSchema: Seq[Attribute],
+    newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
+    fanout: Int = WindowSegmentTree.DefaultFanout,
+    blockSize: Int = WindowSegmentTree.DefaultBlockSize,
+    maxCachedBlocks: Option[Int] = None,
+    spillThreshold: Int = Int.MaxValue,
+    inMemoryThreshold: Int = Int.MaxValue,
+    taskMemoryManager: TaskMemoryManager = null)
+  extends AutoCloseable {
+
+  require(fanout >= 2, s"fanout must be >= 2, got $fanout")
+  require(blockSize >= 1, s"blockSize must be >= 1, got $blockSize")
+  require(functions.nonEmpty, "WindowSegmentTree requires at least one aggregate function")
+  maxCachedBlocks.foreach { n =>
+    require(n >= 1, s"maxCachedBlocks must be >= 1 when specified, got $n")
+  }
+  require(taskMemoryManager != null,
+    "WindowSegmentTree requires a non-null TaskMemoryManager; " +
+      "in tests use `new TaskMemoryManager(new TestMemoryManager(conf), 0)`")
+
+  // ---------- Schemas & projections ----------
+
+  private val bufferAttrs: Seq[AttributeReference] =
+    functions.flatMap(_.aggBufferAttributes).toImmutableArraySeq
+  private val rightAttrs: Seq[AttributeReference] =
+    functions.flatMap(_.inputAggBufferAttributes).toImmutableArraySeq
+  private val bufferDataTypes: IndexedSeq[DataType] =
+    bufferAttrs.map(_.dataType).toIndexedSeq
+
+  private val initialValues: Seq[Expression] = functions.flatMap(_.initialValues).toIndexedSeq
+  private val updateExpressions: Seq[Expression] =
+    functions.flatMap(_.updateExpressions).toIndexedSeq
+  private val mergeExpressions: Seq[Expression] =
+    functions.flatMap(_.mergeExpressions).toIndexedSeq
+
+  private[this] val initProj: MutableProjection = newMutableProjection(initialValues, Nil)
+  private[this] val updateProj: MutableProjection =
+    newMutableProjection(updateExpressions, bufferAttrs ++ inputSchema)
+  private[this] val mergeProj: MutableProjection =
+    newMutableProjection(mergeExpressions, bufferAttrs ++ rightAttrs)
+
+  private val inputUnsafeProj: UnsafeProjection =
+    UnsafeProjection.create(inputSchema.map(_.dataType).toArray)
+
+  private[this] val joinedRow = new JoinedRow()
+
+  // ---------- State ----------
+
+  private var numRows: Int = 0
+  private var numBlocks: Int = 0
+  private var rowArray: ExternalAppendOnlyUnsafeRowArray = _
+  private var closed: Boolean = false
+
+  /** Always-resident per-block root aggregates. `blockAggregates(i)` =
+   *  merged buffer over all rows in block i. */
+  private var blockAggregates: Array[InternalRow] = Array.empty
+
+  /** Rough byte width of one aggregate buffer row. Chosen at 16 B/field as a
+   *  conservative heap-overhead-aware lower bound for a
+   *  `SpecificInternalRow` slot: primitive `MutableValue` is 8 B, boxed
+   *  references and object headers push the effective footprint higher.
+   *  Tighter per-type sizing (real boxing cost, variable-length fields) is
+   *  intentionally out of scope here; TaskMemoryManager remains the hard
+   *  backstop via spill / OOM.
+   *  TODO(SPARK-XXXXX): per-type width estimator keyed on
+   *  `bufferDataTypes` (primitive 16 B, String/Binary/Decimal wider). */
+  private val bufferWidthBytes: Long = {
+    val bytesPerField = 16L
+    math.max(1L, bufferDataTypes.size.toLong * bytesPerField)
+  }
+
+  /** Number of aggregate-buffer slots cached per block (contract I5).
+   *
+   *  Invariant: equals `sum over levels L of levels(L).length` for any
+   *  block materialized by [[buildBlockLevels]]. Level 0 holds `blockSize`
+   *  leaf buffers and each subsequent level holds `ceil(prev / fanout)`
+   *  parent buffers until a single root remains. The iterative ceiling
+   *  matches the allocation in [[buildBlockLevels]] for every
+   *  `(blockSize, fanout)` pair, including non-power-of-`fanout` cases.
+   *  For `blockSize == 1` the block is a single leaf with no parent
+   *  levels, so this returns 1.
+   *  TODO(SPARK-XXXXX): drop the leaf term when [[buildBlockLevels]]
+   *  switches to on-demand leaf recomputation. */
+  private val cachedSlotsPerBlock: Long = {
+    var n = blockSize.toLong
+    var sum = n
+    while (n > 1L) {
+      n = (n + fanout - 1) / fanout
+      sum += n
+    }
+    sum
+  }
+
+  /** Bytes accounted per cached block (contract I5). Conservative: assumes
+   *  every block is full; tail block (`numRows % blockSize != 0`) will
+   *  hold fewer leaves, giving a small headroom. */
+  private[this] val blockBytes: Long =
+    math.max(1L, cachedSlotsPerBlock * bufferWidthBytes)
+
+  /** `spans(L)` = number of leaves covered by a single node at level L. Depends
+   *  only on fanout + blockSize, so precomputed once. */
+  private val spans: Array[Int] = {
+    val maxLevel = {
+      var lvl = 0
+      var span = 1L
+      while (span < blockSize) { span *= fanout; lvl += 1 }
+      lvl
+    }
+    val arr = new Array[Int](maxLevel + 1)
+    var s = 1L
+    var i = 0
+    while (i <= maxLevel) {
+      arr(i) = if (s > Int.MaxValue) Int.MaxValue else s.toInt
+      s *= fanout
+      i += 1
+    }
+    arr
+  }
+
+  /** LRU cache of per-block internal node arrays. Key = blockIdx.
+   *  Value = `Array[Array[InternalRow]]` with levels(0..h). Auto-eviction via
+   *  `removeEldestEntry` is disabled (contract I3) -- eviction is driven
+   *  explicitly from [[ensureBlockLevels]] (capacity overflow) or
+   *  [[SegTreeSpiller.spill]] (TMM pressure). Each cache entry maps 1:1 to
+   *  one [[acquireBlockMemory]] accounting. Callers (e.g.
+   *  `SegmentTreeWindowFunctionFrame`) should pass a W-aware
+   *  value like `ceil(W / blockSize) + 2`. */
+  private val blockLevelsCache: JLinkedHashMap[Integer, Array[Array[InternalRow]]] =
+    new JLinkedHashMap[Integer, Array[Array[InternalRow]]](16, 0.75f, true) {
+      override def removeEldestEntry(
+          eldest: JMap.Entry[Integer, Array[Array[InternalRow]]]): Boolean = false
+    }
+
+  // ---------- Memory consumer (contract Section 2.2) ----------
+
+  /**
+   * Private MemoryConsumer tracking cached block levels under TMM.
+   *
+   * Heap accounting only (no Tungsten pages): uses
+   * [[MemoryConsumer.acquireMemory]] / [[MemoryConsumer.freeMemory]]. The
+   * [[MemoryConsumer]] base class records `used` via an `AtomicLong` when
+   * we call these -- so TMM's consumer-priority sort in
+   * `acquireExecutionMemory` sees our pressure accurately.
+   *
+   * @note `spill()` MUST NOT call `acquireMemory` (contract I1).
+   */
+  private final class SegTreeSpiller extends MemoryConsumer(
+      taskMemoryManager,
+      taskMemoryManager.pageSizeBytes(),
+      taskMemoryManager.getTungstenMemoryMode()) {

Review Comment:
   Using `taskMemoryManager.getTungstenMemoryMode()` registers the spiller as `ON_HEAP` or `OFF_HEAP` depending on Tungsten mode, but the actual cached state (`SpecificInternalRow` buffers, `Array[Array[InternalRow]]`) is always on the JVM heap. Under OFF_HEAP Tungsten these on-heap allocations get charged to the off-heap pool — phantom pressure on the off-heap budget and no accounting of real heap pressure. The `T9 OFF_HEAP path` test codifies this behavior but may be enshrining a bug. Consider hardcoding `MemoryMode.ON_HEAP` since these allocations are unambiguously on-heap.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/SegmentTreeWindowFunctionFrame.scala:
##########
@@ -0,0 +1,280 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.execution.window
+
+import org.apache.spark.TaskContext
+import org.apache.spark.memory.TaskMemoryManager
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, Expression, FrameType, MutableProjection, RangeFrame, RowFrame, UnsafeRow}
+import org.apache.spark.sql.catalyst.expressions.aggregate.DeclarativeAggregate
+import org.apache.spark.sql.execution.ExternalAppendOnlyUnsafeRowArray
+import org.apache.spark.sql.execution.metric.SQLMetric
+import org.apache.spark.sql.internal.SQLConf
+
+/**
+ * Moving-frame window function frame backed by [[WindowSegmentTree]]. Produces
+ * the same outputs as [[SlidingWindowFunctionFrame]] for RowFrame or
+ * single-column RangeFrame moving frames whose aggregate functions are all
+ * [[DeclarativeAggregate]] with no FILTER/DISTINCT. For partitions below
+ * `spark.sql.window.segmentTree.minPartitionRows`, delegates to a wrapped
+ * [[SlidingWindowFunctionFrame]].
+ *
+ * See `docs/frame-integration-contract.md` Section 1 for the full contract.
+ *
+ * RANGE support (RANGE frame support): when `frameType == RangeFrame`, the per-row
+ * driver uses two forward-only cursors (`lowerIter` / `upperIter`) over the
+ * materialized `rowArray` to advance `lowerBound` / `upperBound`. Endpoints
+ * are monotone per partition (SQL RANGE semantics + sorted input), so total
+ * cursor work is O(n). The segment tree then answers `[lowerBound,
+ * upperBound)` in O(log n).
+ *
+ * @note Not thread-safe.
+ */
+private[window] final class SegmentTreeWindowFunctionFrame(
+    target: InternalRow,
+    processor: AggregateProcessor,
+    functions: Array[DeclarativeAggregate],
+    inputSchema: Seq[Attribute],
+    frameType: FrameType,
+    lbound: BoundOrdering,
+    ubound: BoundOrdering,
+    newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
+    conf: SQLConf,
+    maxCachedBlocks: Option[Int],
+    taskMemoryManager: TaskMemoryManager,
+    numSegmentTreeFrames: Option[SQLMetric] = None,
+    numSegmentTreeFallbackFrames: Option[SQLMetric] = None)
+  extends WindowFunctionFrame with AutoCloseable {
+
+  require(frameType == RowFrame || frameType == RangeFrame,
+    s"SegmentTreeWindowFunctionFrame supports RowFrame or RangeFrame, got $frameType")
+
+  private[this] val fallback =
+    new SlidingWindowFunctionFrame(target, processor, lbound, ubound)
+  private[this] var tree: WindowSegmentTree = _
+
+  // ---- RowFrame-only driver state ----
+  // `boundIter` advances `upperBound` one row at a time (sliding admit loop);
+  // the lower bound is inferred from pure index arithmetic under RowFrame.
+  private[this] var boundIter: Iterator[UnsafeRow] = _
+  private[this] var nextRow: UnsafeRow = _
+
+  // ---- RangeFrame-only driver state ----
+  // Two cursors over `rowArray`; `lowerRow` / `upperRow` hold the currently-
+  // buffered head of each cursor (pre-fetched in `prepare` -- fix so
+  // `RangeBoundOrdering.compare` is never called with a null row on round 0).
+  //
+  // Spill-safety invariant: when `rowArray` spills, its iterator reuses a
+  // single `UnsafeRow` object whose pointer is rebound on each `next()`.
+  // That is tolerated here because the cursor is **read-before-advance**:
+  // each `writeRange` loop iteration reads `lowerRow`/`upperRow` for
+  // comparison before calling `getNextOrNull(...)`. Between `write()`
+  // calls the pointer's content is stable (this frame is the sole consumer
+  // of each iterator). DO NOT cache a historical row into a separate field
+  // without an explicit `.copy()`; the shared reusable UnsafeRow would
+  // silently mutate.
+  private[this] var lowerIter: Iterator[UnsafeRow] = _
+  private[this] var upperIter: Iterator[UnsafeRow] = _
+  private[this] var lowerRow: UnsafeRow = _
+  private[this] var upperRow: UnsafeRow = _
+
+  // Shared endpoints: monotone across `write()` calls within a partition.
+  private[this] var lowerBound: Int = 0
+  private[this] var upperBound: Int = 0
+
+  /**
+   * Runtime dispatch flag: when `true`, `write()`, `currentLowerBound()`,
+   * and `currentUpperBound()` delegate to the wrapped
+   * [[SlidingWindowFunctionFrame]] (small-partition path). Set by
+   * `prepare()` based on partition size vs.
+   * `spark.sql.window.segmentTree.minPartitionRows`.
+   */
+  private[window] var fallbackUsed: Boolean = false
+
+  // Register close() once per frame instance so the tree's block cache and
+  // any open row-array iterators are released when the task completes.
+  // Keeping the registration here (vs. inside the factory closure) avoids
+  // duplicate listeners when the factory is invoked multiple times per task.
+  {
+    val tc = TaskContext.get()
+    if (tc != null) {
+      tc.addTaskCompletionListener[Unit](_ => close())
+    }
+  }
+
+  override def prepare(rows: ExternalAppendOnlyUnsafeRowArray): Unit = {
+    // First-call hygiene: release prior tree/iterators/cursors before building
+    // the new tree. `prepare` is called exactly once per (partition, frame) by
+    // `WindowPartitionEvaluator.fetchNextPartition` (the sole call site); this
+    // mirrors `SlidingWindowFunctionFrame`, which has no guard. Counters bump
+    // unconditionally on the successful branch.
+    if (tree != null) {
+      tree.close()
+      tree = null
+    }
+    closeIters()
+    nextRow = null
+    lowerRow = null
+    upperRow = null
+    lowerBound = 0
+    upperBound = 0
+    if (rows.length < conf.windowSegmentTreeMinPartitionRows) {
+      fallbackUsed = true
+      fallback.prepare(rows)
+      // Count only on the successful fallback path: if `fallback.prepare`
+      // throws, the counter is not bumped.
+      numSegmentTreeFallbackFrames.foreach(_ += 1)
+      return
+    }
+    fallbackUsed = false
+    tree = new WindowSegmentTree(
+      functions,
+      inputSchema,
+      newMutableProjection,
+      fanout = conf.windowSegmentTreeFanout,
+      blockSize = conf.windowSegmentTreeBlockSize,
+      maxCachedBlocks = maxCachedBlocks,
+      taskMemoryManager = taskMemoryManager)
+    // Build first (drains rows into the tree's internal row array), then
+    // open fresh iterator(s) for per-row bound advancement.
+    tree.build(rows.generateIterator())
+    // Count only on the successful segtree path: if `tree.build` throws
+    // (e.g. OOM during block allocation), the counter is not bumped.
+    numSegmentTreeFrames.foreach(_ += 1)
+    frameType match {
+      case RowFrame =>
+        boundIter = rows.generateIterator()
+        nextRow = WindowFunctionFrame.getNextOrNull(boundIter)
+      case RangeFrame =>
+        lowerIter = rows.generateIterator()
+        upperIter = rows.generateIterator()
+        // Pre-seed cursor heads so `RangeBoundOrdering.compare` (which
+        // projects the input row to a scalar) never dereferences null on
+        // round 0. Either may legitimately be null if `rows` is
+        // empty; the advance loops' `!= null` / `< upperBound` guards
+        // handle that.
+        lowerRow = WindowFunctionFrame.getNextOrNull(lowerIter)
+        upperRow = WindowFunctionFrame.getNextOrNull(upperIter)
+    }
+  }
+
+  override def write(index: Int, current: InternalRow): Unit = {
+    if (fallbackUsed) {
+      fallback.write(index, current)
+      return
+    }
+    frameType match {
+      case RowFrame => writeRow(index, current)
+      case RangeFrame => writeRange(index, current)
+    }
+  }
+
+  private def writeRow(index: Int, current: InternalRow): Unit = {

Review Comment:
   `writeRow` and `writeRange` reimplement the monotone-cursor admit/drop loop from `SlidingWindowFunctionFrame.write` (`WindowFunctionFrame.scala:466-499`), swapped from drop-then-admit to admit-then-drop and without the buffer maintenance. I verified the two orderings converge to the same `(lowerBound, upperBound)` at each step for RowFrame, so correctness holds — but two parallel implementations of the same invariant are a maintenance hazard: a future fix to sliding could silently diverge here. Consider extracting the admit/drop cursor advance as a shared helper; only the `queryInto` vs. `processor.initialize+update+evaluate` should differ.



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/window/SegmentTreeWindowFunctionSuite.scala:
##########
@@ -0,0 +1,862 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.execution.window
+
+import org.apache.spark.sql.{DataFrame, Encoder, Encoders, QueryTest, Row}
+import org.apache.spark.sql.expressions.{Aggregator, MutableAggregationBuffer, Window}
+import org.apache.spark.sql.expressions.UserDefinedAggregateFunction
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.test.SharedSparkSession
+import org.apache.spark.sql.types.{DataType, LongType, StructType}
+
+/**
+ * End-to-end tests for the block-chunked segment-tree moving window frame.
+ *
+ * Coverage by section:
+ *   - Coverage: various cases (basic aggregates), various cases (frame boundaries),
+ *                min-partition-rows fallback, AggregateWindowFunction
+ *                regression.
+ *   - Coverage: various cases (NULL, NaN/Infinity), various cases
+ *                (numeric / string / date-timestamp types), various cases
+ *                (unsupported-merge / DISTINCT / feature-flag fallback).
+ *
+  */
+class SegmentTreeWindowFunctionSuite extends QueryTest with SharedSparkSession {
+
+  import testImplicits._
+
+  // Common config: force the segment-tree path regardless of partition size
+  // (we exercise the fallback explicitly below).
+  private val enableSegTree: Map[String, String] = Map(
+    SQLConf.WINDOW_SEGMENT_TREE_ENABLED.key -> "true",
+    SQLConf.WINDOW_SEGMENT_TREE_MIN_PARTITION_ROWS.key -> "1")
+
+  private val disableSegTree: Map[String, String] = Map(
+    SQLConf.WINDOW_SEGMENT_TREE_ENABLED.key -> "false")
+
+  /** Build `f(conf)` twice (enabled / disabled) and assert equal results. */
+  private def checkEquivalence(build: () => DataFrame): Unit = {
+    val baseline: Array[Row] = withSQLConf(disableSegTree.toSeq: _*) {
+      build().collect().sortBy(_.toString)
+    }
+    withSQLConf(enableSegTree.toSeq: _*) {
+      val actual = build().collect().sortBy(_.toString)
+      assert(actual.toSeq === baseline.toSeq,
+        s"segment-tree output differs from baseline.\nExpected: ${baseline.toSeq}\n" +
+          s"Actual:   ${actual.toSeq}")
+    }
+  }
+
+  /** Standard fixture: 3 partitions, sizes 40/40/40, values = row index. */
+  private def baseDF: DataFrame = {
+    spark.range(0, 120).selectExpr(
+      "id",
+      "(id % 3) AS pk",
+      "CAST(id AS INT) AS v")
+  }
+
+  private def winSpec(lo: Int, hi: Int) =
+    Window.partitionBy($"pk").orderBy($"id").rowsBetween(lo, hi)
+
+  // ---------------- A1: basic aggregate equivalence ----------------
+
+  test("MIN over ROWS BETWEEN 3 PRECEDING AND 3 FOLLOWING") {
+    checkEquivalence(() =>
+      baseDF.select($"id", $"pk", min($"v").over(winSpec(-3, 3)).as("agg")))
+  }
+
+  test("MAX over ROWS BETWEEN 3 PRECEDING AND 3 FOLLOWING") {
+    checkEquivalence(() =>
+      baseDF.select($"id", $"pk", max($"v").over(winSpec(-3, 3)).as("agg")))
+  }
+
+  test("SUM over ROWS BETWEEN 3 PRECEDING AND 3 FOLLOWING") {
+    checkEquivalence(() =>
+      baseDF.select($"id", $"pk", sum($"v").over(winSpec(-3, 3)).as("agg")))
+  }
+
+  test("COUNT over ROWS BETWEEN 3 PRECEDING AND 3 FOLLOWING") {
+    checkEquivalence(() =>
+      baseDF.select($"id", $"pk", count($"v").over(winSpec(-3, 3)).as("agg")))
+  }
+
+  test("AVG over ROWS BETWEEN 3 PRECEDING AND 3 FOLLOWING") {
+    checkEquivalence(() =>
+      baseDF.select($"id", $"pk", avg($"v").over(winSpec(-3, 3)).as("agg")))
+  }
+
+  test("MIN + MAX + SUM share a single window frame") {
+    checkEquivalence(() =>
+      baseDF.select(
+        $"id",
+        $"pk",
+        min($"v").over(winSpec(-3, 3)).as("mn"),
+        max($"v").over(winSpec(-3, 3)).as("mx"),
+        sum($"v").over(winSpec(-3, 3)).as("sm")))
+  }
+
+  // ---------------- A2: frame-size boundaries ----------------
+
+  test("frame size = 1 (CURRENT ROW only)") {
+    checkEquivalence(() =>
+      baseDF.select($"id", $"pk", sum($"v").over(winSpec(0, 0)).as("agg")))
+  }
+
+  test("frame spans full partition") {
+    // 40 rows per partition; use a wide symmetric window covering it.
+    checkEquivalence(() =>
+      baseDF.select($"id", $"pk", sum($"v").over(winSpec(-100, 100)).as("agg")))
+  }
+
+  test("frame extends past both partition edges") {
+    checkEquivalence(() =>
+      baseDF.select($"id", $"pk",
+        sum($"v").over(winSpec(-50, 50)).as("agg"),
+        min($"v").over(winSpec(-50, 50)).as("mn"),
+        max($"v").over(winSpec(-50, 50)).as("mx")))
+  }
+
+  
+  test("partition below minPartitionRows falls back to SlidingWindowFunctionFrame") {
+    // 5-row partition, min threshold = 10 -> must fall back.
+    val df = spark.range(0, 5).selectExpr(
+      "id", "0 AS pk", "CAST(id AS INT) AS v")
+    val enabledConf = Map(
+      SQLConf.WINDOW_SEGMENT_TREE_ENABLED.key -> "true",
+      SQLConf.WINDOW_SEGMENT_TREE_MIN_PARTITION_ROWS.key -> "10")
+
+    // 1. Result correctness against baseline.
+    val baseline = withSQLConf(disableSegTree.toSeq: _*) {
+      df.select($"id", sum($"v").over(winSpec(-1, 1)).as("s"))
+        .collect().sortBy(_.toString)
+    }
+    val actual = withSQLConf(enabledConf.toSeq: _*) {
+      df.select($"id", sum($"v").over(winSpec(-1, 1)).as("s"))
+        .collect().sortBy(_.toString)
+    }
+    assert(actual.toSeq === baseline.toSeq)
+
+    // 2. Directly exercise the frame to confirm the fallback flag flips.
+    withSQLConf(enabledConf.toSeq: _*) {
+      SegmentTreeWindowTestHelpers.withSmallPartitionFrame(
+        SQLConf.get, rows = 5) { frame =>
+        assert(frame.fallbackUsed,
+          "expected fallbackUsed=true for partition smaller than minPartitionRows")
+      }
+    }
+  }
+
+  
+  test("NTH_VALUE over ROWS frame falls back cleanly (no mergeExpressions crash)") {
+    // NthValue extends DeclarativeAggregate but its mergeExpressions throws
+    // mergeUnsupportedByWindowFunctionError. eligibleForSegTree must exclude it.
+    val df = baseDF
+    val withSegTree = withSQLConf(enableSegTree.toSeq: _*) {
+      df.selectExpr(
+        "id", "pk",
+        "nth_value(v, 3) OVER (PARTITION BY pk ORDER BY id " +
+          "ROWS BETWEEN 5 PRECEDING AND 5 FOLLOWING) AS n3")
+        .collect().sortBy(_.toString)
+    }
+    val baseline = withSQLConf(disableSegTree.toSeq: _*) {
+      df.selectExpr(
+        "id", "pk",
+        "nth_value(v, 3) OVER (PARTITION BY pk ORDER BY id " +
+          "ROWS BETWEEN 5 PRECEDING AND 5 FOLLOWING) AS n3")
+        .collect().sortBy(_.toString)
+    }
+    assert(withSegTree.toSeq === baseline.toSeq)
+  }
+
+  test("ROW_NUMBER over ROWS frame falls back cleanly (no mergeExpressions crash)") {
+    val df = baseDF
+    val withSegTree = withSQLConf(enableSegTree.toSeq: _*) {
+      df.selectExpr(
+        "id", "pk",
+        "row_number() OVER (PARTITION BY pk ORDER BY id) AS rn")
+        .collect().sortBy(_.toString)
+    }
+    val baseline = withSQLConf(disableSegTree.toSeq: _*) {
+      df.selectExpr(
+        "id", "pk",
+        "row_number() OVER (PARTITION BY pk ORDER BY id) AS rn")
+        .collect().sortBy(_.toString)
+    }
+    assert(withSegTree.toSeq === baseline.toSeq)
+  }
+
+    // A3.*: NULL / NaN / Infinity handling
+  // A4.*: numeric / string / date-timestamp types
+  // various cases: unsupported-merge / DISTINCT / feature-flag fallback
+  //
+  // All tests use the same oracle strategy as the frame integration: run with
+  // `segmentTree.enabled=true` (forced via min-rows=1) and with `=false`,
+  // then assert bit-for-bit equal Row sequences. That gives us:
+  //   - Correctness: seg-tree output matches SlidingWindowFunctionFrame
+  //     (the community-validated baseline).
+  //   - Fallback paths: various cases exercise the `eligibleForSegTree` filter,
+  //     which must decline to drive the seg-tree path and hand off to the
+  //     sliding frame; equal rows prove the hand-off preserves semantics.
+
+  // ---------------- A3: NULL / special values ----------------
+
+  test("all-NULL column: MIN/MAX/SUM/AVG/COUNT") {
+    val df = spark.range(0, 30).selectExpr(
+      "id", "(id % 3) AS pk", "CAST(NULL AS INT) AS v")
+    checkEquivalence(() =>
+      df.select($"id", $"pk",
+        min($"v").over(winSpec(-3, 3)).as("mn"),
+        max($"v").over(winSpec(-3, 3)).as("mx"),
+        sum($"v").over(winSpec(-3, 3)).as("sm"),
+        avg($"v").over(winSpec(-3, 3)).as("av"),
+        count($"v").over(winSpec(-3, 3)).as("cn")))
+  }
+
+  test("mixed NULL and non-NULL: NULLs must not leak into MIN/MAX") {
+    // Every 3rd value is NULL. Aggregates must skip them (NULL-agnostic merge).
+    val df = spark.range(0, 60).selectExpr(
+      "id",
+      "(id % 3) AS pk",
+      "CASE WHEN id % 3 = 0 THEN NULL ELSE CAST(id AS INT) END AS v")
+    checkEquivalence(() =>
+      df.select($"id", $"pk",
+        min($"v").over(winSpec(-4, 4)).as("mn"),
+        max($"v").over(winSpec(-4, 4)).as("mx"),
+        sum($"v").over(winSpec(-4, 4)).as("sm"),
+        count($"v").over(winSpec(-4, 4)).as("cn")))
+  }
+
+  test("Double NaN and +/-Infinity propagate correctly through MIN/MAX/SUM") {
+    // Spark's NaN ordering: NaN is treated as greater than +Inf for MIN/MAX.
+    // +Inf + -Inf = NaN for SUM. The seg-tree path uses DeclarativeAggregate's
+    // own merge, so behavior must match the baseline exactly.
+    val df = spark.range(0, 30).selectExpr(
+      "id",
+      "(id % 2) AS pk",
+      """CASE
+           WHEN id % 7 = 0 THEN double('NaN')
+           WHEN id % 7 = 1 THEN double('Infinity')
+           WHEN id % 7 = 2 THEN double('-Infinity')
+           ELSE CAST(id AS DOUBLE)
+         END AS v""")
+    checkEquivalence(() =>
+      df.select($"id", $"pk",
+        min($"v").over(winSpec(-3, 3)).as("mn"),
+        max($"v").over(winSpec(-3, 3)).as("mx"),
+        sum($"v").over(winSpec(-3, 3)).as("sm")))
+  }
+
+  // ---------------- A4: data types ----------------
+
+  test("numeric types: Int / Long / Double / Decimal") {
+    val df = spark.range(0, 60).selectExpr(
+      "id",
+      "(id % 3) AS pk",
+      "CAST(id AS INT)             AS vi",
+      "CAST(id * 1000000L AS LONG) AS vl",
+      "CAST(id AS DOUBLE) + 0.25   AS vd",
+      "CAST(id AS DECIMAL(20,4))   AS vdec")
+    checkEquivalence(() =>
+      df.select($"id", $"pk",
+        sum($"vi").over(winSpec(-2, 2)).as("si"),
+        min($"vl").over(winSpec(-2, 2)).as("ml"),
+        max($"vd").over(winSpec(-2, 2)).as("xd"),
+        sum($"vdec").over(winSpec(-2, 2)).as("sdec"),
+        avg($"vdec").over(winSpec(-2, 2)).as("adec")))
+  }
+
+  test("String lexicographic MIN/MAX") {
+    // Deliberately non-monotone string values so that MIN/MAX actually
+    // exercise segment-tree merge rather than trivially matching the edge.
+    val df = spark.range(0, 40).selectExpr(
+      "id",
+      "(id % 2) AS pk",
+      "CONCAT('s', LPAD(CAST((id * 37) % 97 AS STRING), 3, '0')) AS v")
+    checkEquivalence(() =>
+      df.select($"id", $"pk",
+        min($"v").over(winSpec(-3, 3)).as("mn"),
+        max($"v").over(winSpec(-3, 3)).as("mx")))
+  }
+
+  test("Date / Timestamp MIN/MAX") {
+    val df = spark.range(0, 40).selectExpr(
+      "id",
+      "(id % 2) AS pk",
+      "date_add(DATE'2020-01-01', CAST((id * 13) % 365 AS INT)) AS vd",
+      "CAST(TIMESTAMP'2020-01-01 00:00:00' + " +
+        "make_interval(0, 0, 0, 0, 0, 0, CAST(id AS DECIMAL(18,6))) AS TIMESTAMP) AS vt")
+    checkEquivalence(() =>
+      df.select($"id", $"pk",
+        min($"vd").over(winSpec(-3, 3)).as("mnd"),
+        max($"vd").over(winSpec(-3, 3)).as("mxd"),
+        min($"vt").over(winSpec(-3, 3)).as("mnt"),
+        max($"vt").over(winSpec(-3, 3)).as("mxt")))
+  }
+
+  
+  test("collect_list falls back cleanly (non-DeclarativeAggregate)") {
+    // collect_list is a Collect(TypedImperativeAggregate) -- not a
+    // DeclarativeAggregate, so eligibleForSegTree must decline and the
+    // sliding frame must take over.
+    checkEquivalence(() =>
+      baseDF.select($"id", $"pk",
+        collect_list($"v").over(winSpec(-2, 2)).as("lst")))
+  }
+
+  test("DISTINCT window aggregate is rejected by analyzer regardless of seg-tree flag") {
+    // Spark does not support DISTINCT window aggregates at all -- the analyzer
+    // throws DISTINCT_WINDOW_FUNCTION_UNSUPPORTED before we ever reach frame
+    // construction. The seg-tree feature flag must not alter this behavior.
+    def run(): Unit = {
+      baseDF.select($"id", $"pk",
+        count_distinct($"v").over(winSpec(-3, 3)).as("cd")).collect()
+    }
+    withSQLConf(disableSegTree.toSeq: _*) {
+      val e = intercept[org.apache.spark.sql.AnalysisException](run())
+      assert(e.getMessage.contains("DISTINCT_WINDOW_FUNCTION_UNSUPPORTED"))
+    }
+    withSQLConf(enableSegTree.toSeq: _*) {
+      val e = intercept[org.apache.spark.sql.AnalysisException](run())
+      assert(e.getMessage.contains("DISTINCT_WINDOW_FUNCTION_UNSUPPORTED"))
+    }
+  }
+
+  test("feature flag off: segmentTree.enabled=false yields baseline semantics") {
+    // Sanity check: disabling the flag on a workload the seg-tree path would
+    // otherwise handle (MIN, wide frame, partitions above the min-rows
+    // threshold) still produces the SlidingWindowFunctionFrame answer.
+    val df = baseDF
+    val expected = withSQLConf(disableSegTree.toSeq: _*) {
+      df.select($"id", $"pk", min($"v").over(winSpec(-3, 3)).as("mn"))
+        .collect().sortBy(_.toString).toSeq
+    }
+    // Explicit disable with the full-size partition config (no min-rows
+    // override). This exercises the flag-off branch of eligibleForSegTree.
+    withSQLConf(
+      SQLConf.WINDOW_SEGMENT_TREE_ENABLED.key -> "false",
+      SQLConf.WINDOW_SEGMENT_TREE_MIN_PARTITION_ROWS.key -> "1024") {
+      val actual = df.select($"id", $"pk", min($"v").over(winSpec(-3, 3)).as("mn"))
+        .collect().sortBy(_.toString).toSeq
+      assert(actual === expected)
+    }
+  }
+
+    // A5.*: RANGE frame equivalence between seg-tree path and sliding baseline.
+  //
+  // The factory (`eligibleForSegTree`) now admits RangeFrame when orderSpec
+  // has exactly one ordering expression. These tests exercise the
+  // frameType-aware admit/drop loops in SegmentTreeWindowFunctionFrame.
+  //
+  // All tests follow the same oracle pattern as NULL/NaN/collation coverage: run the same
+  // query twice (seg-tree on / off) and assert equal Row sequences.
+  // Aggregates are MIN/MAX (non-invertible) to guarantee the seg-tree
+  // code path is actually exercised rather than short-circuited.
+
+  /** Run `sql` twice (flag off / on) and checkAnswer equality. */
+  private def checkRangeEquivalence(df: DataFrame, query: String): Unit = {
+    df.createOrReplaceTempView("t")
+    try {
+      val baseline = withSQLConf(disableSegTree.toSeq: _*) {
+        spark.sql(query).collect().sortBy(_.toString)
+      }
+      withSQLConf(enableSegTree.toSeq: _*) {
+        val actual = spark.sql(query).collect().sortBy(_.toString)
+        assert(actual.toSeq === baseline.toSeq,
+          s"segment-tree output differs from baseline.\nExpected: ${baseline.toSeq}\n" +
+            s"Actual:   ${actual.toSeq}")
+      }
+    } finally {
+      spark.catalog.dropTempView("t")
+    }
+  }
+
+  test("-- RANGE INT offset basic (non-uniform gaps, MIN/MAX)") {
+    // Non-uniform k gaps (1, 3, 4, 4, 7, 10, 15, ...) so that the frame
+    // edges shift by variable amounts and admit/drop loops must consult
+    // the order-key comparator rather than just row count.
+    val df = spark.range(0, 40).selectExpr(
+      "CAST(id AS INT) AS id",
+      "(CAST(id AS INT) % 2) AS pk",
+      "CAST(CASE CAST(id AS INT) % 7 " +
+        "WHEN 0 THEN 1 WHEN 1 THEN 3 WHEN 2 THEN 4 WHEN 3 THEN 4 " +
+        "WHEN 4 THEN 7 WHEN 5 THEN 10 ELSE 15 END + (CAST(id AS INT) / 7) * 20 AS INT) AS k",
+      "CAST((id * 31) % 97 AS INT) AS v")
+    checkRangeEquivalence(df,
+      """SELECT id, pk,
+        |  MIN(v) OVER (PARTITION BY pk ORDER BY k
+        |    RANGE BETWEEN 2 PRECEDING AND 2 FOLLOWING) AS mn,
+        |  MAX(v) OVER (PARTITION BY pk ORDER BY k
+        |    RANGE BETWEEN 2 PRECEDING AND 2 FOLLOWING) AS mx
+        |FROM t""".stripMargin)
+  }
+
+  test("-- RANGE Timestamp with INTERVAL offset (MAX)") {
+    // Irregular gaps: 30min / 90min / 2h / 30min / ... so frame edges
+    // crossing the 1-hour bound must rely on the timestamp comparator.
+    val df = spark.range(0, 30).selectExpr(
+      "CAST(id AS INT) AS id",
+      "(CAST(id AS INT) % 2) AS pk",
+      "CAST(TIMESTAMP'2024-01-01 10:00:00' + " +
+        "make_interval(0, 0, 0, 0, 0, 30 * CAST(id AS INT) * " +
+        "(CASE CAST(id AS INT) % 3 WHEN 0 THEN 1 WHEN 1 THEN 3 ELSE 4 END), 0) " +
+        "AS TIMESTAMP) AS ts",
+      "CAST((id * 17) % 53 AS INT) AS v")
+    checkRangeEquivalence(df,
+      """SELECT id, pk,
+        |  MAX(v) OVER (PARTITION BY pk ORDER BY ts
+        |    RANGE BETWEEN INTERVAL '1' HOUR PRECEDING
+        |              AND INTERVAL '1' HOUR FOLLOWING) AS mx
+        |FROM t""".stripMargin)
+  }
+
+  test("-- RANGE with tie (duplicate order keys) inclusion at boundary") {
+    // k = [1, 2, 2, 2, 3, 4, 5] repeated across partitions. A frame of
+    // `0 PRECEDING AND 0 FOLLOWING` must include the FULL tie group at
+    // the current row's k, not just the current row itself. If the
+    // seg-tree path confuses RANGE with ROWS the tie group of k=2 would
+    // return a per-row MIN/MAX rather than a group-level one.
+    val rows = (0 until 40).map { i =>
+      val k = Seq(1, 2, 2, 2, 3, 4, 5)(i % 7)
+      (i, i % 2, k, (i * 13) % 41)
+    }
+    val df = rows.toDF("id", "pk", "k", "v")
+    checkRangeEquivalence(df,
+      """SELECT id, pk, k,
+        |  MIN(v) OVER (PARTITION BY pk ORDER BY k
+        |    RANGE BETWEEN 0 PRECEDING AND 0 FOLLOWING) AS mn,
+        |  MAX(v) OVER (PARTITION BY pk ORDER BY k
+        |    RANGE BETWEEN 0 PRECEDING AND 0 FOLLOWING) AS mx
+        |FROM t""".stripMargin)
+  }
+
+  test("-- RANGE frame wider than partition (C4: admit/drop loops no-op)") {
+    // Partition size 5 rows, frame covers everything. Once the first
+    // batch is admitted, the admit/drop loops in the seg-tree frame must
+    // detect the effective frame is unchanged and skip work.
+    val df = spark.range(0, 25).selectExpr(
+      "CAST(id AS INT) AS id",
+      "(CAST(id AS INT) / 5) AS pk",
+      "CAST((id * 7) % 23 AS INT) AS k",
+      "CAST((id * 19) % 101 AS INT) AS v")
+    checkRangeEquivalence(df,
+      """SELECT id, pk,
+        |  MIN(v) OVER (PARTITION BY pk ORDER BY k
+        |    RANGE BETWEEN 100 PRECEDING AND 100 FOLLOWING) AS mn,
+        |  MAX(v) OVER (PARTITION BY pk ORDER BY k
+        |    RANGE BETWEEN 100 PRECEDING AND 100 FOLLOWING) AS mx
+        |FROM t""".stripMargin)
+  }
+
+  test("-- RANGE with NULL order key (NULLS FIRST / NULLS LAST)") {
+    // k = [NULL, NULL, 1, 2, 3, NULL] repeated. Spark groups all NULLs
+    // into a single equivalence class at head (NULLS FIRST) or tail
+    // (NULLS LAST). The seg-tree admit/drop loops must treat NULL as a
+    // tie group identically to the sliding baseline.
+    val rows = (0 until 36).map { i =>
+      val kOpt: Option[Int] = (i % 6) match {
+        case 0 | 1 | 5 => None
+        case 2 => Some(1)
+        case 3 => Some(2)
+        case _ => Some(3)
+      }
+      (i, i % 2, kOpt, (i * 11) % 37)
+    }
+    val df = rows.toDF("id", "pk", "k", "v")
+    checkRangeEquivalence(df,
+      """SELECT id, pk,
+        |  MIN(v) OVER (PARTITION BY pk ORDER BY k ASC NULLS FIRST
+        |    RANGE BETWEEN 1 PRECEDING AND 1 FOLLOWING) AS mn_nf,
+        |  MAX(v) OVER (PARTITION BY pk ORDER BY k ASC NULLS FIRST
+        |    RANGE BETWEEN 1 PRECEDING AND 1 FOLLOWING) AS mx_nf,
+        |  MIN(v) OVER (PARTITION BY pk ORDER BY k ASC NULLS LAST
+        |    RANGE BETWEEN 1 PRECEDING AND 1 FOLLOWING) AS mn_nl,
+        |  MAX(v) OVER (PARTITION BY pk ORDER BY k ASC NULLS LAST
+        |    RANGE BETWEEN 1 PRECEDING AND 1 FOLLOWING) AS mx_nl
+        |FROM t""".stripMargin)
+  }
+
+    // Decimal overflow across seg-tree block merge
+  // BinaryType MIN/MAX across seg-tree block merge
+  // UDAF (ScalaUDAF / ScalaAggregator) fallback
+  //
+  // All Decimal/Binary tests force blockSize=16 (the minimum the config
+  // allows) + window size > blockSize so the seg-tree path crosses at
+  // least one block boundary (exercises `mergeExpressions` rather than
+  // only `update`). Design doc asked for blockSize=4 but the SQLConf
+  // validator rejects anything below 16; scaling data/frame up preserves
+  // the merge-path coverage the doc intended.
+
+  private val segTreeBlock: String = "16"
+  private val segTreeFramePrec: Int = 17
+  private val segTreeRows: Int = 20
+
+  private def withSegTreeBlock(conf: (String, String)*)(body: => Unit): Unit = {
+    val extra = Seq(SQLConf.WINDOW_SEGMENT_TREE_BLOCK_SIZE.key -> segTreeBlock) ++ conf
+    withSQLConf(extra: _*)(body)
+  }
+
+  
+  /**
+   * 20 rows in a single partition, Decimal(38, 0) values near the type's
+   * upper bound. Frame of `segTreeFramePrec` PRECEDING..CURRENT ROW means
+   * any window with >= 2 such rows overflows the widened Sum buffer
+   * (Decimal(38,0) widened to Decimal(38,0); any addition above 1e38
+   * overflows). Block size 16 + frame 17 forces cross-block merge.
+   */
+  private def decimalOverflowDF: DataFrame = {
+    // 9e37 -- below Decimal(38,0) MAX (~9.99e37), but 2x overflows.
+    val big = "90000000000000000000000000000000000000"  // 38 digits
+    spark.range(0, segTreeRows.toLong).selectExpr(
+      "CAST(id AS INT) AS id",
+      "0 AS pk",
+      s"CAST('$big' AS DECIMAL(38, 0)) AS v")
+  }
+
+  private val decimalOverflowSql: String =
+    s"""SELECT id, pk,
+       |  SUM(v) OVER (PARTITION BY pk ORDER BY id
+       |    ROWS BETWEEN $segTreeFramePrec PRECEDING AND CURRENT ROW) AS s
+       |FROM t""".stripMargin
+
+  test("a -- Decimal overflow ANSI on, seg-tree matches sliding (both throw)") {
+    val df = decimalOverflowDF
+    df.createOrReplaceTempView("t")
+    try {
+      withSegTreeBlock(SQLConf.ANSI_ENABLED.key -> "true") {
+        withSQLConf(disableSegTree.toSeq: _*) {
+          val e = intercept[Exception] {
+            spark.sql(decimalOverflowSql).collect()
+          }
+          assert(rootArithmeticCause(e).isDefined,
+            s"expected ArithmeticException root cause, got: ${e.getMessage}")
+        }
+        withSQLConf(enableSegTree.toSeq: _*) {
+          val e = intercept[Exception] {
+            spark.sql(decimalOverflowSql).collect()
+          }
+          assert(rootArithmeticCause(e).isDefined,
+            s"expected ArithmeticException root cause, got: ${e.getMessage}")
+        }
+      }
+    } finally {
+      spark.catalog.dropTempView("t")
+    }
+  }
+
+  test("b -- Decimal overflow ANSI off, seg-tree matches sliding (NULL on overflow)") {
+    val df = decimalOverflowDF
+    df.createOrReplaceTempView("t")
+    try {
+      withSegTreeBlock(SQLConf.ANSI_ENABLED.key -> "false") {
+        val baseline = withSQLConf(disableSegTree.toSeq: _*) {
+          spark.sql(decimalOverflowSql).collect().sortBy(_.toString)
+        }
+        // At least one row must be NULL so we know overflow actually fired.
+        assert(baseline.exists(_.isNullAt(2)),
+          "baseline should contain NULL overflow rows; test data may be too small")
+        withSQLConf(enableSegTree.toSeq: _*) {
+          val actual = spark.sql(decimalOverflowSql).collect().sortBy(_.toString)
+          assert(actual.toSeq === baseline.toSeq)
+        }
+      }
+    } finally {
+      spark.catalog.dropTempView("t")
+    }
+  }
+
+  test("c -- mid-window Decimal overflow slides past (seg-tree == sliding)") {
+    // 24 rows, blockSize=16. Frame ROWS BETWEEN 3 PRECEDING AND CURRENT ROW
+    // (size 4). Near-MAX values at ids 14,15,16,17 so any 4-row window
+    // containing >=2 of them overflows. Windows at:
+    //   id<14 or id>20   -> safe
+    //   id in [15..20]   -> overlaps >=2 big values -> NULL
+    // The big-value band (14..17) straddles the block boundary at id=16,
+    // guaranteeing cross-block merge paths see overflowing buffers.
+    val big = "90000000000000000000000000000000000000"
+    val df = spark.range(0, 24).selectExpr(
+      "CAST(id AS INT) AS id",
+      "0 AS pk",
+      s"""CASE WHEN id IN (14, 15, 16, 17)
+              THEN CAST('$big' AS DECIMAL(38, 0))
+              ELSE CAST(id AS DECIMAL(38, 0))
+         END AS v""")
+    df.createOrReplaceTempView("t")
+    try {
+      val sqlStr =
+        """SELECT id, pk,
+          |  SUM(v) OVER (PARTITION BY pk ORDER BY id
+          |    ROWS BETWEEN 3 PRECEDING AND CURRENT ROW) AS s
+          |FROM t""".stripMargin
+      withSegTreeBlock(SQLConf.ANSI_ENABLED.key -> "false") {
+        val baseline = withSQLConf(disableSegTree.toSeq: _*) {
+          spark.sql(sqlStr).collect().sortBy(_.toString)
+        }
+        // Sanity: overflow fired on some rows AND window slides past to
+        // recover non-NULL on the tail rows.
+        assert(baseline.exists(_.isNullAt(2)),
+          "baseline should contain NULL overflow rows")
+        assert(baseline.exists(r => r.getInt(0) >= 21 && !r.isNullAt(2)),
+          "rows with id>=21 should be non-NULL (window slid past big values)")
+        withSQLConf(enableSegTree.toSeq: _*) {
+          val actual = spark.sql(sqlStr).collect().sortBy(_.toString)
+          assert(actual.toSeq === baseline.toSeq)
+        }
+      }
+    } finally {
+      spark.catalog.dropTempView("t")
+    }
+  }
+
+  /** Walk a SparkException chain for an ArithmeticException (ANSI overflow). */
+  private def rootArithmeticCause(t: Throwable): Option[Throwable] = {
+    var cur: Throwable = t
+    while (cur != null) {
+      if (cur.isInstanceOf[ArithmeticException]) return Some(cur)
+      cur = cur.getCause
+    }
+    None
+  }

Review Comment:
   Walking the cause chain for a target type is already available via `org.apache.commons.lang3.exception.ExceptionUtils.getRootCause`, which Spark tests use extensively. Optional simplification — something like `Option(ExceptionUtils.getRootCause(e)).collect { case a: ArithmeticException => a }` — just less bespoke test plumbing.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowSegmentTree.scala:
##########
@@ -0,0 +1,610 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.execution.window
+
+import java.util.{LinkedHashMap => JLinkedHashMap, Map => JMap}
+
+import scala.collection.mutable
+
+import org.apache.spark.{SparkEnv, SparkException, TaskContext}
+import org.apache.spark.memory.{MemoryConsumer, TaskMemoryManager}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.expressions.aggregate.DeclarativeAggregate
+import org.apache.spark.sql.errors.QueryExecutionErrors
+import org.apache.spark.sql.execution.ExternalAppendOnlyUnsafeRowArray
+import org.apache.spark.sql.types.DataType
+import org.apache.spark.util.ArrayImplicits._
+
+/**
+ * Block-chunked segment tree for range aggregate queries over window partitions.
+ *
+ * See `the class documentation`
+ * for the full design (API contract Section 2, block-chunked memory layout Section 3,
+ * DeclarativeAggregate binding Section 4, error handling Section 5, test hooks Section 6).
+ *
+ * initial implementation scope: correctness only. The data layer uses
+ * `ExternalAppendOnlyUnsafeRowArray` to hold input rows (spillable). Each
+ * block materializes its own small segment tree (levels 0..h). Internal
+ * nodes are cached in an LRU keyed by block index; block root aggregates
+ * (block pre-aggregates) stay resident for all blocks.
+ *
+ * Note: the design doc Section 3.3 specifies leaves are NOT materialized and
+ * recomputed from the spillable array on demand. For initial implementation simplicity
+ * we materialize leaves inside the per-block internal node arrays.
+ * // TODO(SPARK-XXXXX) re-assess after Frame integration.
+ *
+ * @note Instances are not thread-safe.
+ */
+private[window] class WindowSegmentTree(
+    functions: Array[DeclarativeAggregate],
+    inputSchema: Seq[Attribute],
+    newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
+    fanout: Int = WindowSegmentTree.DefaultFanout,
+    blockSize: Int = WindowSegmentTree.DefaultBlockSize,
+    maxCachedBlocks: Option[Int] = None,
+    spillThreshold: Int = Int.MaxValue,
+    inMemoryThreshold: Int = Int.MaxValue,
+    taskMemoryManager: TaskMemoryManager = null)
+  extends AutoCloseable {
+
+  require(fanout >= 2, s"fanout must be >= 2, got $fanout")
+  require(blockSize >= 1, s"blockSize must be >= 1, got $blockSize")
+  require(functions.nonEmpty, "WindowSegmentTree requires at least one aggregate function")
+  maxCachedBlocks.foreach { n =>
+    require(n >= 1, s"maxCachedBlocks must be >= 1 when specified, got $n")
+  }
+  require(taskMemoryManager != null,
+    "WindowSegmentTree requires a non-null TaskMemoryManager; " +
+      "in tests use `new TaskMemoryManager(new TestMemoryManager(conf), 0)`")
+
+  // ---------- Schemas & projections ----------
+
+  private val bufferAttrs: Seq[AttributeReference] =
+    functions.flatMap(_.aggBufferAttributes).toImmutableArraySeq
+  private val rightAttrs: Seq[AttributeReference] =
+    functions.flatMap(_.inputAggBufferAttributes).toImmutableArraySeq
+  private val bufferDataTypes: IndexedSeq[DataType] =
+    bufferAttrs.map(_.dataType).toIndexedSeq
+
+  private val initialValues: Seq[Expression] = functions.flatMap(_.initialValues).toIndexedSeq
+  private val updateExpressions: Seq[Expression] =
+    functions.flatMap(_.updateExpressions).toIndexedSeq
+  private val mergeExpressions: Seq[Expression] =
+    functions.flatMap(_.mergeExpressions).toIndexedSeq
+
+  private[this] val initProj: MutableProjection = newMutableProjection(initialValues, Nil)
+  private[this] val updateProj: MutableProjection =
+    newMutableProjection(updateExpressions, bufferAttrs ++ inputSchema)
+  private[this] val mergeProj: MutableProjection =
+    newMutableProjection(mergeExpressions, bufferAttrs ++ rightAttrs)
+
+  private val inputUnsafeProj: UnsafeProjection =
+    UnsafeProjection.create(inputSchema.map(_.dataType).toArray)
+
+  private[this] val joinedRow = new JoinedRow()
+
+  // ---------- State ----------
+
+  private var numRows: Int = 0
+  private var numBlocks: Int = 0
+  private var rowArray: ExternalAppendOnlyUnsafeRowArray = _
+  private var closed: Boolean = false
+
+  /** Always-resident per-block root aggregates. `blockAggregates(i)` =
+   *  merged buffer over all rows in block i. */
+  private var blockAggregates: Array[InternalRow] = Array.empty
+
+  /** Rough byte width of one aggregate buffer row. Chosen at 16 B/field as a
+   *  conservative heap-overhead-aware lower bound for a
+   *  `SpecificInternalRow` slot: primitive `MutableValue` is 8 B, boxed
+   *  references and object headers push the effective footprint higher.
+   *  Tighter per-type sizing (real boxing cost, variable-length fields) is
+   *  intentionally out of scope here; TaskMemoryManager remains the hard
+   *  backstop via spill / OOM.
+   *  TODO(SPARK-XXXXX): per-type width estimator keyed on
+   *  `bufferDataTypes` (primitive 16 B, String/Binary/Decimal wider). */
+  private val bufferWidthBytes: Long = {
+    val bytesPerField = 16L
+    math.max(1L, bufferDataTypes.size.toLong * bytesPerField)
+  }
+
+  /** Number of aggregate-buffer slots cached per block (contract I5).
+   *
+   *  Invariant: equals `sum over levels L of levels(L).length` for any
+   *  block materialized by [[buildBlockLevels]]. Level 0 holds `blockSize`
+   *  leaf buffers and each subsequent level holds `ceil(prev / fanout)`
+   *  parent buffers until a single root remains. The iterative ceiling
+   *  matches the allocation in [[buildBlockLevels]] for every
+   *  `(blockSize, fanout)` pair, including non-power-of-`fanout` cases.
+   *  For `blockSize == 1` the block is a single leaf with no parent
+   *  levels, so this returns 1.
+   *  TODO(SPARK-XXXXX): drop the leaf term when [[buildBlockLevels]]
+   *  switches to on-demand leaf recomputation. */
+  private val cachedSlotsPerBlock: Long = {
+    var n = blockSize.toLong
+    var sum = n
+    while (n > 1L) {
+      n = (n + fanout - 1) / fanout
+      sum += n
+    }
+    sum
+  }
+
+  /** Bytes accounted per cached block (contract I5). Conservative: assumes
+   *  every block is full; tail block (`numRows % blockSize != 0`) will
+   *  hold fewer leaves, giving a small headroom. */
+  private[this] val blockBytes: Long =
+    math.max(1L, cachedSlotsPerBlock * bufferWidthBytes)
+
+  /** `spans(L)` = number of leaves covered by a single node at level L. Depends
+   *  only on fanout + blockSize, so precomputed once. */
+  private val spans: Array[Int] = {
+    val maxLevel = {
+      var lvl = 0
+      var span = 1L
+      while (span < blockSize) { span *= fanout; lvl += 1 }
+      lvl
+    }
+    val arr = new Array[Int](maxLevel + 1)
+    var s = 1L
+    var i = 0
+    while (i <= maxLevel) {
+      arr(i) = if (s > Int.MaxValue) Int.MaxValue else s.toInt
+      s *= fanout
+      i += 1
+    }
+    arr
+  }
+
+  /** LRU cache of per-block internal node arrays. Key = blockIdx.
+   *  Value = `Array[Array[InternalRow]]` with levels(0..h). Auto-eviction via
+   *  `removeEldestEntry` is disabled (contract I3) -- eviction is driven
+   *  explicitly from [[ensureBlockLevels]] (capacity overflow) or
+   *  [[SegTreeSpiller.spill]] (TMM pressure). Each cache entry maps 1:1 to
+   *  one [[acquireBlockMemory]] accounting. Callers (e.g.
+   *  `SegmentTreeWindowFunctionFrame`) should pass a W-aware
+   *  value like `ceil(W / blockSize) + 2`. */
+  private val blockLevelsCache: JLinkedHashMap[Integer, Array[Array[InternalRow]]] =
+    new JLinkedHashMap[Integer, Array[Array[InternalRow]]](16, 0.75f, true) {
+      override def removeEldestEntry(
+          eldest: JMap.Entry[Integer, Array[Array[InternalRow]]]): Boolean = false
+    }
+
+  // ---------- Memory consumer (contract Section 2.2) ----------
+
+  /**
+   * Private MemoryConsumer tracking cached block levels under TMM.
+   *
+   * Heap accounting only (no Tungsten pages): uses
+   * [[MemoryConsumer.acquireMemory]] / [[MemoryConsumer.freeMemory]]. The
+   * [[MemoryConsumer]] base class records `used` via an `AtomicLong` when
+   * we call these -- so TMM's consumer-priority sort in
+   * `acquireExecutionMemory` sees our pressure accurately.
+   *
+   * @note `spill()` MUST NOT call `acquireMemory` (contract I1).
+   */
+  private final class SegTreeSpiller extends MemoryConsumer(
+      taskMemoryManager,
+      taskMemoryManager.pageSizeBytes(),
+      taskMemoryManager.getTungstenMemoryMode()) {
+    override def spill(size: Long, trigger: MemoryConsumer): Long = {
+      // I2: self-trigger short-circuit. Prevents re-entrant eviction when
+      // our own acquireMemory() triggers TMM to poll us.
+      if (trigger eq this) return 0L
+      // I8: rowArray spilled-to-disk detection. If the rowArray has already
+      // spilled, evicting our cache is counter-productive (rebuild would
+      // O(blockStart)-scan the spill file). Return 0L to let TMM fall
+      // through to the next consumer.
+      //
+      // TODO(SPARK-XXXXX) #segtree-spill-priority (contract Section 7 O4): current
+      // heuristic uses `spillSize > 0` as the "has spilled" signal. A more
+      // precise check would consult `UnsafeExternalSorter.getSpillWriters`
+      // state, but that API is not public. Re-evaluate after benchmark.
+      // FIXME(kentyao): upstream a public "hasSpilled" hook on the array.
+      if (rowArray != null && rowArray.spillSize > 0) return 0L
+      evictUntil(size)
+    }
+  }
+
+  private[this] val spiller: SegTreeSpiller = new SegTreeSpiller
+
+  // Task kill / completion fall-back: ensure cache is freed even if caller
+  // forgets close() (contract Section 2.5). Frame already registers a
+  // listener too; double close is idempotent (contract I4).
+  {
+    val tc = TaskContext.get()
+    if (tc != null) {
+      tc.addTaskCompletionListener[Unit](_ => close())
+    }
+  }
+
+  // ---------- Public API ----------
+
+  def size: Int = numRows
+
+  /**
+   * Drain `rows` into this tree, replacing any previously built state.
+   * Exception-safe: if iteration or aggregation throws, the previously built
+   * state (if any) is preserved.
+   */
+  def build(rows: Iterator[InternalRow]): Unit = {
+    val oldArray = rowArray
+    var newArray: ExternalAppendOnlyUnsafeRowArray = null
+    try {
+      newArray = newRowArray()
+      while (rows.hasNext) {
+        val r = rows.next()
+        val u = inputUnsafeProj(r)
+        newArray.add(u)

Review Comment:
   The tree owns its own `ExternalAppendOnlyUnsafeRowArray` and drains the caller's iterator into it, while `WindowPartitionEvaluator.buffer` still holds the same rows — roughly 2× memory for the partition during segtree execution. For the large-partition case the feature is meant to accelerate, this undercuts the optimization. The tree already supports `rowArray.generateIterator(startIndex)` for block reads, so the tree could operate against the caller's rowArray directly (pass the array in `build`/`prepare` rather than an iterator). If block-level random access requires an owned array, please document the 2× memory cost in the PR description / user-facing conf doc.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowEvaluatorFactoryBase.scala:
##########
@@ -191,13 +200,17 @@ trait WindowEvaluatorFactoryBase {
         // in a single Window physical node. Therefore, we can assume no SQL aggregation
         // functions if Pandas UDF exists. In the future, we might mix Pandas UDF and SQL
         // aggregation function in a single physical node.
-        def processor = if (functions.exists(_.isInstanceOf[PythonFuncExpression])) {
+        val aggFilters: Array[Option[Expression]] = expressions.map {
+          case WindowExpression(ae: AggregateExpression, _) => ae.filter
+          case _ => None
+        }.toArray
+        // Shared per (key) across the factory closure's invocations; each
+        // Frame calls `processor.initialize(...)` in `prepare`, so cross-

Review Comment:
   The comment claims "each Frame calls `processor.initialize(...)` in `prepare`", but `SegmentTreeWindowFunctionFrame.prepare` does NOT — only the embedded fallback does. The segtree path relies on `processor.evaluate(source, target)` against an external buffer and never touches the internal one. (This is a different concern from the Copilot comment on the "listener registration idempotent" parenthetical below.) Please also note that cross-partition reuse is safe for segtree *because* it never reads the internal buffer — that's the load-bearing invariant, not that `initialize` is always called.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowEvaluatorFactoryBase.scala:
##########
@@ -295,4 +344,63 @@ trait WindowEvaluatorFactoryBase {
     }
   }
 
+  /**
+   * Segment-tree path eligibility. The tree relies on `DeclarativeAggregate.mergeExpressions`,
+   * which [[AggregateWindowFunction]]s (e.g. NthValue, NTile, Rank, RowNumber, NullIndex) refuse
+   * with `mergeUnsupportedByWindowFunctionError`. They extend DeclarativeAggregate but are
+   * NOT merge-capable, so we must exclude them here even though the base-class check passes.
+   * Normal aggregate window expressions reach this code as the inner DeclarativeAggregate
+   * unwrapped from [[AggregateExpression]] (see `windowFrameExpressionFactoryPairs.collect`).
+   */
+  private def eligibleForSegTree(
+      functions: Array[Expression],
+      filters: Array[Option[Expression]],
+      frameType: FrameType): Boolean = {
+    // RANGE is accepted only for single-column order specs. Multi-column
+    // RANGE with non-zero offset is already rejected by `createBoundOrdering`
+    // (see the `RangeFrame, _` internalError branch above), so gating here
+    // on `orderSpec.size == 1` matches the Sliding-path invariant exactly.
+    val frameTypeOk = frameType match {
+      case RowFrame => true
+      case RangeFrame => orderSpec.size == 1
+    }
+    SQLConf.get.windowSegmentTreeEnabled &&
+      frameTypeOk &&
+      filters.forall(_.isEmpty) &&
+      functions.forall { f =>
+        f.isInstanceOf[DeclarativeAggregate] && !f.isInstanceOf[AggregateWindowFunction]

Review Comment:
   The PR description advertises a 9-function allowlist (`MIN/MAX/SUM/COUNT/AVG/STDDEV_POP/STDDEV_SAMP/VAR_POP/VAR_SAMP`), but this filter accepts any non-window `DeclarativeAggregate`. `First`, `Last`, `AnyValue`, `BitAndAgg`/`BitOrAgg`/`BitXorAgg`, `BoolAnd`, `BoolOr`, the `Regr*` family, and others all route through the segtree path silently, yet the test suites exercise only the 9 advertised aggregates. Either tighten eligibility to an explicit allowlist that matches the description, or add coverage for every eligible `DeclarativeAggregate` and update the description. The safer choice for a new opt-in feature is the allowlist.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/AggregateProcessor.scala:
##########
@@ -181,7 +181,12 @@ private[window] final class AggregateProcessor(
   }
 
   /** Evaluate buffer. */
-  def evaluate(target: InternalRow): Unit = {
-    evaluateProjection.target(target)(buffer)
+  def evaluate(target: InternalRow): Unit = evaluate(buffer, target)
+
+  /** Evaluate using an arbitrary `source` buffer (e.g. a segment-tree query
+   *  result) instead of the internal one. See
+   *  `docs/frame-integration-contract.md` Section 3. */
+  private[window] def evaluate(source: InternalRow, target: InternalRow): Unit = {

Review Comment:
   `source` must share the processor's internal `aggBufferAttributes` layout; today `eligibleForSegTree` enforces this (no `SizeBasedWindowFunction`, same function list drives both schemas) but the contract is invisible at the call site and easy to break from either end. Two small asks:
   
   1. `docs/frame-integration-contract.md` doesn't exist in the repo — please inline the contract into the Scaladoc here (same applies to the `docs/frame-integration-contract.md` refs in `SegmentTreeWindowFunctionFrame.scala:37` and `WindowSegmentTree.scala:286`).
   2. Consider a debug-only schema assertion comparing `bufferSchema` with the source's expected shape so future drift surfaces loudly.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -4002,6 +4002,47 @@ object SQLConf {
         "The threshold of window group limit must be -1, 0 or positive integer.")
       .createWithDefault(1000)
 
+  val WINDOW_SEGMENT_TREE_ENABLED =
+    buildConf("spark.sql.window.segmentTree.enabled")
+      .doc("Use block-chunked segment tree for moving aggregate window frames " +
+        "whose functions are all DeclarativeAggregate without FILTER/DISTINCT.")
+      .version("4.2.0")
+      .booleanConf
+      .createWithDefault(false)

Review Comment:
   Two of the four new confs are public (`spark.sql.window.segmentTree.enabled` and `.blockSize`), both pinned at `version=4.2.0`, while the PR description labels the feature "WIP / Draft." Public `SQLConf`s become a long-tail deprecation commitment once they ship. Is the public surface intentional for a WIP feature? Demoting both to `.internal()` for the initial landing and promoting once the design stabilizes would give you more freedom to evolve defaults / names.



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/window/WindowSegmentTreeMemorySuite.scala:
##########
@@ -0,0 +1,375 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.execution.window
+
+import java.util.Properties
+
+import org.apache.spark.{LocalSparkContext, SparkConf, SparkContext, SparkFunSuite, TaskContext, TaskContextImpl}
+import org.apache.spark.executor.TaskMetrics
+import org.apache.spark.memory.{MemoryConsumer, MemoryMode, SparkOutOfMemoryError, TaskMemoryManager, TestMemoryManager}
+import org.apache.spark.metrics.MetricsSystem
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, AttributeReference, Expression, GenericInternalRow, MutableProjection, SpecificInternalRow}
+import org.apache.spark.sql.catalyst.expressions.aggregate.{DeclarativeAggregate, Min}
+import org.apache.spark.sql.catalyst.expressions.codegen.GenerateMutableProjection
+import org.apache.spark.sql.types.IntegerType
+
+/**
+ * Memory-manager integration tests for [[WindowSegmentTree]] (memory-manager integration).
+ * Exercises the matrix defined in
+ * `the PR description` Section 5.
+ *
+ * Tests T5 (rowArray-spilled priority) and T8 (task-kill listener) are
+ * deferred -- tracked as upstream follow-up JIRAs (spill priority and
+ * memory-manager integration); stubs are `ignore`d
+ * with a pointer comment so the matrix stays visible.
+ */
+class WindowSegmentTreeMemorySuite extends SparkFunSuite with LocalSparkContext {
+
+  // ---- common fixtures ----
+
+  private val inputAttr: AttributeReference =
+    AttributeReference("v", IntegerType, nullable = true)()
+  private val inputSchema: Seq[Attribute] = Seq(inputAttr)
+
+  private def newMutableProjection
+      : (Seq[Expression], Seq[Attribute]) => MutableProjection =
+    (exprs, attrs) => GenerateMutableProjection.generate(exprs, attrs)
+
+  private def minAgg: DeclarativeAggregate = Min(inputAttr)
+
+  /**
+   * Construct a standalone `TaskMemoryManager` backed by `TestMemoryManager`
+   * (not routed through `SparkEnv`), install a matching `TaskContextImpl`,
+   * and run `body`. Restores the previous `TaskContext` on exit.
+   *
+   * @param budget  initial available execution memory; use `Long.MaxValue`
+   *                for T2 and a tight value (e.g. 2 * blockBytes) for T3.
+   * @param offHeap when true, enables Tungsten off-heap mode (T9).
+   */
+  private def withTmm[T](budget: Long = Long.MaxValue, offHeap: Boolean = false)
+      (body: (TaskMemoryManager, TestMemoryManager) => T): T = {
+    val conf = new SparkConf(false)
+      .set("spark.memory.offHeap.enabled", offHeap.toString)
+      .set("spark.memory.offHeap.size", "1048576")
+    if (sc == null) {
+      sc = new SparkContext("local", "WindowSegmentTreeMemorySuite", conf)
+    }
+    val mm = new TestMemoryManager(conf)
+    mm.limit(budget)
+    val tmm = new TaskMemoryManager(mm, 0)
+    val prev = TaskContext.get()
+    val tc = new TaskContextImpl(
+      stageId = 0, stageAttemptNumber = 0, partitionId = 0,
+      taskAttemptId = 0, attemptNumber = 0, numPartitions = 1,
+      taskMemoryManager = tmm,
+      localProperties = new Properties,
+      metricsSystem = null.asInstanceOf[MetricsSystem],
+      taskMetrics = TaskMetrics.empty,
+      cpus = 1)
+    TaskContext.setTaskContext(tc)
+    try body(tmm, mm)
+    finally {
+      if (prev != null) TaskContext.setTaskContext(prev) else TaskContext.unset()
+    }
+  }
+
+  private def buildTree(
+      tmm: TaskMemoryManager,
+      values: Seq[Int],
+      fanout: Int = 4,
+      blockSize: Int = 8,
+      maxCachedBlocks: Option[Int] = Some(2)): WindowSegmentTree = {
+    val tree = new WindowSegmentTree(
+      Array(minAgg), inputSchema, newMutableProjection,
+      fanout = fanout, blockSize = blockSize,
+      maxCachedBlocks = maxCachedBlocks,
+      taskMemoryManager = tmm)
+    val rows = values.iterator.map { v =>
+      val r = new GenericInternalRow(1); r.update(0, v); r.asInstanceOf[InternalRow]
+    }
+    tree.build(rows)
+    tree
+  }
+
+  private def newOutBuffer(): SpecificInternalRow =
+    new SpecificInternalRow(Seq[org.apache.spark.sql.types.DataType](IntegerType))
+
+  private def queryMin(tree: WindowSegmentTree, lo: Int, hi: Int): Any = {
+    val out = newOutBuffer()
+    tree.query(lo, hi, out)
+    if (out.isNullAt(0)) null else out.getInt(0)
+  }
+
+  private def naiveMin(vs: Seq[Int], lo: Int, hi: Int): Any =
+    if (lo >= hi) null else vs.slice(lo, hi).min
+
+  // ---- T1 ----
+  test("T1 constructor rejects null TaskMemoryManager") {
+    val ex = intercept[IllegalArgumentException] {
+      new WindowSegmentTree(
+        Array(minAgg), inputSchema, newMutableProjection,
+        taskMemoryManager = null)
+    }
+    assert(ex.getMessage.contains("non-null TaskMemoryManager"))
+  }
+
+  // ---- T2 ----
+  test("T2 ample budget: query correctness and positive memory usage") {
+    withTmm() { (tmm, _) =>
+      val values = Seq(5, 2, 9, 1, 7, 3, 4, 8, 6, 0, 11, 12, 13, 14, 15, 16)
+      val tree = buildTree(tmm, values, fanout = 4, blockSize = 4,
+        maxCachedBlocks = Some(4))
+      try {
+        // Force a couple of block-level queries so the LRU actually populates.
+        assert(queryMin(tree, 0, values.length) == values.min)
+        assert(queryMin(tree, 1, 14) == naiveMin(values, 1, 14))
+        assert(queryMin(tree, 5, 11) == naiveMin(values, 5, 11))
+        // Memory consumption strictly positive because at least one block
+        // level has been cached and the spiller acquired bytes for it.
+        assert(tmm.getMemoryConsumptionForThisTask > 0L,
+          "Expected positive memory consumption after caching block levels")
+      } finally tree.close()
+      // After close: all acquired bytes must be released.
+      assert(tmm.getMemoryConsumptionForThisTask == 0L,
+        "Memory consumption must return to 0 after close()")
+    }
+  }
+
+  // ---- T3 ----
+  test("T3 tight budget forces spill: results still match baseline") {
+    val values = (0 until 40).map(i => (i * 37 + 11) % 97)
+    // Collect the baseline under an ample budget.
+    val baseline: Seq[Any] = {
+      var captured: Seq[Any] = Seq.empty
+      withTmm() { (tmm, _) =>
+        val tree = buildTree(tmm, values, fanout = 4, blockSize = 4,
+          maxCachedBlocks = Some(3))
+        try {
+          captured = (0 to values.length by 5).map(i => queryMin(tree, 0, i))
+        } finally {
+          tree.close()
+        }
+      }
+      captured
+    }
+    // Tight budget: only ~1 block's worth of headroom. Any new block that
+    // needs levels will force the spiller to evict the prior block.
+    //
+    // Sizing: for (fanout=4, blockSize=4) the cached level shape is
+    // [4, 1] slots; at bufferWidth=16 B per slot blockBytes = 5 * 16 = 80 B.
+    // budget=128 B admits exactly one block and forces spill on the second.
+    withTmm(budget = 128L) { (tmm, _) =>
+      val tree = buildTree(tmm, values, fanout = 4, blockSize = 4,
+        maxCachedBlocks = Some(3))
+      try {
+        val observed = (0 to values.length by 5).map(i => queryMin(tree, 0, i))
+        assert(observed == baseline,
+          s"spill-path answers diverged: observed=$observed baseline=$baseline")
+      } finally tree.close()
+      assert(tmm.getMemoryConsumptionForThisTask == 0L)
+    }
+  }
+
+  // ---- T4 ----
+  test("T4 self-trigger: spill(_, this) returns 0 and does not evict") {
+    withTmm() { (tmm, _) =>
+      val tree = buildTree(tmm, (0 until 16), fanout = 4, blockSize = 4,
+        maxCachedBlocks = Some(3))
+      try {
+        // Warm the cache.
+        assert(queryMin(tree, 0, 16) == 0)
+        val before = tmm.getMemoryConsumptionForThisTask
+        assert(before > 0L, "precondition: some block levels must be cached")
+        val spiller = tree.testOnlySpiller()
+        val freed = spiller.spill(Long.MaxValue, spiller)
+        assert(freed == 0L, s"self-trigger spill must return 0L, got $freed")
+        val after = tmm.getMemoryConsumptionForThisTask
+        assert(after == before,
+          s"cache size must not change on self-trigger (before=$before after=$after)")
+      } finally tree.close()
+    }
+  }
+
+  // ---- T6 ----
+  test("T6 close() is idempotent and releases all acquired bytes") {
+    withTmm() { (tmm, _) =>
+      val tree = buildTree(tmm, (0 until 20), fanout = 4, blockSize = 4,
+        maxCachedBlocks = Some(3))
+      assert(queryMin(tree, 0, 20) == 0)
+      val peak = tmm.getMemoryConsumptionForThisTask
+      assert(peak > 0L)
+      tree.close()
+      assert(tmm.getMemoryConsumptionForThisTask == 0L,
+        "Memory must be fully released after first close()")
+      // Second close must be a no-op (no double-free, no throw).
+      tree.close()
+      assert(tmm.getMemoryConsumptionForThisTask == 0L,
+        "Second close() must remain a no-op")
+    }
+  }
+
+  // ---- T7 ----
+  test("T7 prepare mid-way failure releases all previously acquired blocks") {
+    // Inject failure by pre-setting consequentOOM to a moderate N so the
+    // spiller's acquireMemory returns 0 after the first few successful blocks.
+    withTmm() { (tmm, mm) =>
+      val values = (0 until 40).map(i => 40 - i)
+      val tree = buildTree(tmm, values, fanout = 4, blockSize = 4,
+        maxCachedBlocks = Some(10))
+      try {
+        // Warm up: query to populate a couple of cache entries.
+        assert(queryMin(tree, 0, 40) == 1)
+        // Now force the *next* acquireMemory calls to fail, then trigger a
+        // cold-cache path by forcing evict + re-acquire. We release everything
+        // first so a subsequent query path must re-acquire.
+        val spiller = tree.testOnlySpiller()
+        spiller.spill(Long.MaxValue, new MemoryConsumer(tmm,
+            tmm.pageSizeBytes(), MemoryMode.ON_HEAP) {
+          override def spill(size: Long, trigger: MemoryConsumer): Long = 0L
+        })
+        assert(tmm.getMemoryConsumptionForThisTask == 0L,
+          "after full spill, accounting must be zero")
+        // Force the next N acquireMemory calls to grant 0 bytes (hard OOM).
+        // With maxCachedBlocks=10 and a cold cache, ensureBlockLevels will
+        // call acquireBlockMemory; both initial grant and post-evict retry
+        // will see 0 -> SparkOutOfMemoryError.
+        mm.markConsequentOOM(10)
+        val ex = intercept[SparkOutOfMemoryError](queryMin(tree, 0, 20))
+        assert(ex.getMessage.contains("UNABLE_TO_ACQUIRE_MEMORY") ||
+          ex.getMessage.contains("unable"),

Review Comment:
   The dedicated `cannotAcquireMemoryForWindowAggregateError` factory now pins the error class to `UNABLE_TO_ACQUIRE_MEMORY`; the `|| "unable"` disjunct predates that and is now strictly less precise.
   
   ```suggestion
           val ex = intercept[SparkOutOfMemoryError](queryMin(tree, 0, 20))
           assert(ex.getMessage.contains("UNABLE_TO_ACQUIRE_MEMORY"),
             s"unexpected OOM message: ${ex.getMessage}")
   ```



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowSegmentTree.scala:
##########
@@ -0,0 +1,610 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.execution.window
+
+import java.util.{LinkedHashMap => JLinkedHashMap, Map => JMap}
+
+import scala.collection.mutable
+
+import org.apache.spark.{SparkEnv, SparkException, TaskContext}
+import org.apache.spark.memory.{MemoryConsumer, TaskMemoryManager}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.expressions.aggregate.DeclarativeAggregate
+import org.apache.spark.sql.errors.QueryExecutionErrors
+import org.apache.spark.sql.execution.ExternalAppendOnlyUnsafeRowArray
+import org.apache.spark.sql.types.DataType
+import org.apache.spark.util.ArrayImplicits._
+
+/**
+ * Block-chunked segment tree for range aggregate queries over window partitions.
+ *
+ * See `the class documentation`
+ * for the full design (API contract Section 2, block-chunked memory layout Section 3,
+ * DeclarativeAggregate binding Section 4, error handling Section 5, test hooks Section 6).
+ *
+ * initial implementation scope: correctness only. The data layer uses
+ * `ExternalAppendOnlyUnsafeRowArray` to hold input rows (spillable). Each
+ * block materializes its own small segment tree (levels 0..h). Internal
+ * nodes are cached in an LRU keyed by block index; block root aggregates
+ * (block pre-aggregates) stay resident for all blocks.
+ *
+ * Note: the design doc Section 3.3 specifies leaves are NOT materialized and
+ * recomputed from the spillable array on demand. For initial implementation simplicity
+ * we materialize leaves inside the per-block internal node arrays.
+ * // TODO(SPARK-XXXXX) re-assess after Frame integration.
+ *
+ * @note Instances are not thread-safe.
+ */
+private[window] class WindowSegmentTree(
+    functions: Array[DeclarativeAggregate],
+    inputSchema: Seq[Attribute],
+    newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
+    fanout: Int = WindowSegmentTree.DefaultFanout,
+    blockSize: Int = WindowSegmentTree.DefaultBlockSize,
+    maxCachedBlocks: Option[Int] = None,
+    spillThreshold: Int = Int.MaxValue,
+    inMemoryThreshold: Int = Int.MaxValue,
+    taskMemoryManager: TaskMemoryManager = null)
+  extends AutoCloseable {
+
+  require(fanout >= 2, s"fanout must be >= 2, got $fanout")
+  require(blockSize >= 1, s"blockSize must be >= 1, got $blockSize")
+  require(functions.nonEmpty, "WindowSegmentTree requires at least one aggregate function")
+  maxCachedBlocks.foreach { n =>
+    require(n >= 1, s"maxCachedBlocks must be >= 1 when specified, got $n")
+  }
+  require(taskMemoryManager != null,
+    "WindowSegmentTree requires a non-null TaskMemoryManager; " +
+      "in tests use `new TaskMemoryManager(new TestMemoryManager(conf), 0)`")
+
+  // ---------- Schemas & projections ----------
+
+  private val bufferAttrs: Seq[AttributeReference] =
+    functions.flatMap(_.aggBufferAttributes).toImmutableArraySeq
+  private val rightAttrs: Seq[AttributeReference] =
+    functions.flatMap(_.inputAggBufferAttributes).toImmutableArraySeq
+  private val bufferDataTypes: IndexedSeq[DataType] =
+    bufferAttrs.map(_.dataType).toIndexedSeq
+
+  private val initialValues: Seq[Expression] = functions.flatMap(_.initialValues).toIndexedSeq
+  private val updateExpressions: Seq[Expression] =
+    functions.flatMap(_.updateExpressions).toIndexedSeq
+  private val mergeExpressions: Seq[Expression] =
+    functions.flatMap(_.mergeExpressions).toIndexedSeq
+
+  private[this] val initProj: MutableProjection = newMutableProjection(initialValues, Nil)
+  private[this] val updateProj: MutableProjection =
+    newMutableProjection(updateExpressions, bufferAttrs ++ inputSchema)
+  private[this] val mergeProj: MutableProjection =
+    newMutableProjection(mergeExpressions, bufferAttrs ++ rightAttrs)
+
+  private val inputUnsafeProj: UnsafeProjection =
+    UnsafeProjection.create(inputSchema.map(_.dataType).toArray)
+
+  private[this] val joinedRow = new JoinedRow()
+
+  // ---------- State ----------
+
+  private var numRows: Int = 0
+  private var numBlocks: Int = 0
+  private var rowArray: ExternalAppendOnlyUnsafeRowArray = _
+  private var closed: Boolean = false
+
+  /** Always-resident per-block root aggregates. `blockAggregates(i)` =
+   *  merged buffer over all rows in block i. */
+  private var blockAggregates: Array[InternalRow] = Array.empty
+
+  /** Rough byte width of one aggregate buffer row. Chosen at 16 B/field as a
+   *  conservative heap-overhead-aware lower bound for a
+   *  `SpecificInternalRow` slot: primitive `MutableValue` is 8 B, boxed
+   *  references and object headers push the effective footprint higher.
+   *  Tighter per-type sizing (real boxing cost, variable-length fields) is
+   *  intentionally out of scope here; TaskMemoryManager remains the hard
+   *  backstop via spill / OOM.
+   *  TODO(SPARK-XXXXX): per-type width estimator keyed on
+   *  `bufferDataTypes` (primitive 16 B, String/Binary/Decimal wider). */
+  private val bufferWidthBytes: Long = {
+    val bytesPerField = 16L
+    math.max(1L, bufferDataTypes.size.toLong * bytesPerField)
+  }
+
+  /** Number of aggregate-buffer slots cached per block (contract I5).
+   *
+   *  Invariant: equals `sum over levels L of levels(L).length` for any
+   *  block materialized by [[buildBlockLevels]]. Level 0 holds `blockSize`
+   *  leaf buffers and each subsequent level holds `ceil(prev / fanout)`
+   *  parent buffers until a single root remains. The iterative ceiling
+   *  matches the allocation in [[buildBlockLevels]] for every
+   *  `(blockSize, fanout)` pair, including non-power-of-`fanout` cases.
+   *  For `blockSize == 1` the block is a single leaf with no parent
+   *  levels, so this returns 1.
+   *  TODO(SPARK-XXXXX): drop the leaf term when [[buildBlockLevels]]
+   *  switches to on-demand leaf recomputation. */
+  private val cachedSlotsPerBlock: Long = {
+    var n = blockSize.toLong
+    var sum = n
+    while (n > 1L) {
+      n = (n + fanout - 1) / fanout
+      sum += n
+    }
+    sum
+  }
+
+  /** Bytes accounted per cached block (contract I5). Conservative: assumes
+   *  every block is full; tail block (`numRows % blockSize != 0`) will
+   *  hold fewer leaves, giving a small headroom. */
+  private[this] val blockBytes: Long =
+    math.max(1L, cachedSlotsPerBlock * bufferWidthBytes)
+
+  /** `spans(L)` = number of leaves covered by a single node at level L. Depends
+   *  only on fanout + blockSize, so precomputed once. */
+  private val spans: Array[Int] = {
+    val maxLevel = {
+      var lvl = 0
+      var span = 1L
+      while (span < blockSize) { span *= fanout; lvl += 1 }
+      lvl
+    }
+    val arr = new Array[Int](maxLevel + 1)
+    var s = 1L
+    var i = 0
+    while (i <= maxLevel) {
+      arr(i) = if (s > Int.MaxValue) Int.MaxValue else s.toInt
+      s *= fanout
+      i += 1
+    }
+    arr
+  }
+
+  /** LRU cache of per-block internal node arrays. Key = blockIdx.
+   *  Value = `Array[Array[InternalRow]]` with levels(0..h). Auto-eviction via
+   *  `removeEldestEntry` is disabled (contract I3) -- eviction is driven
+   *  explicitly from [[ensureBlockLevels]] (capacity overflow) or
+   *  [[SegTreeSpiller.spill]] (TMM pressure). Each cache entry maps 1:1 to
+   *  one [[acquireBlockMemory]] accounting. Callers (e.g.
+   *  `SegmentTreeWindowFunctionFrame`) should pass a W-aware
+   *  value like `ceil(W / blockSize) + 2`. */
+  private val blockLevelsCache: JLinkedHashMap[Integer, Array[Array[InternalRow]]] =
+    new JLinkedHashMap[Integer, Array[Array[InternalRow]]](16, 0.75f, true) {
+      override def removeEldestEntry(
+          eldest: JMap.Entry[Integer, Array[Array[InternalRow]]]): Boolean = false
+    }
+
+  // ---------- Memory consumer (contract Section 2.2) ----------
+
+  /**
+   * Private MemoryConsumer tracking cached block levels under TMM.
+   *
+   * Heap accounting only (no Tungsten pages): uses
+   * [[MemoryConsumer.acquireMemory]] / [[MemoryConsumer.freeMemory]]. The
+   * [[MemoryConsumer]] base class records `used` via an `AtomicLong` when
+   * we call these -- so TMM's consumer-priority sort in
+   * `acquireExecutionMemory` sees our pressure accurately.
+   *
+   * @note `spill()` MUST NOT call `acquireMemory` (contract I1).
+   */
+  private final class SegTreeSpiller extends MemoryConsumer(
+      taskMemoryManager,
+      taskMemoryManager.pageSizeBytes(),
+      taskMemoryManager.getTungstenMemoryMode()) {
+    override def spill(size: Long, trigger: MemoryConsumer): Long = {
+      // I2: self-trigger short-circuit. Prevents re-entrant eviction when
+      // our own acquireMemory() triggers TMM to poll us.
+      if (trigger eq this) return 0L
+      // I8: rowArray spilled-to-disk detection. If the rowArray has already
+      // spilled, evicting our cache is counter-productive (rebuild would
+      // O(blockStart)-scan the spill file). Return 0L to let TMM fall
+      // through to the next consumer.
+      //
+      // TODO(SPARK-XXXXX) #segtree-spill-priority (contract Section 7 O4): current
+      // heuristic uses `spillSize > 0` as the "has spilled" signal. A more
+      // precise check would consult `UnsafeExternalSorter.getSpillWriters`
+      // state, but that API is not public. Re-evaluate after benchmark.
+      // FIXME(kentyao): upstream a public "hasSpilled" hook on the array.
+      if (rowArray != null && rowArray.spillSize > 0) return 0L
+      evictUntil(size)
+    }
+  }
+
+  private[this] val spiller: SegTreeSpiller = new SegTreeSpiller
+
+  // Task kill / completion fall-back: ensure cache is freed even if caller
+  // forgets close() (contract Section 2.5). Frame already registers a
+  // listener too; double close is idempotent (contract I4).
+  {
+    val tc = TaskContext.get()
+    if (tc != null) {

Review Comment:
   The tree and the frame each register their own `TaskCompletionListener` to call `close()` (frame: `SegmentTreeWindowFunctionFrame.scala:113-118`). In the production frame path this is two listeners per tree — the frame's listener already drives `tree.close()`. Safe because `close` is idempotent, but noise in the listener chain. Consider dropping the tree's own listener in the frame-driven path (keep it only behind a `registerSelfClose: Boolean` ctor flag for standalone test use), and document that the frame owns lifetime.



-- 
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@spark.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-56546][SQL] Block-chunked segment-tree window frame for non-invertible sliding aggregates [spark]

Posted by "yaooqinn (via GitHub)" <gi...@apache.org>.
yaooqinn commented on code in PR #55422:
URL: https://github.com/apache/spark/pull/55422#discussion_r3135556875


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -4049,6 +4049,51 @@ object SQLConf {
         "The threshold of window group limit must be -1, 0 or positive integer.")
       .createWithDefault(1000)
 
+  val WINDOW_SEGMENT_TREE_ENABLED =
+    buildConf("spark.sql.window.segmentTree.enabled")
+      .withBindingPolicy(ConfigBindingPolicy.SESSION)
+      .doc("Use block-chunked segment tree for moving aggregate window frames " +
+        "whose functions are all DeclarativeAggregate without FILTER/DISTINCT.")
+      .version("4.2.0")

Review Comment:
   The internal ones are just in case any regression we haven't found yet by microbenchmark. It's unlikely for users to tune in daily workload. And even `blockSize` can be marked as internal, however it has a bigger chance to be tuned based on the environments



-- 
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@spark.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [WIP][SPARK-56546][SQL] Block-chunked segment-tree window frame for non-invertible sliding aggregates [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #55422:
URL: https://github.com/apache/spark/pull/55422#discussion_r3110849715


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowSegmentTree.scala:
##########
@@ -0,0 +1,601 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.execution.window
+
+import java.util.{LinkedHashMap => JLinkedHashMap, Map => JMap}
+
+import scala.collection.mutable
+
+import org.apache.spark.{SparkEnv, SparkException, TaskContext}
+import org.apache.spark.memory.{MemoryConsumer, TaskMemoryManager}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.expressions.aggregate.DeclarativeAggregate
+import org.apache.spark.sql.errors.QueryExecutionErrors
+import org.apache.spark.sql.execution.ExternalAppendOnlyUnsafeRowArray
+import org.apache.spark.sql.types.DataType
+import org.apache.spark.util.ArrayImplicits._
+
+/**

Review Comment:
   The class doc explains *what* the structure is but not *why* segment tree over alternatives — and that omission matters because alternative optimizations for the same problem exist (monotonic deque for MIN/MAX; add/remove with inverse for invertible aggregates). The load-bearing correctness argument for tree merges is twofold and currently implicit:
   
   1. **No inverse required** — any aggregate whose `mergeExpressions` is associative works, including MIN/MAX and other non-invertible cases.
   2. **Bounded FP error per query** — tree merges do O(log W) additions per query with no cumulative state, so floating-point error is bounded per output row. Any add/remove / inverse-based scheme (cf. SPARK-36844) accumulates error across the whole partition and drifts over long partitions.
   
   The second point in particular is the reason to prefer segtree for STDDEV/VAR/FP-SUM even though an inverse-based O(1) approach looks cheaper on paper. Worth adding a short paragraph to the class doc so future authors considering alternative optimizations understand what property was preserved here.



-- 
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@spark.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-56546][SQL] Block-chunked segment-tree window frame for non-invertible sliding aggregates [spark]

Posted by "dongjoon-hyun (via GitHub)" <gi...@apache.org>.
dongjoon-hyun commented on code in PR #55422:
URL: https://github.com/apache/spark/pull/55422#discussion_r3148723575


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/SegmentTreeWindowFunctionFrame.scala:
##########
@@ -0,0 +1,292 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.execution.window
+
+import org.apache.spark.TaskContext
+import org.apache.spark.memory.TaskMemoryManager
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, Expression, FrameType, MutableProjection, RangeFrame, RowFrame, UnsafeRow}
+import org.apache.spark.sql.catalyst.expressions.aggregate.DeclarativeAggregate
+import org.apache.spark.sql.execution.ExternalAppendOnlyUnsafeRowArray
+import org.apache.spark.sql.execution.metric.SQLMetric
+import org.apache.spark.sql.internal.SQLConf
+
+/**
+ * Moving-frame window function frame backed by [[WindowSegmentTree]]. Produces
+ * the same outputs as [[SlidingWindowFunctionFrame]] for RowFrame or
+ * single-column RangeFrame moving frames whose aggregates are all
+ * [[DeclarativeAggregate]] with no FILTER/DISTINCT. For partitions below
+ * `spark.sql.window.segmentTree.minPartitionRows`, delegates to a wrapped
+ * [[SlidingWindowFunctionFrame]]. Under RANGE, two forward-only cursors
+ * (`lowerIter` / `upperIter`) advance the bounds in O(n) total; the segtree
+ * answers `[lowerBound, upperBound)` in O(log n).
+ *
+ * @note Not thread-safe.
+ */
+private[window] final class SegmentTreeWindowFunctionFrame(
+    target: InternalRow,
+    processor: AggregateProcessor,
+    functions: Array[DeclarativeAggregate],
+    inputSchema: Seq[Attribute],
+    frameType: FrameType,
+    lbound: BoundOrdering,
+    ubound: BoundOrdering,
+    newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
+    conf: SQLConf,
+    maxCachedBlocks: Option[Int],
+    taskMemoryManager: TaskMemoryManager,
+    numSegmentTreeFrames: Option[SQLMetric] = None,
+    numSegmentTreeFallbackFrames: Option[SQLMetric] = None)
+  extends WindowFunctionFrame with AutoCloseable {
+
+  require(frameType == RowFrame || frameType == RangeFrame,
+    s"SegmentTreeWindowFunctionFrame supports RowFrame or RangeFrame, got $frameType")
+
+  private[this] var fallback: SlidingWindowFunctionFrame = _
+  private[this] var tree: WindowSegmentTree = _
+
+  /** Allocate a fresh fallback sliding-window frame. Called lazily from
+   *  `prepare()` on the small-partition path. Factored out for testability
+   *  (subclasses can inject a throwing fallback for prepare-failure tests). */

Review Comment:
   nit. The trailing `*/` looks like a typo. Please place it in a new line.



-- 
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@spark.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-56546][SQL] Block-chunked segment-tree window frame for non-invertible sliding aggregates [spark]

Posted by "dongjoon-hyun (via GitHub)" <gi...@apache.org>.
dongjoon-hyun commented on code in PR #55422:
URL: https://github.com/apache/spark/pull/55422#discussion_r3148779222


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowSegmentTree.scala:
##########
@@ -0,0 +1,592 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.execution.window
+
+import java.util.{LinkedHashMap => JLinkedHashMap, Map => JMap}
+
+import scala.collection.mutable
+
+import org.apache.spark.SparkException
+import org.apache.spark.memory.{MemoryConsumer, MemoryMode, TaskMemoryManager}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.expressions.aggregate.{Average, Count, DeclarativeAggregate, Max, Min, StddevPop, StddevSamp, Sum, VariancePop, VarianceSamp}
+import org.apache.spark.sql.errors.QueryExecutionErrors
+import org.apache.spark.sql.execution.ExternalAppendOnlyUnsafeRowArray
+import org.apache.spark.sql.types.DataType
+import org.apache.spark.util.ArrayImplicits._
+
+/**
+ * Block-chunked segment tree for moving-frame window aggregates. Partitions are
+ * split into blocks of `blockSize` rows; each block has its own small segtree
+ * (fanout `F`, height `h`). Block roots stay resident; internal nodes are cached
+ * in an LRU keyed by block index. Queries cost O(log W).
+ *
+ * Memory accounting invariants:
+ *  - I1: `SegTreeSpiller.spill()` MUST NOT call `acquireMemory` on its own
+ *        consumer (would deadlock TMM's consumer-priority sort). All acquires
+ *        happen on the hot path ([[ensureBlockLevels]]).
+ *  - I2: `spill(_, trigger)` returns 0 when `trigger eq this` (self-trigger
+ *        short-circuit) to prevent re-entrant eviction.
+ *  - I3: LRU `removeEldestEntry` is disabled; eviction is driven explicitly
+ *        from [[ensureBlockLevels]] or [[SegTreeSpiller.spill]].
+ *  - I4: Every successful [[acquireBlockMemory]] is paired with exactly one
+ *        [[releaseBlockMemory]]. [[close]] is idempotent.
+ *  - I5: Per-block bytes are a conservative upper bound (full block, 16 B/field).
+ *  - I8: If `rowArray` already spilled to disk, `spill` returns 0 (rebuild
+ *        would O(blockStart)-scan the spill file).
+ *
+ * @note Instances are not thread-safe.
+ */
+private[window] class WindowSegmentTree(
+    functions: Array[DeclarativeAggregate],
+    inputSchema: Seq[Attribute],
+    newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
+    fanout: Int = WindowSegmentTree.DefaultFanout,
+    blockSize: Int = WindowSegmentTree.DefaultBlockSize,
+    maxCachedBlocks: Option[Int] = None,
+    taskMemoryManager: TaskMemoryManager = null)
+  extends AutoCloseable {
+
+  require(fanout >= 2, s"fanout must be >= 2, got $fanout")
+  require(blockSize >= 1, s"blockSize must be >= 1, got $blockSize")
+  require(functions.nonEmpty, "WindowSegmentTree requires at least one aggregate function")
+  maxCachedBlocks.foreach { n =>
+    require(n >= 1, s"maxCachedBlocks must be >= 1 when specified, got $n")
+  }
+  require(taskMemoryManager != null,
+    "WindowSegmentTree requires a non-null TaskMemoryManager; " +
+      "in tests use `new TaskMemoryManager(new TestMemoryManager(conf), 0)`")
+
+  // ---------- Schemas & projections ----------
+
+  private val bufferAttrs: Seq[AttributeReference] =
+    functions.flatMap(_.aggBufferAttributes).toImmutableArraySeq
+  private val rightAttrs: Seq[AttributeReference] =
+    functions.flatMap(_.inputAggBufferAttributes).toImmutableArraySeq
+  private val bufferDataTypes: IndexedSeq[DataType] =
+    bufferAttrs.map(_.dataType).toIndexedSeq
+
+  private val initialValues: Seq[Expression] = functions.flatMap(_.initialValues).toIndexedSeq
+  private val updateExpressions: Seq[Expression] =
+    functions.flatMap(_.updateExpressions).toIndexedSeq
+  private val mergeExpressions: Seq[Expression] =
+    functions.flatMap(_.mergeExpressions).toIndexedSeq
+
+  private[this] val initProj: MutableProjection = newMutableProjection(initialValues, Nil)
+  private[this] val updateProj: MutableProjection =
+    newMutableProjection(updateExpressions, bufferAttrs ++ inputSchema)
+  private[this] val mergeProj: MutableProjection =
+    newMutableProjection(mergeExpressions, bufferAttrs ++ rightAttrs)
+
+  private[this] val joinedRow = new JoinedRow()
+
+  // ---------- State ----------
+
+  private var numRows: Int = 0
+  private var numBlocks: Int = 0
+  private var rowArray: ExternalAppendOnlyUnsafeRowArray = _
+  private var closed: Boolean = false
+
+  /** Always-resident per-block root aggregates: `blockAggregates(i)` =
+   *  merged buffer over all rows in block i. */
+  private var blockAggregates: Array[InternalRow] = Array.empty
+
+  /** Conservative byte width of one aggregate buffer row at 16 B/field:
+   *  primitive `MutableValue` is 8 B, boxed references and object headers
+   *  push the effective footprint higher. Tighter per-type sizing is out
+   *  of scope; TaskMemoryManager remains the hard backstop via spill / OOM. */
+  private val bufferWidthBytes: Long = {
+    val bytesPerField = 16L
+    math.max(1L, bufferDataTypes.size.toLong * bytesPerField)
+  }
+
+  /** Number of aggregate-buffer slots cached per block (see I5).
+   *
+   *  Invariant: equals `sum over levels L of levels(L).length` for any block
+   *  built by [[buildBlockLevels]]: level 0 holds `blockSize` leaves and each
+   *  next level holds `ceil(prev / fanout)` parents until a single root
+   *  remains. For `blockSize == 1` this is 1 (single leaf, no parents). */
+  private val cachedSlotsPerBlock: Long = {
+    var n = blockSize.toLong
+    var sum = n
+    while (n > 1L) {
+      n = (n + fanout - 1) / fanout
+      sum += n
+    }
+    sum
+  }
+
+  /** Bytes accounted per cached block (see I5). Conservative: assumes every
+   *  block is full; tail block leaves a small headroom. */
+  private[this] val blockBytes: Long =
+    math.max(1L, cachedSlotsPerBlock * bufferWidthBytes)
+
+  /** `spans(L)` = number of leaves covered by a single node at level L. Depends
+   *  only on fanout + blockSize, so precomputed once. */
+  private val spans: Array[Int] = {
+    val maxLevel = {
+      var lvl = 0
+      var span = 1L
+      while (span < blockSize) { span *= fanout; lvl += 1 }
+      lvl
+    }
+    val arr = new Array[Int](maxLevel + 1)
+    var s = 1L
+    var i = 0
+    while (i <= maxLevel) {
+      arr(i) = if (s > Int.MaxValue) Int.MaxValue else s.toInt
+      s *= fanout
+      i += 1
+    }
+    arr
+  }
+
+  /** LRU cache of per-block internal node arrays. Key = blockIdx;
+   *  value = `Array[Array[InternalRow]]` with levels(0..h). Auto-eviction
+   *  via `removeEldestEntry` is disabled (I3) -- driven explicitly from
+   *  [[ensureBlockLevels]] or [[SegTreeSpiller.spill]]. Each entry maps 1:1
+   *  to one [[acquireBlockMemory]] accounting. Callers should pass a W-aware
+   *  `maxCachedBlocks` like `ceil(W / blockSize) + 2`. */
+  private val blockLevelsCache: JLinkedHashMap[Integer, Array[Array[InternalRow]]] =
+    new JLinkedHashMap[Integer, Array[Array[InternalRow]]](16, 0.75f, true) {
+      override def removeEldestEntry(
+          eldest: JMap.Entry[Integer, Array[Array[InternalRow]]]): Boolean = false
+    }
+
+  // ---------- Memory consumer ----------
+
+  /**
+   * Private MemoryConsumer tracking cached block levels under TMM. Heap-only
+   * (no Tungsten pages): uses [[MemoryConsumer.acquireMemory]] /
+   * [[MemoryConsumer.freeMemory]], which update the base class `used`
+   * AtomicLong so TMM's consumer-priority sort sees our pressure accurately.
+   *
+   * Hardcoded [[MemoryMode.ON_HEAP]] (not `tmm.getTungstenMemoryMode`): the
+   * cache holds plain JVM objects (`SpecificInternalRow` /
+   * `Array[Array[InternalRow]]`), never Tungsten pages. Under
+   * `spark.memory.offHeap.enabled=true`, enrolling as OFF_HEAP would let
+   * TMM pick us as a spill candidate for off-heap pressure; our `spill()`
+   * would then phantom-credit the off-heap pool without releasing any
+   * off-heap bytes, violating [[TaskMemoryManager#acquireExecutionMemory]]'s
+   * same-pool spill contract. Mirrors
+   * [[org.apache.spark.util.collection.Spillable]], which also hardcodes
+   * ON_HEAP for the same reason. Consequence under off-heap Tungsten: I8
+   * (below) degrades to a no-op because segtree and `rowArray` live in
+   * different pools -- a loss of optimization, not a correctness hazard.
+   *
+   * @note `spill()` MUST NOT call `acquireMemory` (see I1).
+   */
+  private final class SegTreeSpiller extends MemoryConsumer(
+      taskMemoryManager,
+      taskMemoryManager.pageSizeBytes(),
+      MemoryMode.ON_HEAP) {
+    override def spill(size: Long, trigger: MemoryConsumer): Long = {
+      // I2: self-trigger short-circuit (prevent re-entrant eviction).
+      if (trigger eq this) return 0L
+      // I8: rowArray already spilled -- evicting our cache is counter-productive
+      // (rebuild would O(blockStart)-scan the spill file). `spillSize > 0` is
+      // the available "has spilled" signal (UnsafeExternalSorter state is not
+      // public).
+      if (rowArray != null && rowArray.spillSize > 0) return 0L
+      evictUntil(size)
+    }
+  }
+
+  private[this] val spiller: SegTreeSpiller = new SegTreeSpiller
+
+  // ---------- Public API ----------
+
+  def size: Int = numRows
+
+  /**
+   * Build the tree against a caller-owned row array.
+   *
+   * Ownership: the tree holds a reference to `rows` for its lifetime but does
+   * NOT own it -- the caller (typically `WindowPartitionEvaluator.buffer`)
+   * manages `clear()` / lifetime at partition boundaries. `close()` drops
+   * the reference without mutating the array.
+   *
+   * Exception-safe: if aggregation throws, previously built state is preserved.
+   */
+  def build(rows: ExternalAppendOnlyUnsafeRowArray): Unit = {
+    // rows.length is Int by design; check guards against future widening.
+    val n = rows.length
+    if (n < 0) {
+      throw SparkException.internalError(
+        s"WindowSegmentTree cannot hold more than Int.MaxValue rows, got $n")
+    }
+    val nBlocks = if (n == 0) 0 else (n + blockSize - 1) / blockSize
+    val newBlockAggs = computeBlockAggregates(rows, n, nBlocks)
+
+    // Commit.
+    rowArray = rows
+    numRows = n
+    numBlocks = nBlocks
+    blockAggregates = newBlockAggs
+    // Rebuild invalidates cached block levels; release accounting first (I4).
+    releaseAllCachedBlocks()
+  }
+
+  /**
+   * Query [lo, hi) and directly evaluate the result via `processor.evaluate`
+   * into `target`. Uses an internal pre-allocated buffer so no per-call
+   * allocation is needed.
+   */
+  private[window] def queryInto(
+      lo: Int, hi: Int, processor: AggregateProcessor, target: InternalRow): Unit = {
+    query(lo, hi, internalQueryBuffer)
+    processor.evaluate(internalQueryBuffer, target)
+  }
+
+  private[this] val internalQueryBuffer: InternalRow = newBuffer()
+
+  def query(lo: Int, hi: Int, outBuffer: InternalRow): Unit = {
+    if (lo < 0 || hi > numRows || lo > hi) {
+      throw SparkException.internalError(
+        s"Invalid range [lo=$lo, hi=$hi) for size=$numRows")
+    }
+    // Reset outBuffer to identity only after bounds validation.
+    initProj.target(outBuffer)(InternalRow.empty)
+    if (lo == hi) return
+
+    val blo = lo / blockSize
+    val bhi = (hi - 1) / blockSize
+
+    if (blo == bhi) {
+      val blockStart = blo * blockSize
+      mergeBlockRange(blo, lo - blockStart, hi - blockStart, outBuffer)
+    } else {
+      // left partial
+      val loStart = blo * blockSize
+      val loBlockRows = math.min(blockSize, numRows - loStart)
+      mergeBlockRange(blo, lo - loStart, loBlockRows, outBuffer)
+      // full blocks
+      var b = blo + 1
+      while (b < bhi) {
+        mergeInto(outBuffer, blockAggregates(b))
+        b += 1
+      }
+      // right partial
+      val hiStart = bhi * blockSize
+      mergeBlockRange(bhi, 0, hi - hiStart, outBuffer)
+    }
+  }
+
+  /** Terminal: releases all state. Idempotent (I4). */
+  override def close(): Unit = {
+    if (closed) return
+    // Free all cached-block accounting before dropping references.
+    releaseAllCachedBlocks()
+    closeRowArray()
+    blockAggregates = Array.empty
+    numRows = 0
+    numBlocks = 0
+    closed = true
+  }
+
+  // ---------- Test hooks (package-private) ----------
+
+  private[window] def peekBlockCount: Int = numBlocks
+
+  private[window] def testOnlySpiller(): MemoryConsumer = spiller
+
+  /** Test-only accessor for the per-block memory accounting value. */
+  private[window] def peekBlockBytes: Long = blockBytes
+
+  /** NOTE: test-only; promotes block to MRU in the LRU cache as a side effect. */
+  private[window] def peekLevelSize(blockIdx: Int, level: Int): Int = {
+    val levels = ensureBlockLevels(blockIdx)
+    levels(level).length
+  }
+
+  /** NOTE: test-only; promotes block to MRU in the LRU cache as a side effect. */
+  private[window] def peekLevelCount(blockIdx: Int): Int = {
+    val levels = ensureBlockLevels(blockIdx)
+    levels.length
+  }
+
+  // ---------- Internals ----------
+
+  private def computeBlockAggregates(
+      array: ExternalAppendOnlyUnsafeRowArray,
+      n: Int,
+      nBlocks: Int): Array[InternalRow] = {
+    if (n == 0) return Array.empty
+    val result = new Array[InternalRow](nBlocks)
+    val iter = array.generateIterator()
+    var b = 0
+    while (b < nBlocks) {
+      val buf = newBuffer()
+      initProj.target(buf)(InternalRow.empty)
+      val start = b * blockSize
+      val end = math.min(start + blockSize, n)
+      var i = start
+      while (i < end) {
+        if (!iter.hasNext) {
+          throw SparkException.internalError("rowArray iterator exhausted unexpectedly")
+        }
+        val row = iter.next()
+        updateProj.target(buf)(joinedRow(buf, row))
+        i += 1
+      }
+      result(b) = buf
+      b += 1
+    }
+    result
+  }
+
+  /** Merge `src` buffer into `dst` buffer using mergeProj. */
+  private def mergeInto(dst: InternalRow, src: InternalRow): Unit = {
+    mergeProj.target(dst)(joinedRow(dst, src))
+  }
+
+  private def newBuffer(): InternalRow =
+    new SpecificInternalRow(bufferDataTypes)
+
+  /** Merge the given leaf range [lo, hi) inside `blockIdx` into `out`. */
+  private def mergeBlockRange(
+      blockIdx: Int, lo: Int, hi: Int, out: InternalRow): Unit = {
+    if (lo >= hi) return
+    val levels = ensureBlockLevels(blockIdx)
+    val blockRows = levels(0).length
+    val topLevel = levels.length - 1
+    queryDescend(levels, blockRows, topLevel, 0, lo, hi, out)
+  }
+
+  /** Descend the (per-block) segment tree merging any node fully contained
+   *  in [queryLo, queryHi) into `out`. A node at (level L, index idx) covers
+   *  leaves `[idx * span, min((idx+1)*span, blockRows))` where span = F^L. */
+  private def queryDescend(
+      levels: Array[Array[InternalRow]],
+      blockRows: Int,
+      level: Int,
+      idx: Int,
+      queryLo: Int,
+      queryHi: Int,
+      out: InternalRow): Unit = {
+    val span = spans(level)
+    val nodeLo = idx * span
+    val nodeHi = math.min(nodeLo + span, blockRows)
+    if (queryLo >= nodeHi || queryHi <= nodeLo) return
+    if (queryLo <= nodeLo && nodeHi <= queryHi) {
+      mergeInto(out, levels(level)(idx))
+      return
+    }
+    val childLevel = level - 1
+    val childLevelSize = levels(childLevel).length
+    var c = 0
+    while (c < fanout) {
+      val childIdx = idx * fanout + c
+      if (childIdx < childLevelSize) {
+        queryDescend(levels, blockRows, childLevel, childIdx, queryLo, queryHi, out)
+      }
+      c += 1
+    }
+  }
+
+  /** Build (or fetch from LRU) the full per-block levels array.
+   *  Protocol: acquire memory -> build -> cache. Eviction on capacity
+   *  overflow or on TMM spill request. */
+  private def ensureBlockLevels(blockIdx: Int): Array[Array[InternalRow]] = {
+    val cached = blockLevelsCache.get(Integer.valueOf(blockIdx))
+    if (cached != null) return cached
+
+    // Enforce LRU capacity before building a new entry (I3).
+    val cap = maxCachedBlocks.getOrElse(Int.MaxValue)
+    while (blockLevelsCache.size() >= cap) {
+      if (!evictEldest()) return throwCacheEvictFailed(blockIdx)
+    }
+
+    // Acquire accounting; on partial grant, try one manual evict-and-retry.
+    if (!acquireBlockMemory(blockIdx)) {
+      if (!evictEldest() || !acquireBlockMemory(blockIdx)) {
+        // scalastyle:off throwerror
+        throw QueryExecutionErrors.cannotAcquireMemoryForWindowAggregateError(
+          blockBytes, 0L)
+        // scalastyle:on throwerror
+      }
+    }
+
+    // If buildBlockLevels throws, release the just-acquired memory (I4).
+    val levels =
+      try buildBlockLevels(blockIdx)
+      catch { case t: Throwable => releaseBlockMemory(); throw t }
+    blockLevelsCache.put(Integer.valueOf(blockIdx), levels)
+    levels
+  }
+
+  private def buildBlockLevels(blockIdx: Int): Array[Array[InternalRow]] = {
+    val blockStart = blockIdx * blockSize
+    val blockRows = math.min(blockSize, numRows - blockStart)
+
+    // Level 0: one aggregate per row in the block.
+    val leaves = new Array[InternalRow](blockRows)
+    val iter = rowArray.generateIterator(blockStart)
+    var i = 0
+    while (i < blockRows) {
+      if (!iter.hasNext) {
+        throw SparkException.internalError(
+          s"rowArray iterator exhausted at block $blockIdx row $i")
+      }
+      val row = iter.next()
+      val buf = newBuffer()
+      initProj.target(buf)(InternalRow.empty)
+      updateProj.target(buf)(joinedRow(buf, row))
+      leaves(i) = buf
+      i += 1
+    }
+
+    val allLevels = mutable.ArrayBuffer[Array[InternalRow]](leaves)
+    var prev = leaves
+    while (prev.length > 1) {
+      val parentCount = (prev.length + fanout - 1) / fanout
+      val parents = new Array[InternalRow](parentCount)
+      var p = 0
+      while (p < parentCount) {
+        val buf = newBuffer()
+        initProj.target(buf)(InternalRow.empty)
+        val childStart = p * fanout
+        val childEnd = math.min(childStart + fanout, prev.length)
+        var c = childStart
+        while (c < childEnd) {
+          mergeInto(buf, prev(c))
+          c += 1
+        }
+        parents(p) = buf
+        p += 1
+      }
+      allLevels += parents
+      prev = parents
+    }
+    allLevels.toArray
+  }
+
+  private def throwCacheEvictFailed(blockIdx: Int): Nothing = {
+    throw SparkException.internalError(
+      s"LRU cache eviction failed for block $blockIdx (size=${blockLevelsCache.size})")
+  }
+
+  // ---------- Memory accounting helpers ----------
+
+  /** Try to acquire `blockBytes` for one cached block. Returns true on full
+   *  grant, false on partial (after rolling the partial grant back). Must
+   *  not be called from within [[SegTreeSpiller.spill]] (I1). */
+  private def acquireBlockMemory(blockIdx: Int): Boolean = {

Review Comment:
   `blockIdx` seems to be unused. Shall we remove this argument to simplify?



-- 
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@spark.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-56546][SQL] Block-chunked segment-tree window frame for non-invertible sliding aggregates [spark]

Posted by "dongjoon-hyun (via GitHub)" <gi...@apache.org>.
dongjoon-hyun commented on code in PR #55422:
URL: https://github.com/apache/spark/pull/55422#discussion_r3148825366


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/AggregateProcessor.scala:
##########
@@ -181,7 +181,26 @@ private[window] final class AggregateProcessor(
   }
 
   /** Evaluate buffer. */
-  def evaluate(target: InternalRow): Unit = {
-    evaluateProjection.target(target)(buffer)
+  def evaluate(target: InternalRow): Unit = evaluate(buffer, target)
+
+  /**
+   * Evaluate using an arbitrary `source` buffer (e.g. a segment-tree query
+   * result) instead of the internal one.
+   *
+   * '''Contract''': `source` must share this processor's internal
+   * `aggBufferAttributes` layout -- same field count, same dataTypes, in the
+   * same order. The segment-tree path enforces this upstream in
+   * `WindowEvaluatorFactoryBase.eligibleForSegTree` (rejects
+   * `SizeBasedWindowFunction`; the same `functions: Array[DeclarativeAggregate]`

Review Comment:
   Since this PR uses a while-list like the following currently, we had better mention it instead of `SizeBasedWindowFunction` here. If we want to mention `SizeBasedWindowFunction`, it should be mentioned in `def isEligible` or `val EligibleAggregates`.
   
   ```scala
     val EligibleAggregates: Set[Class[_ <: DeclarativeAggregate]] = Set(
       classOf[Min],
       classOf[Max],
       classOf[Sum],
       classOf[Count],
       classOf[Average],
       classOf[StddevPop],
       classOf[StddevSamp],
       classOf[VariancePop],
       classOf[VarianceSamp]
     )
   
     /**
      * Returns true iff `f` is a [[DeclarativeAggregate]] on the explicit segment-tree
      * allowlist. See [[EligibleAggregates]] for the rationale and excluded aggregates.
      */
     def isEligible(f: Expression): Boolean = f match {
       case agg: DeclarativeAggregate => EligibleAggregates.contains(agg.getClass) 
       case _ => false
     }
   ```



-- 
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@spark.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-56546][SQL] Block-chunked segment-tree window frame for non-invertible sliding aggregates [spark]

Posted by "LuciferYang (via GitHub)" <gi...@apache.org>.
LuciferYang commented on code in PR #55422:
URL: https://github.com/apache/spark/pull/55422#discussion_r3122411364


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowEvaluatorFactoryBase.scala:
##########
@@ -295,4 +342,58 @@ trait WindowEvaluatorFactoryBase {
     }
   }
 
+  /**
+   * Segment-tree path eligibility. The tree relies on
+   * `DeclarativeAggregate.mergeExpressions`, which [[AggregateWindowFunction]]s
+   * (NthValue, NTile, Rank, RowNumber, NullIndex) refuse via
+   * `mergeUnsupportedByWindowFunctionError`: they extend DeclarativeAggregate
+   * but are NOT merge-capable. Normal aggregate window expressions reach this
+   * code as the inner DeclarativeAggregate unwrapped from
+   * [[AggregateExpression]] (see `windowFrameExpressionFactoryPairs.collect`).
+   */
+  private def eligibleForSegTree(
+      functions: Array[Expression],
+      filters: Array[Option[Expression]],
+      frameType: FrameType): Boolean = {
+    // RANGE accepted only for single-column order specs. Multi-column RANGE
+    // with non-zero offset is already rejected by `createBoundOrdering`, so
+    // gating here on `orderSpec.size == 1` matches the Sliding-path invariant.
+    val frameTypeOk = frameType match {
+      case RowFrame => true
+      case RangeFrame => orderSpec.size == 1
+    }
+    SQLConf.get.windowSegmentTreeEnabled &&
+      frameTypeOk &&
+      filters.forall(_.isEmpty) &&

Review Comment:
   `aggFilters` is built by pattern-matching `AggregateExpression.filter`. If any analyzer rule rewrites `AGG(x) FILTER (WHERE p)` into `AGG(If(p, x, null))` inside the aggregate function before Window, `ae.filter.isEmpty` returns true and the filtered aggregate silently takes the segtree path. Should add a defensive test (`AGG(x) FILTER (WHERE p) OVER (…)` with the conf enabled) that asserts either (a) the fallback frame is used, or (b) results match the naive oracle.



-- 
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@spark.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [WIP][SPARK-56546][SQL] Block-chunked segment-tree window frame for non-invertible sliding aggregates [spark]

Posted by "yaooqinn (via GitHub)" <gi...@apache.org>.
yaooqinn commented on code in PR #55422:
URL: https://github.com/apache/spark/pull/55422#discussion_r3114835957


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowSegmentTree.scala:
##########
@@ -0,0 +1,610 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.execution.window
+
+import java.util.{LinkedHashMap => JLinkedHashMap, Map => JMap}
+
+import scala.collection.mutable
+
+import org.apache.spark.{SparkEnv, SparkException, TaskContext}
+import org.apache.spark.memory.{MemoryConsumer, TaskMemoryManager}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.expressions.aggregate.DeclarativeAggregate
+import org.apache.spark.sql.errors.QueryExecutionErrors
+import org.apache.spark.sql.execution.ExternalAppendOnlyUnsafeRowArray
+import org.apache.spark.sql.types.DataType
+import org.apache.spark.util.ArrayImplicits._
+
+/**
+ * Block-chunked segment tree for range aggregate queries over window partitions.
+ *
+ * See `the class documentation`
+ * for the full design (API contract Section 2, block-chunked memory layout Section 3,
+ * DeclarativeAggregate binding Section 4, error handling Section 5, test hooks Section 6).
+ *
+ * initial implementation scope: correctness only. The data layer uses
+ * `ExternalAppendOnlyUnsafeRowArray` to hold input rows (spillable). Each
+ * block materializes its own small segment tree (levels 0..h). Internal
+ * nodes are cached in an LRU keyed by block index; block root aggregates
+ * (block pre-aggregates) stay resident for all blocks.
+ *
+ * Note: the design doc Section 3.3 specifies leaves are NOT materialized and
+ * recomputed from the spillable array on demand. For initial implementation simplicity
+ * we materialize leaves inside the per-block internal node arrays.
+ * // TODO(SPARK-XXXXX) re-assess after Frame integration.
+ *
+ * @note Instances are not thread-safe.
+ */
+private[window] class WindowSegmentTree(
+    functions: Array[DeclarativeAggregate],
+    inputSchema: Seq[Attribute],
+    newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
+    fanout: Int = WindowSegmentTree.DefaultFanout,
+    blockSize: Int = WindowSegmentTree.DefaultBlockSize,
+    maxCachedBlocks: Option[Int] = None,
+    spillThreshold: Int = Int.MaxValue,
+    inMemoryThreshold: Int = Int.MaxValue,
+    taskMemoryManager: TaskMemoryManager = null)
+  extends AutoCloseable {
+
+  require(fanout >= 2, s"fanout must be >= 2, got $fanout")
+  require(blockSize >= 1, s"blockSize must be >= 1, got $blockSize")
+  require(functions.nonEmpty, "WindowSegmentTree requires at least one aggregate function")
+  maxCachedBlocks.foreach { n =>
+    require(n >= 1, s"maxCachedBlocks must be >= 1 when specified, got $n")
+  }
+  require(taskMemoryManager != null,
+    "WindowSegmentTree requires a non-null TaskMemoryManager; " +
+      "in tests use `new TaskMemoryManager(new TestMemoryManager(conf), 0)`")
+
+  // ---------- Schemas & projections ----------
+
+  private val bufferAttrs: Seq[AttributeReference] =
+    functions.flatMap(_.aggBufferAttributes).toImmutableArraySeq
+  private val rightAttrs: Seq[AttributeReference] =
+    functions.flatMap(_.inputAggBufferAttributes).toImmutableArraySeq
+  private val bufferDataTypes: IndexedSeq[DataType] =
+    bufferAttrs.map(_.dataType).toIndexedSeq
+
+  private val initialValues: Seq[Expression] = functions.flatMap(_.initialValues).toIndexedSeq
+  private val updateExpressions: Seq[Expression] =
+    functions.flatMap(_.updateExpressions).toIndexedSeq
+  private val mergeExpressions: Seq[Expression] =
+    functions.flatMap(_.mergeExpressions).toIndexedSeq
+
+  private[this] val initProj: MutableProjection = newMutableProjection(initialValues, Nil)
+  private[this] val updateProj: MutableProjection =
+    newMutableProjection(updateExpressions, bufferAttrs ++ inputSchema)
+  private[this] val mergeProj: MutableProjection =
+    newMutableProjection(mergeExpressions, bufferAttrs ++ rightAttrs)
+
+  private val inputUnsafeProj: UnsafeProjection =
+    UnsafeProjection.create(inputSchema.map(_.dataType).toArray)
+
+  private[this] val joinedRow = new JoinedRow()
+
+  // ---------- State ----------
+
+  private var numRows: Int = 0
+  private var numBlocks: Int = 0
+  private var rowArray: ExternalAppendOnlyUnsafeRowArray = _
+  private var closed: Boolean = false
+
+  /** Always-resident per-block root aggregates. `blockAggregates(i)` =
+   *  merged buffer over all rows in block i. */
+  private var blockAggregates: Array[InternalRow] = Array.empty
+
+  /** Rough byte width of one aggregate buffer row. Chosen at 16 B/field as a
+   *  conservative heap-overhead-aware lower bound for a
+   *  `SpecificInternalRow` slot: primitive `MutableValue` is 8 B, boxed
+   *  references and object headers push the effective footprint higher.
+   *  Tighter per-type sizing (real boxing cost, variable-length fields) is
+   *  intentionally out of scope here; TaskMemoryManager remains the hard
+   *  backstop via spill / OOM.
+   *  TODO(SPARK-XXXXX): per-type width estimator keyed on
+   *  `bufferDataTypes` (primitive 16 B, String/Binary/Decimal wider). */
+  private val bufferWidthBytes: Long = {
+    val bytesPerField = 16L
+    math.max(1L, bufferDataTypes.size.toLong * bytesPerField)
+  }
+
+  /** Number of aggregate-buffer slots cached per block (contract I5).
+   *
+   *  Invariant: equals `sum over levels L of levels(L).length` for any
+   *  block materialized by [[buildBlockLevels]]. Level 0 holds `blockSize`
+   *  leaf buffers and each subsequent level holds `ceil(prev / fanout)`
+   *  parent buffers until a single root remains. The iterative ceiling
+   *  matches the allocation in [[buildBlockLevels]] for every
+   *  `(blockSize, fanout)` pair, including non-power-of-`fanout` cases.
+   *  For `blockSize == 1` the block is a single leaf with no parent
+   *  levels, so this returns 1.
+   *  TODO(SPARK-XXXXX): drop the leaf term when [[buildBlockLevels]]
+   *  switches to on-demand leaf recomputation. */
+  private val cachedSlotsPerBlock: Long = {
+    var n = blockSize.toLong
+    var sum = n
+    while (n > 1L) {
+      n = (n + fanout - 1) / fanout
+      sum += n
+    }
+    sum
+  }
+
+  /** Bytes accounted per cached block (contract I5). Conservative: assumes
+   *  every block is full; tail block (`numRows % blockSize != 0`) will
+   *  hold fewer leaves, giving a small headroom. */
+  private[this] val blockBytes: Long =
+    math.max(1L, cachedSlotsPerBlock * bufferWidthBytes)
+
+  /** `spans(L)` = number of leaves covered by a single node at level L. Depends
+   *  only on fanout + blockSize, so precomputed once. */
+  private val spans: Array[Int] = {
+    val maxLevel = {
+      var lvl = 0
+      var span = 1L
+      while (span < blockSize) { span *= fanout; lvl += 1 }
+      lvl
+    }
+    val arr = new Array[Int](maxLevel + 1)
+    var s = 1L
+    var i = 0
+    while (i <= maxLevel) {
+      arr(i) = if (s > Int.MaxValue) Int.MaxValue else s.toInt
+      s *= fanout
+      i += 1
+    }
+    arr
+  }
+
+  /** LRU cache of per-block internal node arrays. Key = blockIdx.
+   *  Value = `Array[Array[InternalRow]]` with levels(0..h). Auto-eviction via
+   *  `removeEldestEntry` is disabled (contract I3) -- eviction is driven
+   *  explicitly from [[ensureBlockLevels]] (capacity overflow) or
+   *  [[SegTreeSpiller.spill]] (TMM pressure). Each cache entry maps 1:1 to
+   *  one [[acquireBlockMemory]] accounting. Callers (e.g.
+   *  `SegmentTreeWindowFunctionFrame`) should pass a W-aware
+   *  value like `ceil(W / blockSize) + 2`. */
+  private val blockLevelsCache: JLinkedHashMap[Integer, Array[Array[InternalRow]]] =
+    new JLinkedHashMap[Integer, Array[Array[InternalRow]]](16, 0.75f, true) {
+      override def removeEldestEntry(
+          eldest: JMap.Entry[Integer, Array[Array[InternalRow]]]): Boolean = false
+    }
+
+  // ---------- Memory consumer (contract Section 2.2) ----------
+
+  /**
+   * Private MemoryConsumer tracking cached block levels under TMM.
+   *
+   * Heap accounting only (no Tungsten pages): uses
+   * [[MemoryConsumer.acquireMemory]] / [[MemoryConsumer.freeMemory]]. The
+   * [[MemoryConsumer]] base class records `used` via an `AtomicLong` when
+   * we call these -- so TMM's consumer-priority sort in
+   * `acquireExecutionMemory` sees our pressure accurately.
+   *
+   * @note `spill()` MUST NOT call `acquireMemory` (contract I1).
+   */
+  private final class SegTreeSpiller extends MemoryConsumer(
+      taskMemoryManager,
+      taskMemoryManager.pageSizeBytes(),
+      taskMemoryManager.getTungstenMemoryMode()) {

Review Comment:
   Thanks — this is exactly the trade-off I'd like your read on before we pick a direction, because an earlier internal design pass landed on the opposite conclusion and neither side has a clean win on paper.
   
   **Argument for hardcoding `ON_HEAP` (your point).** The cached state is unambiguously on-heap:
   - `SpecificInternalRow` aggregate buffers (generic object arrays)
   - `Array[Array[InternalRow]]` block-level arrays
   - `ExternalAppendOnlyUnsafeRowArray` pages live on-heap regardless of Tungsten mode
   
   Registering the spiller as `OFF_HEAP` under `spark.memory.offHeap.enabled=true` charges those on-heap allocations to the off-heap pool — phantom pressure with no accounting of real heap pressure. The `T9 OFF_HEAP path` test in `WindowSegmentTreeMemorySuite` enshrines this.
   
   **Counter-argument for keeping `getTungstenMemoryMode()`.** TMM sorts consumers by `getUsed()` descending inside `acquireExecutionMemory` / `trySpillAndAcquire`, but **per pool**. Off-heap mode uses two pools:
   - Off-heap pool: `BytesToBytesMap`, `UnsafeExternalSorter` pages, any Tungsten consumer
   - On-heap pool: segtree (if hardcoded) + a few stragglers
   
   If segtree pins to `ON_HEAP` while `rowArray` (via `ExternalAppendOnlyUnsafeRowArray` → `UnsafeExternalSorter`) follows Tungsten, the two land in **different pools**. Two consequences:
   1. Cooperative spill ordering becomes cross-pool: TMM's `getUsed` descending sort no longer orders segtree vs. rowArray against each other — they compete inside their own pool only. The `I8 rowArray-spilled short-circuit` (`WindowSegmentTree.scala:206`) was designed assuming co-pool ordering so segtree can see rowArray pressure first.
   2. `peakExecutionMemory` reporting splits across pools; the invariant "segtree ≤ rowArray at peak" becomes harder to verify from `TaskMetrics`.
   
   **Questions for your take:**
   - Is the cross-pool spill-ordering concern material in practice? My read of `ExecutionMemoryPool` says sorting is within-pool; if segtree goes on-heap in off-heap mode, the only thing that pressures segtree is other on-heap consumers (mostly none in the Window path), so `I8` short-circuit effectively never fires because the pools don't see each other's pressure. That argues *against* the cross-pool concern.
   - If we hardcode `ON_HEAP`, do you prefer (a) T9 flips to assert the on-heap charge even under off-heap mode, or (b) T9 gets deleted as enshrining the wrong semantics?
   
   I'll hold the change until we align — happy to take it either way with your call.
   



-- 
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@spark.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-56546][SQL] Block-chunked segment-tree window frame for non-invertible sliding aggregates [spark]

Posted by "yaooqinn (via GitHub)" <gi...@apache.org>.
yaooqinn commented on PR #55422:
URL: https://github.com/apache/spark/pull/55422#issuecomment-4302287425

   Friendly ping 🙏 whenever you have a spare cycle — thanks! cc @cloud-fan @LuciferYang


-- 
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@spark.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-56546][SQL] Block-chunked segment-tree window frame for non-invertible sliding aggregates [spark]

Posted by "yaooqinn (via GitHub)" <gi...@apache.org>.
yaooqinn commented on PR #55422:
URL: https://github.com/apache/spark/pull/55422#issuecomment-4318117573

   Thank you @peter-toth for the check and approval


-- 
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@spark.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [WIP][SPARK-56546][SQL] Block-chunked segment-tree window frame for non-invertible sliding aggregates [spark]

Posted by "yaooqinn (via GitHub)" <gi...@apache.org>.
yaooqinn commented on code in PR #55422:
URL: https://github.com/apache/spark/pull/55422#discussion_r3117201342


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowSegmentTree.scala:
##########
@@ -0,0 +1,610 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.execution.window
+
+import java.util.{LinkedHashMap => JLinkedHashMap, Map => JMap}
+
+import scala.collection.mutable
+
+import org.apache.spark.{SparkEnv, SparkException, TaskContext}
+import org.apache.spark.memory.{MemoryConsumer, TaskMemoryManager}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.expressions.aggregate.DeclarativeAggregate
+import org.apache.spark.sql.errors.QueryExecutionErrors
+import org.apache.spark.sql.execution.ExternalAppendOnlyUnsafeRowArray
+import org.apache.spark.sql.types.DataType
+import org.apache.spark.util.ArrayImplicits._
+
+/**
+ * Block-chunked segment tree for range aggregate queries over window partitions.
+ *
+ * See `the class documentation`
+ * for the full design (API contract Section 2, block-chunked memory layout Section 3,
+ * DeclarativeAggregate binding Section 4, error handling Section 5, test hooks Section 6).
+ *
+ * initial implementation scope: correctness only. The data layer uses
+ * `ExternalAppendOnlyUnsafeRowArray` to hold input rows (spillable). Each
+ * block materializes its own small segment tree (levels 0..h). Internal
+ * nodes are cached in an LRU keyed by block index; block root aggregates
+ * (block pre-aggregates) stay resident for all blocks.
+ *
+ * Note: the design doc Section 3.3 specifies leaves are NOT materialized and
+ * recomputed from the spillable array on demand. For initial implementation simplicity
+ * we materialize leaves inside the per-block internal node arrays.
+ * // TODO(SPARK-XXXXX) re-assess after Frame integration.
+ *
+ * @note Instances are not thread-safe.
+ */
+private[window] class WindowSegmentTree(
+    functions: Array[DeclarativeAggregate],
+    inputSchema: Seq[Attribute],
+    newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
+    fanout: Int = WindowSegmentTree.DefaultFanout,
+    blockSize: Int = WindowSegmentTree.DefaultBlockSize,
+    maxCachedBlocks: Option[Int] = None,
+    spillThreshold: Int = Int.MaxValue,
+    inMemoryThreshold: Int = Int.MaxValue,
+    taskMemoryManager: TaskMemoryManager = null)
+  extends AutoCloseable {
+
+  require(fanout >= 2, s"fanout must be >= 2, got $fanout")
+  require(blockSize >= 1, s"blockSize must be >= 1, got $blockSize")
+  require(functions.nonEmpty, "WindowSegmentTree requires at least one aggregate function")
+  maxCachedBlocks.foreach { n =>
+    require(n >= 1, s"maxCachedBlocks must be >= 1 when specified, got $n")
+  }
+  require(taskMemoryManager != null,
+    "WindowSegmentTree requires a non-null TaskMemoryManager; " +
+      "in tests use `new TaskMemoryManager(new TestMemoryManager(conf), 0)`")
+
+  // ---------- Schemas & projections ----------
+
+  private val bufferAttrs: Seq[AttributeReference] =
+    functions.flatMap(_.aggBufferAttributes).toImmutableArraySeq
+  private val rightAttrs: Seq[AttributeReference] =
+    functions.flatMap(_.inputAggBufferAttributes).toImmutableArraySeq
+  private val bufferDataTypes: IndexedSeq[DataType] =
+    bufferAttrs.map(_.dataType).toIndexedSeq
+
+  private val initialValues: Seq[Expression] = functions.flatMap(_.initialValues).toIndexedSeq
+  private val updateExpressions: Seq[Expression] =
+    functions.flatMap(_.updateExpressions).toIndexedSeq
+  private val mergeExpressions: Seq[Expression] =
+    functions.flatMap(_.mergeExpressions).toIndexedSeq
+
+  private[this] val initProj: MutableProjection = newMutableProjection(initialValues, Nil)
+  private[this] val updateProj: MutableProjection =
+    newMutableProjection(updateExpressions, bufferAttrs ++ inputSchema)
+  private[this] val mergeProj: MutableProjection =
+    newMutableProjection(mergeExpressions, bufferAttrs ++ rightAttrs)
+
+  private val inputUnsafeProj: UnsafeProjection =
+    UnsafeProjection.create(inputSchema.map(_.dataType).toArray)
+
+  private[this] val joinedRow = new JoinedRow()
+
+  // ---------- State ----------
+
+  private var numRows: Int = 0
+  private var numBlocks: Int = 0
+  private var rowArray: ExternalAppendOnlyUnsafeRowArray = _
+  private var closed: Boolean = false
+
+  /** Always-resident per-block root aggregates. `blockAggregates(i)` =
+   *  merged buffer over all rows in block i. */
+  private var blockAggregates: Array[InternalRow] = Array.empty
+
+  /** Rough byte width of one aggregate buffer row. Chosen at 16 B/field as a
+   *  conservative heap-overhead-aware lower bound for a
+   *  `SpecificInternalRow` slot: primitive `MutableValue` is 8 B, boxed
+   *  references and object headers push the effective footprint higher.
+   *  Tighter per-type sizing (real boxing cost, variable-length fields) is
+   *  intentionally out of scope here; TaskMemoryManager remains the hard
+   *  backstop via spill / OOM.
+   *  TODO(SPARK-XXXXX): per-type width estimator keyed on
+   *  `bufferDataTypes` (primitive 16 B, String/Binary/Decimal wider). */
+  private val bufferWidthBytes: Long = {
+    val bytesPerField = 16L
+    math.max(1L, bufferDataTypes.size.toLong * bytesPerField)
+  }
+
+  /** Number of aggregate-buffer slots cached per block (contract I5).
+   *
+   *  Invariant: equals `sum over levels L of levels(L).length` for any
+   *  block materialized by [[buildBlockLevels]]. Level 0 holds `blockSize`
+   *  leaf buffers and each subsequent level holds `ceil(prev / fanout)`
+   *  parent buffers until a single root remains. The iterative ceiling
+   *  matches the allocation in [[buildBlockLevels]] for every
+   *  `(blockSize, fanout)` pair, including non-power-of-`fanout` cases.
+   *  For `blockSize == 1` the block is a single leaf with no parent
+   *  levels, so this returns 1.
+   *  TODO(SPARK-XXXXX): drop the leaf term when [[buildBlockLevels]]
+   *  switches to on-demand leaf recomputation. */
+  private val cachedSlotsPerBlock: Long = {
+    var n = blockSize.toLong
+    var sum = n
+    while (n > 1L) {
+      n = (n + fanout - 1) / fanout
+      sum += n
+    }
+    sum
+  }
+
+  /** Bytes accounted per cached block (contract I5). Conservative: assumes
+   *  every block is full; tail block (`numRows % blockSize != 0`) will
+   *  hold fewer leaves, giving a small headroom. */
+  private[this] val blockBytes: Long =
+    math.max(1L, cachedSlotsPerBlock * bufferWidthBytes)
+
+  /** `spans(L)` = number of leaves covered by a single node at level L. Depends
+   *  only on fanout + blockSize, so precomputed once. */
+  private val spans: Array[Int] = {
+    val maxLevel = {
+      var lvl = 0
+      var span = 1L
+      while (span < blockSize) { span *= fanout; lvl += 1 }
+      lvl
+    }
+    val arr = new Array[Int](maxLevel + 1)
+    var s = 1L
+    var i = 0
+    while (i <= maxLevel) {
+      arr(i) = if (s > Int.MaxValue) Int.MaxValue else s.toInt
+      s *= fanout
+      i += 1
+    }
+    arr
+  }
+
+  /** LRU cache of per-block internal node arrays. Key = blockIdx.
+   *  Value = `Array[Array[InternalRow]]` with levels(0..h). Auto-eviction via
+   *  `removeEldestEntry` is disabled (contract I3) -- eviction is driven
+   *  explicitly from [[ensureBlockLevels]] (capacity overflow) or
+   *  [[SegTreeSpiller.spill]] (TMM pressure). Each cache entry maps 1:1 to
+   *  one [[acquireBlockMemory]] accounting. Callers (e.g.
+   *  `SegmentTreeWindowFunctionFrame`) should pass a W-aware
+   *  value like `ceil(W / blockSize) + 2`. */
+  private val blockLevelsCache: JLinkedHashMap[Integer, Array[Array[InternalRow]]] =
+    new JLinkedHashMap[Integer, Array[Array[InternalRow]]](16, 0.75f, true) {
+      override def removeEldestEntry(
+          eldest: JMap.Entry[Integer, Array[Array[InternalRow]]]): Boolean = false
+    }
+
+  // ---------- Memory consumer (contract Section 2.2) ----------
+
+  /**
+   * Private MemoryConsumer tracking cached block levels under TMM.
+   *
+   * Heap accounting only (no Tungsten pages): uses
+   * [[MemoryConsumer.acquireMemory]] / [[MemoryConsumer.freeMemory]]. The
+   * [[MemoryConsumer]] base class records `used` via an `AtomicLong` when
+   * we call these -- so TMM's consumer-priority sort in
+   * `acquireExecutionMemory` sees our pressure accurately.
+   *
+   * @note `spill()` MUST NOT call `acquireMemory` (contract I1).
+   */
+  private final class SegTreeSpiller extends MemoryConsumer(
+      taskMemoryManager,
+      taskMemoryManager.pageSizeBytes(),
+      taskMemoryManager.getTungstenMemoryMode()) {
+    override def spill(size: Long, trigger: MemoryConsumer): Long = {
+      // I2: self-trigger short-circuit. Prevents re-entrant eviction when
+      // our own acquireMemory() triggers TMM to poll us.
+      if (trigger eq this) return 0L
+      // I8: rowArray spilled-to-disk detection. If the rowArray has already
+      // spilled, evicting our cache is counter-productive (rebuild would
+      // O(blockStart)-scan the spill file). Return 0L to let TMM fall
+      // through to the next consumer.
+      //
+      // TODO(SPARK-XXXXX) #segtree-spill-priority (contract Section 7 O4): current
+      // heuristic uses `spillSize > 0` as the "has spilled" signal. A more
+      // precise check would consult `UnsafeExternalSorter.getSpillWriters`
+      // state, but that API is not public. Re-evaluate after benchmark.
+      // FIXME(kentyao): upstream a public "hasSpilled" hook on the array.
+      if (rowArray != null && rowArray.spillSize > 0) return 0L
+      evictUntil(size)
+    }
+  }
+
+  private[this] val spiller: SegTreeSpiller = new SegTreeSpiller
+
+  // Task kill / completion fall-back: ensure cache is freed even if caller
+  // forgets close() (contract Section 2.5). Frame already registers a
+  // listener too; double close is idempotent (contract I4).
+  {
+    val tc = TaskContext.get()
+    if (tc != null) {
+      tc.addTaskCompletionListener[Unit](_ => close())
+    }
+  }
+
+  // ---------- Public API ----------
+
+  def size: Int = numRows
+
+  /**
+   * Drain `rows` into this tree, replacing any previously built state.
+   * Exception-safe: if iteration or aggregation throws, the previously built
+   * state (if any) is preserved.
+   */
+  def build(rows: Iterator[InternalRow]): Unit = {
+    val oldArray = rowArray
+    var newArray: ExternalAppendOnlyUnsafeRowArray = null
+    try {
+      newArray = newRowArray()
+      while (rows.hasNext) {
+        val r = rows.next()
+        val u = inputUnsafeProj(r)
+        newArray.add(u)

Review Comment:
   Thanks for the careful read -- worth clarifying, since the scaladoc phrasing was misleading.
   
   The tree does not own or copy a row array: `build(rows: ExternalAppendOnlyUnsafeRowArray)` stores the caller's reference (`WindowSegmentTree.scala` `rowArray = rows`), and `computeBlockAggregates` / `buildBlockLevels` read it via `generateIterator` / `generateIterator(startIndex)` -- no drain, no copy. The `rows` passed from `SegmentTreeWindowFunctionFrame.prepare` is the same `ExternalAppendOnlyUnsafeRowArray` owned by `WindowPartitionEvaluator.buffer`, so there is no 2x row footprint.
   
   The genuine extra memory is two sets of aggregator buffers (not rows): (1) `blockAggregates`, O(n / blockSize) buffers; (2) cached block levels, bounded by `maxCachedBlocks` and accounted to `TaskMemoryManager`. Aggregator buffer width is a handful of longs/doubles, typically one to two orders of magnitude smaller than UnsafeRow width.
   
   Updated in 63e29170359:
   - tightened the `WindowSegmentTree` layout scaladoc to say "references the caller-owned" row array explicitly.
   - added a "Memory footprint" section to the PR description making the footprint breakdown explicit.



-- 
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@spark.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-56546][SQL] Block-chunked segment-tree window frame for non-invertible sliding aggregates [spark]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #55422:
URL: https://github.com/apache/spark/pull/55422#discussion_r3122401335


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowEvaluatorFactoryBase.scala:
##########
@@ -295,4 +342,58 @@ trait WindowEvaluatorFactoryBase {
     }
   }
 
+  /**
+   * Segment-tree path eligibility. The tree relies on
+   * `DeclarativeAggregate.mergeExpressions`, which [[AggregateWindowFunction]]s
+   * (NthValue, NTile, Rank, RowNumber, NullIndex) refuse via
+   * `mergeUnsupportedByWindowFunctionError`: they extend DeclarativeAggregate
+   * but are NOT merge-capable. Normal aggregate window expressions reach this
+   * code as the inner DeclarativeAggregate unwrapped from
+   * [[AggregateExpression]] (see `windowFrameExpressionFactoryPairs.collect`).
+   */
+  private def eligibleForSegTree(
+      functions: Array[Expression],
+      filters: Array[Option[Expression]],
+      frameType: FrameType): Boolean = {
+    // RANGE accepted only for single-column order specs. Multi-column RANGE
+    // with non-zero offset is already rejected by `createBoundOrdering`, so
+    // gating here on `orderSpec.size == 1` matches the Sliding-path invariant.
+    val frameTypeOk = frameType match {
+      case RowFrame => true
+      case RangeFrame => orderSpec.size == 1
+    }
+    SQLConf.get.windowSegmentTreeEnabled &&
+      frameTypeOk &&
+      filters.forall(_.isEmpty) &&
+      functions.forall(WindowSegmentTree.isEligible) &&
+      !functions.exists {
+        case ae: AggregateExpression => ae.isDistinct
+        case _ => false
+      }
+  }

Review Comment:
   `eligibleForSegTree` tries to reject DISTINCT via `functions.exists { case ae: AggregateExpression => ae.isDistinct }`, but `functions` here are the *inner* expressions (e.g. `Min`, `Sum`) extracted from `AggregateExpression`, so this check will never match and is effectively dead/misleading. Consider either removing it (since DISTINCT window aggregates are already analyzer-rejected) or plumb a distinct flag from `WindowExpression(ae: AggregateExpression, _)` (similar to how `aggFilters` is derived) and gate on that instead.



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/window/SegmentTreeWindowFunctionSuite.scala:
##########
@@ -0,0 +1,892 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.execution.window
+
+import org.apache.spark.sql.{DataFrame, Encoder, Encoders, QueryTest, Row}
+import org.apache.spark.sql.expressions.{Aggregator, MutableAggregationBuffer, Window}
+import org.apache.spark.sql.expressions.UserDefinedAggregateFunction
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.test.SharedSparkSession
+import org.apache.spark.sql.types.{DataType, LongType, StructType}
+import org.apache.spark.util.SparkErrorUtils
+
+/**
+ * End-to-end tests for the block-chunked segment-tree moving window frame.
+ * Covers basic aggregates, frame boundaries, min-rows fallback, NULL/NaN,
+ * numeric/string/date-timestamp types, RANGE, Decimal/Binary merge, UDAF
+ * fallback, and frame lifecycle.
+ */
+class SegmentTreeWindowFunctionSuite extends QueryTest with SharedSparkSession {
+
+  import testImplicits._
+
+  // Force seg-tree path regardless of partition size (fallback exercised explicitly).
+  private val enableSegTree: Map[String, String] = Map(
+    SQLConf.WINDOW_SEGMENT_TREE_ENABLED.key -> "true",
+    SQLConf.WINDOW_SEGMENT_TREE_MIN_PARTITION_ROWS.key -> "1")
+
+  private val disableSegTree: Map[String, String] = Map(
+    SQLConf.WINDOW_SEGMENT_TREE_ENABLED.key -> "false")
+
+  /** Build `f(conf)` twice (enabled / disabled) and assert equal results. */
+  private def checkEquivalence(build: () => DataFrame): Unit = {
+    val baseline: Array[Row] = withSQLConf(disableSegTree.toSeq: _*) {
+      build().collect().sortBy(_.toString)
+    }
+    withSQLConf(enableSegTree.toSeq: _*) {
+      val actual = build().collect().sortBy(_.toString)
+      assert(actual.toSeq === baseline.toSeq,

Review Comment:
   `checkEquivalence` sorts results by `Row.toString`, but `Row.toString` can be unstable for some value types (notably `Array[Byte]` where the element `toString` is address-based). That can reorder baseline vs actual differently and cause false failures. Since this suite already extends `QueryTest`, consider using `prepareAnswer(..., isSorted = false)` / `sameRows` or sorting by stable keys (e.g. `id`, `pk`) instead of `toString`.
   ```suggestion
         build().collect()
       }
       withSQLConf(enableSegTree.toSeq: _*) {
         val actual = build().collect()
         assert(sameRows(actual.toSeq, baseline.toSeq),
   ```



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowSegmentTree.scala:
##########
@@ -0,0 +1,592 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.execution.window
+
+import java.util.{LinkedHashMap => JLinkedHashMap, Map => JMap}
+
+import scala.collection.mutable
+
+import org.apache.spark.SparkException
+import org.apache.spark.memory.{MemoryConsumer, MemoryMode, TaskMemoryManager}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.expressions.aggregate.{Average, Count, DeclarativeAggregate, Max, Min, StddevPop, StddevSamp, Sum, VariancePop, VarianceSamp}
+import org.apache.spark.sql.errors.QueryExecutionErrors
+import org.apache.spark.sql.execution.ExternalAppendOnlyUnsafeRowArray
+import org.apache.spark.sql.types.DataType
+import org.apache.spark.util.ArrayImplicits._
+
+/**
+ * Block-chunked segment tree for moving-frame window aggregates. Partitions are
+ * split into blocks of `blockSize` rows; each block has its own small segtree
+ * (fanout `F`, height `h`). Block roots stay resident; internal nodes are cached
+ * in an LRU keyed by block index. Queries cost O(log W).
+ *
+ * Memory accounting invariants:
+ *  - I1: `SegTreeSpiller.spill()` MUST NOT call `acquireMemory` on its own
+ *        consumer (would deadlock TMM's consumer-priority sort). All acquires
+ *        happen on the hot path ([[ensureBlockLevels]]).
+ *  - I2: `spill(_, trigger)` returns 0 when `trigger eq this` (self-trigger
+ *        short-circuit) to prevent re-entrant eviction.
+ *  - I3: LRU `removeEldestEntry` is disabled; eviction is driven explicitly
+ *        from [[ensureBlockLevels]] or [[SegTreeSpiller.spill]].
+ *  - I4: Every successful [[acquireBlockMemory]] is paired with exactly one
+ *        [[releaseBlockMemory]]. [[close]] is idempotent.
+ *  - I5: Per-block bytes are a conservative upper bound (full block, 16 B/field).
+ *  - I8: If `rowArray` already spilled to disk, `spill` returns 0 (rebuild
+ *        would O(blockStart)-scan the spill file).
+ *
+ * @note Instances are not thread-safe.
+ */
+private[window] class WindowSegmentTree(
+    functions: Array[DeclarativeAggregate],
+    inputSchema: Seq[Attribute],
+    newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
+    fanout: Int = WindowSegmentTree.DefaultFanout,
+    blockSize: Int = WindowSegmentTree.DefaultBlockSize,
+    maxCachedBlocks: Option[Int] = None,
+    taskMemoryManager: TaskMemoryManager = null)
+  extends AutoCloseable {
+
+  require(fanout >= 2, s"fanout must be >= 2, got $fanout")
+  require(blockSize >= 1, s"blockSize must be >= 1, got $blockSize")
+  require(functions.nonEmpty, "WindowSegmentTree requires at least one aggregate function")
+  maxCachedBlocks.foreach { n =>
+    require(n >= 1, s"maxCachedBlocks must be >= 1 when specified, got $n")
+  }
+  require(taskMemoryManager != null,
+    "WindowSegmentTree requires a non-null TaskMemoryManager; " +
+      "in tests use `new TaskMemoryManager(new TestMemoryManager(conf), 0)`")
+
+  // ---------- Schemas & projections ----------
+
+  private val bufferAttrs: Seq[AttributeReference] =
+    functions.flatMap(_.aggBufferAttributes).toImmutableArraySeq
+  private val rightAttrs: Seq[AttributeReference] =
+    functions.flatMap(_.inputAggBufferAttributes).toImmutableArraySeq
+  private val bufferDataTypes: IndexedSeq[DataType] =
+    bufferAttrs.map(_.dataType).toIndexedSeq
+
+  private val initialValues: Seq[Expression] = functions.flatMap(_.initialValues).toIndexedSeq
+  private val updateExpressions: Seq[Expression] =
+    functions.flatMap(_.updateExpressions).toIndexedSeq
+  private val mergeExpressions: Seq[Expression] =
+    functions.flatMap(_.mergeExpressions).toIndexedSeq
+
+  private[this] val initProj: MutableProjection = newMutableProjection(initialValues, Nil)
+  private[this] val updateProj: MutableProjection =
+    newMutableProjection(updateExpressions, bufferAttrs ++ inputSchema)
+  private[this] val mergeProj: MutableProjection =
+    newMutableProjection(mergeExpressions, bufferAttrs ++ rightAttrs)
+
+  private[this] val joinedRow = new JoinedRow()
+
+  // ---------- State ----------
+
+  private var numRows: Int = 0
+  private var numBlocks: Int = 0
+  private var rowArray: ExternalAppendOnlyUnsafeRowArray = _
+  private var closed: Boolean = false
+
+  /** Always-resident per-block root aggregates: `blockAggregates(i)` =
+   *  merged buffer over all rows in block i. */
+  private var blockAggregates: Array[InternalRow] = Array.empty
+
+  /** Conservative byte width of one aggregate buffer row at 16 B/field:
+   *  primitive `MutableValue` is 8 B, boxed references and object headers
+   *  push the effective footprint higher. Tighter per-type sizing is out
+   *  of scope; TaskMemoryManager remains the hard backstop via spill / OOM. */
+  private val bufferWidthBytes: Long = {
+    val bytesPerField = 16L
+    math.max(1L, bufferDataTypes.size.toLong * bytesPerField)
+  }
+
+  /** Number of aggregate-buffer slots cached per block (see I5).
+   *
+   *  Invariant: equals `sum over levels L of levels(L).length` for any block
+   *  built by [[buildBlockLevels]]: level 0 holds `blockSize` leaves and each
+   *  next level holds `ceil(prev / fanout)` parents until a single root
+   *  remains. For `blockSize == 1` this is 1 (single leaf, no parents). */
+  private val cachedSlotsPerBlock: Long = {
+    var n = blockSize.toLong
+    var sum = n
+    while (n > 1L) {
+      n = (n + fanout - 1) / fanout
+      sum += n
+    }
+    sum
+  }
+
+  /** Bytes accounted per cached block (see I5). Conservative: assumes every
+   *  block is full; tail block leaves a small headroom. */
+  private[this] val blockBytes: Long =
+    math.max(1L, cachedSlotsPerBlock * bufferWidthBytes)
+
+  /** `spans(L)` = number of leaves covered by a single node at level L. Depends
+   *  only on fanout + blockSize, so precomputed once. */
+  private val spans: Array[Int] = {
+    val maxLevel = {
+      var lvl = 0
+      var span = 1L
+      while (span < blockSize) { span *= fanout; lvl += 1 }
+      lvl
+    }
+    val arr = new Array[Int](maxLevel + 1)
+    var s = 1L
+    var i = 0
+    while (i <= maxLevel) {
+      arr(i) = if (s > Int.MaxValue) Int.MaxValue else s.toInt
+      s *= fanout
+      i += 1
+    }
+    arr
+  }
+
+  /** LRU cache of per-block internal node arrays. Key = blockIdx;
+   *  value = `Array[Array[InternalRow]]` with levels(0..h). Auto-eviction
+   *  via `removeEldestEntry` is disabled (I3) -- driven explicitly from
+   *  [[ensureBlockLevels]] or [[SegTreeSpiller.spill]]. Each entry maps 1:1
+   *  to one [[acquireBlockMemory]] accounting. Callers should pass a W-aware
+   *  `maxCachedBlocks` like `ceil(W / blockSize) + 2`. */
+  private val blockLevelsCache: JLinkedHashMap[Integer, Array[Array[InternalRow]]] =
+    new JLinkedHashMap[Integer, Array[Array[InternalRow]]](16, 0.75f, true) {
+      override def removeEldestEntry(
+          eldest: JMap.Entry[Integer, Array[Array[InternalRow]]]): Boolean = false
+    }
+
+  // ---------- Memory consumer ----------
+
+  /**
+   * Private MemoryConsumer tracking cached block levels under TMM. Heap-only
+   * (no Tungsten pages): uses [[MemoryConsumer.acquireMemory]] /
+   * [[MemoryConsumer.freeMemory]], which update the base class `used`
+   * AtomicLong so TMM's consumer-priority sort sees our pressure accurately.
+   *
+   * Hardcoded [[MemoryMode.ON_HEAP]] (not `tmm.getTungstenMemoryMode`): the
+   * cache holds plain JVM objects (`SpecificInternalRow` /
+   * `Array[Array[InternalRow]]`), never Tungsten pages. Under
+   * `spark.memory.offHeap.enabled=true`, enrolling as OFF_HEAP would let
+   * TMM pick us as a spill candidate for off-heap pressure; our `spill()`
+   * would then phantom-credit the off-heap pool without releasing any
+   * off-heap bytes, violating [[TaskMemoryManager#acquireExecutionMemory]]'s
+   * same-pool spill contract. Mirrors
+   * [[org.apache.spark.util.collection.Spillable]], which also hardcodes
+   * ON_HEAP for the same reason. Consequence under off-heap Tungsten: I8
+   * (below) degrades to a no-op because segtree and `rowArray` live in
+   * different pools -- a loss of optimization, not a correctness hazard.
+   *
+   * @note `spill()` MUST NOT call `acquireMemory` (see I1).
+   */
+  private final class SegTreeSpiller extends MemoryConsumer(
+      taskMemoryManager,
+      taskMemoryManager.pageSizeBytes(),
+      MemoryMode.ON_HEAP) {
+    override def spill(size: Long, trigger: MemoryConsumer): Long = {
+      // I2: self-trigger short-circuit (prevent re-entrant eviction).
+      if (trigger eq this) return 0L
+      // I8: rowArray already spilled -- evicting our cache is counter-productive
+      // (rebuild would O(blockStart)-scan the spill file). `spillSize > 0` is
+      // the available "has spilled" signal (UnsafeExternalSorter state is not
+      // public).
+      if (rowArray != null && rowArray.spillSize > 0) return 0L
+      evictUntil(size)
+    }
+  }
+
+  private[this] val spiller: SegTreeSpiller = new SegTreeSpiller
+
+  // ---------- Public API ----------
+
+  def size: Int = numRows
+
+  /**
+   * Build the tree against a caller-owned row array.
+   *
+   * Ownership: the tree holds a reference to `rows` for its lifetime but does
+   * NOT own it -- the caller (typically `WindowPartitionEvaluator.buffer`)
+   * manages `clear()` / lifetime at partition boundaries. `close()` drops
+   * the reference without mutating the array.
+   *
+   * Exception-safe: if aggregation throws, previously built state is preserved.
+   */
+  def build(rows: ExternalAppendOnlyUnsafeRowArray): Unit = {
+    // rows.length is Int by design; check guards against future widening.
+    val n = rows.length
+    if (n < 0) {
+      throw SparkException.internalError(
+        s"WindowSegmentTree cannot hold more than Int.MaxValue rows, got $n")
+    }
+    val nBlocks = if (n == 0) 0 else (n + blockSize - 1) / blockSize
+    val newBlockAggs = computeBlockAggregates(rows, n, nBlocks)
+
+    // Commit.
+    rowArray = rows
+    numRows = n
+    numBlocks = nBlocks
+    blockAggregates = newBlockAggs
+    // Rebuild invalidates cached block levels; release accounting first (I4).
+    releaseAllCachedBlocks()
+  }
+
+  /**
+   * Query [lo, hi) and directly evaluate the result via `processor.evaluate`
+   * into `target`. Uses an internal pre-allocated buffer so no per-call
+   * allocation is needed.
+   */
+  private[window] def queryInto(
+      lo: Int, hi: Int, processor: AggregateProcessor, target: InternalRow): Unit = {
+    query(lo, hi, internalQueryBuffer)
+    processor.evaluate(internalQueryBuffer, target)
+  }
+
+  private[this] val internalQueryBuffer: InternalRow = newBuffer()
+
+  def query(lo: Int, hi: Int, outBuffer: InternalRow): Unit = {
+    if (lo < 0 || hi > numRows || lo > hi) {
+      throw SparkException.internalError(
+        s"Invalid range [lo=$lo, hi=$hi) for size=$numRows")
+    }
+    // Reset outBuffer to identity only after bounds validation.
+    initProj.target(outBuffer)(InternalRow.empty)
+    if (lo == hi) return
+
+    val blo = lo / blockSize
+    val bhi = (hi - 1) / blockSize
+
+    if (blo == bhi) {
+      val blockStart = blo * blockSize
+      mergeBlockRange(blo, lo - blockStart, hi - blockStart, outBuffer)
+    } else {
+      // left partial
+      val loStart = blo * blockSize
+      val loBlockRows = math.min(blockSize, numRows - loStart)
+      mergeBlockRange(blo, lo - loStart, loBlockRows, outBuffer)
+      // full blocks
+      var b = blo + 1
+      while (b < bhi) {
+        mergeInto(outBuffer, blockAggregates(b))
+        b += 1
+      }
+      // right partial
+      val hiStart = bhi * blockSize
+      mergeBlockRange(bhi, 0, hi - hiStart, outBuffer)
+    }
+  }
+
+  /** Terminal: releases all state. Idempotent (I4). */
+  override def close(): Unit = {
+    if (closed) return
+    // Free all cached-block accounting before dropping references.
+    releaseAllCachedBlocks()
+    closeRowArray()
+    blockAggregates = Array.empty
+    numRows = 0
+    numBlocks = 0
+    closed = true
+  }
+
+  // ---------- Test hooks (package-private) ----------
+
+  private[window] def peekBlockCount: Int = numBlocks
+
+  private[window] def testOnlySpiller(): MemoryConsumer = spiller
+
+  /** Test-only accessor for the per-block memory accounting value. */
+  private[window] def peekBlockBytes: Long = blockBytes
+
+  /** NOTE: test-only; promotes block to MRU in the LRU cache as a side effect. */
+  private[window] def peekLevelSize(blockIdx: Int, level: Int): Int = {
+    val levels = ensureBlockLevels(blockIdx)
+    levels(level).length
+  }
+
+  /** NOTE: test-only; promotes block to MRU in the LRU cache as a side effect. */
+  private[window] def peekLevelCount(blockIdx: Int): Int = {
+    val levels = ensureBlockLevels(blockIdx)
+    levels.length
+  }
+
+  // ---------- Internals ----------
+
+  private def computeBlockAggregates(
+      array: ExternalAppendOnlyUnsafeRowArray,
+      n: Int,
+      nBlocks: Int): Array[InternalRow] = {
+    if (n == 0) return Array.empty
+    val result = new Array[InternalRow](nBlocks)
+    val iter = array.generateIterator()
+    var b = 0
+    while (b < nBlocks) {
+      val buf = newBuffer()
+      initProj.target(buf)(InternalRow.empty)
+      val start = b * blockSize
+      val end = math.min(start + blockSize, n)
+      var i = start
+      while (i < end) {
+        if (!iter.hasNext) {
+          throw SparkException.internalError("rowArray iterator exhausted unexpectedly")
+        }
+        val row = iter.next()
+        updateProj.target(buf)(joinedRow(buf, row))
+        i += 1
+      }
+      result(b) = buf
+      b += 1
+    }
+    result
+  }
+
+  /** Merge `src` buffer into `dst` buffer using mergeProj. */
+  private def mergeInto(dst: InternalRow, src: InternalRow): Unit = {
+    mergeProj.target(dst)(joinedRow(dst, src))
+  }
+
+  private def newBuffer(): InternalRow =
+    new SpecificInternalRow(bufferDataTypes)
+
+  /** Merge the given leaf range [lo, hi) inside `blockIdx` into `out`. */
+  private def mergeBlockRange(
+      blockIdx: Int, lo: Int, hi: Int, out: InternalRow): Unit = {
+    if (lo >= hi) return
+    val levels = ensureBlockLevels(blockIdx)
+    val blockRows = levels(0).length
+    val topLevel = levels.length - 1
+    queryDescend(levels, blockRows, topLevel, 0, lo, hi, out)
+  }
+
+  /** Descend the (per-block) segment tree merging any node fully contained
+   *  in [queryLo, queryHi) into `out`. A node at (level L, index idx) covers
+   *  leaves `[idx * span, min((idx+1)*span, blockRows))` where span = F^L. */
+  private def queryDescend(
+      levels: Array[Array[InternalRow]],
+      blockRows: Int,
+      level: Int,
+      idx: Int,
+      queryLo: Int,
+      queryHi: Int,
+      out: InternalRow): Unit = {
+    val span = spans(level)
+    val nodeLo = idx * span
+    val nodeHi = math.min(nodeLo + span, blockRows)
+    if (queryLo >= nodeHi || queryHi <= nodeLo) return
+    if (queryLo <= nodeLo && nodeHi <= queryHi) {
+      mergeInto(out, levels(level)(idx))
+      return
+    }
+    val childLevel = level - 1
+    val childLevelSize = levels(childLevel).length
+    var c = 0
+    while (c < fanout) {
+      val childIdx = idx * fanout + c
+      if (childIdx < childLevelSize) {
+        queryDescend(levels, blockRows, childLevel, childIdx, queryLo, queryHi, out)
+      }
+      c += 1
+    }
+  }
+
+  /** Build (or fetch from LRU) the full per-block levels array.
+   *  Protocol: acquire memory -> build -> cache. Eviction on capacity
+   *  overflow or on TMM spill request. */
+  private def ensureBlockLevels(blockIdx: Int): Array[Array[InternalRow]] = {
+    val cached = blockLevelsCache.get(Integer.valueOf(blockIdx))
+    if (cached != null) return cached
+
+    // Enforce LRU capacity before building a new entry (I3).
+    val cap = maxCachedBlocks.getOrElse(Int.MaxValue)
+    while (blockLevelsCache.size() >= cap) {
+      if (!evictEldest()) return throwCacheEvictFailed(blockIdx)
+    }
+
+    // Acquire accounting; on partial grant, try one manual evict-and-retry.
+    if (!acquireBlockMemory(blockIdx)) {
+      if (!evictEldest() || !acquireBlockMemory(blockIdx)) {
+        // scalastyle:off throwerror
+        throw QueryExecutionErrors.cannotAcquireMemoryForWindowAggregateError(
+          blockBytes, 0L)
+        // scalastyle:on throwerror

Review Comment:
   The OOM error is always constructed with `receivedBytes = 0L`, even though `acquireMemory(blockBytes)` may return a partial grant that is then rolled back in `acquireBlockMemory`. This makes the diagnostic parameters misleading. Consider returning the actual granted bytes from `acquireBlockMemory` (or capturing it) and passing that value into `cannotAcquireMemoryForWindowAggregateError`.



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/window/SegmentTreeWindowFunctionSuite.scala:
##########
@@ -0,0 +1,892 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.execution.window
+
+import org.apache.spark.sql.{DataFrame, Encoder, Encoders, QueryTest, Row}
+import org.apache.spark.sql.expressions.{Aggregator, MutableAggregationBuffer, Window}
+import org.apache.spark.sql.expressions.UserDefinedAggregateFunction
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.test.SharedSparkSession
+import org.apache.spark.sql.types.{DataType, LongType, StructType}
+import org.apache.spark.util.SparkErrorUtils
+
+/**
+ * End-to-end tests for the block-chunked segment-tree moving window frame.
+ * Covers basic aggregates, frame boundaries, min-rows fallback, NULL/NaN,
+ * numeric/string/date-timestamp types, RANGE, Decimal/Binary merge, UDAF
+ * fallback, and frame lifecycle.
+ */
+class SegmentTreeWindowFunctionSuite extends QueryTest with SharedSparkSession {
+
+  import testImplicits._
+
+  // Force seg-tree path regardless of partition size (fallback exercised explicitly).
+  private val enableSegTree: Map[String, String] = Map(
+    SQLConf.WINDOW_SEGMENT_TREE_ENABLED.key -> "true",
+    SQLConf.WINDOW_SEGMENT_TREE_MIN_PARTITION_ROWS.key -> "1")
+
+  private val disableSegTree: Map[String, String] = Map(
+    SQLConf.WINDOW_SEGMENT_TREE_ENABLED.key -> "false")
+
+  /** Build `f(conf)` twice (enabled / disabled) and assert equal results. */
+  private def checkEquivalence(build: () => DataFrame): Unit = {
+    val baseline: Array[Row] = withSQLConf(disableSegTree.toSeq: _*) {
+      build().collect().sortBy(_.toString)
+    }
+    withSQLConf(enableSegTree.toSeq: _*) {
+      val actual = build().collect().sortBy(_.toString)
+      assert(actual.toSeq === baseline.toSeq,
+        s"segment-tree output differs from baseline.\nExpected: ${baseline.toSeq}\n" +
+          s"Actual:   ${actual.toSeq}")
+    }
+  }
+
+  /** Standard fixture: 3 partitions, sizes 40/40/40, values = row index. */
+  private def baseDF: DataFrame = {
+    spark.range(0, 120).selectExpr(
+      "id",
+      "(id % 3) AS pk",
+      "CAST(id AS INT) AS v")
+  }
+
+  private def winSpec(lo: Int, hi: Int) =
+    Window.partitionBy($"pk").orderBy($"id").rowsBetween(lo, hi)
+
+  // A1: basic aggregate equivalence
+
+  test("MIN over ROWS BETWEEN 3 PRECEDING AND 3 FOLLOWING") {
+    checkEquivalence(() =>
+      baseDF.select($"id", $"pk", min($"v").over(winSpec(-3, 3)).as("agg")))
+  }
+
+  test("MAX over ROWS BETWEEN 3 PRECEDING AND 3 FOLLOWING") {
+    checkEquivalence(() =>
+      baseDF.select($"id", $"pk", max($"v").over(winSpec(-3, 3)).as("agg")))
+  }
+
+  test("SUM over ROWS BETWEEN 3 PRECEDING AND 3 FOLLOWING") {
+    checkEquivalence(() =>
+      baseDF.select($"id", $"pk", sum($"v").over(winSpec(-3, 3)).as("agg")))
+  }
+
+  test("COUNT over ROWS BETWEEN 3 PRECEDING AND 3 FOLLOWING") {
+    checkEquivalence(() =>
+      baseDF.select($"id", $"pk", count($"v").over(winSpec(-3, 3)).as("agg")))
+  }
+
+  test("AVG over ROWS BETWEEN 3 PRECEDING AND 3 FOLLOWING") {
+    checkEquivalence(() =>
+      baseDF.select($"id", $"pk", avg($"v").over(winSpec(-3, 3)).as("agg")))
+  }
+
+  test("MIN + MAX + SUM share a single window frame") {
+    checkEquivalence(() =>
+      baseDF.select(
+        $"id",
+        $"pk",
+        min($"v").over(winSpec(-3, 3)).as("mn"),
+        max($"v").over(winSpec(-3, 3)).as("mx"),
+        sum($"v").over(winSpec(-3, 3)).as("sm")))
+  }
+
+  // A2: frame-size boundaries
+
+  test("frame size = 1 (CURRENT ROW only)") {
+    checkEquivalence(() =>
+      baseDF.select($"id", $"pk", sum($"v").over(winSpec(0, 0)).as("agg")))
+  }
+
+  test("frame spans full partition") {
+    checkEquivalence(() =>
+      baseDF.select($"id", $"pk", sum($"v").over(winSpec(-100, 100)).as("agg")))
+  }
+
+  test("frame extends past both partition edges") {
+    checkEquivalence(() =>
+      baseDF.select($"id", $"pk",
+        sum($"v").over(winSpec(-50, 50)).as("agg"),
+        min($"v").over(winSpec(-50, 50)).as("mn"),
+        max($"v").over(winSpec(-50, 50)).as("mx")))
+  }
+
+
+  test("partition below minPartitionRows falls back to SlidingWindowFunctionFrame") {
+    // 5-row partition, min threshold = 10 -> must fall back.
+    val df = spark.range(0, 5).selectExpr(
+      "id", "0 AS pk", "CAST(id AS INT) AS v")
+    val enabledConf = Map(
+      SQLConf.WINDOW_SEGMENT_TREE_ENABLED.key -> "true",
+      SQLConf.WINDOW_SEGMENT_TREE_MIN_PARTITION_ROWS.key -> "10")
+
+    val baseline = withSQLConf(disableSegTree.toSeq: _*) {
+      df.select($"id", sum($"v").over(winSpec(-1, 1)).as("s"))
+        .collect().sortBy(_.toString)
+    }
+    val actual = withSQLConf(enabledConf.toSeq: _*) {
+      df.select($"id", sum($"v").over(winSpec(-1, 1)).as("s"))
+        .collect().sortBy(_.toString)
+    }
+    assert(actual.toSeq === baseline.toSeq)
+
+    // Confirm the fallback flag actually flipped.
+    withSQLConf(enabledConf.toSeq: _*) {
+      SegmentTreeWindowTestHelpers.withSmallPartitionFrame(
+        SQLConf.get, rows = 5) { frame =>
+        assert(frame.fallbackUsed,
+          "expected fallbackUsed=true for partition smaller than minPartitionRows")
+      }
+    }
+  }
+
+
+  test("NTH_VALUE over ROWS frame falls back cleanly (no mergeExpressions crash)") {
+    // NthValue extends DeclarativeAggregate but its mergeExpressions throws
+    // mergeUnsupportedByWindowFunctionError. eligibleForSegTree must exclude it.
+    val df = baseDF
+    val withSegTree = withSQLConf(enableSegTree.toSeq: _*) {
+      df.selectExpr(
+        "id", "pk",
+        "nth_value(v, 3) OVER (PARTITION BY pk ORDER BY id " +
+          "ROWS BETWEEN 5 PRECEDING AND 5 FOLLOWING) AS n3")
+        .collect().sortBy(_.toString)
+    }
+    val baseline = withSQLConf(disableSegTree.toSeq: _*) {
+      df.selectExpr(
+        "id", "pk",
+        "nth_value(v, 3) OVER (PARTITION BY pk ORDER BY id " +
+          "ROWS BETWEEN 5 PRECEDING AND 5 FOLLOWING) AS n3")
+        .collect().sortBy(_.toString)
+    }
+    assert(withSegTree.toSeq === baseline.toSeq)
+  }
+
+  test("ROW_NUMBER over ROWS frame falls back cleanly (no mergeExpressions crash)") {
+    val df = baseDF
+    val withSegTree = withSQLConf(enableSegTree.toSeq: _*) {
+      df.selectExpr(
+        "id", "pk",
+        "row_number() OVER (PARTITION BY pk ORDER BY id) AS rn")
+        .collect().sortBy(_.toString)
+    }
+    val baseline = withSQLConf(disableSegTree.toSeq: _*) {
+      df.selectExpr(
+        "id", "pk",
+        "row_number() OVER (PARTITION BY pk ORDER BY id) AS rn")
+        .collect().sortBy(_.toString)
+    }
+    assert(withSegTree.toSeq === baseline.toSeq)
+  }
+
+  // A3: NULL/NaN/Infinity; A4: numeric/string/date-timestamp types.
+  // Unsupported-merge / DISTINCT / feature-flag fallback.
+  // Oracle: run with seg-tree enabled and disabled, assert equal Row sequences.
+
+  // A3: NULL / special values
+
+  test("all-NULL column: MIN/MAX/SUM/AVG/COUNT") {
+    val df = spark.range(0, 30).selectExpr(
+      "id", "(id % 3) AS pk", "CAST(NULL AS INT) AS v")
+    checkEquivalence(() =>
+      df.select($"id", $"pk",
+        min($"v").over(winSpec(-3, 3)).as("mn"),
+        max($"v").over(winSpec(-3, 3)).as("mx"),
+        sum($"v").over(winSpec(-3, 3)).as("sm"),
+        avg($"v").over(winSpec(-3, 3)).as("av"),
+        count($"v").over(winSpec(-3, 3)).as("cn")))
+  }
+
+  test("mixed NULL and non-NULL: NULLs must not leak into MIN/MAX") {
+    // Every 3rd value is NULL. Aggregates must skip them (NULL-agnostic merge).
+    val df = spark.range(0, 60).selectExpr(
+      "id",
+      "(id % 3) AS pk",
+      "CASE WHEN id % 3 = 0 THEN NULL ELSE CAST(id AS INT) END AS v")
+    checkEquivalence(() =>
+      df.select($"id", $"pk",
+        min($"v").over(winSpec(-4, 4)).as("mn"),
+        max($"v").over(winSpec(-4, 4)).as("mx"),
+        sum($"v").over(winSpec(-4, 4)).as("sm"),
+        count($"v").over(winSpec(-4, 4)).as("cn")))
+  }
+
+  test("Double NaN and +/-Infinity propagate correctly through MIN/MAX/SUM") {
+    // Trap: NaN > +Inf in Spark's MIN/MAX ordering; +Inf + -Inf = NaN in SUM.
+    // Seg-tree uses DeclarativeAggregate.merge; behavior must match baseline.
+    val df = spark.range(0, 30).selectExpr(
+      "id",
+      "(id % 2) AS pk",
+      """CASE
+           WHEN id % 7 = 0 THEN double('NaN')
+           WHEN id % 7 = 1 THEN double('Infinity')
+           WHEN id % 7 = 2 THEN double('-Infinity')
+           ELSE CAST(id AS DOUBLE)
+         END AS v""")
+    checkEquivalence(() =>
+      df.select($"id", $"pk",
+        min($"v").over(winSpec(-3, 3)).as("mn"),
+        max($"v").over(winSpec(-3, 3)).as("mx"),
+        sum($"v").over(winSpec(-3, 3)).as("sm")))
+  }
+
+  // A4: data types
+
+  test("numeric types: Int / Long / Double / Decimal") {
+    val df = spark.range(0, 60).selectExpr(
+      "id",
+      "(id % 3) AS pk",
+      "CAST(id AS INT)             AS vi",
+      "CAST(id * 1000000L AS LONG) AS vl",
+      "CAST(id AS DOUBLE) + 0.25   AS vd",
+      "CAST(id AS DECIMAL(20,4))   AS vdec")
+    checkEquivalence(() =>
+      df.select($"id", $"pk",
+        sum($"vi").over(winSpec(-2, 2)).as("si"),
+        min($"vl").over(winSpec(-2, 2)).as("ml"),
+        max($"vd").over(winSpec(-2, 2)).as("xd"),
+        sum($"vdec").over(winSpec(-2, 2)).as("sdec"),
+        avg($"vdec").over(winSpec(-2, 2)).as("adec")))
+  }
+
+  test("String lexicographic MIN/MAX") {
+    // Non-monotone values so MIN/MAX exercise the seg-tree merge (not edge).
+    val df = spark.range(0, 40).selectExpr(
+      "id",
+      "(id % 2) AS pk",
+      "CONCAT('s', LPAD(CAST((id * 37) % 97 AS STRING), 3, '0')) AS v")
+    checkEquivalence(() =>
+      df.select($"id", $"pk",
+        min($"v").over(winSpec(-3, 3)).as("mn"),
+        max($"v").over(winSpec(-3, 3)).as("mx")))
+  }
+
+  test("Date / Timestamp MIN/MAX") {
+    val df = spark.range(0, 40).selectExpr(
+      "id",
+      "(id % 2) AS pk",
+      "date_add(DATE'2020-01-01', CAST((id * 13) % 365 AS INT)) AS vd",
+      "CAST(TIMESTAMP'2020-01-01 00:00:00' + " +
+        "make_interval(0, 0, 0, 0, 0, 0, CAST(id AS DECIMAL(18,6))) AS TIMESTAMP) AS vt")
+    checkEquivalence(() =>
+      df.select($"id", $"pk",
+        min($"vd").over(winSpec(-3, 3)).as("mnd"),
+        max($"vd").over(winSpec(-3, 3)).as("mxd"),
+        min($"vt").over(winSpec(-3, 3)).as("mnt"),
+        max($"vt").over(winSpec(-3, 3)).as("mxt")))
+  }
+
+
+  test("collect_list falls back cleanly (non-DeclarativeAggregate)") {
+    // collect_list is TypedImperativeAggregate; eligibleForSegTree must decline.
+    checkEquivalence(() =>
+      baseDF.select($"id", $"pk",
+        collect_list($"v").over(winSpec(-2, 2)).as("lst")))
+  }
+
+  test("DISTINCT window aggregate is rejected by analyzer regardless of seg-tree flag") {
+    // Analyzer throws DISTINCT_WINDOW_FUNCTION_UNSUPPORTED before frame
+    // construction; seg-tree flag must not alter this behavior.
+    def run(): Unit = {
+      baseDF.select($"id", $"pk",
+        count_distinct($"v").over(winSpec(-3, 3)).as("cd")).collect()
+    }
+    withSQLConf(disableSegTree.toSeq: _*) {
+      val e = intercept[org.apache.spark.sql.AnalysisException](run())
+      assert(e.getMessage.contains("DISTINCT_WINDOW_FUNCTION_UNSUPPORTED"))
+    }
+    withSQLConf(enableSegTree.toSeq: _*) {
+      val e = intercept[org.apache.spark.sql.AnalysisException](run())
+      assert(e.getMessage.contains("DISTINCT_WINDOW_FUNCTION_UNSUPPORTED"))
+    }
+  }
+
+  test("feature flag off: segmentTree.enabled=false yields baseline semantics") {
+    // Sanity: disabling the flag on a seg-tree-eligible workload still
+    // produces the SlidingWindowFunctionFrame answer.
+    val df = baseDF
+    val expected = withSQLConf(disableSegTree.toSeq: _*) {
+      df.select($"id", $"pk", min($"v").over(winSpec(-3, 3)).as("mn"))
+        .collect().sortBy(_.toString).toSeq
+    }
+    withSQLConf(
+      SQLConf.WINDOW_SEGMENT_TREE_ENABLED.key -> "false",
+      SQLConf.WINDOW_SEGMENT_TREE_MIN_PARTITION_ROWS.key -> "1024") {
+      val actual = df.select($"id", $"pk", min($"v").over(winSpec(-3, 3)).as("mn"))
+        .collect().sortBy(_.toString).toSeq
+      assert(actual === expected)
+    }
+  }
+
+    // A5: RANGE frame equivalence (single-order-expr admission).
+  // MIN/MAX non-invertible, guaranteeing seg-tree path is exercised.
+
+  /** Run `sql` twice (flag off / on) and checkAnswer equality. */
+  private def checkRangeEquivalence(df: DataFrame, query: String): Unit = {
+    df.createOrReplaceTempView("t")
+    try {
+      val baseline = withSQLConf(disableSegTree.toSeq: _*) {
+        spark.sql(query).collect().sortBy(_.toString)
+      }
+      withSQLConf(enableSegTree.toSeq: _*) {
+        val actual = spark.sql(query).collect().sortBy(_.toString)
+        assert(actual.toSeq === baseline.toSeq,
+          s"segment-tree output differs from baseline.\nExpected: ${baseline.toSeq}\n" +
+            s"Actual:   ${actual.toSeq}")
+      }
+    } finally {
+      spark.catalog.dropTempView("t")
+    }
+  }
+
+  test("-- RANGE INT offset basic (non-uniform gaps, MIN/MAX)") {
+    // Non-uniform gaps so admit/drop loops must consult the order-key comparator.
+    val df = spark.range(0, 40).selectExpr(
+      "CAST(id AS INT) AS id",
+      "(CAST(id AS INT) % 2) AS pk",
+      "CAST(CASE CAST(id AS INT) % 7 " +
+        "WHEN 0 THEN 1 WHEN 1 THEN 3 WHEN 2 THEN 4 WHEN 3 THEN 4 " +
+        "WHEN 4 THEN 7 WHEN 5 THEN 10 ELSE 15 END + (CAST(id AS INT) / 7) * 20 AS INT) AS k",
+      "CAST((id * 31) % 97 AS INT) AS v")
+    checkRangeEquivalence(df,
+      """SELECT id, pk,
+        |  MIN(v) OVER (PARTITION BY pk ORDER BY k
+        |    RANGE BETWEEN 2 PRECEDING AND 2 FOLLOWING) AS mn,
+        |  MAX(v) OVER (PARTITION BY pk ORDER BY k
+        |    RANGE BETWEEN 2 PRECEDING AND 2 FOLLOWING) AS mx
+        |FROM t""".stripMargin)
+  }
+
+  test("-- RANGE Timestamp with INTERVAL offset (MAX)") {
+    // Irregular gaps force the timestamp comparator at the 1-hour boundary.
+    val df = spark.range(0, 30).selectExpr(
+      "CAST(id AS INT) AS id",
+      "(CAST(id AS INT) % 2) AS pk",
+      "CAST(TIMESTAMP'2024-01-01 10:00:00' + " +
+        "make_interval(0, 0, 0, 0, 0, 30 * CAST(id AS INT) * " +
+        "(CASE CAST(id AS INT) % 3 WHEN 0 THEN 1 WHEN 1 THEN 3 ELSE 4 END), 0) " +
+        "AS TIMESTAMP) AS ts",
+      "CAST((id * 17) % 53 AS INT) AS v")
+    checkRangeEquivalence(df,
+      """SELECT id, pk,
+        |  MAX(v) OVER (PARTITION BY pk ORDER BY ts
+        |    RANGE BETWEEN INTERVAL '1' HOUR PRECEDING
+        |              AND INTERVAL '1' HOUR FOLLOWING) AS mx
+        |FROM t""".stripMargin)
+  }
+
+  test("-- RANGE with tie (duplicate order keys) inclusion at boundary") {
+    // Trap: RANGE `0 PRECEDING AND 0 FOLLOWING` must include the FULL tie
+    // group at the current row's key, not just the current row. A ROWS-vs-
+    // RANGE confusion would return per-row MIN/MAX instead of group-level.
+    val rows = (0 until 40).map { i =>
+      val k = Seq(1, 2, 2, 2, 3, 4, 5)(i % 7)
+      (i, i % 2, k, (i * 13) % 41)
+    }
+    val df = rows.toDF("id", "pk", "k", "v")
+    checkRangeEquivalence(df,
+      """SELECT id, pk, k,
+        |  MIN(v) OVER (PARTITION BY pk ORDER BY k
+        |    RANGE BETWEEN 0 PRECEDING AND 0 FOLLOWING) AS mn,
+        |  MAX(v) OVER (PARTITION BY pk ORDER BY k
+        |    RANGE BETWEEN 0 PRECEDING AND 0 FOLLOWING) AS mx
+        |FROM t""".stripMargin)
+  }
+
+  test("-- RANGE frame wider than partition (C4: admit/drop loops no-op)") {
+    // Once the first batch is admitted, admit/drop must detect no change
+    // and skip work.
+    val df = spark.range(0, 25).selectExpr(
+      "CAST(id AS INT) AS id",
+      "(CAST(id AS INT) / 5) AS pk",
+      "CAST((id * 7) % 23 AS INT) AS k",
+      "CAST((id * 19) % 101 AS INT) AS v")
+    checkRangeEquivalence(df,
+      """SELECT id, pk,
+        |  MIN(v) OVER (PARTITION BY pk ORDER BY k
+        |    RANGE BETWEEN 100 PRECEDING AND 100 FOLLOWING) AS mn,
+        |  MAX(v) OVER (PARTITION BY pk ORDER BY k
+        |    RANGE BETWEEN 100 PRECEDING AND 100 FOLLOWING) AS mx
+        |FROM t""".stripMargin)
+  }
+
+  test("-- RANGE with NULL order key (NULLS FIRST / NULLS LAST)") {
+    // Trap: Spark groups all NULLs into a single equivalence class at head
+    // (NULLS FIRST) or tail (NULLS LAST); seg-tree must treat NULL as a
+    // tie group identical to the sliding baseline.
+    val rows = (0 until 36).map { i =>
+      val kOpt: Option[Int] = (i % 6) match {
+        case 0 | 1 | 5 => None
+        case 2 => Some(1)
+        case 3 => Some(2)
+        case _ => Some(3)
+      }
+      (i, i % 2, kOpt, (i * 11) % 37)
+    }
+    val df = rows.toDF("id", "pk", "k", "v")
+    checkRangeEquivalence(df,
+      """SELECT id, pk,
+        |  MIN(v) OVER (PARTITION BY pk ORDER BY k ASC NULLS FIRST
+        |    RANGE BETWEEN 1 PRECEDING AND 1 FOLLOWING) AS mn_nf,
+        |  MAX(v) OVER (PARTITION BY pk ORDER BY k ASC NULLS FIRST
+        |    RANGE BETWEEN 1 PRECEDING AND 1 FOLLOWING) AS mx_nf,
+        |  MIN(v) OVER (PARTITION BY pk ORDER BY k ASC NULLS LAST
+        |    RANGE BETWEEN 1 PRECEDING AND 1 FOLLOWING) AS mn_nl,
+        |  MAX(v) OVER (PARTITION BY pk ORDER BY k ASC NULLS LAST
+        |    RANGE BETWEEN 1 PRECEDING AND 1 FOLLOWING) AS mx_nl
+        |FROM t""".stripMargin)
+  }
+
+    // Decimal overflow / BinaryType MIN/MAX across block merge; UDAF fallback.
+  // Trap: blockSize=16 is SQLConf minimum; frame > blockSize ensures the
+  // seg-tree merge path is actually crossed.
+
+  private val segTreeBlock: String = "16"
+  private val segTreeFramePrec: Int = 17
+  private val segTreeRows: Int = 20
+
+  private def withSegTreeBlock(conf: (String, String)*)(body: => Unit): Unit = {
+    val extra = Seq(SQLConf.WINDOW_SEGMENT_TREE_BLOCK_SIZE.key -> segTreeBlock) ++ conf
+    withSQLConf(extra: _*)(body)
+  }
+
+
+  /**
+   * 20 rows in one partition, Decimal(38, 0) values near the type's upper
+   * bound; frame of `segTreeFramePrec` PRECEDING..CURRENT ROW makes any
+   * >=2-row window overflow Sum. Block 16 + frame 17 forces cross-block merge.
+   */
+  private def decimalOverflowDF: DataFrame = {
+    // 9e37 -- below Decimal(38,0) MAX (~9.99e37), but 2x overflows.
+    val big = "90000000000000000000000000000000000000"  // 38 digits
+    spark.range(0, segTreeRows.toLong).selectExpr(
+      "CAST(id AS INT) AS id",
+      "0 AS pk",
+      s"CAST('$big' AS DECIMAL(38, 0)) AS v")
+  }
+
+  private val decimalOverflowSql: String =
+    s"""SELECT id, pk,
+       |  SUM(v) OVER (PARTITION BY pk ORDER BY id
+       |    ROWS BETWEEN $segTreeFramePrec PRECEDING AND CURRENT ROW) AS s
+       |FROM t""".stripMargin
+
+  test("a -- Decimal overflow ANSI on, seg-tree matches sliding (both throw)") {
+    val df = decimalOverflowDF
+    df.createOrReplaceTempView("t")
+    try {
+      withSegTreeBlock(SQLConf.ANSI_ENABLED.key -> "true") {
+        withSQLConf(disableSegTree.toSeq: _*) {
+          val e = intercept[Exception] {
+            spark.sql(decimalOverflowSql).collect()
+          }
+          assert(hasArithmeticCause(e),
+            s"expected ArithmeticException root cause, got: ${e.getMessage}")
+        }
+        withSQLConf(enableSegTree.toSeq: _*) {
+          val e = intercept[Exception] {
+            spark.sql(decimalOverflowSql).collect()
+          }
+          assert(hasArithmeticCause(e),
+            s"expected ArithmeticException root cause, got: ${e.getMessage}")
+        }
+      }
+    } finally {
+      spark.catalog.dropTempView("t")
+    }
+  }
+
+  test("b -- Decimal overflow ANSI off, seg-tree matches sliding (NULL on overflow)") {
+    val df = decimalOverflowDF
+    df.createOrReplaceTempView("t")
+    try {
+      withSegTreeBlock(SQLConf.ANSI_ENABLED.key -> "false") {
+        val baseline = withSQLConf(disableSegTree.toSeq: _*) {
+          spark.sql(decimalOverflowSql).collect().sortBy(_.toString)
+        }
+        // At least one row must be NULL so we know overflow actually fired.
+        assert(baseline.exists(_.isNullAt(2)),
+          "baseline should contain NULL overflow rows; test data may be too small")
+        withSQLConf(enableSegTree.toSeq: _*) {
+          val actual = spark.sql(decimalOverflowSql).collect().sortBy(_.toString)
+          assert(actual.toSeq === baseline.toSeq)
+        }
+      }
+    } finally {
+      spark.catalog.dropTempView("t")
+    }
+  }
+
+  test("c -- mid-window Decimal overflow slides past (seg-tree == sliding)") {
+    // Big values at ids 14..17 straddle block boundary at id=16, so any
+    // 4-row window overlapping >=2 of them overflows (-> NULL when ANSI off)
+    // and cross-block merge sees overflowing buffers. Rows past id=20 slide
+    // clear and recover non-NULL.
+    val big = "90000000000000000000000000000000000000"
+    val df = spark.range(0, 24).selectExpr(
+      "CAST(id AS INT) AS id",
+      "0 AS pk",
+      s"""CASE WHEN id IN (14, 15, 16, 17)
+              THEN CAST('$big' AS DECIMAL(38, 0))
+              ELSE CAST(id AS DECIMAL(38, 0))
+         END AS v""")
+    df.createOrReplaceTempView("t")
+    try {
+      val sqlStr =
+        """SELECT id, pk,
+          |  SUM(v) OVER (PARTITION BY pk ORDER BY id
+          |    ROWS BETWEEN 3 PRECEDING AND CURRENT ROW) AS s
+          |FROM t""".stripMargin
+      withSegTreeBlock(SQLConf.ANSI_ENABLED.key -> "false") {
+        val baseline = withSQLConf(disableSegTree.toSeq: _*) {
+          spark.sql(sqlStr).collect().sortBy(_.toString)
+        }
+        // Sanity: overflow fired AND later rows recover non-NULL.
+        assert(baseline.exists(_.isNullAt(2)),
+          "baseline should contain NULL overflow rows")
+        assert(baseline.exists(r => r.getInt(0) >= 21 && !r.isNullAt(2)),
+          "rows with id>=21 should be non-NULL (window slid past big values)")
+        withSQLConf(enableSegTree.toSeq: _*) {
+          val actual = spark.sql(sqlStr).collect().sortBy(_.toString)
+          assert(actual.toSeq === baseline.toSeq)
+        }
+      }
+    } finally {
+      spark.catalog.dropTempView("t")
+    }
+  }
+
+  /** True iff the root cause of `t` is an [[ArithmeticException]] (ANSI overflow). */
+  private def hasArithmeticCause(t: Throwable): Boolean =
+    Option(SparkErrorUtils.getRootCause(t)).exists(_.isInstanceOf[ArithmeticException])
+
+
+  /** Pattern of 20 Array[Byte] values used across a. */
+  private def binaryVariedRows: Seq[(Int, Array[Byte])] = {
+    (0 until 20).map { i =>
+      val arr: Array[Byte] = (i % 8) match {
+        case 0 => Array[Byte](0x01, 0x02)
+        case 1 => Array[Byte](0x00)
+        case 2 => Array[Byte](0x7f)
+        case 3 => Array[Byte](0x7f, 0x00)
+        case 4 => Array[Byte](0x10, 0x20, 0x30)
+        case 5 => Array[Byte](0x10, 0x20)
+        case 6 => Array[Byte](0x10)
+        case _ => Array[Byte](0x05, 0x05, 0x05, 0x05)
+      }
+      (i, arr)
+    }
+  }
+
+  test("a -- BinaryType MIN/MAX cross-block merge") {
+    // Varied lengths/content; frame > blockSize guarantees merge path hit.
+    val df = binaryVariedRows.toDF("id", "v").selectExpr("id", "0 AS pk", "v")
+    df.createOrReplaceTempView("t")
+    try {
+      withSegTreeBlock() {
+        val sqlStr =
+          s"""SELECT id, pk,
+             |  MIN(v) OVER (PARTITION BY pk ORDER BY id
+             |    ROWS BETWEEN $segTreeFramePrec PRECEDING AND CURRENT ROW) AS mn,
+             |  MAX(v) OVER (PARTITION BY pk ORDER BY id
+             |    ROWS BETWEEN $segTreeFramePrec PRECEDING AND CURRENT ROW) AS mx
+             |FROM t""".stripMargin
+        val baseline = withSQLConf(disableSegTree.toSeq: _*) {
+          spark.sql(sqlStr).collect().sortBy(_.toString)
+        }
+        withSQLConf(enableSegTree.toSeq: _*) {
+          val actual = spark.sql(sqlStr).collect().sortBy(_.toString)

Review Comment:
   These BinaryType tests sort collected Rows by `_.toString`, but `Row.toString` will include JVM address-based `Array[Byte].toString`, so baseline vs actual can sort into different orders even when results are identical. Prefer sorting by stable columns (e.g. `id`) or using `prepareAnswer(..., isSorted = false)` / `sameRows` from `QueryTest`, which normalizes binary values before sorting.
   ```suggestion
             spark.sql(sqlStr).collect().sortBy(_.getInt(0))
           }
           withSQLConf(enableSegTree.toSeq: _*) {
             val actual = spark.sql(sqlStr).collect().sortBy(_.getInt(0))
   ```



-- 
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@spark.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-56546][SQL] Block-chunked segment-tree window frame for non-invertible sliding aggregates [spark]

Posted by "yaooqinn (via GitHub)" <gi...@apache.org>.
yaooqinn commented on code in PR #55422:
URL: https://github.com/apache/spark/pull/55422#discussion_r3123445243


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowExec.scala:
##########
@@ -91,7 +91,12 @@ case class WindowExec(
     child: SparkPlan)
   extends WindowExecBase {
   override lazy val metrics: Map[String, SQLMetric] = Map(
-    "spillSize" -> SQLMetrics.createSizeMetric(sparkContext, "spill size")
+    "spillSize" -> SQLMetrics.createSizeMetric(sparkContext, "spill size"),
+    "numSegmentTreeFrames" ->
+      SQLMetrics.createMetric(sparkContext, "number of segment-tree frames"),

Review Comment:
   Renamed to `"number of segment-tree frames prepared"` / `"number of segment-tree fallback frames prepared"` — keeps Spark's `"number of ..."` metric-naming convention while adopting the `prepared` verb to make explicit these are per-frame setup events, not per-row bumps. Dropped `(per partition)` since SQLMetrics is already partition-aggregated in the UI. Updated `SegmentTreeWindowMetricsSuite` and `WindowSegmentTreeAllowlistSuite` to match.
   
   Commit: a12ec858ec5
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowEvaluatorFactoryBase.scala:
##########
@@ -295,4 +342,58 @@ trait WindowEvaluatorFactoryBase {
     }
   }
 
+  /**
+   * Segment-tree path eligibility. The tree relies on
+   * `DeclarativeAggregate.mergeExpressions`, which [[AggregateWindowFunction]]s
+   * (NthValue, NTile, Rank, RowNumber, NullIndex) refuse via
+   * `mergeUnsupportedByWindowFunctionError`: they extend DeclarativeAggregate
+   * but are NOT merge-capable. Normal aggregate window expressions reach this
+   * code as the inner DeclarativeAggregate unwrapped from
+   * [[AggregateExpression]] (see `windowFrameExpressionFactoryPairs.collect`).
+   */
+  private def eligibleForSegTree(
+      functions: Array[Expression],
+      filters: Array[Option[Expression]],
+      frameType: FrameType): Boolean = {
+    // RANGE accepted only for single-column order specs. Multi-column RANGE
+    // with non-zero offset is already rejected by `createBoundOrdering`, so
+    // gating here on `orderSpec.size == 1` matches the Sliding-path invariant.
+    val frameTypeOk = frameType match {
+      case RowFrame => true
+      case RangeFrame => orderSpec.size == 1
+    }
+    SQLConf.get.windowSegmentTreeEnabled &&
+      frameTypeOk &&
+      filters.forall(_.isEmpty) &&

Review Comment:
   Added the defensive test in `WindowSegmentTreeAllowlistSuite` — asserts that `AGG(x) FILTER (WHERE p) OVER (...)` does not take the segment-tree path (commit 511f72931ee).
   
   One premise clarification: I traced the existing analyzer/optimizer rules that touch `AggregateExpression.filter`, and the only one is `EliminateAggregateFilter`, which folds `Literal.TrueLiteral` / `FalseLiteral` — it doesn't rewrite `FILTER (WHERE p)` into `If(p, x, null)` or otherwise strip a non-literal predicate. So `filters.forall(_.isEmpty)` is a sound gate today. The new test is a sentinel: if any future rule ever erases a non-trivial `filter`, this suite fails and forces an explicit eligibility review before the filtered aggregate silently admits into segtree.
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowSegmentTree.scala:
##########
@@ -0,0 +1,592 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.execution.window
+
+import java.util.{LinkedHashMap => JLinkedHashMap, Map => JMap}
+
+import scala.collection.mutable
+
+import org.apache.spark.SparkException
+import org.apache.spark.memory.{MemoryConsumer, MemoryMode, TaskMemoryManager}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.expressions.aggregate.{Average, Count, DeclarativeAggregate, Max, Min, StddevPop, StddevSamp, Sum, VariancePop, VarianceSamp}
+import org.apache.spark.sql.errors.QueryExecutionErrors
+import org.apache.spark.sql.execution.ExternalAppendOnlyUnsafeRowArray
+import org.apache.spark.sql.types.DataType
+import org.apache.spark.util.ArrayImplicits._
+
+/**
+ * Block-chunked segment tree for moving-frame window aggregates. Partitions are
+ * split into blocks of `blockSize` rows; each block has its own small segtree
+ * (fanout `F`, height `h`). Block roots stay resident; internal nodes are cached
+ * in an LRU keyed by block index. Queries cost O(log W).
+ *
+ * Memory accounting invariants:
+ *  - I1: `SegTreeSpiller.spill()` MUST NOT call `acquireMemory` on its own
+ *        consumer (would deadlock TMM's consumer-priority sort). All acquires
+ *        happen on the hot path ([[ensureBlockLevels]]).
+ *  - I2: `spill(_, trigger)` returns 0 when `trigger eq this` (self-trigger
+ *        short-circuit) to prevent re-entrant eviction.
+ *  - I3: LRU `removeEldestEntry` is disabled; eviction is driven explicitly
+ *        from [[ensureBlockLevels]] or [[SegTreeSpiller.spill]].
+ *  - I4: Every successful [[acquireBlockMemory]] is paired with exactly one
+ *        [[releaseBlockMemory]]. [[close]] is idempotent.
+ *  - I5: Per-block bytes are a conservative upper bound (full block, 16 B/field).
+ *  - I8: If `rowArray` already spilled to disk, `spill` returns 0 (rebuild
+ *        would O(blockStart)-scan the spill file).
+ *
+ * @note Instances are not thread-safe.
+ */
+private[window] class WindowSegmentTree(
+    functions: Array[DeclarativeAggregate],
+    inputSchema: Seq[Attribute],
+    newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
+    fanout: Int = WindowSegmentTree.DefaultFanout,
+    blockSize: Int = WindowSegmentTree.DefaultBlockSize,
+    maxCachedBlocks: Option[Int] = None,
+    taskMemoryManager: TaskMemoryManager = null)
+  extends AutoCloseable {
+
+  require(fanout >= 2, s"fanout must be >= 2, got $fanout")
+  require(blockSize >= 1, s"blockSize must be >= 1, got $blockSize")
+  require(functions.nonEmpty, "WindowSegmentTree requires at least one aggregate function")
+  maxCachedBlocks.foreach { n =>
+    require(n >= 1, s"maxCachedBlocks must be >= 1 when specified, got $n")
+  }
+  require(taskMemoryManager != null,
+    "WindowSegmentTree requires a non-null TaskMemoryManager; " +
+      "in tests use `new TaskMemoryManager(new TestMemoryManager(conf), 0)`")
+
+  // ---------- Schemas & projections ----------
+
+  private val bufferAttrs: Seq[AttributeReference] =
+    functions.flatMap(_.aggBufferAttributes).toImmutableArraySeq
+  private val rightAttrs: Seq[AttributeReference] =
+    functions.flatMap(_.inputAggBufferAttributes).toImmutableArraySeq
+  private val bufferDataTypes: IndexedSeq[DataType] =
+    bufferAttrs.map(_.dataType).toIndexedSeq
+
+  private val initialValues: Seq[Expression] = functions.flatMap(_.initialValues).toIndexedSeq
+  private val updateExpressions: Seq[Expression] =
+    functions.flatMap(_.updateExpressions).toIndexedSeq
+  private val mergeExpressions: Seq[Expression] =
+    functions.flatMap(_.mergeExpressions).toIndexedSeq
+
+  private[this] val initProj: MutableProjection = newMutableProjection(initialValues, Nil)
+  private[this] val updateProj: MutableProjection =
+    newMutableProjection(updateExpressions, bufferAttrs ++ inputSchema)
+  private[this] val mergeProj: MutableProjection =
+    newMutableProjection(mergeExpressions, bufferAttrs ++ rightAttrs)
+
+  private[this] val joinedRow = new JoinedRow()
+
+  // ---------- State ----------
+
+  private var numRows: Int = 0
+  private var numBlocks: Int = 0
+  private var rowArray: ExternalAppendOnlyUnsafeRowArray = _
+  private var closed: Boolean = false
+
+  /** Always-resident per-block root aggregates: `blockAggregates(i)` =
+   *  merged buffer over all rows in block i. */
+  private var blockAggregates: Array[InternalRow] = Array.empty
+
+  /** Conservative byte width of one aggregate buffer row at 16 B/field:
+   *  primitive `MutableValue` is 8 B, boxed references and object headers
+   *  push the effective footprint higher. Tighter per-type sizing is out
+   *  of scope; TaskMemoryManager remains the hard backstop via spill / OOM. */
+  private val bufferWidthBytes: Long = {
+    val bytesPerField = 16L
+    math.max(1L, bufferDataTypes.size.toLong * bytesPerField)
+  }
+
+  /** Number of aggregate-buffer slots cached per block (see I5).
+   *
+   *  Invariant: equals `sum over levels L of levels(L).length` for any block
+   *  built by [[buildBlockLevels]]: level 0 holds `blockSize` leaves and each
+   *  next level holds `ceil(prev / fanout)` parents until a single root
+   *  remains. For `blockSize == 1` this is 1 (single leaf, no parents). */
+  private val cachedSlotsPerBlock: Long = {
+    var n = blockSize.toLong
+    var sum = n
+    while (n > 1L) {
+      n = (n + fanout - 1) / fanout
+      sum += n
+    }
+    sum
+  }
+
+  /** Bytes accounted per cached block (see I5). Conservative: assumes every
+   *  block is full; tail block leaves a small headroom. */
+  private[this] val blockBytes: Long =
+    math.max(1L, cachedSlotsPerBlock * bufferWidthBytes)
+
+  /** `spans(L)` = number of leaves covered by a single node at level L. Depends
+   *  only on fanout + blockSize, so precomputed once. */
+  private val spans: Array[Int] = {
+    val maxLevel = {
+      var lvl = 0
+      var span = 1L
+      while (span < blockSize) { span *= fanout; lvl += 1 }
+      lvl
+    }
+    val arr = new Array[Int](maxLevel + 1)
+    var s = 1L
+    var i = 0
+    while (i <= maxLevel) {
+      arr(i) = if (s > Int.MaxValue) Int.MaxValue else s.toInt
+      s *= fanout
+      i += 1
+    }
+    arr
+  }
+
+  /** LRU cache of per-block internal node arrays. Key = blockIdx;
+   *  value = `Array[Array[InternalRow]]` with levels(0..h). Auto-eviction
+   *  via `removeEldestEntry` is disabled (I3) -- driven explicitly from
+   *  [[ensureBlockLevels]] or [[SegTreeSpiller.spill]]. Each entry maps 1:1
+   *  to one [[acquireBlockMemory]] accounting. Callers should pass a W-aware
+   *  `maxCachedBlocks` like `ceil(W / blockSize) + 2`. */
+  private val blockLevelsCache: JLinkedHashMap[Integer, Array[Array[InternalRow]]] =
+    new JLinkedHashMap[Integer, Array[Array[InternalRow]]](16, 0.75f, true) {
+      override def removeEldestEntry(
+          eldest: JMap.Entry[Integer, Array[Array[InternalRow]]]): Boolean = false
+    }
+
+  // ---------- Memory consumer ----------
+
+  /**
+   * Private MemoryConsumer tracking cached block levels under TMM. Heap-only
+   * (no Tungsten pages): uses [[MemoryConsumer.acquireMemory]] /
+   * [[MemoryConsumer.freeMemory]], which update the base class `used`
+   * AtomicLong so TMM's consumer-priority sort sees our pressure accurately.
+   *
+   * Hardcoded [[MemoryMode.ON_HEAP]] (not `tmm.getTungstenMemoryMode`): the
+   * cache holds plain JVM objects (`SpecificInternalRow` /
+   * `Array[Array[InternalRow]]`), never Tungsten pages. Under
+   * `spark.memory.offHeap.enabled=true`, enrolling as OFF_HEAP would let
+   * TMM pick us as a spill candidate for off-heap pressure; our `spill()`
+   * would then phantom-credit the off-heap pool without releasing any
+   * off-heap bytes, violating [[TaskMemoryManager#acquireExecutionMemory]]'s
+   * same-pool spill contract. Mirrors
+   * [[org.apache.spark.util.collection.Spillable]], which also hardcodes
+   * ON_HEAP for the same reason. Consequence under off-heap Tungsten: I8
+   * (below) degrades to a no-op because segtree and `rowArray` live in
+   * different pools -- a loss of optimization, not a correctness hazard.
+   *
+   * @note `spill()` MUST NOT call `acquireMemory` (see I1).
+   */
+  private final class SegTreeSpiller extends MemoryConsumer(
+      taskMemoryManager,
+      taskMemoryManager.pageSizeBytes(),
+      MemoryMode.ON_HEAP) {
+    override def spill(size: Long, trigger: MemoryConsumer): Long = {
+      // I2: self-trigger short-circuit (prevent re-entrant eviction).
+      if (trigger eq this) return 0L
+      // I8: rowArray already spilled -- evicting our cache is counter-productive
+      // (rebuild would O(blockStart)-scan the spill file). `spillSize > 0` is
+      // the available "has spilled" signal (UnsafeExternalSorter state is not
+      // public).
+      if (rowArray != null && rowArray.spillSize > 0) return 0L
+      evictUntil(size)
+    }
+  }
+
+  private[this] val spiller: SegTreeSpiller = new SegTreeSpiller
+
+  // ---------- Public API ----------
+
+  def size: Int = numRows
+
+  /**
+   * Build the tree against a caller-owned row array.
+   *
+   * Ownership: the tree holds a reference to `rows` for its lifetime but does
+   * NOT own it -- the caller (typically `WindowPartitionEvaluator.buffer`)
+   * manages `clear()` / lifetime at partition boundaries. `close()` drops
+   * the reference without mutating the array.
+   *
+   * Exception-safe: if aggregation throws, previously built state is preserved.
+   */
+  def build(rows: ExternalAppendOnlyUnsafeRowArray): Unit = {
+    // rows.length is Int by design; check guards against future widening.
+    val n = rows.length
+    if (n < 0) {
+      throw SparkException.internalError(
+        s"WindowSegmentTree cannot hold more than Int.MaxValue rows, got $n")
+    }
+    val nBlocks = if (n == 0) 0 else (n + blockSize - 1) / blockSize
+    val newBlockAggs = computeBlockAggregates(rows, n, nBlocks)
+
+    // Commit.
+    rowArray = rows
+    numRows = n
+    numBlocks = nBlocks
+    blockAggregates = newBlockAggs
+    // Rebuild invalidates cached block levels; release accounting first (I4).
+    releaseAllCachedBlocks()
+  }
+
+  /**
+   * Query [lo, hi) and directly evaluate the result via `processor.evaluate`
+   * into `target`. Uses an internal pre-allocated buffer so no per-call
+   * allocation is needed.
+   */
+  private[window] def queryInto(
+      lo: Int, hi: Int, processor: AggregateProcessor, target: InternalRow): Unit = {
+    query(lo, hi, internalQueryBuffer)
+    processor.evaluate(internalQueryBuffer, target)
+  }
+
+  private[this] val internalQueryBuffer: InternalRow = newBuffer()
+
+  def query(lo: Int, hi: Int, outBuffer: InternalRow): Unit = {
+    if (lo < 0 || hi > numRows || lo > hi) {
+      throw SparkException.internalError(
+        s"Invalid range [lo=$lo, hi=$hi) for size=$numRows")
+    }
+    // Reset outBuffer to identity only after bounds validation.
+    initProj.target(outBuffer)(InternalRow.empty)
+    if (lo == hi) return
+
+    val blo = lo / blockSize
+    val bhi = (hi - 1) / blockSize
+
+    if (blo == bhi) {
+      val blockStart = blo * blockSize
+      mergeBlockRange(blo, lo - blockStart, hi - blockStart, outBuffer)
+    } else {
+      // left partial
+      val loStart = blo * blockSize
+      val loBlockRows = math.min(blockSize, numRows - loStart)
+      mergeBlockRange(blo, lo - loStart, loBlockRows, outBuffer)
+      // full blocks
+      var b = blo + 1
+      while (b < bhi) {
+        mergeInto(outBuffer, blockAggregates(b))
+        b += 1
+      }
+      // right partial
+      val hiStart = bhi * blockSize
+      mergeBlockRange(bhi, 0, hi - hiStart, outBuffer)
+    }
+  }
+
+  /** Terminal: releases all state. Idempotent (I4). */
+  override def close(): Unit = {
+    if (closed) return
+    // Free all cached-block accounting before dropping references.
+    releaseAllCachedBlocks()
+    closeRowArray()
+    blockAggregates = Array.empty
+    numRows = 0
+    numBlocks = 0
+    closed = true
+  }
+
+  // ---------- Test hooks (package-private) ----------
+
+  private[window] def peekBlockCount: Int = numBlocks
+
+  private[window] def testOnlySpiller(): MemoryConsumer = spiller
+
+  /** Test-only accessor for the per-block memory accounting value. */
+  private[window] def peekBlockBytes: Long = blockBytes
+
+  /** NOTE: test-only; promotes block to MRU in the LRU cache as a side effect. */
+  private[window] def peekLevelSize(blockIdx: Int, level: Int): Int = {
+    val levels = ensureBlockLevels(blockIdx)
+    levels(level).length
+  }
+
+  /** NOTE: test-only; promotes block to MRU in the LRU cache as a side effect. */
+  private[window] def peekLevelCount(blockIdx: Int): Int = {
+    val levels = ensureBlockLevels(blockIdx)
+    levels.length
+  }
+
+  // ---------- Internals ----------
+
+  private def computeBlockAggregates(
+      array: ExternalAppendOnlyUnsafeRowArray,
+      n: Int,
+      nBlocks: Int): Array[InternalRow] = {
+    if (n == 0) return Array.empty
+    val result = new Array[InternalRow](nBlocks)
+    val iter = array.generateIterator()
+    var b = 0
+    while (b < nBlocks) {
+      val buf = newBuffer()
+      initProj.target(buf)(InternalRow.empty)
+      val start = b * blockSize
+      val end = math.min(start + blockSize, n)
+      var i = start
+      while (i < end) {
+        if (!iter.hasNext) {
+          throw SparkException.internalError("rowArray iterator exhausted unexpectedly")
+        }
+        val row = iter.next()
+        updateProj.target(buf)(joinedRow(buf, row))
+        i += 1
+      }
+      result(b) = buf
+      b += 1
+    }
+    result
+  }
+
+  /** Merge `src` buffer into `dst` buffer using mergeProj. */
+  private def mergeInto(dst: InternalRow, src: InternalRow): Unit = {
+    mergeProj.target(dst)(joinedRow(dst, src))
+  }
+
+  private def newBuffer(): InternalRow =
+    new SpecificInternalRow(bufferDataTypes)
+
+  /** Merge the given leaf range [lo, hi) inside `blockIdx` into `out`. */
+  private def mergeBlockRange(
+      blockIdx: Int, lo: Int, hi: Int, out: InternalRow): Unit = {
+    if (lo >= hi) return
+    val levels = ensureBlockLevels(blockIdx)
+    val blockRows = levels(0).length
+    val topLevel = levels.length - 1
+    queryDescend(levels, blockRows, topLevel, 0, lo, hi, out)
+  }
+
+  /** Descend the (per-block) segment tree merging any node fully contained
+   *  in [queryLo, queryHi) into `out`. A node at (level L, index idx) covers
+   *  leaves `[idx * span, min((idx+1)*span, blockRows))` where span = F^L. */
+  private def queryDescend(
+      levels: Array[Array[InternalRow]],
+      blockRows: Int,
+      level: Int,
+      idx: Int,
+      queryLo: Int,
+      queryHi: Int,
+      out: InternalRow): Unit = {
+    val span = spans(level)
+    val nodeLo = idx * span
+    val nodeHi = math.min(nodeLo + span, blockRows)
+    if (queryLo >= nodeHi || queryHi <= nodeLo) return
+    if (queryLo <= nodeLo && nodeHi <= queryHi) {
+      mergeInto(out, levels(level)(idx))
+      return
+    }
+    val childLevel = level - 1
+    val childLevelSize = levels(childLevel).length
+    var c = 0
+    while (c < fanout) {
+      val childIdx = idx * fanout + c
+      if (childIdx < childLevelSize) {
+        queryDescend(levels, blockRows, childLevel, childIdx, queryLo, queryHi, out)
+      }
+      c += 1
+    }
+  }
+
+  /** Build (or fetch from LRU) the full per-block levels array.
+   *  Protocol: acquire memory -> build -> cache. Eviction on capacity
+   *  overflow or on TMM spill request. */
+  private def ensureBlockLevels(blockIdx: Int): Array[Array[InternalRow]] = {
+    val cached = blockLevelsCache.get(Integer.valueOf(blockIdx))
+    if (cached != null) return cached
+
+    // Enforce LRU capacity before building a new entry (I3).
+    val cap = maxCachedBlocks.getOrElse(Int.MaxValue)
+    while (blockLevelsCache.size() >= cap) {
+      if (!evictEldest()) return throwCacheEvictFailed(blockIdx)
+    }
+
+    // Acquire accounting; on partial grant, try one manual evict-and-retry.
+    if (!acquireBlockMemory(blockIdx)) {
+      if (!evictEldest() || !acquireBlockMemory(blockIdx)) {
+        // scalastyle:off throwerror
+        throw QueryExecutionErrors.cannotAcquireMemoryForWindowAggregateError(
+          blockBytes, 0L)
+        // scalastyle:on throwerror
+      }
+    }
+
+    // If buildBlockLevels throws, release the just-acquired memory (I4).
+    val levels =
+      try buildBlockLevels(blockIdx)
+      catch { case t: Throwable => releaseBlockMemory(); throw t }
+    blockLevelsCache.put(Integer.valueOf(blockIdx), levels)
+    levels
+  }
+
+  private def buildBlockLevels(blockIdx: Int): Array[Array[InternalRow]] = {
+    val blockStart = blockIdx * blockSize
+    val blockRows = math.min(blockSize, numRows - blockStart)
+
+    // Level 0: one aggregate per row in the block.
+    val leaves = new Array[InternalRow](blockRows)
+    val iter = rowArray.generateIterator(blockStart)
+    var i = 0
+    while (i < blockRows) {
+      if (!iter.hasNext) {
+        throw SparkException.internalError(
+          s"rowArray iterator exhausted at block $blockIdx row $i")
+      }
+      val row = iter.next()
+      val buf = newBuffer()
+      initProj.target(buf)(InternalRow.empty)
+      updateProj.target(buf)(joinedRow(buf, row))
+      leaves(i) = buf
+      i += 1
+    }
+
+    val allLevels = mutable.ArrayBuffer[Array[InternalRow]](leaves)
+    var prev = leaves
+    while (prev.length > 1) {
+      val parentCount = (prev.length + fanout - 1) / fanout
+      val parents = new Array[InternalRow](parentCount)
+      var p = 0
+      while (p < parentCount) {
+        val buf = newBuffer()
+        initProj.target(buf)(InternalRow.empty)
+        val childStart = p * fanout
+        val childEnd = math.min(childStart + fanout, prev.length)
+        var c = childStart
+        while (c < childEnd) {
+          mergeInto(buf, prev(c))
+          c += 1
+        }
+        parents(p) = buf
+        p += 1
+      }
+      allLevels += parents
+      prev = parents
+    }
+    allLevels.toArray
+  }
+
+  private def throwCacheEvictFailed(blockIdx: Int): Nothing = {
+    throw SparkException.internalError(
+      s"LRU cache eviction failed for block $blockIdx (size=${blockLevelsCache.size})")
+  }
+
+  // ---------- Memory accounting helpers ----------
+
+  /** Try to acquire `blockBytes` for one cached block. Returns true on full
+   *  grant, false on partial (after rolling the partial grant back). Must
+   *  not be called from within [[SegTreeSpiller.spill]] (I1). */
+  private def acquireBlockMemory(blockIdx: Int): Boolean = {
+    val granted = spiller.acquireMemory(blockBytes)
+    if (granted < blockBytes) {
+      if (granted > 0) spiller.freeMemory(granted)
+      false
+    } else {
+      true
+    }
+  }
+
+  /** Release the accounting for one block. Caller ensures pairing with a
+   *  prior successful [[acquireBlockMemory]] (I4). */
+  private def releaseBlockMemory(): Unit = {
+    spiller.freeMemory(blockBytes)
+  }
+
+  /** Evict LRU blocks until `target` bytes have been freed (or cache is
+   *  empty). Returns freed bytes. Called from [[SegTreeSpiller.spill]]. */
+  private def evictUntil(target: Long): Long = {
+    var freed = 0L
+    while (freed < target && !blockLevelsCache.isEmpty) {
+      freed += evictEldestReturnBytes()
+    }
+    freed
+  }
+
+  /** Evict one LRU block. Returns true if a block was evicted. */
+  private def evictEldest(): Boolean = {
+    if (blockLevelsCache.isEmpty) return false
+    evictEldestReturnBytes()
+    true
+  }
+
+  private def evictEldestReturnBytes(): Long = {
+    val it = blockLevelsCache.entrySet().iterator()
+    if (!it.hasNext) return 0L
+    val head = it.next()
+    it.remove()
+    releaseBlockMemory()
+    blockBytes
+  }
+
+  /** Release accounting for all cached blocks and clear the cache. */
+  private def releaseAllCachedBlocks(): Unit = {
+    val n = blockLevelsCache.size()
+    if (n > 0) {
+      blockLevelsCache.clear()
+      spiller.freeMemory(n.toLong * blockBytes)
+    }
+  }
+
+  private def closeRowArray(): Unit = {
+    // rowArray is caller-owned (see `build` docstring); drop the reference only.
+    rowArray = null
+  }
+}
+
+private[window] object WindowSegmentTree {
+  val DefaultFanout: Int = 16
+  val DefaultBlockSize: Int = 65536
+
+  /**
+   * Explicit allowlist of [[DeclarativeAggregate]] subclasses safe for
+   * segment-tree execution. Safe iff combine semantics form a commutative
+   * monoid on the partial-buffer representation (associativity +
+   * compatibility with `mergeExpressions`):
+   *
+   *   - [[Min]], [[Max]]: idempotent semilattice.
+   *   - [[Sum]], [[Count]]: additive monoid.
+   *   - [[Average]]: sum + count, both additive monoids.
+   *   - [[StddevPop]], [[StddevSamp]], [[VariancePop]], [[VarianceSamp]]:
+   *     Welford (count, mean, M2) is associative -- see
+   *     CentralMomentAgg.mergeExpressions.
+   *
+   * Intentionally excluded (tracked as follow-up): HyperLogLogPlusPlus /
+   * ApproxCountDistinct (sketch-buffer interaction unaudited), First / Last
+   * (order-dependent), CollectList / CollectSet (unbounded buffer growth),
+   * Percentile / ApproxPercentile (sorted-sketch buffer), and any
+   * ImperativeAggregate (excluded by the type check).
+   *
+   * Callers should use [[isEligible]] rather than `contains` directly.
+   */
+  val EligibleAggregates: Set[Class[_ <: DeclarativeAggregate]] = Set(
+    classOf[Min],
+    classOf[Max],
+    classOf[Sum],
+    classOf[Count],
+    classOf[Average],
+    classOf[StddevPop],
+    classOf[StddevSamp],
+    classOf[VariancePop],
+    classOf[VarianceSamp]
+  )
+
+  /**
+   * Returns true iff `f` is a [[DeclarativeAggregate]] on the explicit segment-tree
+   * allowlist. See [[EligibleAggregates]] for the rationale and excluded aggregates.
+   */
+  def isEligible(f: Expression): Boolean = f match {
+    case agg: DeclarativeAggregate => EligibleAggregates.contains(agg.getClass)

Review Comment:
   Thanks for the suggestion. Before I apply it I'd like to confirm the intent, since the two forms differ in safety posture:
   
   - `contains(agg.getClass)` — precise class equality. Subclasses of the 9 listed aggregates are rejected and take the fallback path.
   - `exists(_.isInstance(agg))` — accepts subclasses too.
   
   The monoid-safety argument in the `EligibleAggregates` scaladoc is established **per concrete class**: `Min`/`Max` idempotent semilattice, `Sum`/`Count` additive monoid, Welford for the variance/stddev family, etc. A subclass that overrides `mergeExpressions` in a non-associative way would silently take the segment-tree path under `isInstance`, whereas `contains` forces an explicit audit-and-add step.
   
   Spark currently has zero non-test subclasses of these 9 classes, so both forms are behaviorally identical today. The question is the design posture for future subclasses:
   
   1. If the suggestion is a Scala-idiom preference, I'd prefer to keep `contains` and extend the scaladoc to spell out "precise class equality by design — subclasses must be audited and added to the allowlist explicitly."
   2. If you'd like the allowlist to be inheritance-open, I can switch to `isInstance` and add a scaladoc warning that any subclass overriding `mergeExpressions` must preserve associativity.
   
   Either is fine — I just want to be sure we pick the one you intended.
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowEvaluatorFactoryBase.scala:
##########
@@ -295,4 +342,58 @@ trait WindowEvaluatorFactoryBase {
     }
   }
 
+  /**
+   * Segment-tree path eligibility. The tree relies on
+   * `DeclarativeAggregate.mergeExpressions`, which [[AggregateWindowFunction]]s
+   * (NthValue, NTile, Rank, RowNumber, NullIndex) refuse via
+   * `mergeUnsupportedByWindowFunctionError`: they extend DeclarativeAggregate
+   * but are NOT merge-capable. Normal aggregate window expressions reach this
+   * code as the inner DeclarativeAggregate unwrapped from
+   * [[AggregateExpression]] (see `windowFrameExpressionFactoryPairs.collect`).
+   */
+  private def eligibleForSegTree(
+      functions: Array[Expression],
+      filters: Array[Option[Expression]],
+      frameType: FrameType): Boolean = {
+    // RANGE accepted only for single-column order specs. Multi-column RANGE
+    // with non-zero offset is already rejected by `createBoundOrdering`, so
+    // gating here on `orderSpec.size == 1` matches the Sliding-path invariant.
+    val frameTypeOk = frameType match {
+      case RowFrame => true
+      case RangeFrame => orderSpec.size == 1

Review Comment:
   Thanks for the detailed coverage checklist — let me break these into buckets so we can agree on PR scope before I push a ~200 LoC test+bench commit.
   
   **Already covered (verified in `SegmentTreeWindowFunctionSuite`):**
   - `RANGE with tie (duplicate order keys) inclusion at boundary` covers endpoint-tie inclusion for `RANGE 0 PRECEDING AND 0 FOLLOWING`.
   - Block-boundary traps are exercised on `Row` frames at `blockSize=16` (SQLConf min) in several tests (`varied lengths ... frame > blockSize`, etc.).
   
   **Straightforward to add in this PR (proposal: yes):**
   - (a) Non-zero-offset RANGE tie cases — `RANGE 1 PRECEDING AND 1 FOLLOWING` with duplicated order keys at both endpoints. Handful of SQL tests.
   - (b-partial) RANGE × block-boundary: parametrize the existing varied-length suite over `blockSize ∈ {16, 32, 128}` for RANGE frames.
   - (c) RANGE-produced empty frames — sparse order keys such that a narrow `RANGE n PRECEDING AND n FOLLOWING` emits zero rows for some current-row positions.
   
   **Requires infrastructure work (proposal: follow-up JIRA):**
   - (d) `WindowSegmentTreePropertySuite` parametrized over `FrameType`. The current suite drives row-by-row through an in-memory `WindowSegmentTree`; RANGE semantics need bound-ordering + order-key generation that matches the executor path, which is a non-trivial harness extension. Happy to file as a subtask.
   - (e) `estimateMaxCachedBlocks` RangeFrame default `Some(8)` thrashing at `W >> 8·blockSize`. The current value is a static fallback (RANGE width is data-dependent, so no static width inference is possible). A proper fix needs a dedicated thrash-boundary benchmark + a data-aware heuristic; I'd prefer to split this out so the benchmark numbers and heuristic can be iterated independently without regating this PR's 3-JDK bench pipeline again. Follow-up JIRA works for me.
   
   Does this split look right? If you'd rather see (d) or (e) in this PR, I'll fold them in — just want to avoid another full bench re-run if it's deferrable.
   



-- 
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@spark.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-56546][SQL] Block-chunked segment-tree window frame for non-invertible sliding aggregates [spark]

Posted by "yaooqinn (via GitHub)" <gi...@apache.org>.
yaooqinn commented on code in PR #55422:
URL: https://github.com/apache/spark/pull/55422#discussion_r3124361905


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/SegmentTreeWindowFunctionFrame.scala:
##########
@@ -0,0 +1,280 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.execution.window
+
+import org.apache.spark.TaskContext
+import org.apache.spark.memory.TaskMemoryManager
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, Expression, FrameType, MutableProjection, RangeFrame, RowFrame, UnsafeRow}
+import org.apache.spark.sql.catalyst.expressions.aggregate.DeclarativeAggregate
+import org.apache.spark.sql.execution.ExternalAppendOnlyUnsafeRowArray
+import org.apache.spark.sql.execution.metric.SQLMetric
+import org.apache.spark.sql.internal.SQLConf
+
+/**
+ * Moving-frame window function frame backed by [[WindowSegmentTree]]. Produces
+ * the same outputs as [[SlidingWindowFunctionFrame]] for RowFrame or
+ * single-column RangeFrame moving frames whose aggregate functions are all
+ * [[DeclarativeAggregate]] with no FILTER/DISTINCT. For partitions below
+ * `spark.sql.window.segmentTree.minPartitionRows`, delegates to a wrapped
+ * [[SlidingWindowFunctionFrame]].
+ *
+ * See `docs/frame-integration-contract.md` Section 1 for the full contract.
+ *
+ * RANGE support (RANGE frame support): when `frameType == RangeFrame`, the per-row
+ * driver uses two forward-only cursors (`lowerIter` / `upperIter`) over the
+ * materialized `rowArray` to advance `lowerBound` / `upperBound`. Endpoints
+ * are monotone per partition (SQL RANGE semantics + sorted input), so total
+ * cursor work is O(n). The segment tree then answers `[lowerBound,
+ * upperBound)` in O(log n).
+ *
+ * @note Not thread-safe.
+ */
+private[window] final class SegmentTreeWindowFunctionFrame(
+    target: InternalRow,
+    processor: AggregateProcessor,
+    functions: Array[DeclarativeAggregate],
+    inputSchema: Seq[Attribute],
+    frameType: FrameType,
+    lbound: BoundOrdering,
+    ubound: BoundOrdering,
+    newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
+    conf: SQLConf,
+    maxCachedBlocks: Option[Int],
+    taskMemoryManager: TaskMemoryManager,
+    numSegmentTreeFrames: Option[SQLMetric] = None,
+    numSegmentTreeFallbackFrames: Option[SQLMetric] = None)
+  extends WindowFunctionFrame with AutoCloseable {
+
+  require(frameType == RowFrame || frameType == RangeFrame,
+    s"SegmentTreeWindowFunctionFrame supports RowFrame or RangeFrame, got $frameType")
+
+  private[this] val fallback =
+    new SlidingWindowFunctionFrame(target, processor, lbound, ubound)
+  private[this] var tree: WindowSegmentTree = _
+
+  // ---- RowFrame-only driver state ----
+  // `boundIter` advances `upperBound` one row at a time (sliding admit loop);
+  // the lower bound is inferred from pure index arithmetic under RowFrame.
+  private[this] var boundIter: Iterator[UnsafeRow] = _
+  private[this] var nextRow: UnsafeRow = _
+
+  // ---- RangeFrame-only driver state ----
+  // Two cursors over `rowArray`; `lowerRow` / `upperRow` hold the currently-
+  // buffered head of each cursor (pre-fetched in `prepare` -- fix so
+  // `RangeBoundOrdering.compare` is never called with a null row on round 0).
+  //
+  // Spill-safety invariant: when `rowArray` spills, its iterator reuses a
+  // single `UnsafeRow` object whose pointer is rebound on each `next()`.
+  // That is tolerated here because the cursor is **read-before-advance**:
+  // each `writeRange` loop iteration reads `lowerRow`/`upperRow` for
+  // comparison before calling `getNextOrNull(...)`. Between `write()`
+  // calls the pointer's content is stable (this frame is the sole consumer
+  // of each iterator). DO NOT cache a historical row into a separate field
+  // without an explicit `.copy()`; the shared reusable UnsafeRow would
+  // silently mutate.
+  private[this] var lowerIter: Iterator[UnsafeRow] = _
+  private[this] var upperIter: Iterator[UnsafeRow] = _
+  private[this] var lowerRow: UnsafeRow = _
+  private[this] var upperRow: UnsafeRow = _
+
+  // Shared endpoints: monotone across `write()` calls within a partition.
+  private[this] var lowerBound: Int = 0
+  private[this] var upperBound: Int = 0
+
+  /**
+   * Runtime dispatch flag: when `true`, `write()`, `currentLowerBound()`,
+   * and `currentUpperBound()` delegate to the wrapped
+   * [[SlidingWindowFunctionFrame]] (small-partition path). Set by
+   * `prepare()` based on partition size vs.
+   * `spark.sql.window.segmentTree.minPartitionRows`.
+   */
+  private[window] var fallbackUsed: Boolean = false
+
+  // Register close() once per frame instance so the tree's block cache and
+  // any open row-array iterators are released when the task completes.
+  // Keeping the registration here (vs. inside the factory closure) avoids
+  // duplicate listeners when the factory is invoked multiple times per task.
+  {
+    val tc = TaskContext.get()
+    if (tc != null) {
+      tc.addTaskCompletionListener[Unit](_ => close())
+    }
+  }
+
+  override def prepare(rows: ExternalAppendOnlyUnsafeRowArray): Unit = {
+    // First-call hygiene: release prior tree/iterators/cursors before building
+    // the new tree. `prepare` is called exactly once per (partition, frame) by
+    // `WindowPartitionEvaluator.fetchNextPartition` (the sole call site); this
+    // mirrors `SlidingWindowFunctionFrame`, which has no guard. Counters bump
+    // unconditionally on the successful branch.
+    if (tree != null) {
+      tree.close()
+      tree = null
+    }
+    closeIters()
+    nextRow = null
+    lowerRow = null
+    upperRow = null
+    lowerBound = 0
+    upperBound = 0
+    if (rows.length < conf.windowSegmentTreeMinPartitionRows) {
+      fallbackUsed = true
+      fallback.prepare(rows)
+      // Count only on the successful fallback path: if `fallback.prepare`
+      // throws, the counter is not bumped.
+      numSegmentTreeFallbackFrames.foreach(_ += 1)
+      return
+    }
+    fallbackUsed = false
+    tree = new WindowSegmentTree(
+      functions,
+      inputSchema,
+      newMutableProjection,
+      fanout = conf.windowSegmentTreeFanout,
+      blockSize = conf.windowSegmentTreeBlockSize,
+      maxCachedBlocks = maxCachedBlocks,
+      taskMemoryManager = taskMemoryManager)
+    // Build first (drains rows into the tree's internal row array), then
+    // open fresh iterator(s) for per-row bound advancement.
+    tree.build(rows.generateIterator())
+    // Count only on the successful segtree path: if `tree.build` throws
+    // (e.g. OOM during block allocation), the counter is not bumped.
+    numSegmentTreeFrames.foreach(_ += 1)
+    frameType match {
+      case RowFrame =>
+        boundIter = rows.generateIterator()
+        nextRow = WindowFunctionFrame.getNextOrNull(boundIter)
+      case RangeFrame =>
+        lowerIter = rows.generateIterator()
+        upperIter = rows.generateIterator()
+        // Pre-seed cursor heads so `RangeBoundOrdering.compare` (which
+        // projects the input row to a scalar) never dereferences null on
+        // round 0. Either may legitimately be null if `rows` is
+        // empty; the advance loops' `!= null` / `< upperBound` guards
+        // handle that.
+        lowerRow = WindowFunctionFrame.getNextOrNull(lowerIter)
+        upperRow = WindowFunctionFrame.getNextOrNull(upperIter)
+    }
+  }
+
+  override def write(index: Int, current: InternalRow): Unit = {
+    if (fallbackUsed) {
+      fallback.write(index, current)
+      return
+    }
+    frameType match {
+      case RowFrame => writeRow(index, current)
+      case RangeFrame => writeRange(index, current)
+    }
+  }
+
+  private def writeRow(index: Int, current: InternalRow): Unit = {

Review Comment:
   The duplication is intentional and documented in `f8109f1e77b` — added a comment on `writeRow`/`writeRange` noting they mirror `SlidingWindowFunctionFrame.write`'s `(lowerBound, upperBound)` monotone-cursor invariant, with admit-then-drop (no buffer to maintain) instead of drop-then-admit.
   
   Equivalence is guarded by `SegmentTreeWindowFunctionSuite`'s flag-on/off tests (`checkRangeEquivalence`, `feature flag off ...`, fallback suite), which compare segtree output against the Sliding baseline for identical queries — any future drift in Sliding's boundary semantics will fail these.
   
   I considered extracting a shared `MonotoneAdmitDropCursor`, but the two frames diverge on state (Sliding maintains an `ArrayDeque`, segtree keeps only cursors) and on admit-branch semantics (Sliding fuses admit+drop via `if (lbound.compare…) lowerBound += 1 else buffer.add`, segtree splits them). A shared helper would need ≥2 callback hooks and would touch the Sliding hot path, which seems disproportionate for this PR. Happy to revisit if you'd prefer.



-- 
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@spark.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-56546][SQL] Block-chunked segment-tree window frame for non-invertible sliding aggregates [spark]

Posted by "yaooqinn (via GitHub)" <gi...@apache.org>.
yaooqinn commented on PR #55422:
URL: https://github.com/apache/spark/pull/55422#issuecomment-4395401247

   HI @dongjoon-hyun, can you take another look?
   


-- 
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@spark.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [WIP][SPARK-56546][SQL] Block-chunked segment-tree window frame for non-invertible sliding aggregates [spark]

Posted by "yaooqinn (via GitHub)" <gi...@apache.org>.
yaooqinn commented on code in PR #55422:
URL: https://github.com/apache/spark/pull/55422#discussion_r3115435106


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowEvaluatorFactoryBase.scala:
##########
@@ -191,13 +200,17 @@ trait WindowEvaluatorFactoryBase {
         // in a single Window physical node. Therefore, we can assume no SQL aggregation
         // functions if Pandas UDF exists. In the future, we might mix Pandas UDF and SQL
         // aggregation function in a single physical node.
-        def processor = if (functions.exists(_.isInstanceOf[PythonFuncExpression])) {
+        val aggFilters: Array[Option[Expression]] = expressions.map {
+          case WindowExpression(ae: AggregateExpression, _) => ae.filter
+          case _ => None
+        }.toArray
+        // Shared per (key) across the factory closure's invocations; each
+        // Frame calls `processor.initialize(...)` in `prepare`, so cross-
+        // partition reuse is safe. Previously `def`, which re-allocated on
+        // every factory application (keeping listener registration idempotent).

Review Comment:
   Addressed in `79e42da60ad` (R3-cleanup-oss). Thank you for the advice!



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowSegmentTree.scala:
##########
@@ -0,0 +1,610 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.execution.window
+
+import java.util.{LinkedHashMap => JLinkedHashMap, Map => JMap}
+
+import scala.collection.mutable
+
+import org.apache.spark.{SparkEnv, SparkException, TaskContext}
+import org.apache.spark.memory.{MemoryConsumer, TaskMemoryManager}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.expressions.aggregate.DeclarativeAggregate
+import org.apache.spark.sql.errors.QueryExecutionErrors
+import org.apache.spark.sql.execution.ExternalAppendOnlyUnsafeRowArray
+import org.apache.spark.sql.types.DataType
+import org.apache.spark.util.ArrayImplicits._
+
+/**
+ * Block-chunked segment tree for range aggregate queries over window partitions.
+ *
+ * See `the class documentation`
+ * for the full design (API contract Section 2, block-chunked memory layout Section 3,
+ * DeclarativeAggregate binding Section 4, error handling Section 5, test hooks Section 6).
+ *
+ * initial implementation scope: correctness only. The data layer uses
+ * `ExternalAppendOnlyUnsafeRowArray` to hold input rows (spillable). Each
+ * block materializes its own small segment tree (levels 0..h). Internal
+ * nodes are cached in an LRU keyed by block index; block root aggregates
+ * (block pre-aggregates) stay resident for all blocks.
+ *
+ * Note: the design doc Section 3.3 specifies leaves are NOT materialized and
+ * recomputed from the spillable array on demand. For initial implementation simplicity
+ * we materialize leaves inside the per-block internal node arrays.
+ * // TODO(SPARK-XXXXX) re-assess after Frame integration.

Review Comment:
   Addressed in `79e42da60ad` (R3-cleanup-oss). Thank you for the advice!



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowSegmentTree.scala:
##########
@@ -0,0 +1,610 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.execution.window
+
+import java.util.{LinkedHashMap => JLinkedHashMap, Map => JMap}
+
+import scala.collection.mutable
+
+import org.apache.spark.{SparkEnv, SparkException, TaskContext}
+import org.apache.spark.memory.{MemoryConsumer, TaskMemoryManager}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.expressions.aggregate.DeclarativeAggregate
+import org.apache.spark.sql.errors.QueryExecutionErrors
+import org.apache.spark.sql.execution.ExternalAppendOnlyUnsafeRowArray
+import org.apache.spark.sql.types.DataType
+import org.apache.spark.util.ArrayImplicits._
+
+/**
+ * Block-chunked segment tree for range aggregate queries over window partitions.
+ *
+ * See `the class documentation`
+ * for the full design (API contract Section 2, block-chunked memory layout Section 3,
+ * DeclarativeAggregate binding Section 4, error handling Section 5, test hooks Section 6).
+ *
+ * initial implementation scope: correctness only. The data layer uses
+ * `ExternalAppendOnlyUnsafeRowArray` to hold input rows (spillable). Each
+ * block materializes its own small segment tree (levels 0..h). Internal
+ * nodes are cached in an LRU keyed by block index; block root aggregates
+ * (block pre-aggregates) stay resident for all blocks.
+ *
+ * Note: the design doc Section 3.3 specifies leaves are NOT materialized and
+ * recomputed from the spillable array on demand. For initial implementation simplicity
+ * we materialize leaves inside the per-block internal node arrays.
+ * // TODO(SPARK-XXXXX) re-assess after Frame integration.
+ *
+ * @note Instances are not thread-safe.
+ */
+private[window] class WindowSegmentTree(
+    functions: Array[DeclarativeAggregate],
+    inputSchema: Seq[Attribute],
+    newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
+    fanout: Int = WindowSegmentTree.DefaultFanout,
+    blockSize: Int = WindowSegmentTree.DefaultBlockSize,
+    maxCachedBlocks: Option[Int] = None,
+    spillThreshold: Int = Int.MaxValue,
+    inMemoryThreshold: Int = Int.MaxValue,
+    taskMemoryManager: TaskMemoryManager = null)
+  extends AutoCloseable {
+
+  require(fanout >= 2, s"fanout must be >= 2, got $fanout")
+  require(blockSize >= 1, s"blockSize must be >= 1, got $blockSize")
+  require(functions.nonEmpty, "WindowSegmentTree requires at least one aggregate function")
+  maxCachedBlocks.foreach { n =>
+    require(n >= 1, s"maxCachedBlocks must be >= 1 when specified, got $n")
+  }
+  require(taskMemoryManager != null,
+    "WindowSegmentTree requires a non-null TaskMemoryManager; " +
+      "in tests use `new TaskMemoryManager(new TestMemoryManager(conf), 0)`")
+
+  // ---------- Schemas & projections ----------
+
+  private val bufferAttrs: Seq[AttributeReference] =
+    functions.flatMap(_.aggBufferAttributes).toImmutableArraySeq
+  private val rightAttrs: Seq[AttributeReference] =
+    functions.flatMap(_.inputAggBufferAttributes).toImmutableArraySeq
+  private val bufferDataTypes: IndexedSeq[DataType] =
+    bufferAttrs.map(_.dataType).toIndexedSeq
+
+  private val initialValues: Seq[Expression] = functions.flatMap(_.initialValues).toIndexedSeq
+  private val updateExpressions: Seq[Expression] =
+    functions.flatMap(_.updateExpressions).toIndexedSeq
+  private val mergeExpressions: Seq[Expression] =
+    functions.flatMap(_.mergeExpressions).toIndexedSeq
+
+  private[this] val initProj: MutableProjection = newMutableProjection(initialValues, Nil)
+  private[this] val updateProj: MutableProjection =
+    newMutableProjection(updateExpressions, bufferAttrs ++ inputSchema)
+  private[this] val mergeProj: MutableProjection =
+    newMutableProjection(mergeExpressions, bufferAttrs ++ rightAttrs)
+
+  private val inputUnsafeProj: UnsafeProjection =
+    UnsafeProjection.create(inputSchema.map(_.dataType).toArray)
+
+  private[this] val joinedRow = new JoinedRow()
+
+  // ---------- State ----------
+
+  private var numRows: Int = 0
+  private var numBlocks: Int = 0
+  private var rowArray: ExternalAppendOnlyUnsafeRowArray = _
+  private var closed: Boolean = false
+
+  /** Always-resident per-block root aggregates. `blockAggregates(i)` =
+   *  merged buffer over all rows in block i. */
+  private var blockAggregates: Array[InternalRow] = Array.empty
+
+  /** Rough byte width of one aggregate buffer row. Chosen at 16 B/field as a
+   *  conservative heap-overhead-aware lower bound for a
+   *  `SpecificInternalRow` slot: primitive `MutableValue` is 8 B, boxed
+   *  references and object headers push the effective footprint higher.
+   *  Tighter per-type sizing (real boxing cost, variable-length fields) is
+   *  intentionally out of scope here; TaskMemoryManager remains the hard
+   *  backstop via spill / OOM.
+   *  TODO(SPARK-XXXXX): per-type width estimator keyed on
+   *  `bufferDataTypes` (primitive 16 B, String/Binary/Decimal wider). */

Review Comment:
   Addressed in `79e42da60ad` (R3-cleanup-oss). Thank you for the advice!



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowSegmentTree.scala:
##########
@@ -0,0 +1,610 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.execution.window
+
+import java.util.{LinkedHashMap => JLinkedHashMap, Map => JMap}
+
+import scala.collection.mutable
+
+import org.apache.spark.{SparkEnv, SparkException, TaskContext}
+import org.apache.spark.memory.{MemoryConsumer, TaskMemoryManager}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.expressions.aggregate.DeclarativeAggregate
+import org.apache.spark.sql.errors.QueryExecutionErrors
+import org.apache.spark.sql.execution.ExternalAppendOnlyUnsafeRowArray
+import org.apache.spark.sql.types.DataType
+import org.apache.spark.util.ArrayImplicits._
+
+/**
+ * Block-chunked segment tree for range aggregate queries over window partitions.
+ *
+ * See `the class documentation`
+ * for the full design (API contract Section 2, block-chunked memory layout Section 3,
+ * DeclarativeAggregate binding Section 4, error handling Section 5, test hooks Section 6).
+ *
+ * initial implementation scope: correctness only. The data layer uses
+ * `ExternalAppendOnlyUnsafeRowArray` to hold input rows (spillable). Each
+ * block materializes its own small segment tree (levels 0..h). Internal
+ * nodes are cached in an LRU keyed by block index; block root aggregates
+ * (block pre-aggregates) stay resident for all blocks.
+ *
+ * Note: the design doc Section 3.3 specifies leaves are NOT materialized and
+ * recomputed from the spillable array on demand. For initial implementation simplicity
+ * we materialize leaves inside the per-block internal node arrays.
+ * // TODO(SPARK-XXXXX) re-assess after Frame integration.
+ *
+ * @note Instances are not thread-safe.
+ */
+private[window] class WindowSegmentTree(
+    functions: Array[DeclarativeAggregate],
+    inputSchema: Seq[Attribute],
+    newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
+    fanout: Int = WindowSegmentTree.DefaultFanout,
+    blockSize: Int = WindowSegmentTree.DefaultBlockSize,
+    maxCachedBlocks: Option[Int] = None,
+    spillThreshold: Int = Int.MaxValue,
+    inMemoryThreshold: Int = Int.MaxValue,
+    taskMemoryManager: TaskMemoryManager = null)
+  extends AutoCloseable {
+
+  require(fanout >= 2, s"fanout must be >= 2, got $fanout")
+  require(blockSize >= 1, s"blockSize must be >= 1, got $blockSize")
+  require(functions.nonEmpty, "WindowSegmentTree requires at least one aggregate function")
+  maxCachedBlocks.foreach { n =>
+    require(n >= 1, s"maxCachedBlocks must be >= 1 when specified, got $n")
+  }
+  require(taskMemoryManager != null,
+    "WindowSegmentTree requires a non-null TaskMemoryManager; " +
+      "in tests use `new TaskMemoryManager(new TestMemoryManager(conf), 0)`")
+
+  // ---------- Schemas & projections ----------
+
+  private val bufferAttrs: Seq[AttributeReference] =
+    functions.flatMap(_.aggBufferAttributes).toImmutableArraySeq
+  private val rightAttrs: Seq[AttributeReference] =
+    functions.flatMap(_.inputAggBufferAttributes).toImmutableArraySeq
+  private val bufferDataTypes: IndexedSeq[DataType] =
+    bufferAttrs.map(_.dataType).toIndexedSeq
+
+  private val initialValues: Seq[Expression] = functions.flatMap(_.initialValues).toIndexedSeq
+  private val updateExpressions: Seq[Expression] =
+    functions.flatMap(_.updateExpressions).toIndexedSeq
+  private val mergeExpressions: Seq[Expression] =
+    functions.flatMap(_.mergeExpressions).toIndexedSeq
+
+  private[this] val initProj: MutableProjection = newMutableProjection(initialValues, Nil)
+  private[this] val updateProj: MutableProjection =
+    newMutableProjection(updateExpressions, bufferAttrs ++ inputSchema)
+  private[this] val mergeProj: MutableProjection =
+    newMutableProjection(mergeExpressions, bufferAttrs ++ rightAttrs)
+
+  private val inputUnsafeProj: UnsafeProjection =
+    UnsafeProjection.create(inputSchema.map(_.dataType).toArray)
+
+  private[this] val joinedRow = new JoinedRow()
+
+  // ---------- State ----------
+
+  private var numRows: Int = 0
+  private var numBlocks: Int = 0
+  private var rowArray: ExternalAppendOnlyUnsafeRowArray = _
+  private var closed: Boolean = false
+
+  /** Always-resident per-block root aggregates. `blockAggregates(i)` =
+   *  merged buffer over all rows in block i. */
+  private var blockAggregates: Array[InternalRow] = Array.empty
+
+  /** Rough byte width of one aggregate buffer row. Chosen at 16 B/field as a
+   *  conservative heap-overhead-aware lower bound for a
+   *  `SpecificInternalRow` slot: primitive `MutableValue` is 8 B, boxed
+   *  references and object headers push the effective footprint higher.
+   *  Tighter per-type sizing (real boxing cost, variable-length fields) is
+   *  intentionally out of scope here; TaskMemoryManager remains the hard
+   *  backstop via spill / OOM.
+   *  TODO(SPARK-XXXXX): per-type width estimator keyed on
+   *  `bufferDataTypes` (primitive 16 B, String/Binary/Decimal wider). */
+  private val bufferWidthBytes: Long = {
+    val bytesPerField = 16L
+    math.max(1L, bufferDataTypes.size.toLong * bytesPerField)
+  }
+
+  /** Number of aggregate-buffer slots cached per block (contract I5).
+   *
+   *  Invariant: equals `sum over levels L of levels(L).length` for any
+   *  block materialized by [[buildBlockLevels]]. Level 0 holds `blockSize`
+   *  leaf buffers and each subsequent level holds `ceil(prev / fanout)`
+   *  parent buffers until a single root remains. The iterative ceiling
+   *  matches the allocation in [[buildBlockLevels]] for every
+   *  `(blockSize, fanout)` pair, including non-power-of-`fanout` cases.
+   *  For `blockSize == 1` the block is a single leaf with no parent
+   *  levels, so this returns 1.
+   *  TODO(SPARK-XXXXX): drop the leaf term when [[buildBlockLevels]]
+   *  switches to on-demand leaf recomputation. */

Review Comment:
   Addressed in `79e42da60ad` (R3-cleanup-oss). Thank you for the advice!



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowSegmentTree.scala:
##########
@@ -0,0 +1,610 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.execution.window
+
+import java.util.{LinkedHashMap => JLinkedHashMap, Map => JMap}
+
+import scala.collection.mutable
+
+import org.apache.spark.{SparkEnv, SparkException, TaskContext}
+import org.apache.spark.memory.{MemoryConsumer, TaskMemoryManager}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.expressions.aggregate.DeclarativeAggregate
+import org.apache.spark.sql.errors.QueryExecutionErrors
+import org.apache.spark.sql.execution.ExternalAppendOnlyUnsafeRowArray
+import org.apache.spark.sql.types.DataType
+import org.apache.spark.util.ArrayImplicits._
+
+/**
+ * Block-chunked segment tree for range aggregate queries over window partitions.
+ *
+ * See `the class documentation`
+ * for the full design (API contract Section 2, block-chunked memory layout Section 3,
+ * DeclarativeAggregate binding Section 4, error handling Section 5, test hooks Section 6).
+ *
+ * initial implementation scope: correctness only. The data layer uses
+ * `ExternalAppendOnlyUnsafeRowArray` to hold input rows (spillable). Each
+ * block materializes its own small segment tree (levels 0..h). Internal
+ * nodes are cached in an LRU keyed by block index; block root aggregates
+ * (block pre-aggregates) stay resident for all blocks.
+ *
+ * Note: the design doc Section 3.3 specifies leaves are NOT materialized and
+ * recomputed from the spillable array on demand. For initial implementation simplicity
+ * we materialize leaves inside the per-block internal node arrays.
+ * // TODO(SPARK-XXXXX) re-assess after Frame integration.
+ *
+ * @note Instances are not thread-safe.
+ */
+private[window] class WindowSegmentTree(
+    functions: Array[DeclarativeAggregate],
+    inputSchema: Seq[Attribute],
+    newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
+    fanout: Int = WindowSegmentTree.DefaultFanout,
+    blockSize: Int = WindowSegmentTree.DefaultBlockSize,
+    maxCachedBlocks: Option[Int] = None,
+    spillThreshold: Int = Int.MaxValue,
+    inMemoryThreshold: Int = Int.MaxValue,
+    taskMemoryManager: TaskMemoryManager = null)
+  extends AutoCloseable {
+
+  require(fanout >= 2, s"fanout must be >= 2, got $fanout")
+  require(blockSize >= 1, s"blockSize must be >= 1, got $blockSize")
+  require(functions.nonEmpty, "WindowSegmentTree requires at least one aggregate function")
+  maxCachedBlocks.foreach { n =>
+    require(n >= 1, s"maxCachedBlocks must be >= 1 when specified, got $n")
+  }
+  require(taskMemoryManager != null,
+    "WindowSegmentTree requires a non-null TaskMemoryManager; " +
+      "in tests use `new TaskMemoryManager(new TestMemoryManager(conf), 0)`")
+
+  // ---------- Schemas & projections ----------
+
+  private val bufferAttrs: Seq[AttributeReference] =
+    functions.flatMap(_.aggBufferAttributes).toImmutableArraySeq
+  private val rightAttrs: Seq[AttributeReference] =
+    functions.flatMap(_.inputAggBufferAttributes).toImmutableArraySeq
+  private val bufferDataTypes: IndexedSeq[DataType] =
+    bufferAttrs.map(_.dataType).toIndexedSeq
+
+  private val initialValues: Seq[Expression] = functions.flatMap(_.initialValues).toIndexedSeq
+  private val updateExpressions: Seq[Expression] =
+    functions.flatMap(_.updateExpressions).toIndexedSeq
+  private val mergeExpressions: Seq[Expression] =
+    functions.flatMap(_.mergeExpressions).toIndexedSeq
+
+  private[this] val initProj: MutableProjection = newMutableProjection(initialValues, Nil)
+  private[this] val updateProj: MutableProjection =
+    newMutableProjection(updateExpressions, bufferAttrs ++ inputSchema)
+  private[this] val mergeProj: MutableProjection =
+    newMutableProjection(mergeExpressions, bufferAttrs ++ rightAttrs)
+
+  private val inputUnsafeProj: UnsafeProjection =
+    UnsafeProjection.create(inputSchema.map(_.dataType).toArray)
+
+  private[this] val joinedRow = new JoinedRow()
+
+  // ---------- State ----------
+
+  private var numRows: Int = 0
+  private var numBlocks: Int = 0
+  private var rowArray: ExternalAppendOnlyUnsafeRowArray = _
+  private var closed: Boolean = false
+
+  /** Always-resident per-block root aggregates. `blockAggregates(i)` =
+   *  merged buffer over all rows in block i. */
+  private var blockAggregates: Array[InternalRow] = Array.empty
+
+  /** Rough byte width of one aggregate buffer row. Chosen at 16 B/field as a
+   *  conservative heap-overhead-aware lower bound for a
+   *  `SpecificInternalRow` slot: primitive `MutableValue` is 8 B, boxed
+   *  references and object headers push the effective footprint higher.
+   *  Tighter per-type sizing (real boxing cost, variable-length fields) is
+   *  intentionally out of scope here; TaskMemoryManager remains the hard
+   *  backstop via spill / OOM.
+   *  TODO(SPARK-XXXXX): per-type width estimator keyed on
+   *  `bufferDataTypes` (primitive 16 B, String/Binary/Decimal wider). */
+  private val bufferWidthBytes: Long = {
+    val bytesPerField = 16L
+    math.max(1L, bufferDataTypes.size.toLong * bytesPerField)
+  }
+
+  /** Number of aggregate-buffer slots cached per block (contract I5).
+   *
+   *  Invariant: equals `sum over levels L of levels(L).length` for any
+   *  block materialized by [[buildBlockLevels]]. Level 0 holds `blockSize`
+   *  leaf buffers and each subsequent level holds `ceil(prev / fanout)`
+   *  parent buffers until a single root remains. The iterative ceiling
+   *  matches the allocation in [[buildBlockLevels]] for every
+   *  `(blockSize, fanout)` pair, including non-power-of-`fanout` cases.
+   *  For `blockSize == 1` the block is a single leaf with no parent
+   *  levels, so this returns 1.
+   *  TODO(SPARK-XXXXX): drop the leaf term when [[buildBlockLevels]]
+   *  switches to on-demand leaf recomputation. */
+  private val cachedSlotsPerBlock: Long = {
+    var n = blockSize.toLong
+    var sum = n
+    while (n > 1L) {
+      n = (n + fanout - 1) / fanout
+      sum += n
+    }
+    sum
+  }
+
+  /** Bytes accounted per cached block (contract I5). Conservative: assumes
+   *  every block is full; tail block (`numRows % blockSize != 0`) will
+   *  hold fewer leaves, giving a small headroom. */
+  private[this] val blockBytes: Long =
+    math.max(1L, cachedSlotsPerBlock * bufferWidthBytes)
+
+  /** `spans(L)` = number of leaves covered by a single node at level L. Depends
+   *  only on fanout + blockSize, so precomputed once. */
+  private val spans: Array[Int] = {
+    val maxLevel = {
+      var lvl = 0
+      var span = 1L
+      while (span < blockSize) { span *= fanout; lvl += 1 }
+      lvl
+    }
+    val arr = new Array[Int](maxLevel + 1)
+    var s = 1L
+    var i = 0
+    while (i <= maxLevel) {
+      arr(i) = if (s > Int.MaxValue) Int.MaxValue else s.toInt
+      s *= fanout
+      i += 1
+    }
+    arr
+  }
+
+  /** LRU cache of per-block internal node arrays. Key = blockIdx.
+   *  Value = `Array[Array[InternalRow]]` with levels(0..h). Auto-eviction via
+   *  `removeEldestEntry` is disabled (contract I3) -- eviction is driven
+   *  explicitly from [[ensureBlockLevels]] (capacity overflow) or
+   *  [[SegTreeSpiller.spill]] (TMM pressure). Each cache entry maps 1:1 to
+   *  one [[acquireBlockMemory]] accounting. Callers (e.g.
+   *  `SegmentTreeWindowFunctionFrame`) should pass a W-aware
+   *  value like `ceil(W / blockSize) + 2`. */
+  private val blockLevelsCache: JLinkedHashMap[Integer, Array[Array[InternalRow]]] =
+    new JLinkedHashMap[Integer, Array[Array[InternalRow]]](16, 0.75f, true) {
+      override def removeEldestEntry(
+          eldest: JMap.Entry[Integer, Array[Array[InternalRow]]]): Boolean = false
+    }
+
+  // ---------- Memory consumer (contract Section 2.2) ----------
+
+  /**
+   * Private MemoryConsumer tracking cached block levels under TMM.
+   *
+   * Heap accounting only (no Tungsten pages): uses
+   * [[MemoryConsumer.acquireMemory]] / [[MemoryConsumer.freeMemory]]. The
+   * [[MemoryConsumer]] base class records `used` via an `AtomicLong` when
+   * we call these -- so TMM's consumer-priority sort in
+   * `acquireExecutionMemory` sees our pressure accurately.
+   *
+   * @note `spill()` MUST NOT call `acquireMemory` (contract I1).
+   */
+  private final class SegTreeSpiller extends MemoryConsumer(
+      taskMemoryManager,
+      taskMemoryManager.pageSizeBytes(),
+      taskMemoryManager.getTungstenMemoryMode()) {
+    override def spill(size: Long, trigger: MemoryConsumer): Long = {
+      // I2: self-trigger short-circuit. Prevents re-entrant eviction when
+      // our own acquireMemory() triggers TMM to poll us.
+      if (trigger eq this) return 0L
+      // I8: rowArray spilled-to-disk detection. If the rowArray has already
+      // spilled, evicting our cache is counter-productive (rebuild would
+      // O(blockStart)-scan the spill file). Return 0L to let TMM fall
+      // through to the next consumer.
+      //
+      // TODO(SPARK-XXXXX) #segtree-spill-priority (contract Section 7 O4): current

Review Comment:
   Addressed in `79e42da60ad` (R3-cleanup-oss). Thank you for the advice!



-- 
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@spark.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-56546][SQL] Block-chunked segment-tree window frame for non-invertible sliding aggregates [spark]

Posted by "dongjoon-hyun (via GitHub)" <gi...@apache.org>.
dongjoon-hyun commented on code in PR #55422:
URL: https://github.com/apache/spark/pull/55422#discussion_r3148760653


##########
sql/core/src/test/scala/org/apache/spark/sql/execution/window/SegmentTreeWindowTestHelpers.scala:
##########
@@ -0,0 +1,176 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.execution.window
+
+import org.apache.spark.{SparkEnv, TaskContext}
+import org.apache.spark.memory.MemoryTestingUtils
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.expressions.aggregate.Sum
+import org.apache.spark.sql.catalyst.expressions.codegen.GenerateMutableProjection
+import org.apache.spark.sql.execution.ExternalAppendOnlyUnsafeRowArray
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.IntegerType
+
+/**
+ * Shared helpers for segment-tree window-frame tests. Kept in the same
+ * package so tests can reach `private[window]` hooks on
+ * [[SegmentTreeWindowFunctionFrame]] (see contract Section 1.3).
+ */
+private[window] object SegmentTreeWindowTestHelpers {

Review Comment:
   Could you rename this to `SegmentTreeWindowTestHelper`?
   
   ```
   $ find . -name '*Helper.scala' | wc -l
         92
   $ find . -name '*Helpers.scala' | wc -l
          4
   ```



-- 
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@spark.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-56546][SQL] Block-chunked segment-tree window frame for non-invertible sliding aggregates [spark]

Posted by "LuciferYang (via GitHub)" <gi...@apache.org>.
LuciferYang commented on code in PR #55422:
URL: https://github.com/apache/spark/pull/55422#discussion_r3135529893


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -4049,6 +4049,51 @@ object SQLConf {
         "The threshold of window group limit must be -1, 0 or positive integer.")
       .createWithDefault(1000)
 
+  val WINDOW_SEGMENT_TREE_ENABLED =
+    buildConf("spark.sql.window.segmentTree.enabled")
+      .withBindingPolicy(ConfigBindingPolicy.SESSION)
+      .doc("Use block-chunked segment tree for moving aggregate window frames " +
+        "whose functions are all DeclarativeAggregate without FILTER/DISTINCT.")
+      .version("4.2.0")

Review Comment:
   Are two of the configurations marked `internal`, while the other two are not?



-- 
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@spark.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-56546][SQL] Block-chunked segment-tree window frame for non-invertible sliding aggregates [spark]

Posted by "yaooqinn (via GitHub)" <gi...@apache.org>.
yaooqinn commented on PR #55422:
URL: https://github.com/apache/spark/pull/55422#issuecomment-4403359635

   Merged to master/4.x/4.2, thank you @LuciferYang @peter-toth @dongjoon-hyun for the review


-- 
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@spark.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [WIP][SPARK-56546][SQL] Block-chunked segment-tree window frame for non-invertible sliding aggregates [spark]

Posted by "yaooqinn (via GitHub)" <gi...@apache.org>.
yaooqinn commented on code in PR #55422:
URL: https://github.com/apache/spark/pull/55422#discussion_r3114835957


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowSegmentTree.scala:
##########
@@ -0,0 +1,610 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.execution.window
+
+import java.util.{LinkedHashMap => JLinkedHashMap, Map => JMap}
+
+import scala.collection.mutable
+
+import org.apache.spark.{SparkEnv, SparkException, TaskContext}
+import org.apache.spark.memory.{MemoryConsumer, TaskMemoryManager}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.expressions.aggregate.DeclarativeAggregate
+import org.apache.spark.sql.errors.QueryExecutionErrors
+import org.apache.spark.sql.execution.ExternalAppendOnlyUnsafeRowArray
+import org.apache.spark.sql.types.DataType
+import org.apache.spark.util.ArrayImplicits._
+
+/**
+ * Block-chunked segment tree for range aggregate queries over window partitions.
+ *
+ * See `the class documentation`
+ * for the full design (API contract Section 2, block-chunked memory layout Section 3,
+ * DeclarativeAggregate binding Section 4, error handling Section 5, test hooks Section 6).
+ *
+ * initial implementation scope: correctness only. The data layer uses
+ * `ExternalAppendOnlyUnsafeRowArray` to hold input rows (spillable). Each
+ * block materializes its own small segment tree (levels 0..h). Internal
+ * nodes are cached in an LRU keyed by block index; block root aggregates
+ * (block pre-aggregates) stay resident for all blocks.
+ *
+ * Note: the design doc Section 3.3 specifies leaves are NOT materialized and
+ * recomputed from the spillable array on demand. For initial implementation simplicity
+ * we materialize leaves inside the per-block internal node arrays.
+ * // TODO(SPARK-XXXXX) re-assess after Frame integration.
+ *
+ * @note Instances are not thread-safe.
+ */
+private[window] class WindowSegmentTree(
+    functions: Array[DeclarativeAggregate],
+    inputSchema: Seq[Attribute],
+    newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
+    fanout: Int = WindowSegmentTree.DefaultFanout,
+    blockSize: Int = WindowSegmentTree.DefaultBlockSize,
+    maxCachedBlocks: Option[Int] = None,
+    spillThreshold: Int = Int.MaxValue,
+    inMemoryThreshold: Int = Int.MaxValue,
+    taskMemoryManager: TaskMemoryManager = null)
+  extends AutoCloseable {
+
+  require(fanout >= 2, s"fanout must be >= 2, got $fanout")
+  require(blockSize >= 1, s"blockSize must be >= 1, got $blockSize")
+  require(functions.nonEmpty, "WindowSegmentTree requires at least one aggregate function")
+  maxCachedBlocks.foreach { n =>
+    require(n >= 1, s"maxCachedBlocks must be >= 1 when specified, got $n")
+  }
+  require(taskMemoryManager != null,
+    "WindowSegmentTree requires a non-null TaskMemoryManager; " +
+      "in tests use `new TaskMemoryManager(new TestMemoryManager(conf), 0)`")
+
+  // ---------- Schemas & projections ----------
+
+  private val bufferAttrs: Seq[AttributeReference] =
+    functions.flatMap(_.aggBufferAttributes).toImmutableArraySeq
+  private val rightAttrs: Seq[AttributeReference] =
+    functions.flatMap(_.inputAggBufferAttributes).toImmutableArraySeq
+  private val bufferDataTypes: IndexedSeq[DataType] =
+    bufferAttrs.map(_.dataType).toIndexedSeq
+
+  private val initialValues: Seq[Expression] = functions.flatMap(_.initialValues).toIndexedSeq
+  private val updateExpressions: Seq[Expression] =
+    functions.flatMap(_.updateExpressions).toIndexedSeq
+  private val mergeExpressions: Seq[Expression] =
+    functions.flatMap(_.mergeExpressions).toIndexedSeq
+
+  private[this] val initProj: MutableProjection = newMutableProjection(initialValues, Nil)
+  private[this] val updateProj: MutableProjection =
+    newMutableProjection(updateExpressions, bufferAttrs ++ inputSchema)
+  private[this] val mergeProj: MutableProjection =
+    newMutableProjection(mergeExpressions, bufferAttrs ++ rightAttrs)
+
+  private val inputUnsafeProj: UnsafeProjection =
+    UnsafeProjection.create(inputSchema.map(_.dataType).toArray)
+
+  private[this] val joinedRow = new JoinedRow()
+
+  // ---------- State ----------
+
+  private var numRows: Int = 0
+  private var numBlocks: Int = 0
+  private var rowArray: ExternalAppendOnlyUnsafeRowArray = _
+  private var closed: Boolean = false
+
+  /** Always-resident per-block root aggregates. `blockAggregates(i)` =
+   *  merged buffer over all rows in block i. */
+  private var blockAggregates: Array[InternalRow] = Array.empty
+
+  /** Rough byte width of one aggregate buffer row. Chosen at 16 B/field as a
+   *  conservative heap-overhead-aware lower bound for a
+   *  `SpecificInternalRow` slot: primitive `MutableValue` is 8 B, boxed
+   *  references and object headers push the effective footprint higher.
+   *  Tighter per-type sizing (real boxing cost, variable-length fields) is
+   *  intentionally out of scope here; TaskMemoryManager remains the hard
+   *  backstop via spill / OOM.
+   *  TODO(SPARK-XXXXX): per-type width estimator keyed on
+   *  `bufferDataTypes` (primitive 16 B, String/Binary/Decimal wider). */
+  private val bufferWidthBytes: Long = {
+    val bytesPerField = 16L
+    math.max(1L, bufferDataTypes.size.toLong * bytesPerField)
+  }
+
+  /** Number of aggregate-buffer slots cached per block (contract I5).
+   *
+   *  Invariant: equals `sum over levels L of levels(L).length` for any
+   *  block materialized by [[buildBlockLevels]]. Level 0 holds `blockSize`
+   *  leaf buffers and each subsequent level holds `ceil(prev / fanout)`
+   *  parent buffers until a single root remains. The iterative ceiling
+   *  matches the allocation in [[buildBlockLevels]] for every
+   *  `(blockSize, fanout)` pair, including non-power-of-`fanout` cases.
+   *  For `blockSize == 1` the block is a single leaf with no parent
+   *  levels, so this returns 1.
+   *  TODO(SPARK-XXXXX): drop the leaf term when [[buildBlockLevels]]
+   *  switches to on-demand leaf recomputation. */
+  private val cachedSlotsPerBlock: Long = {
+    var n = blockSize.toLong
+    var sum = n
+    while (n > 1L) {
+      n = (n + fanout - 1) / fanout
+      sum += n
+    }
+    sum
+  }
+
+  /** Bytes accounted per cached block (contract I5). Conservative: assumes
+   *  every block is full; tail block (`numRows % blockSize != 0`) will
+   *  hold fewer leaves, giving a small headroom. */
+  private[this] val blockBytes: Long =
+    math.max(1L, cachedSlotsPerBlock * bufferWidthBytes)
+
+  /** `spans(L)` = number of leaves covered by a single node at level L. Depends
+   *  only on fanout + blockSize, so precomputed once. */
+  private val spans: Array[Int] = {
+    val maxLevel = {
+      var lvl = 0
+      var span = 1L
+      while (span < blockSize) { span *= fanout; lvl += 1 }
+      lvl
+    }
+    val arr = new Array[Int](maxLevel + 1)
+    var s = 1L
+    var i = 0
+    while (i <= maxLevel) {
+      arr(i) = if (s > Int.MaxValue) Int.MaxValue else s.toInt
+      s *= fanout
+      i += 1
+    }
+    arr
+  }
+
+  /** LRU cache of per-block internal node arrays. Key = blockIdx.
+   *  Value = `Array[Array[InternalRow]]` with levels(0..h). Auto-eviction via
+   *  `removeEldestEntry` is disabled (contract I3) -- eviction is driven
+   *  explicitly from [[ensureBlockLevels]] (capacity overflow) or
+   *  [[SegTreeSpiller.spill]] (TMM pressure). Each cache entry maps 1:1 to
+   *  one [[acquireBlockMemory]] accounting. Callers (e.g.
+   *  `SegmentTreeWindowFunctionFrame`) should pass a W-aware
+   *  value like `ceil(W / blockSize) + 2`. */
+  private val blockLevelsCache: JLinkedHashMap[Integer, Array[Array[InternalRow]]] =
+    new JLinkedHashMap[Integer, Array[Array[InternalRow]]](16, 0.75f, true) {
+      override def removeEldestEntry(
+          eldest: JMap.Entry[Integer, Array[Array[InternalRow]]]): Boolean = false
+    }
+
+  // ---------- Memory consumer (contract Section 2.2) ----------
+
+  /**
+   * Private MemoryConsumer tracking cached block levels under TMM.
+   *
+   * Heap accounting only (no Tungsten pages): uses
+   * [[MemoryConsumer.acquireMemory]] / [[MemoryConsumer.freeMemory]]. The
+   * [[MemoryConsumer]] base class records `used` via an `AtomicLong` when
+   * we call these -- so TMM's consumer-priority sort in
+   * `acquireExecutionMemory` sees our pressure accurately.
+   *
+   * @note `spill()` MUST NOT call `acquireMemory` (contract I1).
+   */
+  private final class SegTreeSpiller extends MemoryConsumer(
+      taskMemoryManager,
+      taskMemoryManager.pageSizeBytes(),
+      taskMemoryManager.getTungstenMemoryMode()) {

Review Comment:
   Thanks — this is exactly the trade-off I'd like your read on before we pick a direction, because an earlier internal design pass landed on the opposite conclusion and neither side has a clean win on paper.
   
   **Argument for hardcoding `ON_HEAP` (your point).** The cached state is unambiguously on-heap:
   - `SpecificInternalRow` aggregate buffers (generic object arrays)
   - `Array[Array[InternalRow]]` block-level arrays
   - `ExternalAppendOnlyUnsafeRowArray` pages live on-heap regardless of Tungsten mode
   
   Registering the spiller as `OFF_HEAP` under `spark.memory.offHeap.enabled=true` charges those on-heap allocations to the off-heap pool — phantom pressure with no accounting of real heap pressure. The `T9 OFF_HEAP path` test in `WindowSegmentTreeMemorySuite` enshrines this.
   
   **Counter-argument for keeping `getTungstenMemoryMode()`.** TMM sorts consumers by `getUsed()` descending inside `acquireExecutionMemory` / `trySpillAndAcquire`, but **per pool**. Off-heap mode uses two pools:
   - Off-heap pool: `BytesToBytesMap`, `UnsafeExternalSorter` pages, any Tungsten consumer
   - On-heap pool: segtree (if hardcoded) + a few stragglers
   
   If segtree pins to `ON_HEAP` while `rowArray` (via `ExternalAppendOnlyUnsafeRowArray` → `UnsafeExternalSorter`) follows Tungsten, the two land in **different pools**. Two consequences:
   1. Cooperative spill ordering becomes cross-pool: TMM's `getUsed` descending sort no longer orders segtree vs. rowArray against each other — they compete inside their own pool only. The `rowArray-spilled short-circuit` (`WindowSegmentTree.scala:206`) was designed assuming co-pool ordering so segtree can see rowArray pressure first.
   2. `peakExecutionMemory` reporting splits across pools; the invariant "segtree ≤ rowArray at peak" becomes harder to verify from `TaskMetrics`.
   
   **Questions for your take:**
   - Is the cross-pool spill-ordering concern material in practice? My read of `ExecutionMemoryPool` says sorting is within-pool; if segtree goes on-heap in off-heap mode, the only thing that pressures segtree is other on-heap consumers (mostly none in the Window path), so  short-circuit effectively never fires because the pools don't see each other's pressure. That argues *against* the cross-pool concern.
   - If we hardcode `ON_HEAP`, do you prefer (a) flips to assert the on-heap charge even under off-heap mode, or (b) gets deleted as enshrining the wrong semantics?
   
   I'll hold the change until we align — happy to take it either way with your call.
   



-- 
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@spark.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-56546][SQL] Block-chunked segment-tree window frame for non-invertible sliding aggregates [spark]

Posted by "yaooqinn (via GitHub)" <gi...@apache.org>.
yaooqinn commented on code in PR #55422:
URL: https://github.com/apache/spark/pull/55422#discussion_r3122383828


##########
sql/core/src/test/scala/org/apache/spark/sql/internal/SQLConfSuite.scala:
##########
@@ -597,4 +597,16 @@ class SQLConfSuite extends QueryTest with SharedSparkSession {
     assert(e.getMessage.contains("forceSnapshotUploadOnLag"))
     assert(e.getMessage.contains("coordinatorReportSnapshotUploadLag"))
   }
+
+  test("SPARK-56546: segment-tree SQLConf entries declare SESSION bindingPolicy") {
+    import org.apache.spark.internal.config.ConfigBindingPolicy
+    Seq(
+      SQLConf.WINDOW_SEGMENT_TREE_ENABLED,
+      SQLConf.WINDOW_SEGMENT_TREE_MIN_PARTITION_ROWS,
+      SQLConf.WINDOW_SEGMENT_TREE_BLOCK_SIZE,
+      SQLConf.WINDOW_SEGMENT_TREE_FANOUT).foreach { entry =>
+      assert(entry.bindingPolicy === Some(ConfigBindingPolicy.SESSION),
+        s"${entry.key} must declare SESSION bindingPolicy")
+    }
+  }

Review Comment:
   ```suggestion
   ```



-- 
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@spark.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-56546][SQL] Block-chunked segment-tree window frame for non-invertible sliding aggregates [spark]

Posted by "yaooqinn (via GitHub)" <gi...@apache.org>.
yaooqinn commented on PR #55422:
URL: https://github.com/apache/spark/pull/55422#issuecomment-4310781196

   Thank you @LuciferYang for the approval. I'll leave this PR open for at least 2-weeks for more people to get a chance to review


-- 
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@spark.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-56546][SQL] Block-chunked segment-tree window frame for non-invertible sliding aggregates [spark]

Posted by "dongjoon-hyun (via GitHub)" <gi...@apache.org>.
dongjoon-hyun commented on code in PR #55422:
URL: https://github.com/apache/spark/pull/55422#discussion_r3148800436


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowEvaluatorFactoryBase.scala:
##########
@@ -295,4 +342,59 @@ trait WindowEvaluatorFactoryBase {
     }
   }
 
+  /**
+   * Segment-tree path eligibility. The tree relies on
+   * `DeclarativeAggregate.mergeExpressions`, which [[AggregateWindowFunction]]s
+   * (NthValue, NTile, Rank, RowNumber, NullIndex) refuse via
+   * `mergeUnsupportedByWindowFunctionError`: they extend DeclarativeAggregate
+   * but are NOT merge-capable. Normal aggregate window expressions reach this
+   * code as the inner DeclarativeAggregate unwrapped from
+   * [[AggregateExpression]] (see `windowFrameExpressionFactoryPairs.collect`).
+   *
+   * DISTINCT aggregate window expressions are already rejected earlier in
+   * analysis by `WindowResolution.checkWindowFunction`
+   * (error class `DISTINCT_WINDOW_FUNCTION_UNSUPPORTED`), so no explicit
+   * `isDistinct` gate is needed here.
+   */
+  private def eligibleForSegTree(
+      functions: Array[Expression],
+      filters: Array[Option[Expression]],
+      frameType: FrameType): Boolean = {
+    // RANGE accepted only for single-column order specs. Multi-column RANGE
+    // with non-zero offset is already rejected by `createBoundOrdering`, so
+    // gating here on `orderSpec.size == 1` matches the Sliding-path invariant.
+    val frameTypeOk = frameType match {
+      case RowFrame => true
+      case RangeFrame => orderSpec.size == 1
+    }
+    SQLConf.get.windowSegmentTreeEnabled &&

Review Comment:
   Please accept this as a parameter because the caller already has `val conf = SQLConf.get` at line 222.



-- 
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@spark.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-56546][SQL] Block-chunked segment-tree window frame for non-invertible sliding aggregates [spark]

Posted by "yaooqinn (via GitHub)" <gi...@apache.org>.
yaooqinn closed pull request #55422: [SPARK-56546][SQL] Block-chunked segment-tree window frame for non-invertible sliding aggregates
URL: https://github.com/apache/spark/pull/55422


-- 
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@spark.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-56546][SQL] Block-chunked segment-tree window frame for non-invertible sliding aggregates [spark]

Posted by "yaooqinn (via GitHub)" <gi...@apache.org>.
yaooqinn commented on code in PR #55422:
URL: https://github.com/apache/spark/pull/55422#discussion_r3192758791


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/SegmentTreeWindowFunctionFrame.scala:
##########
@@ -0,0 +1,292 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.execution.window
+
+import org.apache.spark.TaskContext
+import org.apache.spark.memory.TaskMemoryManager
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, Expression, FrameType, MutableProjection, RangeFrame, RowFrame, UnsafeRow}
+import org.apache.spark.sql.catalyst.expressions.aggregate.DeclarativeAggregate
+import org.apache.spark.sql.execution.ExternalAppendOnlyUnsafeRowArray
+import org.apache.spark.sql.execution.metric.SQLMetric
+import org.apache.spark.sql.internal.SQLConf
+
+/**
+ * Moving-frame window function frame backed by [[WindowSegmentTree]]. Produces
+ * the same outputs as [[SlidingWindowFunctionFrame]] for RowFrame or
+ * single-column RangeFrame moving frames whose aggregates are all
+ * [[DeclarativeAggregate]] with no FILTER/DISTINCT. For partitions below
+ * `spark.sql.window.segmentTree.minPartitionRows`, delegates to a wrapped
+ * [[SlidingWindowFunctionFrame]]. Under RANGE, two forward-only cursors
+ * (`lowerIter` / `upperIter`) advance the bounds in O(n) total; the segtree
+ * answers `[lowerBound, upperBound)` in O(log n).
+ *
+ * @note Not thread-safe.
+ */
+private[window] final class SegmentTreeWindowFunctionFrame(
+    target: InternalRow,
+    processor: AggregateProcessor,
+    functions: Array[DeclarativeAggregate],
+    inputSchema: Seq[Attribute],
+    frameType: FrameType,
+    lbound: BoundOrdering,
+    ubound: BoundOrdering,
+    newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
+    conf: SQLConf,
+    maxCachedBlocks: Option[Int],
+    taskMemoryManager: TaskMemoryManager,
+    numSegmentTreeFrames: Option[SQLMetric] = None,
+    numSegmentTreeFallbackFrames: Option[SQLMetric] = None)
+  extends WindowFunctionFrame with AutoCloseable {
+
+  require(frameType == RowFrame || frameType == RangeFrame,
+    s"SegmentTreeWindowFunctionFrame supports RowFrame or RangeFrame, got $frameType")
+
+  private[this] var fallback: SlidingWindowFunctionFrame = _
+  private[this] var tree: WindowSegmentTree = _
+
+  /** Allocate a fresh fallback sliding-window frame. Called lazily from
+   *  `prepare()` on the small-partition path. Factored out for testability
+   *  (subclasses can inject a throwing fallback for prepare-failure tests). */

Review Comment:
   Addressed in `1404c5db300` (scaladoc-style). Thank you for the advice!



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/window/SegmentTreeWindowTestHelpers.scala:
##########
@@ -0,0 +1,176 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.execution.window
+
+import org.apache.spark.{SparkEnv, TaskContext}
+import org.apache.spark.memory.MemoryTestingUtils
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.expressions.aggregate.Sum
+import org.apache.spark.sql.catalyst.expressions.codegen.GenerateMutableProjection
+import org.apache.spark.sql.execution.ExternalAppendOnlyUnsafeRowArray
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.IntegerType
+
+/**
+ * Shared helpers for segment-tree window-frame tests. Kept in the same
+ * package so tests can reach `private[window]` hooks on
+ * [[SegmentTreeWindowFunctionFrame]] (see contract Section 1.3).
+ */
+private[window] object SegmentTreeWindowTestHelpers {

Review Comment:
   Addressed in `d2c50b2ecd1` (rename-test-helper). Thank you for the advice!



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowSegmentTree.scala:
##########
@@ -0,0 +1,592 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.execution.window
+
+import java.util.{LinkedHashMap => JLinkedHashMap, Map => JMap}
+
+import scala.collection.mutable
+
+import org.apache.spark.SparkException
+import org.apache.spark.memory.{MemoryConsumer, MemoryMode, TaskMemoryManager}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.expressions.aggregate.{Average, Count, DeclarativeAggregate, Max, Min, StddevPop, StddevSamp, Sum, VariancePop, VarianceSamp}
+import org.apache.spark.sql.errors.QueryExecutionErrors
+import org.apache.spark.sql.execution.ExternalAppendOnlyUnsafeRowArray
+import org.apache.spark.sql.types.DataType
+import org.apache.spark.util.ArrayImplicits._
+
+/**
+ * Block-chunked segment tree for moving-frame window aggregates. Partitions are
+ * split into blocks of `blockSize` rows; each block has its own small segtree
+ * (fanout `F`, height `h`). Block roots stay resident; internal nodes are cached
+ * in an LRU keyed by block index. Queries cost O(log W).
+ *
+ * Memory accounting invariants:
+ *  - I1: `SegTreeSpiller.spill()` MUST NOT call `acquireMemory` on its own
+ *        consumer (would deadlock TMM's consumer-priority sort). All acquires
+ *        happen on the hot path ([[ensureBlockLevels]]).
+ *  - I2: `spill(_, trigger)` returns 0 when `trigger eq this` (self-trigger
+ *        short-circuit) to prevent re-entrant eviction.
+ *  - I3: LRU `removeEldestEntry` is disabled; eviction is driven explicitly
+ *        from [[ensureBlockLevels]] or [[SegTreeSpiller.spill]].
+ *  - I4: Every successful [[acquireBlockMemory]] is paired with exactly one
+ *        [[releaseBlockMemory]]. [[close]] is idempotent.
+ *  - I5: Per-block bytes are a conservative upper bound (full block, 16 B/field).
+ *  - I8: If `rowArray` already spilled to disk, `spill` returns 0 (rebuild
+ *        would O(blockStart)-scan the spill file).
+ *
+ * @note Instances are not thread-safe.
+ */
+private[window] class WindowSegmentTree(
+    functions: Array[DeclarativeAggregate],
+    inputSchema: Seq[Attribute],
+    newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
+    fanout: Int = WindowSegmentTree.DefaultFanout,
+    blockSize: Int = WindowSegmentTree.DefaultBlockSize,
+    maxCachedBlocks: Option[Int] = None,
+    taskMemoryManager: TaskMemoryManager = null)
+  extends AutoCloseable {
+
+  require(fanout >= 2, s"fanout must be >= 2, got $fanout")
+  require(blockSize >= 1, s"blockSize must be >= 1, got $blockSize")
+  require(functions.nonEmpty, "WindowSegmentTree requires at least one aggregate function")
+  maxCachedBlocks.foreach { n =>
+    require(n >= 1, s"maxCachedBlocks must be >= 1 when specified, got $n")
+  }
+  require(taskMemoryManager != null,
+    "WindowSegmentTree requires a non-null TaskMemoryManager; " +
+      "in tests use `new TaskMemoryManager(new TestMemoryManager(conf), 0)`")
+
+  // ---------- Schemas & projections ----------
+
+  private val bufferAttrs: Seq[AttributeReference] =
+    functions.flatMap(_.aggBufferAttributes).toImmutableArraySeq
+  private val rightAttrs: Seq[AttributeReference] =
+    functions.flatMap(_.inputAggBufferAttributes).toImmutableArraySeq
+  private val bufferDataTypes: IndexedSeq[DataType] =
+    bufferAttrs.map(_.dataType).toIndexedSeq
+
+  private val initialValues: Seq[Expression] = functions.flatMap(_.initialValues).toIndexedSeq
+  private val updateExpressions: Seq[Expression] =
+    functions.flatMap(_.updateExpressions).toIndexedSeq
+  private val mergeExpressions: Seq[Expression] =
+    functions.flatMap(_.mergeExpressions).toIndexedSeq
+
+  private[this] val initProj: MutableProjection = newMutableProjection(initialValues, Nil)
+  private[this] val updateProj: MutableProjection =
+    newMutableProjection(updateExpressions, bufferAttrs ++ inputSchema)
+  private[this] val mergeProj: MutableProjection =
+    newMutableProjection(mergeExpressions, bufferAttrs ++ rightAttrs)
+
+  private[this] val joinedRow = new JoinedRow()
+
+  // ---------- State ----------
+
+  private var numRows: Int = 0
+  private var numBlocks: Int = 0
+  private var rowArray: ExternalAppendOnlyUnsafeRowArray = _
+  private var closed: Boolean = false
+
+  /** Always-resident per-block root aggregates: `blockAggregates(i)` =
+   *  merged buffer over all rows in block i. */
+  private var blockAggregates: Array[InternalRow] = Array.empty
+
+  /** Conservative byte width of one aggregate buffer row at 16 B/field:
+   *  primitive `MutableValue` is 8 B, boxed references and object headers
+   *  push the effective footprint higher. Tighter per-type sizing is out
+   *  of scope; TaskMemoryManager remains the hard backstop via spill / OOM. */
+  private val bufferWidthBytes: Long = {
+    val bytesPerField = 16L
+    math.max(1L, bufferDataTypes.size.toLong * bytesPerField)
+  }
+
+  /** Number of aggregate-buffer slots cached per block (see I5).
+   *
+   *  Invariant: equals `sum over levels L of levels(L).length` for any block
+   *  built by [[buildBlockLevels]]: level 0 holds `blockSize` leaves and each
+   *  next level holds `ceil(prev / fanout)` parents until a single root
+   *  remains. For `blockSize == 1` this is 1 (single leaf, no parents). */
+  private val cachedSlotsPerBlock: Long = {
+    var n = blockSize.toLong
+    var sum = n
+    while (n > 1L) {
+      n = (n + fanout - 1) / fanout
+      sum += n
+    }
+    sum
+  }
+
+  /** Bytes accounted per cached block (see I5). Conservative: assumes every
+   *  block is full; tail block leaves a small headroom. */
+  private[this] val blockBytes: Long =
+    math.max(1L, cachedSlotsPerBlock * bufferWidthBytes)
+
+  /** `spans(L)` = number of leaves covered by a single node at level L. Depends
+   *  only on fanout + blockSize, so precomputed once. */
+  private val spans: Array[Int] = {
+    val maxLevel = {
+      var lvl = 0
+      var span = 1L
+      while (span < blockSize) { span *= fanout; lvl += 1 }
+      lvl
+    }
+    val arr = new Array[Int](maxLevel + 1)
+    var s = 1L
+    var i = 0
+    while (i <= maxLevel) {
+      arr(i) = if (s > Int.MaxValue) Int.MaxValue else s.toInt
+      s *= fanout
+      i += 1
+    }
+    arr
+  }
+
+  /** LRU cache of per-block internal node arrays. Key = blockIdx;
+   *  value = `Array[Array[InternalRow]]` with levels(0..h). Auto-eviction
+   *  via `removeEldestEntry` is disabled (I3) -- driven explicitly from
+   *  [[ensureBlockLevels]] or [[SegTreeSpiller.spill]]. Each entry maps 1:1
+   *  to one [[acquireBlockMemory]] accounting. Callers should pass a W-aware
+   *  `maxCachedBlocks` like `ceil(W / blockSize) + 2`. */
+  private val blockLevelsCache: JLinkedHashMap[Integer, Array[Array[InternalRow]]] =
+    new JLinkedHashMap[Integer, Array[Array[InternalRow]]](16, 0.75f, true) {
+      override def removeEldestEntry(
+          eldest: JMap.Entry[Integer, Array[Array[InternalRow]]]): Boolean = false
+    }
+
+  // ---------- Memory consumer ----------
+
+  /**
+   * Private MemoryConsumer tracking cached block levels under TMM. Heap-only
+   * (no Tungsten pages): uses [[MemoryConsumer.acquireMemory]] /
+   * [[MemoryConsumer.freeMemory]], which update the base class `used`
+   * AtomicLong so TMM's consumer-priority sort sees our pressure accurately.
+   *
+   * Hardcoded [[MemoryMode.ON_HEAP]] (not `tmm.getTungstenMemoryMode`): the
+   * cache holds plain JVM objects (`SpecificInternalRow` /
+   * `Array[Array[InternalRow]]`), never Tungsten pages. Under
+   * `spark.memory.offHeap.enabled=true`, enrolling as OFF_HEAP would let
+   * TMM pick us as a spill candidate for off-heap pressure; our `spill()`
+   * would then phantom-credit the off-heap pool without releasing any
+   * off-heap bytes, violating [[TaskMemoryManager#acquireExecutionMemory]]'s
+   * same-pool spill contract. Mirrors
+   * [[org.apache.spark.util.collection.Spillable]], which also hardcodes
+   * ON_HEAP for the same reason. Consequence under off-heap Tungsten: I8
+   * (below) degrades to a no-op because segtree and `rowArray` live in
+   * different pools -- a loss of optimization, not a correctness hazard.
+   *
+   * @note `spill()` MUST NOT call `acquireMemory` (see I1).
+   */
+  private final class SegTreeSpiller extends MemoryConsumer(
+      taskMemoryManager,
+      taskMemoryManager.pageSizeBytes(),
+      MemoryMode.ON_HEAP) {
+    override def spill(size: Long, trigger: MemoryConsumer): Long = {
+      // I2: self-trigger short-circuit (prevent re-entrant eviction).
+      if (trigger eq this) return 0L
+      // I8: rowArray already spilled -- evicting our cache is counter-productive
+      // (rebuild would O(blockStart)-scan the spill file). `spillSize > 0` is
+      // the available "has spilled" signal (UnsafeExternalSorter state is not
+      // public).
+      if (rowArray != null && rowArray.spillSize > 0) return 0L
+      evictUntil(size)
+    }
+  }
+
+  private[this] val spiller: SegTreeSpiller = new SegTreeSpiller
+
+  // ---------- Public API ----------
+
+  def size: Int = numRows
+
+  /**
+   * Build the tree against a caller-owned row array.
+   *
+   * Ownership: the tree holds a reference to `rows` for its lifetime but does
+   * NOT own it -- the caller (typically `WindowPartitionEvaluator.buffer`)
+   * manages `clear()` / lifetime at partition boundaries. `close()` drops
+   * the reference without mutating the array.
+   *
+   * Exception-safe: if aggregation throws, previously built state is preserved.
+   */
+  def build(rows: ExternalAppendOnlyUnsafeRowArray): Unit = {
+    // rows.length is Int by design; check guards against future widening.
+    val n = rows.length
+    if (n < 0) {
+      throw SparkException.internalError(
+        s"WindowSegmentTree cannot hold more than Int.MaxValue rows, got $n")
+    }
+    val nBlocks = if (n == 0) 0 else (n + blockSize - 1) / blockSize
+    val newBlockAggs = computeBlockAggregates(rows, n, nBlocks)
+
+    // Commit.
+    rowArray = rows
+    numRows = n
+    numBlocks = nBlocks
+    blockAggregates = newBlockAggs
+    // Rebuild invalidates cached block levels; release accounting first (I4).
+    releaseAllCachedBlocks()
+  }
+
+  /**
+   * Query [lo, hi) and directly evaluate the result via `processor.evaluate`
+   * into `target`. Uses an internal pre-allocated buffer so no per-call
+   * allocation is needed.
+   */
+  private[window] def queryInto(
+      lo: Int, hi: Int, processor: AggregateProcessor, target: InternalRow): Unit = {
+    query(lo, hi, internalQueryBuffer)
+    processor.evaluate(internalQueryBuffer, target)
+  }
+
+  private[this] val internalQueryBuffer: InternalRow = newBuffer()
+
+  def query(lo: Int, hi: Int, outBuffer: InternalRow): Unit = {
+    if (lo < 0 || hi > numRows || lo > hi) {
+      throw SparkException.internalError(
+        s"Invalid range [lo=$lo, hi=$hi) for size=$numRows")
+    }
+    // Reset outBuffer to identity only after bounds validation.
+    initProj.target(outBuffer)(InternalRow.empty)
+    if (lo == hi) return
+
+    val blo = lo / blockSize
+    val bhi = (hi - 1) / blockSize
+
+    if (blo == bhi) {
+      val blockStart = blo * blockSize
+      mergeBlockRange(blo, lo - blockStart, hi - blockStart, outBuffer)
+    } else {
+      // left partial
+      val loStart = blo * blockSize
+      val loBlockRows = math.min(blockSize, numRows - loStart)
+      mergeBlockRange(blo, lo - loStart, loBlockRows, outBuffer)
+      // full blocks
+      var b = blo + 1
+      while (b < bhi) {
+        mergeInto(outBuffer, blockAggregates(b))
+        b += 1
+      }
+      // right partial
+      val hiStart = bhi * blockSize
+      mergeBlockRange(bhi, 0, hi - hiStart, outBuffer)
+    }
+  }
+
+  /** Terminal: releases all state. Idempotent (I4). */
+  override def close(): Unit = {
+    if (closed) return
+    // Free all cached-block accounting before dropping references.
+    releaseAllCachedBlocks()
+    closeRowArray()
+    blockAggregates = Array.empty
+    numRows = 0
+    numBlocks = 0
+    closed = true
+  }
+
+  // ---------- Test hooks (package-private) ----------
+
+  private[window] def peekBlockCount: Int = numBlocks
+
+  private[window] def testOnlySpiller(): MemoryConsumer = spiller
+
+  /** Test-only accessor for the per-block memory accounting value. */
+  private[window] def peekBlockBytes: Long = blockBytes
+
+  /** NOTE: test-only; promotes block to MRU in the LRU cache as a side effect. */
+  private[window] def peekLevelSize(blockIdx: Int, level: Int): Int = {
+    val levels = ensureBlockLevels(blockIdx)
+    levels(level).length
+  }
+
+  /** NOTE: test-only; promotes block to MRU in the LRU cache as a side effect. */
+  private[window] def peekLevelCount(blockIdx: Int): Int = {
+    val levels = ensureBlockLevels(blockIdx)
+    levels.length
+  }
+
+  // ---------- Internals ----------
+
+  private def computeBlockAggregates(
+      array: ExternalAppendOnlyUnsafeRowArray,
+      n: Int,
+      nBlocks: Int): Array[InternalRow] = {
+    if (n == 0) return Array.empty
+    val result = new Array[InternalRow](nBlocks)
+    val iter = array.generateIterator()
+    var b = 0
+    while (b < nBlocks) {
+      val buf = newBuffer()
+      initProj.target(buf)(InternalRow.empty)
+      val start = b * blockSize
+      val end = math.min(start + blockSize, n)
+      var i = start
+      while (i < end) {
+        if (!iter.hasNext) {
+          throw SparkException.internalError("rowArray iterator exhausted unexpectedly")
+        }
+        val row = iter.next()
+        updateProj.target(buf)(joinedRow(buf, row))
+        i += 1
+      }
+      result(b) = buf
+      b += 1
+    }
+    result
+  }
+
+  /** Merge `src` buffer into `dst` buffer using mergeProj. */
+  private def mergeInto(dst: InternalRow, src: InternalRow): Unit = {
+    mergeProj.target(dst)(joinedRow(dst, src))
+  }
+
+  private def newBuffer(): InternalRow =
+    new SpecificInternalRow(bufferDataTypes)
+
+  /** Merge the given leaf range [lo, hi) inside `blockIdx` into `out`. */
+  private def mergeBlockRange(
+      blockIdx: Int, lo: Int, hi: Int, out: InternalRow): Unit = {
+    if (lo >= hi) return
+    val levels = ensureBlockLevels(blockIdx)
+    val blockRows = levels(0).length
+    val topLevel = levels.length - 1
+    queryDescend(levels, blockRows, topLevel, 0, lo, hi, out)
+  }
+
+  /** Descend the (per-block) segment tree merging any node fully contained
+   *  in [queryLo, queryHi) into `out`. A node at (level L, index idx) covers
+   *  leaves `[idx * span, min((idx+1)*span, blockRows))` where span = F^L. */

Review Comment:
   Addressed in `1404c5db300` (scaladoc-style). Thank you for the advice!



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowSegmentTree.scala:
##########
@@ -0,0 +1,592 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.execution.window
+
+import java.util.{LinkedHashMap => JLinkedHashMap, Map => JMap}
+
+import scala.collection.mutable
+
+import org.apache.spark.SparkException
+import org.apache.spark.memory.{MemoryConsumer, MemoryMode, TaskMemoryManager}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.expressions.aggregate.{Average, Count, DeclarativeAggregate, Max, Min, StddevPop, StddevSamp, Sum, VariancePop, VarianceSamp}
+import org.apache.spark.sql.errors.QueryExecutionErrors
+import org.apache.spark.sql.execution.ExternalAppendOnlyUnsafeRowArray
+import org.apache.spark.sql.types.DataType
+import org.apache.spark.util.ArrayImplicits._
+
+/**
+ * Block-chunked segment tree for moving-frame window aggregates. Partitions are
+ * split into blocks of `blockSize` rows; each block has its own small segtree
+ * (fanout `F`, height `h`). Block roots stay resident; internal nodes are cached
+ * in an LRU keyed by block index. Queries cost O(log W).
+ *
+ * Memory accounting invariants:
+ *  - I1: `SegTreeSpiller.spill()` MUST NOT call `acquireMemory` on its own
+ *        consumer (would deadlock TMM's consumer-priority sort). All acquires
+ *        happen on the hot path ([[ensureBlockLevels]]).
+ *  - I2: `spill(_, trigger)` returns 0 when `trigger eq this` (self-trigger
+ *        short-circuit) to prevent re-entrant eviction.
+ *  - I3: LRU `removeEldestEntry` is disabled; eviction is driven explicitly
+ *        from [[ensureBlockLevels]] or [[SegTreeSpiller.spill]].
+ *  - I4: Every successful [[acquireBlockMemory]] is paired with exactly one
+ *        [[releaseBlockMemory]]. [[close]] is idempotent.
+ *  - I5: Per-block bytes are a conservative upper bound (full block, 16 B/field).
+ *  - I8: If `rowArray` already spilled to disk, `spill` returns 0 (rebuild
+ *        would O(blockStart)-scan the spill file).
+ *
+ * @note Instances are not thread-safe.
+ */
+private[window] class WindowSegmentTree(
+    functions: Array[DeclarativeAggregate],
+    inputSchema: Seq[Attribute],
+    newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
+    fanout: Int = WindowSegmentTree.DefaultFanout,
+    blockSize: Int = WindowSegmentTree.DefaultBlockSize,
+    maxCachedBlocks: Option[Int] = None,
+    taskMemoryManager: TaskMemoryManager = null)
+  extends AutoCloseable {
+
+  require(fanout >= 2, s"fanout must be >= 2, got $fanout")
+  require(blockSize >= 1, s"blockSize must be >= 1, got $blockSize")
+  require(functions.nonEmpty, "WindowSegmentTree requires at least one aggregate function")
+  maxCachedBlocks.foreach { n =>
+    require(n >= 1, s"maxCachedBlocks must be >= 1 when specified, got $n")
+  }
+  require(taskMemoryManager != null,
+    "WindowSegmentTree requires a non-null TaskMemoryManager; " +
+      "in tests use `new TaskMemoryManager(new TestMemoryManager(conf), 0)`")
+
+  // ---------- Schemas & projections ----------
+
+  private val bufferAttrs: Seq[AttributeReference] =
+    functions.flatMap(_.aggBufferAttributes).toImmutableArraySeq
+  private val rightAttrs: Seq[AttributeReference] =
+    functions.flatMap(_.inputAggBufferAttributes).toImmutableArraySeq
+  private val bufferDataTypes: IndexedSeq[DataType] =
+    bufferAttrs.map(_.dataType).toIndexedSeq
+
+  private val initialValues: Seq[Expression] = functions.flatMap(_.initialValues).toIndexedSeq
+  private val updateExpressions: Seq[Expression] =
+    functions.flatMap(_.updateExpressions).toIndexedSeq
+  private val mergeExpressions: Seq[Expression] =
+    functions.flatMap(_.mergeExpressions).toIndexedSeq
+
+  private[this] val initProj: MutableProjection = newMutableProjection(initialValues, Nil)
+  private[this] val updateProj: MutableProjection =
+    newMutableProjection(updateExpressions, bufferAttrs ++ inputSchema)
+  private[this] val mergeProj: MutableProjection =
+    newMutableProjection(mergeExpressions, bufferAttrs ++ rightAttrs)
+
+  private[this] val joinedRow = new JoinedRow()
+
+  // ---------- State ----------
+
+  private var numRows: Int = 0
+  private var numBlocks: Int = 0
+  private var rowArray: ExternalAppendOnlyUnsafeRowArray = _
+  private var closed: Boolean = false
+
+  /** Always-resident per-block root aggregates: `blockAggregates(i)` =
+   *  merged buffer over all rows in block i. */
+  private var blockAggregates: Array[InternalRow] = Array.empty
+
+  /** Conservative byte width of one aggregate buffer row at 16 B/field:
+   *  primitive `MutableValue` is 8 B, boxed references and object headers
+   *  push the effective footprint higher. Tighter per-type sizing is out
+   *  of scope; TaskMemoryManager remains the hard backstop via spill / OOM. */
+  private val bufferWidthBytes: Long = {
+    val bytesPerField = 16L
+    math.max(1L, bufferDataTypes.size.toLong * bytesPerField)
+  }
+
+  /** Number of aggregate-buffer slots cached per block (see I5).
+   *
+   *  Invariant: equals `sum over levels L of levels(L).length` for any block
+   *  built by [[buildBlockLevels]]: level 0 holds `blockSize` leaves and each
+   *  next level holds `ceil(prev / fanout)` parents until a single root
+   *  remains. For `blockSize == 1` this is 1 (single leaf, no parents). */
+  private val cachedSlotsPerBlock: Long = {
+    var n = blockSize.toLong
+    var sum = n
+    while (n > 1L) {
+      n = (n + fanout - 1) / fanout
+      sum += n
+    }
+    sum
+  }
+
+  /** Bytes accounted per cached block (see I5). Conservative: assumes every
+   *  block is full; tail block leaves a small headroom. */
+  private[this] val blockBytes: Long =
+    math.max(1L, cachedSlotsPerBlock * bufferWidthBytes)
+
+  /** `spans(L)` = number of leaves covered by a single node at level L. Depends
+   *  only on fanout + blockSize, so precomputed once. */
+  private val spans: Array[Int] = {
+    val maxLevel = {
+      var lvl = 0
+      var span = 1L
+      while (span < blockSize) { span *= fanout; lvl += 1 }
+      lvl
+    }
+    val arr = new Array[Int](maxLevel + 1)
+    var s = 1L
+    var i = 0
+    while (i <= maxLevel) {
+      arr(i) = if (s > Int.MaxValue) Int.MaxValue else s.toInt
+      s *= fanout
+      i += 1
+    }
+    arr
+  }
+
+  /** LRU cache of per-block internal node arrays. Key = blockIdx;
+   *  value = `Array[Array[InternalRow]]` with levels(0..h). Auto-eviction
+   *  via `removeEldestEntry` is disabled (I3) -- driven explicitly from
+   *  [[ensureBlockLevels]] or [[SegTreeSpiller.spill]]. Each entry maps 1:1
+   *  to one [[acquireBlockMemory]] accounting. Callers should pass a W-aware
+   *  `maxCachedBlocks` like `ceil(W / blockSize) + 2`. */
+  private val blockLevelsCache: JLinkedHashMap[Integer, Array[Array[InternalRow]]] =
+    new JLinkedHashMap[Integer, Array[Array[InternalRow]]](16, 0.75f, true) {
+      override def removeEldestEntry(
+          eldest: JMap.Entry[Integer, Array[Array[InternalRow]]]): Boolean = false
+    }
+
+  // ---------- Memory consumer ----------
+
+  /**
+   * Private MemoryConsumer tracking cached block levels under TMM. Heap-only
+   * (no Tungsten pages): uses [[MemoryConsumer.acquireMemory]] /
+   * [[MemoryConsumer.freeMemory]], which update the base class `used`
+   * AtomicLong so TMM's consumer-priority sort sees our pressure accurately.
+   *
+   * Hardcoded [[MemoryMode.ON_HEAP]] (not `tmm.getTungstenMemoryMode`): the
+   * cache holds plain JVM objects (`SpecificInternalRow` /
+   * `Array[Array[InternalRow]]`), never Tungsten pages. Under
+   * `spark.memory.offHeap.enabled=true`, enrolling as OFF_HEAP would let
+   * TMM pick us as a spill candidate for off-heap pressure; our `spill()`
+   * would then phantom-credit the off-heap pool without releasing any
+   * off-heap bytes, violating [[TaskMemoryManager#acquireExecutionMemory]]'s
+   * same-pool spill contract. Mirrors
+   * [[org.apache.spark.util.collection.Spillable]], which also hardcodes
+   * ON_HEAP for the same reason. Consequence under off-heap Tungsten: I8
+   * (below) degrades to a no-op because segtree and `rowArray` live in
+   * different pools -- a loss of optimization, not a correctness hazard.
+   *
+   * @note `spill()` MUST NOT call `acquireMemory` (see I1).
+   */
+  private final class SegTreeSpiller extends MemoryConsumer(
+      taskMemoryManager,
+      taskMemoryManager.pageSizeBytes(),
+      MemoryMode.ON_HEAP) {
+    override def spill(size: Long, trigger: MemoryConsumer): Long = {
+      // I2: self-trigger short-circuit (prevent re-entrant eviction).
+      if (trigger eq this) return 0L
+      // I8: rowArray already spilled -- evicting our cache is counter-productive
+      // (rebuild would O(blockStart)-scan the spill file). `spillSize > 0` is
+      // the available "has spilled" signal (UnsafeExternalSorter state is not
+      // public).
+      if (rowArray != null && rowArray.spillSize > 0) return 0L
+      evictUntil(size)
+    }
+  }
+
+  private[this] val spiller: SegTreeSpiller = new SegTreeSpiller
+
+  // ---------- Public API ----------
+
+  def size: Int = numRows
+
+  /**
+   * Build the tree against a caller-owned row array.
+   *
+   * Ownership: the tree holds a reference to `rows` for its lifetime but does
+   * NOT own it -- the caller (typically `WindowPartitionEvaluator.buffer`)
+   * manages `clear()` / lifetime at partition boundaries. `close()` drops
+   * the reference without mutating the array.
+   *
+   * Exception-safe: if aggregation throws, previously built state is preserved.
+   */
+  def build(rows: ExternalAppendOnlyUnsafeRowArray): Unit = {
+    // rows.length is Int by design; check guards against future widening.
+    val n = rows.length
+    if (n < 0) {
+      throw SparkException.internalError(
+        s"WindowSegmentTree cannot hold more than Int.MaxValue rows, got $n")
+    }
+    val nBlocks = if (n == 0) 0 else (n + blockSize - 1) / blockSize
+    val newBlockAggs = computeBlockAggregates(rows, n, nBlocks)
+
+    // Commit.
+    rowArray = rows
+    numRows = n
+    numBlocks = nBlocks
+    blockAggregates = newBlockAggs
+    // Rebuild invalidates cached block levels; release accounting first (I4).
+    releaseAllCachedBlocks()
+  }
+
+  /**
+   * Query [lo, hi) and directly evaluate the result via `processor.evaluate`
+   * into `target`. Uses an internal pre-allocated buffer so no per-call
+   * allocation is needed.
+   */
+  private[window] def queryInto(
+      lo: Int, hi: Int, processor: AggregateProcessor, target: InternalRow): Unit = {
+    query(lo, hi, internalQueryBuffer)
+    processor.evaluate(internalQueryBuffer, target)
+  }
+
+  private[this] val internalQueryBuffer: InternalRow = newBuffer()
+
+  def query(lo: Int, hi: Int, outBuffer: InternalRow): Unit = {
+    if (lo < 0 || hi > numRows || lo > hi) {
+      throw SparkException.internalError(
+        s"Invalid range [lo=$lo, hi=$hi) for size=$numRows")
+    }
+    // Reset outBuffer to identity only after bounds validation.
+    initProj.target(outBuffer)(InternalRow.empty)
+    if (lo == hi) return
+
+    val blo = lo / blockSize
+    val bhi = (hi - 1) / blockSize
+
+    if (blo == bhi) {
+      val blockStart = blo * blockSize
+      mergeBlockRange(blo, lo - blockStart, hi - blockStart, outBuffer)
+    } else {
+      // left partial
+      val loStart = blo * blockSize
+      val loBlockRows = math.min(blockSize, numRows - loStart)
+      mergeBlockRange(blo, lo - loStart, loBlockRows, outBuffer)
+      // full blocks
+      var b = blo + 1
+      while (b < bhi) {
+        mergeInto(outBuffer, blockAggregates(b))
+        b += 1
+      }
+      // right partial
+      val hiStart = bhi * blockSize
+      mergeBlockRange(bhi, 0, hi - hiStart, outBuffer)
+    }
+  }
+
+  /** Terminal: releases all state. Idempotent (I4). */
+  override def close(): Unit = {
+    if (closed) return
+    // Free all cached-block accounting before dropping references.
+    releaseAllCachedBlocks()
+    closeRowArray()
+    blockAggregates = Array.empty
+    numRows = 0
+    numBlocks = 0
+    closed = true
+  }
+
+  // ---------- Test hooks (package-private) ----------
+
+  private[window] def peekBlockCount: Int = numBlocks
+
+  private[window] def testOnlySpiller(): MemoryConsumer = spiller
+
+  /** Test-only accessor for the per-block memory accounting value. */
+  private[window] def peekBlockBytes: Long = blockBytes
+
+  /** NOTE: test-only; promotes block to MRU in the LRU cache as a side effect. */
+  private[window] def peekLevelSize(blockIdx: Int, level: Int): Int = {
+    val levels = ensureBlockLevels(blockIdx)
+    levels(level).length
+  }
+
+  /** NOTE: test-only; promotes block to MRU in the LRU cache as a side effect. */
+  private[window] def peekLevelCount(blockIdx: Int): Int = {
+    val levels = ensureBlockLevels(blockIdx)
+    levels.length
+  }
+
+  // ---------- Internals ----------
+
+  private def computeBlockAggregates(
+      array: ExternalAppendOnlyUnsafeRowArray,
+      n: Int,
+      nBlocks: Int): Array[InternalRow] = {
+    if (n == 0) return Array.empty
+    val result = new Array[InternalRow](nBlocks)
+    val iter = array.generateIterator()
+    var b = 0
+    while (b < nBlocks) {
+      val buf = newBuffer()
+      initProj.target(buf)(InternalRow.empty)
+      val start = b * blockSize
+      val end = math.min(start + blockSize, n)
+      var i = start
+      while (i < end) {
+        if (!iter.hasNext) {
+          throw SparkException.internalError("rowArray iterator exhausted unexpectedly")
+        }
+        val row = iter.next()
+        updateProj.target(buf)(joinedRow(buf, row))
+        i += 1
+      }
+      result(b) = buf
+      b += 1
+    }
+    result
+  }
+
+  /** Merge `src` buffer into `dst` buffer using mergeProj. */
+  private def mergeInto(dst: InternalRow, src: InternalRow): Unit = {
+    mergeProj.target(dst)(joinedRow(dst, src))
+  }
+
+  private def newBuffer(): InternalRow =
+    new SpecificInternalRow(bufferDataTypes)
+
+  /** Merge the given leaf range [lo, hi) inside `blockIdx` into `out`. */
+  private def mergeBlockRange(
+      blockIdx: Int, lo: Int, hi: Int, out: InternalRow): Unit = {
+    if (lo >= hi) return
+    val levels = ensureBlockLevels(blockIdx)
+    val blockRows = levels(0).length
+    val topLevel = levels.length - 1
+    queryDescend(levels, blockRows, topLevel, 0, lo, hi, out)
+  }
+
+  /** Descend the (per-block) segment tree merging any node fully contained
+   *  in [queryLo, queryHi) into `out`. A node at (level L, index idx) covers
+   *  leaves `[idx * span, min((idx+1)*span, blockRows))` where span = F^L. */
+  private def queryDescend(
+      levels: Array[Array[InternalRow]],
+      blockRows: Int,
+      level: Int,
+      idx: Int,
+      queryLo: Int,
+      queryHi: Int,
+      out: InternalRow): Unit = {
+    val span = spans(level)
+    val nodeLo = idx * span
+    val nodeHi = math.min(nodeLo + span, blockRows)
+    if (queryLo >= nodeHi || queryHi <= nodeLo) return
+    if (queryLo <= nodeLo && nodeHi <= queryHi) {
+      mergeInto(out, levels(level)(idx))
+      return
+    }
+    val childLevel = level - 1
+    val childLevelSize = levels(childLevel).length
+    var c = 0
+    while (c < fanout) {
+      val childIdx = idx * fanout + c
+      if (childIdx < childLevelSize) {
+        queryDescend(levels, blockRows, childLevel, childIdx, queryLo, queryHi, out)
+      }
+      c += 1
+    }
+  }
+
+  /** Build (or fetch from LRU) the full per-block levels array.
+   *  Protocol: acquire memory -> build -> cache. Eviction on capacity
+   *  overflow or on TMM spill request. */
+  private def ensureBlockLevels(blockIdx: Int): Array[Array[InternalRow]] = {
+    val cached = blockLevelsCache.get(Integer.valueOf(blockIdx))
+    if (cached != null) return cached
+
+    // Enforce LRU capacity before building a new entry (I3).
+    val cap = maxCachedBlocks.getOrElse(Int.MaxValue)
+    while (blockLevelsCache.size() >= cap) {
+      if (!evictEldest()) return throwCacheEvictFailed(blockIdx)
+    }
+
+    // Acquire accounting; on partial grant, try one manual evict-and-retry.
+    if (!acquireBlockMemory(blockIdx)) {
+      if (!evictEldest() || !acquireBlockMemory(blockIdx)) {
+        // scalastyle:off throwerror
+        throw QueryExecutionErrors.cannotAcquireMemoryForWindowAggregateError(
+          blockBytes, 0L)
+        // scalastyle:on throwerror
+      }
+    }
+
+    // If buildBlockLevels throws, release the just-acquired memory (I4).
+    val levels =
+      try buildBlockLevels(blockIdx)
+      catch { case t: Throwable => releaseBlockMemory(); throw t }
+    blockLevelsCache.put(Integer.valueOf(blockIdx), levels)
+    levels
+  }
+
+  private def buildBlockLevels(blockIdx: Int): Array[Array[InternalRow]] = {
+    val blockStart = blockIdx * blockSize
+    val blockRows = math.min(blockSize, numRows - blockStart)
+
+    // Level 0: one aggregate per row in the block.
+    val leaves = new Array[InternalRow](blockRows)
+    val iter = rowArray.generateIterator(blockStart)
+    var i = 0
+    while (i < blockRows) {
+      if (!iter.hasNext) {
+        throw SparkException.internalError(
+          s"rowArray iterator exhausted at block $blockIdx row $i")
+      }
+      val row = iter.next()
+      val buf = newBuffer()
+      initProj.target(buf)(InternalRow.empty)
+      updateProj.target(buf)(joinedRow(buf, row))
+      leaves(i) = buf
+      i += 1
+    }
+
+    val allLevels = mutable.ArrayBuffer[Array[InternalRow]](leaves)
+    var prev = leaves
+    while (prev.length > 1) {
+      val parentCount = (prev.length + fanout - 1) / fanout
+      val parents = new Array[InternalRow](parentCount)
+      var p = 0
+      while (p < parentCount) {
+        val buf = newBuffer()
+        initProj.target(buf)(InternalRow.empty)
+        val childStart = p * fanout
+        val childEnd = math.min(childStart + fanout, prev.length)
+        var c = childStart
+        while (c < childEnd) {
+          mergeInto(buf, prev(c))
+          c += 1
+        }
+        parents(p) = buf
+        p += 1
+      }
+      allLevels += parents
+      prev = parents
+    }
+    allLevels.toArray
+  }
+
+  private def throwCacheEvictFailed(blockIdx: Int): Nothing = {
+    throw SparkException.internalError(
+      s"LRU cache eviction failed for block $blockIdx (size=${blockLevelsCache.size})")
+  }
+
+  // ---------- Memory accounting helpers ----------
+
+  /** Try to acquire `blockBytes` for one cached block. Returns true on full
+   *  grant, false on partial (after rolling the partial grant back). Must
+   *  not be called from within [[SegTreeSpiller.spill]] (I1). */
+  private def acquireBlockMemory(blockIdx: Int): Boolean = {

Review Comment:
   Addressed in `1404c5db300` (drop-unused-blockidx). Thank you for the advice!



-- 
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@spark.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-56546][SQL] Block-chunked segment-tree window frame for non-invertible sliding aggregates [spark]

Posted by "LuciferYang (via GitHub)" <gi...@apache.org>.
LuciferYang commented on code in PR #55422:
URL: https://github.com/apache/spark/pull/55422#discussion_r3122425482


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowSegmentTree.scala:
##########
@@ -0,0 +1,592 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.execution.window
+
+import java.util.{LinkedHashMap => JLinkedHashMap, Map => JMap}
+
+import scala.collection.mutable
+
+import org.apache.spark.SparkException
+import org.apache.spark.memory.{MemoryConsumer, MemoryMode, TaskMemoryManager}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.expressions.aggregate.{Average, Count, DeclarativeAggregate, Max, Min, StddevPop, StddevSamp, Sum, VariancePop, VarianceSamp}
+import org.apache.spark.sql.errors.QueryExecutionErrors
+import org.apache.spark.sql.execution.ExternalAppendOnlyUnsafeRowArray
+import org.apache.spark.sql.types.DataType
+import org.apache.spark.util.ArrayImplicits._
+
+/**
+ * Block-chunked segment tree for moving-frame window aggregates. Partitions are
+ * split into blocks of `blockSize` rows; each block has its own small segtree
+ * (fanout `F`, height `h`). Block roots stay resident; internal nodes are cached
+ * in an LRU keyed by block index. Queries cost O(log W).
+ *
+ * Memory accounting invariants:
+ *  - I1: `SegTreeSpiller.spill()` MUST NOT call `acquireMemory` on its own
+ *        consumer (would deadlock TMM's consumer-priority sort). All acquires
+ *        happen on the hot path ([[ensureBlockLevels]]).
+ *  - I2: `spill(_, trigger)` returns 0 when `trigger eq this` (self-trigger
+ *        short-circuit) to prevent re-entrant eviction.
+ *  - I3: LRU `removeEldestEntry` is disabled; eviction is driven explicitly
+ *        from [[ensureBlockLevels]] or [[SegTreeSpiller.spill]].
+ *  - I4: Every successful [[acquireBlockMemory]] is paired with exactly one
+ *        [[releaseBlockMemory]]. [[close]] is idempotent.
+ *  - I5: Per-block bytes are a conservative upper bound (full block, 16 B/field).
+ *  - I8: If `rowArray` already spilled to disk, `spill` returns 0 (rebuild
+ *        would O(blockStart)-scan the spill file).
+ *
+ * @note Instances are not thread-safe.
+ */
+private[window] class WindowSegmentTree(
+    functions: Array[DeclarativeAggregate],
+    inputSchema: Seq[Attribute],
+    newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
+    fanout: Int = WindowSegmentTree.DefaultFanout,
+    blockSize: Int = WindowSegmentTree.DefaultBlockSize,
+    maxCachedBlocks: Option[Int] = None,
+    taskMemoryManager: TaskMemoryManager = null)
+  extends AutoCloseable {
+
+  require(fanout >= 2, s"fanout must be >= 2, got $fanout")
+  require(blockSize >= 1, s"blockSize must be >= 1, got $blockSize")
+  require(functions.nonEmpty, "WindowSegmentTree requires at least one aggregate function")
+  maxCachedBlocks.foreach { n =>
+    require(n >= 1, s"maxCachedBlocks must be >= 1 when specified, got $n")
+  }
+  require(taskMemoryManager != null,
+    "WindowSegmentTree requires a non-null TaskMemoryManager; " +
+      "in tests use `new TaskMemoryManager(new TestMemoryManager(conf), 0)`")
+
+  // ---------- Schemas & projections ----------
+
+  private val bufferAttrs: Seq[AttributeReference] =
+    functions.flatMap(_.aggBufferAttributes).toImmutableArraySeq
+  private val rightAttrs: Seq[AttributeReference] =
+    functions.flatMap(_.inputAggBufferAttributes).toImmutableArraySeq
+  private val bufferDataTypes: IndexedSeq[DataType] =
+    bufferAttrs.map(_.dataType).toIndexedSeq
+
+  private val initialValues: Seq[Expression] = functions.flatMap(_.initialValues).toIndexedSeq
+  private val updateExpressions: Seq[Expression] =
+    functions.flatMap(_.updateExpressions).toIndexedSeq
+  private val mergeExpressions: Seq[Expression] =
+    functions.flatMap(_.mergeExpressions).toIndexedSeq
+
+  private[this] val initProj: MutableProjection = newMutableProjection(initialValues, Nil)
+  private[this] val updateProj: MutableProjection =
+    newMutableProjection(updateExpressions, bufferAttrs ++ inputSchema)
+  private[this] val mergeProj: MutableProjection =
+    newMutableProjection(mergeExpressions, bufferAttrs ++ rightAttrs)
+
+  private[this] val joinedRow = new JoinedRow()
+
+  // ---------- State ----------
+
+  private var numRows: Int = 0
+  private var numBlocks: Int = 0
+  private var rowArray: ExternalAppendOnlyUnsafeRowArray = _
+  private var closed: Boolean = false
+
+  /** Always-resident per-block root aggregates: `blockAggregates(i)` =
+   *  merged buffer over all rows in block i. */
+  private var blockAggregates: Array[InternalRow] = Array.empty
+
+  /** Conservative byte width of one aggregate buffer row at 16 B/field:
+   *  primitive `MutableValue` is 8 B, boxed references and object headers
+   *  push the effective footprint higher. Tighter per-type sizing is out
+   *  of scope; TaskMemoryManager remains the hard backstop via spill / OOM. */
+  private val bufferWidthBytes: Long = {
+    val bytesPerField = 16L
+    math.max(1L, bufferDataTypes.size.toLong * bytesPerField)
+  }
+
+  /** Number of aggregate-buffer slots cached per block (see I5).
+   *
+   *  Invariant: equals `sum over levels L of levels(L).length` for any block
+   *  built by [[buildBlockLevels]]: level 0 holds `blockSize` leaves and each
+   *  next level holds `ceil(prev / fanout)` parents until a single root
+   *  remains. For `blockSize == 1` this is 1 (single leaf, no parents). */
+  private val cachedSlotsPerBlock: Long = {
+    var n = blockSize.toLong
+    var sum = n
+    while (n > 1L) {
+      n = (n + fanout - 1) / fanout
+      sum += n
+    }
+    sum
+  }
+
+  /** Bytes accounted per cached block (see I5). Conservative: assumes every
+   *  block is full; tail block leaves a small headroom. */
+  private[this] val blockBytes: Long =
+    math.max(1L, cachedSlotsPerBlock * bufferWidthBytes)
+
+  /** `spans(L)` = number of leaves covered by a single node at level L. Depends
+   *  only on fanout + blockSize, so precomputed once. */
+  private val spans: Array[Int] = {
+    val maxLevel = {
+      var lvl = 0
+      var span = 1L
+      while (span < blockSize) { span *= fanout; lvl += 1 }
+      lvl
+    }
+    val arr = new Array[Int](maxLevel + 1)
+    var s = 1L
+    var i = 0
+    while (i <= maxLevel) {
+      arr(i) = if (s > Int.MaxValue) Int.MaxValue else s.toInt
+      s *= fanout
+      i += 1
+    }
+    arr
+  }
+
+  /** LRU cache of per-block internal node arrays. Key = blockIdx;
+   *  value = `Array[Array[InternalRow]]` with levels(0..h). Auto-eviction
+   *  via `removeEldestEntry` is disabled (I3) -- driven explicitly from
+   *  [[ensureBlockLevels]] or [[SegTreeSpiller.spill]]. Each entry maps 1:1
+   *  to one [[acquireBlockMemory]] accounting. Callers should pass a W-aware
+   *  `maxCachedBlocks` like `ceil(W / blockSize) + 2`. */
+  private val blockLevelsCache: JLinkedHashMap[Integer, Array[Array[InternalRow]]] =
+    new JLinkedHashMap[Integer, Array[Array[InternalRow]]](16, 0.75f, true) {
+      override def removeEldestEntry(
+          eldest: JMap.Entry[Integer, Array[Array[InternalRow]]]): Boolean = false
+    }
+
+  // ---------- Memory consumer ----------
+
+  /**
+   * Private MemoryConsumer tracking cached block levels under TMM. Heap-only
+   * (no Tungsten pages): uses [[MemoryConsumer.acquireMemory]] /
+   * [[MemoryConsumer.freeMemory]], which update the base class `used`
+   * AtomicLong so TMM's consumer-priority sort sees our pressure accurately.
+   *
+   * Hardcoded [[MemoryMode.ON_HEAP]] (not `tmm.getTungstenMemoryMode`): the
+   * cache holds plain JVM objects (`SpecificInternalRow` /
+   * `Array[Array[InternalRow]]`), never Tungsten pages. Under
+   * `spark.memory.offHeap.enabled=true`, enrolling as OFF_HEAP would let
+   * TMM pick us as a spill candidate for off-heap pressure; our `spill()`
+   * would then phantom-credit the off-heap pool without releasing any
+   * off-heap bytes, violating [[TaskMemoryManager#acquireExecutionMemory]]'s
+   * same-pool spill contract. Mirrors
+   * [[org.apache.spark.util.collection.Spillable]], which also hardcodes
+   * ON_HEAP for the same reason. Consequence under off-heap Tungsten: I8
+   * (below) degrades to a no-op because segtree and `rowArray` live in
+   * different pools -- a loss of optimization, not a correctness hazard.
+   *
+   * @note `spill()` MUST NOT call `acquireMemory` (see I1).
+   */
+  private final class SegTreeSpiller extends MemoryConsumer(
+      taskMemoryManager,
+      taskMemoryManager.pageSizeBytes(),
+      MemoryMode.ON_HEAP) {
+    override def spill(size: Long, trigger: MemoryConsumer): Long = {
+      // I2: self-trigger short-circuit (prevent re-entrant eviction).
+      if (trigger eq this) return 0L
+      // I8: rowArray already spilled -- evicting our cache is counter-productive
+      // (rebuild would O(blockStart)-scan the spill file). `spillSize > 0` is
+      // the available "has spilled" signal (UnsafeExternalSorter state is not
+      // public).
+      if (rowArray != null && rowArray.spillSize > 0) return 0L
+      evictUntil(size)
+    }
+  }
+
+  private[this] val spiller: SegTreeSpiller = new SegTreeSpiller
+
+  // ---------- Public API ----------
+
+  def size: Int = numRows
+
+  /**
+   * Build the tree against a caller-owned row array.
+   *
+   * Ownership: the tree holds a reference to `rows` for its lifetime but does
+   * NOT own it -- the caller (typically `WindowPartitionEvaluator.buffer`)
+   * manages `clear()` / lifetime at partition boundaries. `close()` drops
+   * the reference without mutating the array.
+   *
+   * Exception-safe: if aggregation throws, previously built state is preserved.
+   */
+  def build(rows: ExternalAppendOnlyUnsafeRowArray): Unit = {
+    // rows.length is Int by design; check guards against future widening.
+    val n = rows.length
+    if (n < 0) {
+      throw SparkException.internalError(
+        s"WindowSegmentTree cannot hold more than Int.MaxValue rows, got $n")
+    }
+    val nBlocks = if (n == 0) 0 else (n + blockSize - 1) / blockSize
+    val newBlockAggs = computeBlockAggregates(rows, n, nBlocks)
+
+    // Commit.
+    rowArray = rows
+    numRows = n
+    numBlocks = nBlocks
+    blockAggregates = newBlockAggs
+    // Rebuild invalidates cached block levels; release accounting first (I4).
+    releaseAllCachedBlocks()
+  }
+
+  /**
+   * Query [lo, hi) and directly evaluate the result via `processor.evaluate`
+   * into `target`. Uses an internal pre-allocated buffer so no per-call
+   * allocation is needed.
+   */
+  private[window] def queryInto(
+      lo: Int, hi: Int, processor: AggregateProcessor, target: InternalRow): Unit = {
+    query(lo, hi, internalQueryBuffer)
+    processor.evaluate(internalQueryBuffer, target)
+  }
+
+  private[this] val internalQueryBuffer: InternalRow = newBuffer()
+
+  def query(lo: Int, hi: Int, outBuffer: InternalRow): Unit = {
+    if (lo < 0 || hi > numRows || lo > hi) {
+      throw SparkException.internalError(
+        s"Invalid range [lo=$lo, hi=$hi) for size=$numRows")
+    }
+    // Reset outBuffer to identity only after bounds validation.
+    initProj.target(outBuffer)(InternalRow.empty)
+    if (lo == hi) return
+
+    val blo = lo / blockSize
+    val bhi = (hi - 1) / blockSize
+
+    if (blo == bhi) {
+      val blockStart = blo * blockSize
+      mergeBlockRange(blo, lo - blockStart, hi - blockStart, outBuffer)
+    } else {
+      // left partial
+      val loStart = blo * blockSize
+      val loBlockRows = math.min(blockSize, numRows - loStart)
+      mergeBlockRange(blo, lo - loStart, loBlockRows, outBuffer)
+      // full blocks
+      var b = blo + 1
+      while (b < bhi) {
+        mergeInto(outBuffer, blockAggregates(b))
+        b += 1
+      }
+      // right partial
+      val hiStart = bhi * blockSize
+      mergeBlockRange(bhi, 0, hi - hiStart, outBuffer)
+    }
+  }
+
+  /** Terminal: releases all state. Idempotent (I4). */
+  override def close(): Unit = {
+    if (closed) return
+    // Free all cached-block accounting before dropping references.
+    releaseAllCachedBlocks()
+    closeRowArray()
+    blockAggregates = Array.empty
+    numRows = 0
+    numBlocks = 0
+    closed = true
+  }
+
+  // ---------- Test hooks (package-private) ----------
+
+  private[window] def peekBlockCount: Int = numBlocks
+
+  private[window] def testOnlySpiller(): MemoryConsumer = spiller
+
+  /** Test-only accessor for the per-block memory accounting value. */
+  private[window] def peekBlockBytes: Long = blockBytes
+
+  /** NOTE: test-only; promotes block to MRU in the LRU cache as a side effect. */
+  private[window] def peekLevelSize(blockIdx: Int, level: Int): Int = {
+    val levels = ensureBlockLevels(blockIdx)
+    levels(level).length
+  }
+
+  /** NOTE: test-only; promotes block to MRU in the LRU cache as a side effect. */
+  private[window] def peekLevelCount(blockIdx: Int): Int = {
+    val levels = ensureBlockLevels(blockIdx)
+    levels.length
+  }
+
+  // ---------- Internals ----------
+
+  private def computeBlockAggregates(
+      array: ExternalAppendOnlyUnsafeRowArray,
+      n: Int,
+      nBlocks: Int): Array[InternalRow] = {
+    if (n == 0) return Array.empty
+    val result = new Array[InternalRow](nBlocks)
+    val iter = array.generateIterator()
+    var b = 0
+    while (b < nBlocks) {
+      val buf = newBuffer()
+      initProj.target(buf)(InternalRow.empty)
+      val start = b * blockSize
+      val end = math.min(start + blockSize, n)
+      var i = start
+      while (i < end) {
+        if (!iter.hasNext) {
+          throw SparkException.internalError("rowArray iterator exhausted unexpectedly")
+        }
+        val row = iter.next()
+        updateProj.target(buf)(joinedRow(buf, row))
+        i += 1
+      }
+      result(b) = buf
+      b += 1
+    }
+    result
+  }
+
+  /** Merge `src` buffer into `dst` buffer using mergeProj. */
+  private def mergeInto(dst: InternalRow, src: InternalRow): Unit = {
+    mergeProj.target(dst)(joinedRow(dst, src))
+  }
+
+  private def newBuffer(): InternalRow =
+    new SpecificInternalRow(bufferDataTypes)
+
+  /** Merge the given leaf range [lo, hi) inside `blockIdx` into `out`. */
+  private def mergeBlockRange(
+      blockIdx: Int, lo: Int, hi: Int, out: InternalRow): Unit = {
+    if (lo >= hi) return
+    val levels = ensureBlockLevels(blockIdx)
+    val blockRows = levels(0).length
+    val topLevel = levels.length - 1
+    queryDescend(levels, blockRows, topLevel, 0, lo, hi, out)
+  }
+
+  /** Descend the (per-block) segment tree merging any node fully contained
+   *  in [queryLo, queryHi) into `out`. A node at (level L, index idx) covers
+   *  leaves `[idx * span, min((idx+1)*span, blockRows))` where span = F^L. */
+  private def queryDescend(
+      levels: Array[Array[InternalRow]],
+      blockRows: Int,
+      level: Int,
+      idx: Int,
+      queryLo: Int,
+      queryHi: Int,
+      out: InternalRow): Unit = {
+    val span = spans(level)
+    val nodeLo = idx * span
+    val nodeHi = math.min(nodeLo + span, blockRows)
+    if (queryLo >= nodeHi || queryHi <= nodeLo) return
+    if (queryLo <= nodeLo && nodeHi <= queryHi) {
+      mergeInto(out, levels(level)(idx))
+      return
+    }
+    val childLevel = level - 1
+    val childLevelSize = levels(childLevel).length
+    var c = 0
+    while (c < fanout) {
+      val childIdx = idx * fanout + c
+      if (childIdx < childLevelSize) {
+        queryDescend(levels, blockRows, childLevel, childIdx, queryLo, queryHi, out)
+      }
+      c += 1
+    }
+  }
+
+  /** Build (or fetch from LRU) the full per-block levels array.
+   *  Protocol: acquire memory -> build -> cache. Eviction on capacity
+   *  overflow or on TMM spill request. */
+  private def ensureBlockLevels(blockIdx: Int): Array[Array[InternalRow]] = {
+    val cached = blockLevelsCache.get(Integer.valueOf(blockIdx))
+    if (cached != null) return cached
+
+    // Enforce LRU capacity before building a new entry (I3).
+    val cap = maxCachedBlocks.getOrElse(Int.MaxValue)
+    while (blockLevelsCache.size() >= cap) {
+      if (!evictEldest()) return throwCacheEvictFailed(blockIdx)
+    }
+
+    // Acquire accounting; on partial grant, try one manual evict-and-retry.
+    if (!acquireBlockMemory(blockIdx)) {
+      if (!evictEldest() || !acquireBlockMemory(blockIdx)) {
+        // scalastyle:off throwerror
+        throw QueryExecutionErrors.cannotAcquireMemoryForWindowAggregateError(
+          blockBytes, 0L)
+        // scalastyle:on throwerror
+      }
+    }
+
+    // If buildBlockLevels throws, release the just-acquired memory (I4).
+    val levels =
+      try buildBlockLevels(blockIdx)
+      catch { case t: Throwable => releaseBlockMemory(); throw t }
+    blockLevelsCache.put(Integer.valueOf(blockIdx), levels)
+    levels
+  }
+
+  private def buildBlockLevels(blockIdx: Int): Array[Array[InternalRow]] = {
+    val blockStart = blockIdx * blockSize
+    val blockRows = math.min(blockSize, numRows - blockStart)
+
+    // Level 0: one aggregate per row in the block.
+    val leaves = new Array[InternalRow](blockRows)
+    val iter = rowArray.generateIterator(blockStart)
+    var i = 0
+    while (i < blockRows) {
+      if (!iter.hasNext) {
+        throw SparkException.internalError(
+          s"rowArray iterator exhausted at block $blockIdx row $i")
+      }
+      val row = iter.next()
+      val buf = newBuffer()
+      initProj.target(buf)(InternalRow.empty)
+      updateProj.target(buf)(joinedRow(buf, row))
+      leaves(i) = buf
+      i += 1
+    }
+
+    val allLevels = mutable.ArrayBuffer[Array[InternalRow]](leaves)
+    var prev = leaves
+    while (prev.length > 1) {
+      val parentCount = (prev.length + fanout - 1) / fanout
+      val parents = new Array[InternalRow](parentCount)
+      var p = 0
+      while (p < parentCount) {
+        val buf = newBuffer()
+        initProj.target(buf)(InternalRow.empty)
+        val childStart = p * fanout
+        val childEnd = math.min(childStart + fanout, prev.length)
+        var c = childStart
+        while (c < childEnd) {
+          mergeInto(buf, prev(c))
+          c += 1
+        }
+        parents(p) = buf
+        p += 1
+      }
+      allLevels += parents
+      prev = parents
+    }
+    allLevels.toArray
+  }
+
+  private def throwCacheEvictFailed(blockIdx: Int): Nothing = {
+    throw SparkException.internalError(
+      s"LRU cache eviction failed for block $blockIdx (size=${blockLevelsCache.size})")
+  }
+
+  // ---------- Memory accounting helpers ----------
+
+  /** Try to acquire `blockBytes` for one cached block. Returns true on full
+   *  grant, false on partial (after rolling the partial grant back). Must
+   *  not be called from within [[SegTreeSpiller.spill]] (I1). */
+  private def acquireBlockMemory(blockIdx: Int): Boolean = {
+    val granted = spiller.acquireMemory(blockBytes)
+    if (granted < blockBytes) {
+      if (granted > 0) spiller.freeMemory(granted)
+      false
+    } else {
+      true
+    }
+  }
+
+  /** Release the accounting for one block. Caller ensures pairing with a
+   *  prior successful [[acquireBlockMemory]] (I4). */
+  private def releaseBlockMemory(): Unit = {
+    spiller.freeMemory(blockBytes)
+  }
+
+  /** Evict LRU blocks until `target` bytes have been freed (or cache is
+   *  empty). Returns freed bytes. Called from [[SegTreeSpiller.spill]]. */
+  private def evictUntil(target: Long): Long = {
+    var freed = 0L
+    while (freed < target && !blockLevelsCache.isEmpty) {
+      freed += evictEldestReturnBytes()
+    }
+    freed
+  }
+
+  /** Evict one LRU block. Returns true if a block was evicted. */
+  private def evictEldest(): Boolean = {
+    if (blockLevelsCache.isEmpty) return false
+    evictEldestReturnBytes()
+    true
+  }
+
+  private def evictEldestReturnBytes(): Long = {
+    val it = blockLevelsCache.entrySet().iterator()
+    if (!it.hasNext) return 0L
+    val head = it.next()
+    it.remove()
+    releaseBlockMemory()
+    blockBytes
+  }
+
+  /** Release accounting for all cached blocks and clear the cache. */
+  private def releaseAllCachedBlocks(): Unit = {
+    val n = blockLevelsCache.size()
+    if (n > 0) {
+      blockLevelsCache.clear()
+      spiller.freeMemory(n.toLong * blockBytes)
+    }
+  }
+
+  private def closeRowArray(): Unit = {
+    // rowArray is caller-owned (see `build` docstring); drop the reference only.
+    rowArray = null
+  }
+}
+
+private[window] object WindowSegmentTree {
+  val DefaultFanout: Int = 16
+  val DefaultBlockSize: Int = 65536
+
+  /**
+   * Explicit allowlist of [[DeclarativeAggregate]] subclasses safe for
+   * segment-tree execution. Safe iff combine semantics form a commutative
+   * monoid on the partial-buffer representation (associativity +
+   * compatibility with `mergeExpressions`):
+   *
+   *   - [[Min]], [[Max]]: idempotent semilattice.
+   *   - [[Sum]], [[Count]]: additive monoid.
+   *   - [[Average]]: sum + count, both additive monoids.
+   *   - [[StddevPop]], [[StddevSamp]], [[VariancePop]], [[VarianceSamp]]:
+   *     Welford (count, mean, M2) is associative -- see
+   *     CentralMomentAgg.mergeExpressions.
+   *
+   * Intentionally excluded (tracked as follow-up): HyperLogLogPlusPlus /
+   * ApproxCountDistinct (sketch-buffer interaction unaudited), First / Last
+   * (order-dependent), CollectList / CollectSet (unbounded buffer growth),
+   * Percentile / ApproxPercentile (sorted-sketch buffer), and any
+   * ImperativeAggregate (excluded by the type check).
+   *
+   * Callers should use [[isEligible]] rather than `contains` directly.
+   */
+  val EligibleAggregates: Set[Class[_ <: DeclarativeAggregate]] = Set(
+    classOf[Min],
+    classOf[Max],
+    classOf[Sum],
+    classOf[Count],
+    classOf[Average],
+    classOf[StddevPop],
+    classOf[StddevSamp],
+    classOf[VariancePop],
+    classOf[VarianceSamp]
+  )
+
+  /**
+   * Returns true iff `f` is a [[DeclarativeAggregate]] on the explicit segment-tree
+   * allowlist. See [[EligibleAggregates]] for the rationale and excluded aggregates.
+   */
+  def isEligible(f: Expression): Boolean = f match {
+    case agg: DeclarativeAggregate => EligibleAggregates.contains(agg.getClass)

Review Comment:
   ```suggestion
       case agg: DeclarativeAggregate => EligibleAggregates.exists(_.isInstance(agg))
   ```



-- 
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@spark.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-56546][SQL] Block-chunked segment-tree window frame for non-invertible sliding aggregates [spark]

Posted by "LuciferYang (via GitHub)" <gi...@apache.org>.
LuciferYang commented on code in PR #55422:
URL: https://github.com/apache/spark/pull/55422#discussion_r3122434328


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowExec.scala:
##########
@@ -91,7 +91,12 @@ case class WindowExec(
     child: SparkPlan)
   extends WindowExecBase {
   override lazy val metrics: Map[String, SQLMetric] = Map(
-    "spillSize" -> SQLMetrics.createSizeMetric(sparkContext, "spill size")
+    "spillSize" -> SQLMetrics.createSizeMetric(sparkContext, "spill size"),
+    "numSegmentTreeFrames" ->
+      SQLMetrics.createMetric(sparkContext, "number of segment-tree frames"),

Review Comment:
   nit: segment-tree frames prepared (per partition)?



-- 
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@spark.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [WIP][SPARK-56546][SQL] Block-chunked segment-tree window frame for non-invertible sliding aggregates [spark]

Posted by "yaooqinn (via GitHub)" <gi...@apache.org>.
yaooqinn commented on code in PR #55422:
URL: https://github.com/apache/spark/pull/55422#discussion_r3115436054


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowSegmentTree.scala:
##########
@@ -0,0 +1,610 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.execution.window
+
+import java.util.{LinkedHashMap => JLinkedHashMap, Map => JMap}
+
+import scala.collection.mutable
+
+import org.apache.spark.{SparkEnv, SparkException, TaskContext}
+import org.apache.spark.memory.{MemoryConsumer, TaskMemoryManager}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.expressions.aggregate.DeclarativeAggregate
+import org.apache.spark.sql.errors.QueryExecutionErrors
+import org.apache.spark.sql.execution.ExternalAppendOnlyUnsafeRowArray
+import org.apache.spark.sql.types.DataType
+import org.apache.spark.util.ArrayImplicits._
+
+/**
+ * Block-chunked segment tree for range aggregate queries over window partitions.
+ *
+ * See `the class documentation`
+ * for the full design (API contract Section 2, block-chunked memory layout Section 3,
+ * DeclarativeAggregate binding Section 4, error handling Section 5, test hooks Section 6).
+ *
+ * initial implementation scope: correctness only. The data layer uses
+ * `ExternalAppendOnlyUnsafeRowArray` to hold input rows (spillable). Each
+ * block materializes its own small segment tree (levels 0..h). Internal
+ * nodes are cached in an LRU keyed by block index; block root aggregates
+ * (block pre-aggregates) stay resident for all blocks.
+ *
+ * Note: the design doc Section 3.3 specifies leaves are NOT materialized and
+ * recomputed from the spillable array on demand. For initial implementation simplicity
+ * we materialize leaves inside the per-block internal node arrays.
+ * // TODO(SPARK-XXXXX) re-assess after Frame integration.
+ *
+ * @note Instances are not thread-safe.
+ */
+private[window] class WindowSegmentTree(
+    functions: Array[DeclarativeAggregate],
+    inputSchema: Seq[Attribute],
+    newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
+    fanout: Int = WindowSegmentTree.DefaultFanout,
+    blockSize: Int = WindowSegmentTree.DefaultBlockSize,
+    maxCachedBlocks: Option[Int] = None,
+    spillThreshold: Int = Int.MaxValue,
+    inMemoryThreshold: Int = Int.MaxValue,
+    taskMemoryManager: TaskMemoryManager = null)
+  extends AutoCloseable {
+
+  require(fanout >= 2, s"fanout must be >= 2, got $fanout")
+  require(blockSize >= 1, s"blockSize must be >= 1, got $blockSize")
+  require(functions.nonEmpty, "WindowSegmentTree requires at least one aggregate function")
+  maxCachedBlocks.foreach { n =>
+    require(n >= 1, s"maxCachedBlocks must be >= 1 when specified, got $n")
+  }
+  require(taskMemoryManager != null,
+    "WindowSegmentTree requires a non-null TaskMemoryManager; " +
+      "in tests use `new TaskMemoryManager(new TestMemoryManager(conf), 0)`")
+
+  // ---------- Schemas & projections ----------
+
+  private val bufferAttrs: Seq[AttributeReference] =
+    functions.flatMap(_.aggBufferAttributes).toImmutableArraySeq
+  private val rightAttrs: Seq[AttributeReference] =
+    functions.flatMap(_.inputAggBufferAttributes).toImmutableArraySeq
+  private val bufferDataTypes: IndexedSeq[DataType] =
+    bufferAttrs.map(_.dataType).toIndexedSeq
+
+  private val initialValues: Seq[Expression] = functions.flatMap(_.initialValues).toIndexedSeq
+  private val updateExpressions: Seq[Expression] =
+    functions.flatMap(_.updateExpressions).toIndexedSeq
+  private val mergeExpressions: Seq[Expression] =
+    functions.flatMap(_.mergeExpressions).toIndexedSeq
+
+  private[this] val initProj: MutableProjection = newMutableProjection(initialValues, Nil)
+  private[this] val updateProj: MutableProjection =
+    newMutableProjection(updateExpressions, bufferAttrs ++ inputSchema)
+  private[this] val mergeProj: MutableProjection =
+    newMutableProjection(mergeExpressions, bufferAttrs ++ rightAttrs)
+
+  private val inputUnsafeProj: UnsafeProjection =
+    UnsafeProjection.create(inputSchema.map(_.dataType).toArray)
+
+  private[this] val joinedRow = new JoinedRow()
+
+  // ---------- State ----------
+
+  private var numRows: Int = 0
+  private var numBlocks: Int = 0
+  private var rowArray: ExternalAppendOnlyUnsafeRowArray = _
+  private var closed: Boolean = false
+
+  /** Always-resident per-block root aggregates. `blockAggregates(i)` =
+   *  merged buffer over all rows in block i. */
+  private var blockAggregates: Array[InternalRow] = Array.empty
+
+  /** Rough byte width of one aggregate buffer row. Chosen at 16 B/field as a
+   *  conservative heap-overhead-aware lower bound for a
+   *  `SpecificInternalRow` slot: primitive `MutableValue` is 8 B, boxed
+   *  references and object headers push the effective footprint higher.
+   *  Tighter per-type sizing (real boxing cost, variable-length fields) is
+   *  intentionally out of scope here; TaskMemoryManager remains the hard
+   *  backstop via spill / OOM.
+   *  TODO(SPARK-XXXXX): per-type width estimator keyed on
+   *  `bufferDataTypes` (primitive 16 B, String/Binary/Decimal wider). */
+  private val bufferWidthBytes: Long = {
+    val bytesPerField = 16L
+    math.max(1L, bufferDataTypes.size.toLong * bytesPerField)
+  }
+
+  /** Number of aggregate-buffer slots cached per block (contract I5).
+   *
+   *  Invariant: equals `sum over levels L of levels(L).length` for any
+   *  block materialized by [[buildBlockLevels]]. Level 0 holds `blockSize`
+   *  leaf buffers and each subsequent level holds `ceil(prev / fanout)`
+   *  parent buffers until a single root remains. The iterative ceiling
+   *  matches the allocation in [[buildBlockLevels]] for every
+   *  `(blockSize, fanout)` pair, including non-power-of-`fanout` cases.
+   *  For `blockSize == 1` the block is a single leaf with no parent
+   *  levels, so this returns 1.
+   *  TODO(SPARK-XXXXX): drop the leaf term when [[buildBlockLevels]]
+   *  switches to on-demand leaf recomputation. */
+  private val cachedSlotsPerBlock: Long = {
+    var n = blockSize.toLong
+    var sum = n
+    while (n > 1L) {
+      n = (n + fanout - 1) / fanout
+      sum += n
+    }
+    sum
+  }
+
+  /** Bytes accounted per cached block (contract I5). Conservative: assumes
+   *  every block is full; tail block (`numRows % blockSize != 0`) will
+   *  hold fewer leaves, giving a small headroom. */
+  private[this] val blockBytes: Long =
+    math.max(1L, cachedSlotsPerBlock * bufferWidthBytes)
+
+  /** `spans(L)` = number of leaves covered by a single node at level L. Depends
+   *  only on fanout + blockSize, so precomputed once. */
+  private val spans: Array[Int] = {
+    val maxLevel = {
+      var lvl = 0
+      var span = 1L
+      while (span < blockSize) { span *= fanout; lvl += 1 }
+      lvl
+    }
+    val arr = new Array[Int](maxLevel + 1)
+    var s = 1L
+    var i = 0
+    while (i <= maxLevel) {
+      arr(i) = if (s > Int.MaxValue) Int.MaxValue else s.toInt
+      s *= fanout
+      i += 1
+    }
+    arr
+  }
+
+  /** LRU cache of per-block internal node arrays. Key = blockIdx.
+   *  Value = `Array[Array[InternalRow]]` with levels(0..h). Auto-eviction via
+   *  `removeEldestEntry` is disabled (contract I3) -- eviction is driven
+   *  explicitly from [[ensureBlockLevels]] (capacity overflow) or
+   *  [[SegTreeSpiller.spill]] (TMM pressure). Each cache entry maps 1:1 to
+   *  one [[acquireBlockMemory]] accounting. Callers (e.g.
+   *  `SegmentTreeWindowFunctionFrame`) should pass a W-aware
+   *  value like `ceil(W / blockSize) + 2`. */
+  private val blockLevelsCache: JLinkedHashMap[Integer, Array[Array[InternalRow]]] =
+    new JLinkedHashMap[Integer, Array[Array[InternalRow]]](16, 0.75f, true) {
+      override def removeEldestEntry(
+          eldest: JMap.Entry[Integer, Array[Array[InternalRow]]]): Boolean = false
+    }
+
+  // ---------- Memory consumer (contract Section 2.2) ----------
+
+  /**
+   * Private MemoryConsumer tracking cached block levels under TMM.
+   *
+   * Heap accounting only (no Tungsten pages): uses
+   * [[MemoryConsumer.acquireMemory]] / [[MemoryConsumer.freeMemory]]. The
+   * [[MemoryConsumer]] base class records `used` via an `AtomicLong` when
+   * we call these -- so TMM's consumer-priority sort in
+   * `acquireExecutionMemory` sees our pressure accurately.
+   *
+   * @note `spill()` MUST NOT call `acquireMemory` (contract I1).
+   */
+  private final class SegTreeSpiller extends MemoryConsumer(
+      taskMemoryManager,
+      taskMemoryManager.pageSizeBytes(),
+      taskMemoryManager.getTungstenMemoryMode()) {
+    override def spill(size: Long, trigger: MemoryConsumer): Long = {
+      // I2: self-trigger short-circuit. Prevents re-entrant eviction when
+      // our own acquireMemory() triggers TMM to poll us.
+      if (trigger eq this) return 0L
+      // I8: rowArray spilled-to-disk detection. If the rowArray has already
+      // spilled, evicting our cache is counter-productive (rebuild would
+      // O(blockStart)-scan the spill file). Return 0L to let TMM fall
+      // through to the next consumer.
+      //
+      // TODO(SPARK-XXXXX) #segtree-spill-priority (contract Section 7 O4): current
+      // heuristic uses `spillSize > 0` as the "has spilled" signal. A more
+      // precise check would consult `UnsafeExternalSorter.getSpillWriters`
+      // state, but that API is not public. Re-evaluate after benchmark.
+      // FIXME(kentyao): upstream a public "hasSpilled" hook on the array.

Review Comment:
   Addressed in `79e42da60ad` (R3-cleanup-oss). Thank you for the advice!



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowEvaluatorFactoryBase.scala:
##########
@@ -191,13 +200,17 @@ trait WindowEvaluatorFactoryBase {
         // in a single Window physical node. Therefore, we can assume no SQL aggregation
         // functions if Pandas UDF exists. In the future, we might mix Pandas UDF and SQL
         // aggregation function in a single physical node.
-        def processor = if (functions.exists(_.isInstanceOf[PythonFuncExpression])) {
+        val aggFilters: Array[Option[Expression]] = expressions.map {
+          case WindowExpression(ae: AggregateExpression, _) => ae.filter
+          case _ => None
+        }.toArray
+        // Shared per (key) across the factory closure's invocations; each
+        // Frame calls `processor.initialize(...)` in `prepare`, so cross-

Review Comment:
   Addressed in `79e42da60ad` (R3-cleanup-oss). Thank you for the advice!



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowEvaluatorFactoryBase.scala:
##########
@@ -295,4 +344,63 @@ trait WindowEvaluatorFactoryBase {
     }
   }
 
+  /**
+   * Segment-tree path eligibility. The tree relies on `DeclarativeAggregate.mergeExpressions`,
+   * which [[AggregateWindowFunction]]s (e.g. NthValue, NTile, Rank, RowNumber, NullIndex) refuse
+   * with `mergeUnsupportedByWindowFunctionError`. They extend DeclarativeAggregate but are
+   * NOT merge-capable, so we must exclude them here even though the base-class check passes.
+   * Normal aggregate window expressions reach this code as the inner DeclarativeAggregate
+   * unwrapped from [[AggregateExpression]] (see `windowFrameExpressionFactoryPairs.collect`).
+   */
+  private def eligibleForSegTree(
+      functions: Array[Expression],
+      filters: Array[Option[Expression]],
+      frameType: FrameType): Boolean = {
+    // RANGE is accepted only for single-column order specs. Multi-column
+    // RANGE with non-zero offset is already rejected by `createBoundOrdering`
+    // (see the `RangeFrame, _` internalError branch above), so gating here
+    // on `orderSpec.size == 1` matches the Sliding-path invariant exactly.
+    val frameTypeOk = frameType match {
+      case RowFrame => true
+      case RangeFrame => orderSpec.size == 1
+    }
+    SQLConf.get.windowSegmentTreeEnabled &&
+      frameTypeOk &&
+      filters.forall(_.isEmpty) &&
+      functions.forall { f =>
+        f.isInstanceOf[DeclarativeAggregate] && !f.isInstanceOf[AggregateWindowFunction]

Review Comment:
   Addressed in `80fe0a75993` (F9 allowlist). Thank you for the advice!



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/window/SegmentTreeWindowFunctionSuite.scala:
##########
@@ -0,0 +1,862 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.execution.window
+
+import org.apache.spark.sql.{DataFrame, Encoder, Encoders, QueryTest, Row}
+import org.apache.spark.sql.expressions.{Aggregator, MutableAggregationBuffer, Window}
+import org.apache.spark.sql.expressions.UserDefinedAggregateFunction
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.test.SharedSparkSession
+import org.apache.spark.sql.types.{DataType, LongType, StructType}
+
+/**
+ * End-to-end tests for the block-chunked segment-tree moving window frame.
+ *
+ * Coverage by section:
+ *   - Coverage: various cases (basic aggregates), various cases (frame boundaries),
+ *                min-partition-rows fallback, AggregateWindowFunction
+ *                regression.
+ *   - Coverage: various cases (NULL, NaN/Infinity), various cases
+ *                (numeric / string / date-timestamp types), various cases
+ *                (unsupported-merge / DISTINCT / feature-flag fallback).
+ *
+  */
+class SegmentTreeWindowFunctionSuite extends QueryTest with SharedSparkSession {
+
+  import testImplicits._
+
+  // Common config: force the segment-tree path regardless of partition size
+  // (we exercise the fallback explicitly below).
+  private val enableSegTree: Map[String, String] = Map(
+    SQLConf.WINDOW_SEGMENT_TREE_ENABLED.key -> "true",
+    SQLConf.WINDOW_SEGMENT_TREE_MIN_PARTITION_ROWS.key -> "1")
+
+  private val disableSegTree: Map[String, String] = Map(
+    SQLConf.WINDOW_SEGMENT_TREE_ENABLED.key -> "false")
+
+  /** Build `f(conf)` twice (enabled / disabled) and assert equal results. */
+  private def checkEquivalence(build: () => DataFrame): Unit = {
+    val baseline: Array[Row] = withSQLConf(disableSegTree.toSeq: _*) {
+      build().collect().sortBy(_.toString)
+    }
+    withSQLConf(enableSegTree.toSeq: _*) {
+      val actual = build().collect().sortBy(_.toString)
+      assert(actual.toSeq === baseline.toSeq,
+        s"segment-tree output differs from baseline.\nExpected: ${baseline.toSeq}\n" +
+          s"Actual:   ${actual.toSeq}")
+    }
+  }
+
+  /** Standard fixture: 3 partitions, sizes 40/40/40, values = row index. */
+  private def baseDF: DataFrame = {
+    spark.range(0, 120).selectExpr(
+      "id",
+      "(id % 3) AS pk",
+      "CAST(id AS INT) AS v")
+  }
+
+  private def winSpec(lo: Int, hi: Int) =
+    Window.partitionBy($"pk").orderBy($"id").rowsBetween(lo, hi)
+
+  // ---------------- A1: basic aggregate equivalence ----------------
+
+  test("MIN over ROWS BETWEEN 3 PRECEDING AND 3 FOLLOWING") {
+    checkEquivalence(() =>
+      baseDF.select($"id", $"pk", min($"v").over(winSpec(-3, 3)).as("agg")))
+  }
+
+  test("MAX over ROWS BETWEEN 3 PRECEDING AND 3 FOLLOWING") {
+    checkEquivalence(() =>
+      baseDF.select($"id", $"pk", max($"v").over(winSpec(-3, 3)).as("agg")))
+  }
+
+  test("SUM over ROWS BETWEEN 3 PRECEDING AND 3 FOLLOWING") {
+    checkEquivalence(() =>
+      baseDF.select($"id", $"pk", sum($"v").over(winSpec(-3, 3)).as("agg")))
+  }
+
+  test("COUNT over ROWS BETWEEN 3 PRECEDING AND 3 FOLLOWING") {
+    checkEquivalence(() =>
+      baseDF.select($"id", $"pk", count($"v").over(winSpec(-3, 3)).as("agg")))
+  }
+
+  test("AVG over ROWS BETWEEN 3 PRECEDING AND 3 FOLLOWING") {
+    checkEquivalence(() =>
+      baseDF.select($"id", $"pk", avg($"v").over(winSpec(-3, 3)).as("agg")))
+  }
+
+  test("MIN + MAX + SUM share a single window frame") {
+    checkEquivalence(() =>
+      baseDF.select(
+        $"id",
+        $"pk",
+        min($"v").over(winSpec(-3, 3)).as("mn"),
+        max($"v").over(winSpec(-3, 3)).as("mx"),
+        sum($"v").over(winSpec(-3, 3)).as("sm")))
+  }
+
+  // ---------------- A2: frame-size boundaries ----------------
+
+  test("frame size = 1 (CURRENT ROW only)") {
+    checkEquivalence(() =>
+      baseDF.select($"id", $"pk", sum($"v").over(winSpec(0, 0)).as("agg")))
+  }
+
+  test("frame spans full partition") {
+    // 40 rows per partition; use a wide symmetric window covering it.
+    checkEquivalence(() =>
+      baseDF.select($"id", $"pk", sum($"v").over(winSpec(-100, 100)).as("agg")))
+  }
+
+  test("frame extends past both partition edges") {
+    checkEquivalence(() =>
+      baseDF.select($"id", $"pk",
+        sum($"v").over(winSpec(-50, 50)).as("agg"),
+        min($"v").over(winSpec(-50, 50)).as("mn"),
+        max($"v").over(winSpec(-50, 50)).as("mx")))
+  }
+
+  
+  test("partition below minPartitionRows falls back to SlidingWindowFunctionFrame") {
+    // 5-row partition, min threshold = 10 -> must fall back.
+    val df = spark.range(0, 5).selectExpr(
+      "id", "0 AS pk", "CAST(id AS INT) AS v")
+    val enabledConf = Map(
+      SQLConf.WINDOW_SEGMENT_TREE_ENABLED.key -> "true",
+      SQLConf.WINDOW_SEGMENT_TREE_MIN_PARTITION_ROWS.key -> "10")
+
+    // 1. Result correctness against baseline.
+    val baseline = withSQLConf(disableSegTree.toSeq: _*) {
+      df.select($"id", sum($"v").over(winSpec(-1, 1)).as("s"))
+        .collect().sortBy(_.toString)
+    }
+    val actual = withSQLConf(enabledConf.toSeq: _*) {
+      df.select($"id", sum($"v").over(winSpec(-1, 1)).as("s"))
+        .collect().sortBy(_.toString)
+    }
+    assert(actual.toSeq === baseline.toSeq)
+
+    // 2. Directly exercise the frame to confirm the fallback flag flips.
+    withSQLConf(enabledConf.toSeq: _*) {
+      SegmentTreeWindowTestHelpers.withSmallPartitionFrame(
+        SQLConf.get, rows = 5) { frame =>
+        assert(frame.fallbackUsed,
+          "expected fallbackUsed=true for partition smaller than minPartitionRows")
+      }
+    }
+  }
+
+  
+  test("NTH_VALUE over ROWS frame falls back cleanly (no mergeExpressions crash)") {
+    // NthValue extends DeclarativeAggregate but its mergeExpressions throws
+    // mergeUnsupportedByWindowFunctionError. eligibleForSegTree must exclude it.
+    val df = baseDF
+    val withSegTree = withSQLConf(enableSegTree.toSeq: _*) {
+      df.selectExpr(
+        "id", "pk",
+        "nth_value(v, 3) OVER (PARTITION BY pk ORDER BY id " +
+          "ROWS BETWEEN 5 PRECEDING AND 5 FOLLOWING) AS n3")
+        .collect().sortBy(_.toString)
+    }
+    val baseline = withSQLConf(disableSegTree.toSeq: _*) {
+      df.selectExpr(
+        "id", "pk",
+        "nth_value(v, 3) OVER (PARTITION BY pk ORDER BY id " +
+          "ROWS BETWEEN 5 PRECEDING AND 5 FOLLOWING) AS n3")
+        .collect().sortBy(_.toString)
+    }
+    assert(withSegTree.toSeq === baseline.toSeq)
+  }
+
+  test("ROW_NUMBER over ROWS frame falls back cleanly (no mergeExpressions crash)") {
+    val df = baseDF
+    val withSegTree = withSQLConf(enableSegTree.toSeq: _*) {
+      df.selectExpr(
+        "id", "pk",
+        "row_number() OVER (PARTITION BY pk ORDER BY id) AS rn")
+        .collect().sortBy(_.toString)
+    }
+    val baseline = withSQLConf(disableSegTree.toSeq: _*) {
+      df.selectExpr(
+        "id", "pk",
+        "row_number() OVER (PARTITION BY pk ORDER BY id) AS rn")
+        .collect().sortBy(_.toString)
+    }
+    assert(withSegTree.toSeq === baseline.toSeq)
+  }
+
+    // A3.*: NULL / NaN / Infinity handling
+  // A4.*: numeric / string / date-timestamp types
+  // various cases: unsupported-merge / DISTINCT / feature-flag fallback
+  //
+  // All tests use the same oracle strategy as the frame integration: run with
+  // `segmentTree.enabled=true` (forced via min-rows=1) and with `=false`,
+  // then assert bit-for-bit equal Row sequences. That gives us:
+  //   - Correctness: seg-tree output matches SlidingWindowFunctionFrame
+  //     (the community-validated baseline).
+  //   - Fallback paths: various cases exercise the `eligibleForSegTree` filter,
+  //     which must decline to drive the seg-tree path and hand off to the
+  //     sliding frame; equal rows prove the hand-off preserves semantics.
+
+  // ---------------- A3: NULL / special values ----------------
+
+  test("all-NULL column: MIN/MAX/SUM/AVG/COUNT") {
+    val df = spark.range(0, 30).selectExpr(
+      "id", "(id % 3) AS pk", "CAST(NULL AS INT) AS v")
+    checkEquivalence(() =>
+      df.select($"id", $"pk",
+        min($"v").over(winSpec(-3, 3)).as("mn"),
+        max($"v").over(winSpec(-3, 3)).as("mx"),
+        sum($"v").over(winSpec(-3, 3)).as("sm"),
+        avg($"v").over(winSpec(-3, 3)).as("av"),
+        count($"v").over(winSpec(-3, 3)).as("cn")))
+  }
+
+  test("mixed NULL and non-NULL: NULLs must not leak into MIN/MAX") {
+    // Every 3rd value is NULL. Aggregates must skip them (NULL-agnostic merge).
+    val df = spark.range(0, 60).selectExpr(
+      "id",
+      "(id % 3) AS pk",
+      "CASE WHEN id % 3 = 0 THEN NULL ELSE CAST(id AS INT) END AS v")
+    checkEquivalence(() =>
+      df.select($"id", $"pk",
+        min($"v").over(winSpec(-4, 4)).as("mn"),
+        max($"v").over(winSpec(-4, 4)).as("mx"),
+        sum($"v").over(winSpec(-4, 4)).as("sm"),
+        count($"v").over(winSpec(-4, 4)).as("cn")))
+  }
+
+  test("Double NaN and +/-Infinity propagate correctly through MIN/MAX/SUM") {
+    // Spark's NaN ordering: NaN is treated as greater than +Inf for MIN/MAX.
+    // +Inf + -Inf = NaN for SUM. The seg-tree path uses DeclarativeAggregate's
+    // own merge, so behavior must match the baseline exactly.
+    val df = spark.range(0, 30).selectExpr(
+      "id",
+      "(id % 2) AS pk",
+      """CASE
+           WHEN id % 7 = 0 THEN double('NaN')
+           WHEN id % 7 = 1 THEN double('Infinity')
+           WHEN id % 7 = 2 THEN double('-Infinity')
+           ELSE CAST(id AS DOUBLE)
+         END AS v""")
+    checkEquivalence(() =>
+      df.select($"id", $"pk",
+        min($"v").over(winSpec(-3, 3)).as("mn"),
+        max($"v").over(winSpec(-3, 3)).as("mx"),
+        sum($"v").over(winSpec(-3, 3)).as("sm")))
+  }
+
+  // ---------------- A4: data types ----------------
+
+  test("numeric types: Int / Long / Double / Decimal") {
+    val df = spark.range(0, 60).selectExpr(
+      "id",
+      "(id % 3) AS pk",
+      "CAST(id AS INT)             AS vi",
+      "CAST(id * 1000000L AS LONG) AS vl",
+      "CAST(id AS DOUBLE) + 0.25   AS vd",
+      "CAST(id AS DECIMAL(20,4))   AS vdec")
+    checkEquivalence(() =>
+      df.select($"id", $"pk",
+        sum($"vi").over(winSpec(-2, 2)).as("si"),
+        min($"vl").over(winSpec(-2, 2)).as("ml"),
+        max($"vd").over(winSpec(-2, 2)).as("xd"),
+        sum($"vdec").over(winSpec(-2, 2)).as("sdec"),
+        avg($"vdec").over(winSpec(-2, 2)).as("adec")))
+  }
+
+  test("String lexicographic MIN/MAX") {
+    // Deliberately non-monotone string values so that MIN/MAX actually
+    // exercise segment-tree merge rather than trivially matching the edge.
+    val df = spark.range(0, 40).selectExpr(
+      "id",
+      "(id % 2) AS pk",
+      "CONCAT('s', LPAD(CAST((id * 37) % 97 AS STRING), 3, '0')) AS v")
+    checkEquivalence(() =>
+      df.select($"id", $"pk",
+        min($"v").over(winSpec(-3, 3)).as("mn"),
+        max($"v").over(winSpec(-3, 3)).as("mx")))
+  }
+
+  test("Date / Timestamp MIN/MAX") {
+    val df = spark.range(0, 40).selectExpr(
+      "id",
+      "(id % 2) AS pk",
+      "date_add(DATE'2020-01-01', CAST((id * 13) % 365 AS INT)) AS vd",
+      "CAST(TIMESTAMP'2020-01-01 00:00:00' + " +
+        "make_interval(0, 0, 0, 0, 0, 0, CAST(id AS DECIMAL(18,6))) AS TIMESTAMP) AS vt")
+    checkEquivalence(() =>
+      df.select($"id", $"pk",
+        min($"vd").over(winSpec(-3, 3)).as("mnd"),
+        max($"vd").over(winSpec(-3, 3)).as("mxd"),
+        min($"vt").over(winSpec(-3, 3)).as("mnt"),
+        max($"vt").over(winSpec(-3, 3)).as("mxt")))
+  }
+
+  
+  test("collect_list falls back cleanly (non-DeclarativeAggregate)") {
+    // collect_list is a Collect(TypedImperativeAggregate) -- not a
+    // DeclarativeAggregate, so eligibleForSegTree must decline and the
+    // sliding frame must take over.
+    checkEquivalence(() =>
+      baseDF.select($"id", $"pk",
+        collect_list($"v").over(winSpec(-2, 2)).as("lst")))
+  }
+
+  test("DISTINCT window aggregate is rejected by analyzer regardless of seg-tree flag") {
+    // Spark does not support DISTINCT window aggregates at all -- the analyzer
+    // throws DISTINCT_WINDOW_FUNCTION_UNSUPPORTED before we ever reach frame
+    // construction. The seg-tree feature flag must not alter this behavior.
+    def run(): Unit = {
+      baseDF.select($"id", $"pk",
+        count_distinct($"v").over(winSpec(-3, 3)).as("cd")).collect()
+    }
+    withSQLConf(disableSegTree.toSeq: _*) {
+      val e = intercept[org.apache.spark.sql.AnalysisException](run())
+      assert(e.getMessage.contains("DISTINCT_WINDOW_FUNCTION_UNSUPPORTED"))
+    }
+    withSQLConf(enableSegTree.toSeq: _*) {
+      val e = intercept[org.apache.spark.sql.AnalysisException](run())
+      assert(e.getMessage.contains("DISTINCT_WINDOW_FUNCTION_UNSUPPORTED"))
+    }
+  }
+
+  test("feature flag off: segmentTree.enabled=false yields baseline semantics") {
+    // Sanity check: disabling the flag on a workload the seg-tree path would
+    // otherwise handle (MIN, wide frame, partitions above the min-rows
+    // threshold) still produces the SlidingWindowFunctionFrame answer.
+    val df = baseDF
+    val expected = withSQLConf(disableSegTree.toSeq: _*) {
+      df.select($"id", $"pk", min($"v").over(winSpec(-3, 3)).as("mn"))
+        .collect().sortBy(_.toString).toSeq
+    }
+    // Explicit disable with the full-size partition config (no min-rows
+    // override). This exercises the flag-off branch of eligibleForSegTree.
+    withSQLConf(
+      SQLConf.WINDOW_SEGMENT_TREE_ENABLED.key -> "false",
+      SQLConf.WINDOW_SEGMENT_TREE_MIN_PARTITION_ROWS.key -> "1024") {
+      val actual = df.select($"id", $"pk", min($"v").over(winSpec(-3, 3)).as("mn"))
+        .collect().sortBy(_.toString).toSeq
+      assert(actual === expected)
+    }
+  }
+
+    // A5.*: RANGE frame equivalence between seg-tree path and sliding baseline.
+  //
+  // The factory (`eligibleForSegTree`) now admits RangeFrame when orderSpec
+  // has exactly one ordering expression. These tests exercise the
+  // frameType-aware admit/drop loops in SegmentTreeWindowFunctionFrame.
+  //
+  // All tests follow the same oracle pattern as NULL/NaN/collation coverage: run the same
+  // query twice (seg-tree on / off) and assert equal Row sequences.
+  // Aggregates are MIN/MAX (non-invertible) to guarantee the seg-tree
+  // code path is actually exercised rather than short-circuited.
+
+  /** Run `sql` twice (flag off / on) and checkAnswer equality. */
+  private def checkRangeEquivalence(df: DataFrame, query: String): Unit = {
+    df.createOrReplaceTempView("t")
+    try {
+      val baseline = withSQLConf(disableSegTree.toSeq: _*) {
+        spark.sql(query).collect().sortBy(_.toString)
+      }
+      withSQLConf(enableSegTree.toSeq: _*) {
+        val actual = spark.sql(query).collect().sortBy(_.toString)
+        assert(actual.toSeq === baseline.toSeq,
+          s"segment-tree output differs from baseline.\nExpected: ${baseline.toSeq}\n" +
+            s"Actual:   ${actual.toSeq}")
+      }
+    } finally {
+      spark.catalog.dropTempView("t")
+    }
+  }
+
+  test("-- RANGE INT offset basic (non-uniform gaps, MIN/MAX)") {
+    // Non-uniform k gaps (1, 3, 4, 4, 7, 10, 15, ...) so that the frame
+    // edges shift by variable amounts and admit/drop loops must consult
+    // the order-key comparator rather than just row count.
+    val df = spark.range(0, 40).selectExpr(
+      "CAST(id AS INT) AS id",
+      "(CAST(id AS INT) % 2) AS pk",
+      "CAST(CASE CAST(id AS INT) % 7 " +
+        "WHEN 0 THEN 1 WHEN 1 THEN 3 WHEN 2 THEN 4 WHEN 3 THEN 4 " +
+        "WHEN 4 THEN 7 WHEN 5 THEN 10 ELSE 15 END + (CAST(id AS INT) / 7) * 20 AS INT) AS k",
+      "CAST((id * 31) % 97 AS INT) AS v")
+    checkRangeEquivalence(df,
+      """SELECT id, pk,
+        |  MIN(v) OVER (PARTITION BY pk ORDER BY k
+        |    RANGE BETWEEN 2 PRECEDING AND 2 FOLLOWING) AS mn,
+        |  MAX(v) OVER (PARTITION BY pk ORDER BY k
+        |    RANGE BETWEEN 2 PRECEDING AND 2 FOLLOWING) AS mx
+        |FROM t""".stripMargin)
+  }
+
+  test("-- RANGE Timestamp with INTERVAL offset (MAX)") {
+    // Irregular gaps: 30min / 90min / 2h / 30min / ... so frame edges
+    // crossing the 1-hour bound must rely on the timestamp comparator.
+    val df = spark.range(0, 30).selectExpr(
+      "CAST(id AS INT) AS id",
+      "(CAST(id AS INT) % 2) AS pk",
+      "CAST(TIMESTAMP'2024-01-01 10:00:00' + " +
+        "make_interval(0, 0, 0, 0, 0, 30 * CAST(id AS INT) * " +
+        "(CASE CAST(id AS INT) % 3 WHEN 0 THEN 1 WHEN 1 THEN 3 ELSE 4 END), 0) " +
+        "AS TIMESTAMP) AS ts",
+      "CAST((id * 17) % 53 AS INT) AS v")
+    checkRangeEquivalence(df,
+      """SELECT id, pk,
+        |  MAX(v) OVER (PARTITION BY pk ORDER BY ts
+        |    RANGE BETWEEN INTERVAL '1' HOUR PRECEDING
+        |              AND INTERVAL '1' HOUR FOLLOWING) AS mx
+        |FROM t""".stripMargin)
+  }
+
+  test("-- RANGE with tie (duplicate order keys) inclusion at boundary") {
+    // k = [1, 2, 2, 2, 3, 4, 5] repeated across partitions. A frame of
+    // `0 PRECEDING AND 0 FOLLOWING` must include the FULL tie group at
+    // the current row's k, not just the current row itself. If the
+    // seg-tree path confuses RANGE with ROWS the tie group of k=2 would
+    // return a per-row MIN/MAX rather than a group-level one.
+    val rows = (0 until 40).map { i =>
+      val k = Seq(1, 2, 2, 2, 3, 4, 5)(i % 7)
+      (i, i % 2, k, (i * 13) % 41)
+    }
+    val df = rows.toDF("id", "pk", "k", "v")
+    checkRangeEquivalence(df,
+      """SELECT id, pk, k,
+        |  MIN(v) OVER (PARTITION BY pk ORDER BY k
+        |    RANGE BETWEEN 0 PRECEDING AND 0 FOLLOWING) AS mn,
+        |  MAX(v) OVER (PARTITION BY pk ORDER BY k
+        |    RANGE BETWEEN 0 PRECEDING AND 0 FOLLOWING) AS mx
+        |FROM t""".stripMargin)
+  }
+
+  test("-- RANGE frame wider than partition (C4: admit/drop loops no-op)") {
+    // Partition size 5 rows, frame covers everything. Once the first
+    // batch is admitted, the admit/drop loops in the seg-tree frame must
+    // detect the effective frame is unchanged and skip work.
+    val df = spark.range(0, 25).selectExpr(
+      "CAST(id AS INT) AS id",
+      "(CAST(id AS INT) / 5) AS pk",
+      "CAST((id * 7) % 23 AS INT) AS k",
+      "CAST((id * 19) % 101 AS INT) AS v")
+    checkRangeEquivalence(df,
+      """SELECT id, pk,
+        |  MIN(v) OVER (PARTITION BY pk ORDER BY k
+        |    RANGE BETWEEN 100 PRECEDING AND 100 FOLLOWING) AS mn,
+        |  MAX(v) OVER (PARTITION BY pk ORDER BY k
+        |    RANGE BETWEEN 100 PRECEDING AND 100 FOLLOWING) AS mx
+        |FROM t""".stripMargin)
+  }
+
+  test("-- RANGE with NULL order key (NULLS FIRST / NULLS LAST)") {
+    // k = [NULL, NULL, 1, 2, 3, NULL] repeated. Spark groups all NULLs
+    // into a single equivalence class at head (NULLS FIRST) or tail
+    // (NULLS LAST). The seg-tree admit/drop loops must treat NULL as a
+    // tie group identically to the sliding baseline.
+    val rows = (0 until 36).map { i =>
+      val kOpt: Option[Int] = (i % 6) match {
+        case 0 | 1 | 5 => None
+        case 2 => Some(1)
+        case 3 => Some(2)
+        case _ => Some(3)
+      }
+      (i, i % 2, kOpt, (i * 11) % 37)
+    }
+    val df = rows.toDF("id", "pk", "k", "v")
+    checkRangeEquivalence(df,
+      """SELECT id, pk,
+        |  MIN(v) OVER (PARTITION BY pk ORDER BY k ASC NULLS FIRST
+        |    RANGE BETWEEN 1 PRECEDING AND 1 FOLLOWING) AS mn_nf,
+        |  MAX(v) OVER (PARTITION BY pk ORDER BY k ASC NULLS FIRST
+        |    RANGE BETWEEN 1 PRECEDING AND 1 FOLLOWING) AS mx_nf,
+        |  MIN(v) OVER (PARTITION BY pk ORDER BY k ASC NULLS LAST
+        |    RANGE BETWEEN 1 PRECEDING AND 1 FOLLOWING) AS mn_nl,
+        |  MAX(v) OVER (PARTITION BY pk ORDER BY k ASC NULLS LAST
+        |    RANGE BETWEEN 1 PRECEDING AND 1 FOLLOWING) AS mx_nl
+        |FROM t""".stripMargin)
+  }
+
+    // Decimal overflow across seg-tree block merge
+  // BinaryType MIN/MAX across seg-tree block merge
+  // UDAF (ScalaUDAF / ScalaAggregator) fallback
+  //
+  // All Decimal/Binary tests force blockSize=16 (the minimum the config
+  // allows) + window size > blockSize so the seg-tree path crosses at
+  // least one block boundary (exercises `mergeExpressions` rather than
+  // only `update`). Design doc asked for blockSize=4 but the SQLConf
+  // validator rejects anything below 16; scaling data/frame up preserves
+  // the merge-path coverage the doc intended.
+
+  private val segTreeBlock: String = "16"
+  private val segTreeFramePrec: Int = 17
+  private val segTreeRows: Int = 20
+
+  private def withSegTreeBlock(conf: (String, String)*)(body: => Unit): Unit = {
+    val extra = Seq(SQLConf.WINDOW_SEGMENT_TREE_BLOCK_SIZE.key -> segTreeBlock) ++ conf
+    withSQLConf(extra: _*)(body)
+  }
+
+  
+  /**
+   * 20 rows in a single partition, Decimal(38, 0) values near the type's
+   * upper bound. Frame of `segTreeFramePrec` PRECEDING..CURRENT ROW means
+   * any window with >= 2 such rows overflows the widened Sum buffer
+   * (Decimal(38,0) widened to Decimal(38,0); any addition above 1e38
+   * overflows). Block size 16 + frame 17 forces cross-block merge.
+   */
+  private def decimalOverflowDF: DataFrame = {
+    // 9e37 -- below Decimal(38,0) MAX (~9.99e37), but 2x overflows.
+    val big = "90000000000000000000000000000000000000"  // 38 digits
+    spark.range(0, segTreeRows.toLong).selectExpr(
+      "CAST(id AS INT) AS id",
+      "0 AS pk",
+      s"CAST('$big' AS DECIMAL(38, 0)) AS v")
+  }
+
+  private val decimalOverflowSql: String =
+    s"""SELECT id, pk,
+       |  SUM(v) OVER (PARTITION BY pk ORDER BY id
+       |    ROWS BETWEEN $segTreeFramePrec PRECEDING AND CURRENT ROW) AS s
+       |FROM t""".stripMargin
+
+  test("a -- Decimal overflow ANSI on, seg-tree matches sliding (both throw)") {
+    val df = decimalOverflowDF
+    df.createOrReplaceTempView("t")
+    try {
+      withSegTreeBlock(SQLConf.ANSI_ENABLED.key -> "true") {
+        withSQLConf(disableSegTree.toSeq: _*) {
+          val e = intercept[Exception] {
+            spark.sql(decimalOverflowSql).collect()
+          }
+          assert(rootArithmeticCause(e).isDefined,
+            s"expected ArithmeticException root cause, got: ${e.getMessage}")
+        }
+        withSQLConf(enableSegTree.toSeq: _*) {
+          val e = intercept[Exception] {
+            spark.sql(decimalOverflowSql).collect()
+          }
+          assert(rootArithmeticCause(e).isDefined,
+            s"expected ArithmeticException root cause, got: ${e.getMessage}")
+        }
+      }
+    } finally {
+      spark.catalog.dropTempView("t")
+    }
+  }
+
+  test("b -- Decimal overflow ANSI off, seg-tree matches sliding (NULL on overflow)") {
+    val df = decimalOverflowDF
+    df.createOrReplaceTempView("t")
+    try {
+      withSegTreeBlock(SQLConf.ANSI_ENABLED.key -> "false") {
+        val baseline = withSQLConf(disableSegTree.toSeq: _*) {
+          spark.sql(decimalOverflowSql).collect().sortBy(_.toString)
+        }
+        // At least one row must be NULL so we know overflow actually fired.
+        assert(baseline.exists(_.isNullAt(2)),
+          "baseline should contain NULL overflow rows; test data may be too small")
+        withSQLConf(enableSegTree.toSeq: _*) {
+          val actual = spark.sql(decimalOverflowSql).collect().sortBy(_.toString)
+          assert(actual.toSeq === baseline.toSeq)
+        }
+      }
+    } finally {
+      spark.catalog.dropTempView("t")
+    }
+  }
+
+  test("c -- mid-window Decimal overflow slides past (seg-tree == sliding)") {
+    // 24 rows, blockSize=16. Frame ROWS BETWEEN 3 PRECEDING AND CURRENT ROW
+    // (size 4). Near-MAX values at ids 14,15,16,17 so any 4-row window
+    // containing >=2 of them overflows. Windows at:
+    //   id<14 or id>20   -> safe
+    //   id in [15..20]   -> overlaps >=2 big values -> NULL
+    // The big-value band (14..17) straddles the block boundary at id=16,
+    // guaranteeing cross-block merge paths see overflowing buffers.
+    val big = "90000000000000000000000000000000000000"
+    val df = spark.range(0, 24).selectExpr(
+      "CAST(id AS INT) AS id",
+      "0 AS pk",
+      s"""CASE WHEN id IN (14, 15, 16, 17)
+              THEN CAST('$big' AS DECIMAL(38, 0))
+              ELSE CAST(id AS DECIMAL(38, 0))
+         END AS v""")
+    df.createOrReplaceTempView("t")
+    try {
+      val sqlStr =
+        """SELECT id, pk,
+          |  SUM(v) OVER (PARTITION BY pk ORDER BY id
+          |    ROWS BETWEEN 3 PRECEDING AND CURRENT ROW) AS s
+          |FROM t""".stripMargin
+      withSegTreeBlock(SQLConf.ANSI_ENABLED.key -> "false") {
+        val baseline = withSQLConf(disableSegTree.toSeq: _*) {
+          spark.sql(sqlStr).collect().sortBy(_.toString)
+        }
+        // Sanity: overflow fired on some rows AND window slides past to
+        // recover non-NULL on the tail rows.
+        assert(baseline.exists(_.isNullAt(2)),
+          "baseline should contain NULL overflow rows")
+        assert(baseline.exists(r => r.getInt(0) >= 21 && !r.isNullAt(2)),
+          "rows with id>=21 should be non-NULL (window slid past big values)")
+        withSQLConf(enableSegTree.toSeq: _*) {
+          val actual = spark.sql(sqlStr).collect().sortBy(_.toString)
+          assert(actual.toSeq === baseline.toSeq)
+        }
+      }
+    } finally {
+      spark.catalog.dropTempView("t")
+    }
+  }
+
+  /** Walk a SparkException chain for an ArithmeticException (ANSI overflow). */
+  private def rootArithmeticCause(t: Throwable): Option[Throwable] = {
+    var cur: Throwable = t
+    while (cur != null) {
+      if (cur.isInstanceOf[ArithmeticException]) return Some(cur)
+      cur = cur.getCause
+    }
+    None
+  }

Review Comment:
   Addressed in `6c433a68d78` (R3-T5-exceptionutils). Thank you for the advice!



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/AggregateProcessor.scala:
##########
@@ -181,7 +181,12 @@ private[window] final class AggregateProcessor(
   }
 
   /** Evaluate buffer. */
-  def evaluate(target: InternalRow): Unit = {
-    evaluateProjection.target(target)(buffer)
+  def evaluate(target: InternalRow): Unit = evaluate(buffer, target)
+
+  /** Evaluate using an arbitrary `source` buffer (e.g. a segment-tree query
+   *  result) instead of the internal one. See
+   *  `docs/frame-integration-contract.md` Section 3. */
+  private[window] def evaluate(source: InternalRow, target: InternalRow): Unit = {

Review Comment:
   Addressed in `639e04e7101` (R3-scaladoc-contract). Thank you for the advice!



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowSegmentTree.scala:
##########
@@ -0,0 +1,601 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.execution.window
+
+import java.util.{LinkedHashMap => JLinkedHashMap, Map => JMap}
+
+import scala.collection.mutable
+
+import org.apache.spark.{SparkEnv, SparkException, TaskContext}
+import org.apache.spark.memory.{MemoryConsumer, TaskMemoryManager}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.expressions.aggregate.DeclarativeAggregate
+import org.apache.spark.sql.errors.QueryExecutionErrors
+import org.apache.spark.sql.execution.ExternalAppendOnlyUnsafeRowArray
+import org.apache.spark.sql.types.DataType
+import org.apache.spark.util.ArrayImplicits._
+
+/**

Review Comment:
   Addressed in `639e04e7101` (R3-scaladoc-contract). Thank you for the advice!



-- 
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@spark.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-56546][SQL] Block-chunked segment-tree window frame for non-invertible sliding aggregates [spark]

Posted by "yaooqinn (via GitHub)" <gi...@apache.org>.
yaooqinn commented on code in PR #55422:
URL: https://github.com/apache/spark/pull/55422#discussion_r3118099236


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/errors/QueryExecutionErrors.scala:
##########
@@ -1194,6 +1194,24 @@ private[sql] object QueryExecutionErrors extends QueryErrorsBase with ExecutionE
       new java.util.HashMap[String, String]())
   }
 
+  /**
+   * Thrown when a `WindowSegmentTree` block cannot acquire `requestedBytes`
+   * from the TaskMemoryManager even after a manual evict-and-retry cycle.
+   * `receivedBytes` reports any partial grant already rolled back to the
+   * TMM (currently always `0L` at the sole call site, since partial
+   * grants are rolled back inside `acquireBlockMemory` before reaching
+   * this path). Mirrors the `UNABLE_TO_ACQUIRE_MEMORY` error class.
+   */

Review Comment:
   ```suggestion
   ```



-- 
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@spark.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-56546][SQL] Block-chunked segment-tree window frame for non-invertible sliding aggregates [spark]

Posted by "yaooqinn (via GitHub)" <gi...@apache.org>.
yaooqinn commented on code in PR #55422:
URL: https://github.com/apache/spark/pull/55422#discussion_r3192759338


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowEvaluatorFactoryBase.scala:
##########
@@ -295,4 +342,59 @@ trait WindowEvaluatorFactoryBase {
     }
   }
 
+  /**
+   * Segment-tree path eligibility. The tree relies on
+   * `DeclarativeAggregate.mergeExpressions`, which [[AggregateWindowFunction]]s
+   * (NthValue, NTile, Rank, RowNumber, NullIndex) refuse via
+   * `mergeUnsupportedByWindowFunctionError`: they extend DeclarativeAggregate
+   * but are NOT merge-capable. Normal aggregate window expressions reach this
+   * code as the inner DeclarativeAggregate unwrapped from
+   * [[AggregateExpression]] (see `windowFrameExpressionFactoryPairs.collect`).
+   *
+   * DISTINCT aggregate window expressions are already rejected earlier in
+   * analysis by `WindowResolution.checkWindowFunction`
+   * (error class `DISTINCT_WINDOW_FUNCTION_UNSUPPORTED`), so no explicit
+   * `isDistinct` gate is needed here.
+   */
+  private def eligibleForSegTree(
+      functions: Array[Expression],
+      filters: Array[Option[Expression]],
+      frameType: FrameType): Boolean = {
+    // RANGE accepted only for single-column order specs. Multi-column RANGE
+    // with non-zero offset is already rejected by `createBoundOrdering`, so
+    // gating here on `orderSpec.size == 1` matches the Sliding-path invariant.
+    val frameTypeOk = frameType match {
+      case RowFrame => true
+      case RangeFrame => orderSpec.size == 1
+    }
+    SQLConf.get.windowSegmentTreeEnabled &&

Review Comment:
   Addressed in `eb31df11e5f` (thread-conf-param). Thank you for the advice!



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/AggregateProcessor.scala:
##########
@@ -181,7 +181,26 @@ private[window] final class AggregateProcessor(
   }
 
   /** Evaluate buffer. */
-  def evaluate(target: InternalRow): Unit = {
-    evaluateProjection.target(target)(buffer)
+  def evaluate(target: InternalRow): Unit = evaluate(buffer, target)
+
+  /**
+   * Evaluate using an arbitrary `source` buffer (e.g. a segment-tree query
+   * result) instead of the internal one.
+   *
+   * '''Contract''': `source` must share this processor's internal
+   * `aggBufferAttributes` layout -- same field count, same dataTypes, in the
+   * same order. The segment-tree path enforces this upstream in
+   * `WindowEvaluatorFactoryBase.eligibleForSegTree` (rejects
+   * `SizeBasedWindowFunction`; the same `functions: Array[DeclarativeAggregate]`

Review Comment:
   Addressed in `eb31df11e5f` (allowlist-comment). Thank you for the advice!



-- 
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@spark.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [WIP][SPARK-56546][SQL] Block-chunked segment-tree window frame for non-invertible sliding aggregates [spark]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #55422:
URL: https://github.com/apache/spark/pull/55422#discussion_r3108882112


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowSegmentTree.scala:
##########
@@ -0,0 +1,610 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.execution.window
+
+import java.util.{LinkedHashMap => JLinkedHashMap, Map => JMap}
+
+import scala.collection.mutable
+
+import org.apache.spark.{SparkEnv, SparkException, TaskContext}
+import org.apache.spark.memory.{MemoryConsumer, TaskMemoryManager}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.expressions.aggregate.DeclarativeAggregate
+import org.apache.spark.sql.errors.QueryExecutionErrors
+import org.apache.spark.sql.execution.ExternalAppendOnlyUnsafeRowArray
+import org.apache.spark.sql.types.DataType
+import org.apache.spark.util.ArrayImplicits._
+
+/**
+ * Block-chunked segment tree for range aggregate queries over window partitions.
+ *
+ * See `the class documentation`
+ * for the full design (API contract Section 2, block-chunked memory layout Section 3,
+ * DeclarativeAggregate binding Section 4, error handling Section 5, test hooks Section 6).

Review Comment:
   This file contains merge-blocking placeholders and nonstandard markers: backticked “the class documentation”, multiple `TODO(SPARK-XXXXX)` stubs, and a `FIXME(name)` line. Before merging, please replace placeholders with concrete references (doc path/URL or class name) and actual SPARK JIRA IDs, and convert the `FIXME(...)` to a `TODO(SPARK-xxxxx)` (without personal attribution) so it fits Spark’s tracking conventions.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowEvaluatorFactoryBase.scala:
##########
@@ -295,4 +344,63 @@ trait WindowEvaluatorFactoryBase {
     }
   }
 
+  /**
+   * Segment-tree path eligibility. The tree relies on `DeclarativeAggregate.mergeExpressions`,
+   * which [[AggregateWindowFunction]]s (e.g. NthValue, NTile, Rank, RowNumber, NullIndex) refuse
+   * with `mergeUnsupportedByWindowFunctionError`. They extend DeclarativeAggregate but are
+   * NOT merge-capable, so we must exclude them here even though the base-class check passes.
+   * Normal aggregate window expressions reach this code as the inner DeclarativeAggregate
+   * unwrapped from [[AggregateExpression]] (see `windowFrameExpressionFactoryPairs.collect`).
+   */
+  private def eligibleForSegTree(
+      functions: Array[Expression],
+      filters: Array[Option[Expression]],
+      frameType: FrameType): Boolean = {
+    // RANGE is accepted only for single-column order specs. Multi-column
+    // RANGE with non-zero offset is already rejected by `createBoundOrdering`
+    // (see the `RangeFrame, _` internalError branch above), so gating here
+    // on `orderSpec.size == 1` matches the Sliding-path invariant exactly.
+    val frameTypeOk = frameType match {
+      case RowFrame => true
+      case RangeFrame => orderSpec.size == 1
+    }
+    SQLConf.get.windowSegmentTreeEnabled &&
+      frameTypeOk &&
+      filters.forall(_.isEmpty) &&
+      functions.forall { f =>
+        f.isInstanceOf[DeclarativeAggregate] && !f.isInstanceOf[AggregateWindowFunction]
+      } &&
+      !functions.exists {
+        case ae: AggregateExpression => ae.isDistinct
+        case _ => false
+      }

Review Comment:
   The `DISTINCT` rejection check is ineffective in this context: in the moving-frame branch the `functions` passed into `AggregateProcessor(...)` are the inner aggregate functions (e.g., `Count`, `Sum`) and not `AggregateExpression`, so the `case ae: AggregateExpression => ae.isDistinct` branch will never match. If you want to keep the “no DISTINCT” contract local to eligibility, derive the `isDistinct` flag(s) from the original `expressions` (the `WindowExpression(AggregateExpression, _)` nodes) and pass that information into `eligibleForSegTree`, or perform the distinct check while building `aggFilters` (same place you pattern match on `AggregateExpression`).
   ```suggestion
       val hasDistinctAggregate = windowExpression.exists {
         case WindowExpression(ae: AggregateExpression, _) =>
           ae.isDistinct && functions.exists(_.semanticEquals(ae.aggregateFunction))
         case _ => false
       }
       SQLConf.get.windowSegmentTreeEnabled &&
         frameTypeOk &&
         filters.forall(_.isEmpty) &&
         functions.forall { f =>
           f.isInstanceOf[DeclarativeAggregate] && !f.isInstanceOf[AggregateWindowFunction]
         } &&
         !hasDistinctAggregate
   ```



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowSegmentTree.scala:
##########
@@ -0,0 +1,610 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.execution.window
+
+import java.util.{LinkedHashMap => JLinkedHashMap, Map => JMap}
+
+import scala.collection.mutable
+
+import org.apache.spark.{SparkEnv, SparkException, TaskContext}
+import org.apache.spark.memory.{MemoryConsumer, TaskMemoryManager}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.expressions.aggregate.DeclarativeAggregate
+import org.apache.spark.sql.errors.QueryExecutionErrors
+import org.apache.spark.sql.execution.ExternalAppendOnlyUnsafeRowArray
+import org.apache.spark.sql.types.DataType
+import org.apache.spark.util.ArrayImplicits._
+
+/**
+ * Block-chunked segment tree for range aggregate queries over window partitions.
+ *
+ * See `the class documentation`
+ * for the full design (API contract Section 2, block-chunked memory layout Section 3,
+ * DeclarativeAggregate binding Section 4, error handling Section 5, test hooks Section 6).
+ *
+ * initial implementation scope: correctness only. The data layer uses
+ * `ExternalAppendOnlyUnsafeRowArray` to hold input rows (spillable). Each
+ * block materializes its own small segment tree (levels 0..h). Internal
+ * nodes are cached in an LRU keyed by block index; block root aggregates
+ * (block pre-aggregates) stay resident for all blocks.
+ *
+ * Note: the design doc Section 3.3 specifies leaves are NOT materialized and
+ * recomputed from the spillable array on demand. For initial implementation simplicity
+ * we materialize leaves inside the per-block internal node arrays.
+ * // TODO(SPARK-XXXXX) re-assess after Frame integration.
+ *
+ * @note Instances are not thread-safe.
+ */
+private[window] class WindowSegmentTree(
+    functions: Array[DeclarativeAggregate],
+    inputSchema: Seq[Attribute],
+    newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
+    fanout: Int = WindowSegmentTree.DefaultFanout,
+    blockSize: Int = WindowSegmentTree.DefaultBlockSize,
+    maxCachedBlocks: Option[Int] = None,
+    spillThreshold: Int = Int.MaxValue,
+    inMemoryThreshold: Int = Int.MaxValue,
+    taskMemoryManager: TaskMemoryManager = null)
+  extends AutoCloseable {
+
+  require(fanout >= 2, s"fanout must be >= 2, got $fanout")
+  require(blockSize >= 1, s"blockSize must be >= 1, got $blockSize")
+  require(functions.nonEmpty, "WindowSegmentTree requires at least one aggregate function")
+  maxCachedBlocks.foreach { n =>
+    require(n >= 1, s"maxCachedBlocks must be >= 1 when specified, got $n")
+  }
+  require(taskMemoryManager != null,
+    "WindowSegmentTree requires a non-null TaskMemoryManager; " +
+      "in tests use `new TaskMemoryManager(new TestMemoryManager(conf), 0)`")
+
+  // ---------- Schemas & projections ----------
+
+  private val bufferAttrs: Seq[AttributeReference] =
+    functions.flatMap(_.aggBufferAttributes).toImmutableArraySeq
+  private val rightAttrs: Seq[AttributeReference] =
+    functions.flatMap(_.inputAggBufferAttributes).toImmutableArraySeq
+  private val bufferDataTypes: IndexedSeq[DataType] =
+    bufferAttrs.map(_.dataType).toIndexedSeq
+
+  private val initialValues: Seq[Expression] = functions.flatMap(_.initialValues).toIndexedSeq
+  private val updateExpressions: Seq[Expression] =
+    functions.flatMap(_.updateExpressions).toIndexedSeq
+  private val mergeExpressions: Seq[Expression] =
+    functions.flatMap(_.mergeExpressions).toIndexedSeq
+
+  private[this] val initProj: MutableProjection = newMutableProjection(initialValues, Nil)
+  private[this] val updateProj: MutableProjection =
+    newMutableProjection(updateExpressions, bufferAttrs ++ inputSchema)
+  private[this] val mergeProj: MutableProjection =
+    newMutableProjection(mergeExpressions, bufferAttrs ++ rightAttrs)
+
+  private val inputUnsafeProj: UnsafeProjection =
+    UnsafeProjection.create(inputSchema.map(_.dataType).toArray)
+
+  private[this] val joinedRow = new JoinedRow()
+
+  // ---------- State ----------
+
+  private var numRows: Int = 0
+  private var numBlocks: Int = 0
+  private var rowArray: ExternalAppendOnlyUnsafeRowArray = _
+  private var closed: Boolean = false
+
+  /** Always-resident per-block root aggregates. `blockAggregates(i)` =
+   *  merged buffer over all rows in block i. */
+  private var blockAggregates: Array[InternalRow] = Array.empty
+
+  /** Rough byte width of one aggregate buffer row. Chosen at 16 B/field as a
+   *  conservative heap-overhead-aware lower bound for a
+   *  `SpecificInternalRow` slot: primitive `MutableValue` is 8 B, boxed
+   *  references and object headers push the effective footprint higher.
+   *  Tighter per-type sizing (real boxing cost, variable-length fields) is
+   *  intentionally out of scope here; TaskMemoryManager remains the hard
+   *  backstop via spill / OOM.
+   *  TODO(SPARK-XXXXX): per-type width estimator keyed on
+   *  `bufferDataTypes` (primitive 16 B, String/Binary/Decimal wider). */

Review Comment:
   This file contains merge-blocking placeholders and nonstandard markers: backticked “the class documentation”, multiple `TODO(SPARK-XXXXX)` stubs, and a `FIXME(name)` line. Before merging, please replace placeholders with concrete references (doc path/URL or class name) and actual SPARK JIRA IDs, and convert the `FIXME(...)` to a `TODO(SPARK-xxxxx)` (without personal attribution) so it fits Spark’s tracking conventions.
   ```suggestion
      *  A future refinement could estimate widths from `bufferDataTypes`
      *  (for example, primitive types at 16 B and wider estimates for
      *  StringType, BinaryType, and DecimalType). */
   ```



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowSegmentTree.scala:
##########
@@ -0,0 +1,610 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.execution.window
+
+import java.util.{LinkedHashMap => JLinkedHashMap, Map => JMap}
+
+import scala.collection.mutable
+
+import org.apache.spark.{SparkEnv, SparkException, TaskContext}
+import org.apache.spark.memory.{MemoryConsumer, TaskMemoryManager}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.expressions.aggregate.DeclarativeAggregate
+import org.apache.spark.sql.errors.QueryExecutionErrors
+import org.apache.spark.sql.execution.ExternalAppendOnlyUnsafeRowArray
+import org.apache.spark.sql.types.DataType
+import org.apache.spark.util.ArrayImplicits._
+
+/**
+ * Block-chunked segment tree for range aggregate queries over window partitions.
+ *
+ * See `the class documentation`
+ * for the full design (API contract Section 2, block-chunked memory layout Section 3,
+ * DeclarativeAggregate binding Section 4, error handling Section 5, test hooks Section 6).
+ *
+ * initial implementation scope: correctness only. The data layer uses
+ * `ExternalAppendOnlyUnsafeRowArray` to hold input rows (spillable). Each
+ * block materializes its own small segment tree (levels 0..h). Internal
+ * nodes are cached in an LRU keyed by block index; block root aggregates
+ * (block pre-aggregates) stay resident for all blocks.
+ *
+ * Note: the design doc Section 3.3 specifies leaves are NOT materialized and
+ * recomputed from the spillable array on demand. For initial implementation simplicity
+ * we materialize leaves inside the per-block internal node arrays.
+ * // TODO(SPARK-XXXXX) re-assess after Frame integration.
+ *
+ * @note Instances are not thread-safe.
+ */
+private[window] class WindowSegmentTree(
+    functions: Array[DeclarativeAggregate],
+    inputSchema: Seq[Attribute],
+    newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
+    fanout: Int = WindowSegmentTree.DefaultFanout,
+    blockSize: Int = WindowSegmentTree.DefaultBlockSize,
+    maxCachedBlocks: Option[Int] = None,
+    spillThreshold: Int = Int.MaxValue,
+    inMemoryThreshold: Int = Int.MaxValue,
+    taskMemoryManager: TaskMemoryManager = null)
+  extends AutoCloseable {
+
+  require(fanout >= 2, s"fanout must be >= 2, got $fanout")
+  require(blockSize >= 1, s"blockSize must be >= 1, got $blockSize")
+  require(functions.nonEmpty, "WindowSegmentTree requires at least one aggregate function")
+  maxCachedBlocks.foreach { n =>
+    require(n >= 1, s"maxCachedBlocks must be >= 1 when specified, got $n")
+  }
+  require(taskMemoryManager != null,
+    "WindowSegmentTree requires a non-null TaskMemoryManager; " +
+      "in tests use `new TaskMemoryManager(new TestMemoryManager(conf), 0)`")
+
+  // ---------- Schemas & projections ----------
+
+  private val bufferAttrs: Seq[AttributeReference] =
+    functions.flatMap(_.aggBufferAttributes).toImmutableArraySeq
+  private val rightAttrs: Seq[AttributeReference] =
+    functions.flatMap(_.inputAggBufferAttributes).toImmutableArraySeq
+  private val bufferDataTypes: IndexedSeq[DataType] =
+    bufferAttrs.map(_.dataType).toIndexedSeq
+
+  private val initialValues: Seq[Expression] = functions.flatMap(_.initialValues).toIndexedSeq
+  private val updateExpressions: Seq[Expression] =
+    functions.flatMap(_.updateExpressions).toIndexedSeq
+  private val mergeExpressions: Seq[Expression] =
+    functions.flatMap(_.mergeExpressions).toIndexedSeq
+
+  private[this] val initProj: MutableProjection = newMutableProjection(initialValues, Nil)
+  private[this] val updateProj: MutableProjection =
+    newMutableProjection(updateExpressions, bufferAttrs ++ inputSchema)
+  private[this] val mergeProj: MutableProjection =
+    newMutableProjection(mergeExpressions, bufferAttrs ++ rightAttrs)
+
+  private val inputUnsafeProj: UnsafeProjection =
+    UnsafeProjection.create(inputSchema.map(_.dataType).toArray)
+
+  private[this] val joinedRow = new JoinedRow()
+
+  // ---------- State ----------
+
+  private var numRows: Int = 0
+  private var numBlocks: Int = 0
+  private var rowArray: ExternalAppendOnlyUnsafeRowArray = _
+  private var closed: Boolean = false
+
+  /** Always-resident per-block root aggregates. `blockAggregates(i)` =
+   *  merged buffer over all rows in block i. */
+  private var blockAggregates: Array[InternalRow] = Array.empty
+
+  /** Rough byte width of one aggregate buffer row. Chosen at 16 B/field as a
+   *  conservative heap-overhead-aware lower bound for a
+   *  `SpecificInternalRow` slot: primitive `MutableValue` is 8 B, boxed
+   *  references and object headers push the effective footprint higher.
+   *  Tighter per-type sizing (real boxing cost, variable-length fields) is
+   *  intentionally out of scope here; TaskMemoryManager remains the hard
+   *  backstop via spill / OOM.
+   *  TODO(SPARK-XXXXX): per-type width estimator keyed on
+   *  `bufferDataTypes` (primitive 16 B, String/Binary/Decimal wider). */
+  private val bufferWidthBytes: Long = {
+    val bytesPerField = 16L
+    math.max(1L, bufferDataTypes.size.toLong * bytesPerField)
+  }
+
+  /** Number of aggregate-buffer slots cached per block (contract I5).
+   *
+   *  Invariant: equals `sum over levels L of levels(L).length` for any
+   *  block materialized by [[buildBlockLevels]]. Level 0 holds `blockSize`
+   *  leaf buffers and each subsequent level holds `ceil(prev / fanout)`
+   *  parent buffers until a single root remains. The iterative ceiling
+   *  matches the allocation in [[buildBlockLevels]] for every
+   *  `(blockSize, fanout)` pair, including non-power-of-`fanout` cases.
+   *  For `blockSize == 1` the block is a single leaf with no parent
+   *  levels, so this returns 1.
+   *  TODO(SPARK-XXXXX): drop the leaf term when [[buildBlockLevels]]
+   *  switches to on-demand leaf recomputation. */

Review Comment:
   This file contains merge-blocking placeholders and nonstandard markers: backticked “the class documentation”, multiple `TODO(SPARK-XXXXX)` stubs, and a `FIXME(name)` line. Before merging, please replace placeholders with concrete references (doc path/URL or class name) and actual SPARK JIRA IDs, and convert the `FIXME(...)` to a `TODO(SPARK-xxxxx)` (without personal attribution) so it fits Spark’s tracking conventions.
   ```suggestion
      *  If [[buildBlockLevels]] switches to on-demand leaf recomputation in a
      *  future change, this calculation should drop the leaf term. */
   ```



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowSegmentTree.scala:
##########
@@ -0,0 +1,610 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.execution.window
+
+import java.util.{LinkedHashMap => JLinkedHashMap, Map => JMap}
+
+import scala.collection.mutable
+
+import org.apache.spark.{SparkEnv, SparkException, TaskContext}
+import org.apache.spark.memory.{MemoryConsumer, TaskMemoryManager}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.expressions.aggregate.DeclarativeAggregate
+import org.apache.spark.sql.errors.QueryExecutionErrors
+import org.apache.spark.sql.execution.ExternalAppendOnlyUnsafeRowArray
+import org.apache.spark.sql.types.DataType
+import org.apache.spark.util.ArrayImplicits._
+
+/**
+ * Block-chunked segment tree for range aggregate queries over window partitions.
+ *
+ * See `the class documentation`
+ * for the full design (API contract Section 2, block-chunked memory layout Section 3,
+ * DeclarativeAggregate binding Section 4, error handling Section 5, test hooks Section 6).
+ *
+ * initial implementation scope: correctness only. The data layer uses
+ * `ExternalAppendOnlyUnsafeRowArray` to hold input rows (spillable). Each
+ * block materializes its own small segment tree (levels 0..h). Internal
+ * nodes are cached in an LRU keyed by block index; block root aggregates
+ * (block pre-aggregates) stay resident for all blocks.
+ *
+ * Note: the design doc Section 3.3 specifies leaves are NOT materialized and
+ * recomputed from the spillable array on demand. For initial implementation simplicity
+ * we materialize leaves inside the per-block internal node arrays.
+ * // TODO(SPARK-XXXXX) re-assess after Frame integration.

Review Comment:
   This file contains merge-blocking placeholders and nonstandard markers: backticked “the class documentation”, multiple `TODO(SPARK-XXXXX)` stubs, and a `FIXME(name)` line. Before merging, please replace placeholders with concrete references (doc path/URL or class name) and actual SPARK JIRA IDs, and convert the `FIXME(...)` to a `TODO(SPARK-xxxxx)` (without personal attribution) so it fits Spark’s tracking conventions.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowEvaluatorFactoryBase.scala:
##########
@@ -191,13 +200,17 @@ trait WindowEvaluatorFactoryBase {
         // in a single Window physical node. Therefore, we can assume no SQL aggregation
         // functions if Pandas UDF exists. In the future, we might mix Pandas UDF and SQL
         // aggregation function in a single physical node.
-        def processor = if (functions.exists(_.isInstanceOf[PythonFuncExpression])) {
+        val aggFilters: Array[Option[Expression]] = expressions.map {
+          case WindowExpression(ae: AggregateExpression, _) => ae.filter
+          case _ => None
+        }.toArray
+        // Shared per (key) across the factory closure's invocations; each
+        // Frame calls `processor.initialize(...)` in `prepare`, so cross-
+        // partition reuse is safe. Previously `def`, which re-allocated on
+        // every factory application (keeping listener registration idempotent).

Review Comment:
   The comment “keeping listener registration idempotent” looks inaccurate here: `AggregateProcessor` construction doesn’t register task listeners. Please update the comment to reflect the actual reason for using a `val` (e.g., avoiding per-factory invocation allocation) without referencing listener registration.
   ```suggestion
           // partition reuse is safe. Using a `val` avoids re-allocating the
           // same processor on every factory application.
   ```



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowSegmentTree.scala:
##########
@@ -0,0 +1,610 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.execution.window
+
+import java.util.{LinkedHashMap => JLinkedHashMap, Map => JMap}
+
+import scala.collection.mutable
+
+import org.apache.spark.{SparkEnv, SparkException, TaskContext}
+import org.apache.spark.memory.{MemoryConsumer, TaskMemoryManager}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.expressions.aggregate.DeclarativeAggregate
+import org.apache.spark.sql.errors.QueryExecutionErrors
+import org.apache.spark.sql.execution.ExternalAppendOnlyUnsafeRowArray
+import org.apache.spark.sql.types.DataType
+import org.apache.spark.util.ArrayImplicits._
+
+/**
+ * Block-chunked segment tree for range aggregate queries over window partitions.
+ *
+ * See `the class documentation`
+ * for the full design (API contract Section 2, block-chunked memory layout Section 3,
+ * DeclarativeAggregate binding Section 4, error handling Section 5, test hooks Section 6).
+ *
+ * initial implementation scope: correctness only. The data layer uses
+ * `ExternalAppendOnlyUnsafeRowArray` to hold input rows (spillable). Each
+ * block materializes its own small segment tree (levels 0..h). Internal
+ * nodes are cached in an LRU keyed by block index; block root aggregates
+ * (block pre-aggregates) stay resident for all blocks.
+ *
+ * Note: the design doc Section 3.3 specifies leaves are NOT materialized and
+ * recomputed from the spillable array on demand. For initial implementation simplicity
+ * we materialize leaves inside the per-block internal node arrays.
+ * // TODO(SPARK-XXXXX) re-assess after Frame integration.
+ *
+ * @note Instances are not thread-safe.
+ */
+private[window] class WindowSegmentTree(
+    functions: Array[DeclarativeAggregate],
+    inputSchema: Seq[Attribute],
+    newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
+    fanout: Int = WindowSegmentTree.DefaultFanout,
+    blockSize: Int = WindowSegmentTree.DefaultBlockSize,
+    maxCachedBlocks: Option[Int] = None,
+    spillThreshold: Int = Int.MaxValue,
+    inMemoryThreshold: Int = Int.MaxValue,
+    taskMemoryManager: TaskMemoryManager = null)
+  extends AutoCloseable {
+
+  require(fanout >= 2, s"fanout must be >= 2, got $fanout")
+  require(blockSize >= 1, s"blockSize must be >= 1, got $blockSize")
+  require(functions.nonEmpty, "WindowSegmentTree requires at least one aggregate function")
+  maxCachedBlocks.foreach { n =>
+    require(n >= 1, s"maxCachedBlocks must be >= 1 when specified, got $n")
+  }
+  require(taskMemoryManager != null,
+    "WindowSegmentTree requires a non-null TaskMemoryManager; " +
+      "in tests use `new TaskMemoryManager(new TestMemoryManager(conf), 0)`")
+
+  // ---------- Schemas & projections ----------
+
+  private val bufferAttrs: Seq[AttributeReference] =
+    functions.flatMap(_.aggBufferAttributes).toImmutableArraySeq
+  private val rightAttrs: Seq[AttributeReference] =
+    functions.flatMap(_.inputAggBufferAttributes).toImmutableArraySeq
+  private val bufferDataTypes: IndexedSeq[DataType] =
+    bufferAttrs.map(_.dataType).toIndexedSeq
+
+  private val initialValues: Seq[Expression] = functions.flatMap(_.initialValues).toIndexedSeq
+  private val updateExpressions: Seq[Expression] =
+    functions.flatMap(_.updateExpressions).toIndexedSeq
+  private val mergeExpressions: Seq[Expression] =
+    functions.flatMap(_.mergeExpressions).toIndexedSeq
+
+  private[this] val initProj: MutableProjection = newMutableProjection(initialValues, Nil)
+  private[this] val updateProj: MutableProjection =
+    newMutableProjection(updateExpressions, bufferAttrs ++ inputSchema)
+  private[this] val mergeProj: MutableProjection =
+    newMutableProjection(mergeExpressions, bufferAttrs ++ rightAttrs)
+
+  private val inputUnsafeProj: UnsafeProjection =
+    UnsafeProjection.create(inputSchema.map(_.dataType).toArray)
+
+  private[this] val joinedRow = new JoinedRow()
+
+  // ---------- State ----------
+
+  private var numRows: Int = 0
+  private var numBlocks: Int = 0
+  private var rowArray: ExternalAppendOnlyUnsafeRowArray = _
+  private var closed: Boolean = false
+
+  /** Always-resident per-block root aggregates. `blockAggregates(i)` =
+   *  merged buffer over all rows in block i. */
+  private var blockAggregates: Array[InternalRow] = Array.empty
+
+  /** Rough byte width of one aggregate buffer row. Chosen at 16 B/field as a
+   *  conservative heap-overhead-aware lower bound for a
+   *  `SpecificInternalRow` slot: primitive `MutableValue` is 8 B, boxed
+   *  references and object headers push the effective footprint higher.
+   *  Tighter per-type sizing (real boxing cost, variable-length fields) is
+   *  intentionally out of scope here; TaskMemoryManager remains the hard
+   *  backstop via spill / OOM.
+   *  TODO(SPARK-XXXXX): per-type width estimator keyed on
+   *  `bufferDataTypes` (primitive 16 B, String/Binary/Decimal wider). */
+  private val bufferWidthBytes: Long = {
+    val bytesPerField = 16L
+    math.max(1L, bufferDataTypes.size.toLong * bytesPerField)
+  }
+
+  /** Number of aggregate-buffer slots cached per block (contract I5).
+   *
+   *  Invariant: equals `sum over levels L of levels(L).length` for any
+   *  block materialized by [[buildBlockLevels]]. Level 0 holds `blockSize`
+   *  leaf buffers and each subsequent level holds `ceil(prev / fanout)`
+   *  parent buffers until a single root remains. The iterative ceiling
+   *  matches the allocation in [[buildBlockLevels]] for every
+   *  `(blockSize, fanout)` pair, including non-power-of-`fanout` cases.
+   *  For `blockSize == 1` the block is a single leaf with no parent
+   *  levels, so this returns 1.
+   *  TODO(SPARK-XXXXX): drop the leaf term when [[buildBlockLevels]]
+   *  switches to on-demand leaf recomputation. */
+  private val cachedSlotsPerBlock: Long = {
+    var n = blockSize.toLong
+    var sum = n
+    while (n > 1L) {
+      n = (n + fanout - 1) / fanout
+      sum += n
+    }
+    sum
+  }
+
+  /** Bytes accounted per cached block (contract I5). Conservative: assumes
+   *  every block is full; tail block (`numRows % blockSize != 0`) will
+   *  hold fewer leaves, giving a small headroom. */
+  private[this] val blockBytes: Long =
+    math.max(1L, cachedSlotsPerBlock * bufferWidthBytes)
+
+  /** `spans(L)` = number of leaves covered by a single node at level L. Depends
+   *  only on fanout + blockSize, so precomputed once. */
+  private val spans: Array[Int] = {
+    val maxLevel = {
+      var lvl = 0
+      var span = 1L
+      while (span < blockSize) { span *= fanout; lvl += 1 }
+      lvl
+    }
+    val arr = new Array[Int](maxLevel + 1)
+    var s = 1L
+    var i = 0
+    while (i <= maxLevel) {
+      arr(i) = if (s > Int.MaxValue) Int.MaxValue else s.toInt
+      s *= fanout
+      i += 1
+    }
+    arr
+  }
+
+  /** LRU cache of per-block internal node arrays. Key = blockIdx.
+   *  Value = `Array[Array[InternalRow]]` with levels(0..h). Auto-eviction via
+   *  `removeEldestEntry` is disabled (contract I3) -- eviction is driven
+   *  explicitly from [[ensureBlockLevels]] (capacity overflow) or
+   *  [[SegTreeSpiller.spill]] (TMM pressure). Each cache entry maps 1:1 to
+   *  one [[acquireBlockMemory]] accounting. Callers (e.g.
+   *  `SegmentTreeWindowFunctionFrame`) should pass a W-aware
+   *  value like `ceil(W / blockSize) + 2`. */
+  private val blockLevelsCache: JLinkedHashMap[Integer, Array[Array[InternalRow]]] =
+    new JLinkedHashMap[Integer, Array[Array[InternalRow]]](16, 0.75f, true) {
+      override def removeEldestEntry(
+          eldest: JMap.Entry[Integer, Array[Array[InternalRow]]]): Boolean = false
+    }
+
+  // ---------- Memory consumer (contract Section 2.2) ----------
+
+  /**
+   * Private MemoryConsumer tracking cached block levels under TMM.
+   *
+   * Heap accounting only (no Tungsten pages): uses
+   * [[MemoryConsumer.acquireMemory]] / [[MemoryConsumer.freeMemory]]. The
+   * [[MemoryConsumer]] base class records `used` via an `AtomicLong` when
+   * we call these -- so TMM's consumer-priority sort in
+   * `acquireExecutionMemory` sees our pressure accurately.
+   *
+   * @note `spill()` MUST NOT call `acquireMemory` (contract I1).
+   */
+  private final class SegTreeSpiller extends MemoryConsumer(
+      taskMemoryManager,
+      taskMemoryManager.pageSizeBytes(),
+      taskMemoryManager.getTungstenMemoryMode()) {
+    override def spill(size: Long, trigger: MemoryConsumer): Long = {
+      // I2: self-trigger short-circuit. Prevents re-entrant eviction when
+      // our own acquireMemory() triggers TMM to poll us.
+      if (trigger eq this) return 0L
+      // I8: rowArray spilled-to-disk detection. If the rowArray has already
+      // spilled, evicting our cache is counter-productive (rebuild would
+      // O(blockStart)-scan the spill file). Return 0L to let TMM fall
+      // through to the next consumer.
+      //
+      // TODO(SPARK-XXXXX) #segtree-spill-priority (contract Section 7 O4): current

Review Comment:
   This file contains merge-blocking placeholders and nonstandard markers: backticked “the class documentation”, multiple `TODO(SPARK-XXXXX)` stubs, and a `FIXME(name)` line. Before merging, please replace placeholders with concrete references (doc path/URL or class name) and actual SPARK JIRA IDs, and convert the `FIXME(...)` to a `TODO(SPARK-xxxxx)` (without personal attribution) so it fits Spark’s tracking conventions.



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/window/SegmentTreeWindowMetricsSuite.scala:
##########
@@ -0,0 +1,226 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.execution.window
+
+import org.apache.spark.sql.QueryTest
+import org.apache.spark.sql.execution.SparkPlanInfo
+import org.apache.spark.sql.execution.metric.SQLMetricsTestUtils
+import org.apache.spark.sql.execution.ui.SparkPlanGraph
+import org.apache.spark.sql.expressions.Window
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.test.SharedSparkSession
+
+/**
+ * SQLMetrics visibility coverage for [[SegmentTreeWindowFunctionFrame]].
+ *
+ * segtree-path: segtree path bumps `numSegmentTreeFrames`.
+ * fallback-path: fallback path bumps `numSegmentTreeFallbackFrames`.
+ * feature-flag-off: feature-flag off -> both counters stay at 0 (no false positives).
+ *
+ * See `the PR description (SQLMetrics exposure)`.
+ */
+class SegmentTreeWindowMetricsSuite
+    extends QueryTest with SharedSparkSession with SQLMetricsTestUtils {
+
+  import testImplicits._
+
+  /**
+   * Run `df` and return the first Window node's metric values for the two
+   * segment-tree counters, parsed to Long. (Other metrics like `spillSize`
+   * are UI-pretty-printed strings like "0.0 B (0.0 B, 0.0 B, ...)" and
+   * are skipped.)
+   */
+  private def windowMetricValues(df: org.apache.spark.sql.DataFrame): Map[String, Long] = {
+    val previousExecutionIds = currentExecutionIds()
+    df.collect()
+    sparkContext.listenerBus.waitUntilEmpty(10000)
+    val executionId = currentExecutionIds().diff(previousExecutionIds).head
+    val metricValues = statusStore.executionMetrics(executionId)
+    val graph = SparkPlanGraph(SparkPlanInfo.fromSparkPlan(df.queryExecution.executedPlan))
+    val windowNode = graph.allNodes.find(_.name == "Window").getOrElse {
+      fail(s"No Window node in plan:\n${df.queryExecution.executedPlan}")
+    }
+    val wanted = Set(
+      "number of segment-tree frames",
+      "number of segment-tree fallback frames")
+    windowNode.metrics.filter(m => wanted.contains(m.name)).map { m =>
+      // For sum metrics the UI value is either a plain integer ("3") or the
+      // aggregated form "total (min, med, max (stageId: taskId))\nN (...)".
+      // Grab the first integer run of digits, which is the grand total.
+      val raw = metricValues(m.accumulatorId)
+      val total = "-?\\d+".r.findFirstIn(raw).getOrElse {
+        fail(s"Could not parse integer from metric '${m.name}' value: $raw")
+      }
+      m.name -> total.toLong
+    }.toMap
+  }
+
+  private def baseDF = spark.range(0, 120).selectExpr(
+    "id", "(id % 3) AS pk", "CAST(id AS INT) AS v")
+
+  private val winSpec = Window.partitionBy($"pk").orderBy($"id").rowsBetween(-3, 3)
+
+  test("segment-tree path increments numSegmentTreeFrames (one per frame per partition)") {
+    withSQLConf(
+        SQLConf.WINDOW_SEGMENT_TREE_ENABLED.key -> "true",
+        SQLConf.WINDOW_SEGMENT_TREE_MIN_PARTITION_ROWS.key -> "1",
+        SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false") {
+      // Two aggregates sharing one Window -> one frame, 3 partitions => 3 frames.
+      val df = baseDF.select($"id",
+        min($"v").over(winSpec).as("mn"),
+        max($"v").over(winSpec).as("mx"))
+      val m = windowMetricValues(df)
+      assert(m("number of segment-tree frames") === 3L,
+        s"expected 3 segtree frames (one per partition), got metrics = $m")
+      assert(m("number of segment-tree fallback frames") === 0L,
+        s"fallback counter must be 0 when all partitions take segtree path, got $m")
+    }
+  }
+
+  test("fallback path increments numSegmentTreeFallbackFrames") {
+    withSQLConf(
+        SQLConf.WINDOW_SEGMENT_TREE_ENABLED.key -> "true",
+        // Threshold > partition size (40 rows/partition) forces fallback on every partition.
+        SQLConf.WINDOW_SEGMENT_TREE_MIN_PARTITION_ROWS.key -> "1000",
+        SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false") {
+      val df = baseDF.select($"id", min($"v").over(winSpec).as("mn"))
+      val m = windowMetricValues(df)
+      assert(m("number of segment-tree fallback frames") === 3L,
+        s"expected 3 fallback frames (one per partition under threshold), got $m")
+      assert(m("number of segment-tree frames") === 0L,
+        s"segtree counter must be 0 when all partitions fall back, got $m")
+    }
+  }
+
+  test("feature flag off: both segment-tree counters stay at zero") {
+    withSQLConf(
+        SQLConf.WINDOW_SEGMENT_TREE_ENABLED.key -> "false",
+        SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false") {
+      val df = baseDF.select($"id", min($"v").over(winSpec).as("mn"))
+      val m = windowMetricValues(df)
+      assert(m("number of segment-tree frames") === 0L,
+        s"segtree counter must be 0 when feature flag disabled, got $m")
+      assert(m("number of segment-tree fallback frames") === 0L,
+        s"fallback counter must be 0 when feature flag disabled, got $m")
+    }
+  }
+
+  // ---------------------------------------------------------------------
+  // T1-T4: regression coverage for the removed idempotency guard in
+  // `SegmentTreeWindowFunctionFrame.prepare()` (see the class documentation).
+  // The guard keyed on `(System.identityHashCode(rows), rows.length)`, but
+  // `WindowPartitionEvaluator` reuses a single `ExternalAppendOnlyUnsafeRowArray`
+  // across all partitions in a task, so the identity hash is constant per
+  // task and the discriminator collapsed to `rows.length` -- silently
+  // deduping any two consecutive partitions of equal row count.
+  //
+  // All four tests pin `minPartitionRows = 64` (landed default) so future
+  // default changes don't silently rebucket the fixtures, and use a single
+  // shuffle partition so the Window operator sees `numPartitions >
+  // numTasks` -- the exact shape the the segtree and fallback fixtures happened to avoid.

Review Comment:
   Remove the duplicated word in the comment (‘the the’).
   ```suggestion
     // numTasks` -- the exact shape the segtree and fallback fixtures happened to avoid.
   ```



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowSegmentTree.scala:
##########
@@ -0,0 +1,610 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.execution.window
+
+import java.util.{LinkedHashMap => JLinkedHashMap, Map => JMap}
+
+import scala.collection.mutable
+
+import org.apache.spark.{SparkEnv, SparkException, TaskContext}
+import org.apache.spark.memory.{MemoryConsumer, TaskMemoryManager}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.expressions.aggregate.DeclarativeAggregate
+import org.apache.spark.sql.errors.QueryExecutionErrors
+import org.apache.spark.sql.execution.ExternalAppendOnlyUnsafeRowArray
+import org.apache.spark.sql.types.DataType
+import org.apache.spark.util.ArrayImplicits._
+
+/**
+ * Block-chunked segment tree for range aggregate queries over window partitions.
+ *
+ * See `the class documentation`
+ * for the full design (API contract Section 2, block-chunked memory layout Section 3,
+ * DeclarativeAggregate binding Section 4, error handling Section 5, test hooks Section 6).
+ *
+ * initial implementation scope: correctness only. The data layer uses
+ * `ExternalAppendOnlyUnsafeRowArray` to hold input rows (spillable). Each
+ * block materializes its own small segment tree (levels 0..h). Internal
+ * nodes are cached in an LRU keyed by block index; block root aggregates
+ * (block pre-aggregates) stay resident for all blocks.
+ *
+ * Note: the design doc Section 3.3 specifies leaves are NOT materialized and
+ * recomputed from the spillable array on demand. For initial implementation simplicity
+ * we materialize leaves inside the per-block internal node arrays.
+ * // TODO(SPARK-XXXXX) re-assess after Frame integration.
+ *
+ * @note Instances are not thread-safe.
+ */
+private[window] class WindowSegmentTree(
+    functions: Array[DeclarativeAggregate],
+    inputSchema: Seq[Attribute],
+    newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
+    fanout: Int = WindowSegmentTree.DefaultFanout,
+    blockSize: Int = WindowSegmentTree.DefaultBlockSize,
+    maxCachedBlocks: Option[Int] = None,
+    spillThreshold: Int = Int.MaxValue,
+    inMemoryThreshold: Int = Int.MaxValue,
+    taskMemoryManager: TaskMemoryManager = null)
+  extends AutoCloseable {
+
+  require(fanout >= 2, s"fanout must be >= 2, got $fanout")
+  require(blockSize >= 1, s"blockSize must be >= 1, got $blockSize")
+  require(functions.nonEmpty, "WindowSegmentTree requires at least one aggregate function")
+  maxCachedBlocks.foreach { n =>
+    require(n >= 1, s"maxCachedBlocks must be >= 1 when specified, got $n")
+  }
+  require(taskMemoryManager != null,
+    "WindowSegmentTree requires a non-null TaskMemoryManager; " +
+      "in tests use `new TaskMemoryManager(new TestMemoryManager(conf), 0)`")
+
+  // ---------- Schemas & projections ----------
+
+  private val bufferAttrs: Seq[AttributeReference] =
+    functions.flatMap(_.aggBufferAttributes).toImmutableArraySeq
+  private val rightAttrs: Seq[AttributeReference] =
+    functions.flatMap(_.inputAggBufferAttributes).toImmutableArraySeq
+  private val bufferDataTypes: IndexedSeq[DataType] =
+    bufferAttrs.map(_.dataType).toIndexedSeq
+
+  private val initialValues: Seq[Expression] = functions.flatMap(_.initialValues).toIndexedSeq
+  private val updateExpressions: Seq[Expression] =
+    functions.flatMap(_.updateExpressions).toIndexedSeq
+  private val mergeExpressions: Seq[Expression] =
+    functions.flatMap(_.mergeExpressions).toIndexedSeq
+
+  private[this] val initProj: MutableProjection = newMutableProjection(initialValues, Nil)
+  private[this] val updateProj: MutableProjection =
+    newMutableProjection(updateExpressions, bufferAttrs ++ inputSchema)
+  private[this] val mergeProj: MutableProjection =
+    newMutableProjection(mergeExpressions, bufferAttrs ++ rightAttrs)
+
+  private val inputUnsafeProj: UnsafeProjection =
+    UnsafeProjection.create(inputSchema.map(_.dataType).toArray)
+
+  private[this] val joinedRow = new JoinedRow()
+
+  // ---------- State ----------
+
+  private var numRows: Int = 0
+  private var numBlocks: Int = 0
+  private var rowArray: ExternalAppendOnlyUnsafeRowArray = _
+  private var closed: Boolean = false
+
+  /** Always-resident per-block root aggregates. `blockAggregates(i)` =
+   *  merged buffer over all rows in block i. */
+  private var blockAggregates: Array[InternalRow] = Array.empty
+
+  /** Rough byte width of one aggregate buffer row. Chosen at 16 B/field as a
+   *  conservative heap-overhead-aware lower bound for a
+   *  `SpecificInternalRow` slot: primitive `MutableValue` is 8 B, boxed
+   *  references and object headers push the effective footprint higher.
+   *  Tighter per-type sizing (real boxing cost, variable-length fields) is
+   *  intentionally out of scope here; TaskMemoryManager remains the hard
+   *  backstop via spill / OOM.
+   *  TODO(SPARK-XXXXX): per-type width estimator keyed on
+   *  `bufferDataTypes` (primitive 16 B, String/Binary/Decimal wider). */
+  private val bufferWidthBytes: Long = {
+    val bytesPerField = 16L
+    math.max(1L, bufferDataTypes.size.toLong * bytesPerField)
+  }
+
+  /** Number of aggregate-buffer slots cached per block (contract I5).
+   *
+   *  Invariant: equals `sum over levels L of levels(L).length` for any
+   *  block materialized by [[buildBlockLevels]]. Level 0 holds `blockSize`
+   *  leaf buffers and each subsequent level holds `ceil(prev / fanout)`
+   *  parent buffers until a single root remains. The iterative ceiling
+   *  matches the allocation in [[buildBlockLevels]] for every
+   *  `(blockSize, fanout)` pair, including non-power-of-`fanout` cases.
+   *  For `blockSize == 1` the block is a single leaf with no parent
+   *  levels, so this returns 1.
+   *  TODO(SPARK-XXXXX): drop the leaf term when [[buildBlockLevels]]
+   *  switches to on-demand leaf recomputation. */
+  private val cachedSlotsPerBlock: Long = {
+    var n = blockSize.toLong
+    var sum = n
+    while (n > 1L) {
+      n = (n + fanout - 1) / fanout
+      sum += n
+    }
+    sum
+  }
+
+  /** Bytes accounted per cached block (contract I5). Conservative: assumes
+   *  every block is full; tail block (`numRows % blockSize != 0`) will
+   *  hold fewer leaves, giving a small headroom. */
+  private[this] val blockBytes: Long =
+    math.max(1L, cachedSlotsPerBlock * bufferWidthBytes)
+
+  /** `spans(L)` = number of leaves covered by a single node at level L. Depends
+   *  only on fanout + blockSize, so precomputed once. */
+  private val spans: Array[Int] = {
+    val maxLevel = {
+      var lvl = 0
+      var span = 1L
+      while (span < blockSize) { span *= fanout; lvl += 1 }
+      lvl
+    }
+    val arr = new Array[Int](maxLevel + 1)
+    var s = 1L
+    var i = 0
+    while (i <= maxLevel) {
+      arr(i) = if (s > Int.MaxValue) Int.MaxValue else s.toInt
+      s *= fanout
+      i += 1
+    }
+    arr
+  }
+
+  /** LRU cache of per-block internal node arrays. Key = blockIdx.
+   *  Value = `Array[Array[InternalRow]]` with levels(0..h). Auto-eviction via
+   *  `removeEldestEntry` is disabled (contract I3) -- eviction is driven
+   *  explicitly from [[ensureBlockLevels]] (capacity overflow) or
+   *  [[SegTreeSpiller.spill]] (TMM pressure). Each cache entry maps 1:1 to
+   *  one [[acquireBlockMemory]] accounting. Callers (e.g.
+   *  `SegmentTreeWindowFunctionFrame`) should pass a W-aware
+   *  value like `ceil(W / blockSize) + 2`. */
+  private val blockLevelsCache: JLinkedHashMap[Integer, Array[Array[InternalRow]]] =
+    new JLinkedHashMap[Integer, Array[Array[InternalRow]]](16, 0.75f, true) {
+      override def removeEldestEntry(
+          eldest: JMap.Entry[Integer, Array[Array[InternalRow]]]): Boolean = false
+    }
+
+  // ---------- Memory consumer (contract Section 2.2) ----------
+
+  /**
+   * Private MemoryConsumer tracking cached block levels under TMM.
+   *
+   * Heap accounting only (no Tungsten pages): uses
+   * [[MemoryConsumer.acquireMemory]] / [[MemoryConsumer.freeMemory]]. The
+   * [[MemoryConsumer]] base class records `used` via an `AtomicLong` when
+   * we call these -- so TMM's consumer-priority sort in
+   * `acquireExecutionMemory` sees our pressure accurately.
+   *
+   * @note `spill()` MUST NOT call `acquireMemory` (contract I1).
+   */
+  private final class SegTreeSpiller extends MemoryConsumer(
+      taskMemoryManager,
+      taskMemoryManager.pageSizeBytes(),
+      taskMemoryManager.getTungstenMemoryMode()) {
+    override def spill(size: Long, trigger: MemoryConsumer): Long = {
+      // I2: self-trigger short-circuit. Prevents re-entrant eviction when
+      // our own acquireMemory() triggers TMM to poll us.
+      if (trigger eq this) return 0L
+      // I8: rowArray spilled-to-disk detection. If the rowArray has already
+      // spilled, evicting our cache is counter-productive (rebuild would
+      // O(blockStart)-scan the spill file). Return 0L to let TMM fall
+      // through to the next consumer.
+      //
+      // TODO(SPARK-XXXXX) #segtree-spill-priority (contract Section 7 O4): current
+      // heuristic uses `spillSize > 0` as the "has spilled" signal. A more
+      // precise check would consult `UnsafeExternalSorter.getSpillWriters`
+      // state, but that API is not public. Re-evaluate after benchmark.
+      // FIXME(kentyao): upstream a public "hasSpilled" hook on the array.

Review Comment:
   This file contains merge-blocking placeholders and nonstandard markers: backticked “the class documentation”, multiple `TODO(SPARK-XXXXX)` stubs, and a `FIXME(name)` line. Before merging, please replace placeholders with concrete references (doc path/URL or class name) and actual SPARK JIRA IDs, and convert the `FIXME(...)` to a `TODO(SPARK-xxxxx)` (without personal attribution) so it fits Spark’s tracking conventions.



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/benchmark/WindowBenchmark.scala:
##########
@@ -0,0 +1,412 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.execution.benchmark
+
+import scala.collection.mutable
+
+import org.apache.spark.benchmark.Benchmark
+import org.apache.spark.scheduler.{SparkListener, SparkListenerTaskEnd}
+import org.apache.spark.sql.internal.SQLConf
+
+/**
+ * Benchmark to measure window function performance with bounded ROWS frames.
+ *
+ * Matrix (rev4; see the PR description):
+ *   - Section A: 5 aggregates x 3 cells (naive / segtree default / segtree bs=256),
+ *                per-case N calibrated so naive lands in 3-5s/iter. STDDEV_SAMP keeps
+ *                N=2M (stress: multi-buffer noise demo).
+ *   - Section B: SUM-over-INT, W sweep {10, 50, 201, 4001}; naive / segtree default.
+ *                W=4001 also runs segtree bs=256. W=10 / W=50 are stress cases
+ *                demonstrating Pareto-loss zone (segtree slower than naive).
+ *   - Section F: Spill regression guard, 1M String rows x MAX x W=1001 (stress).
+ *   - Section C: N-sweep {2M, 8M, 16M} segtree-only at W=1001 (stress): memory-pressure
+ *                invariance / sub-linear growth demonstration.
+ *
+ * Reading guide: W-sweep uses different N per point so naive lands in 3-5s. Compare
+ * `Per Row(ns)` column (not Best time) to read O(log W) scaling on segtree side.
+ *
+ * Invocation arguments (positional; dev smoke only, do NOT set with
+ * SPARK_GENERATE_BENCHMARK_FILES=1):
+ *   mainArgs(0) rowCount   if present, run SMOKE mode: Section A (MIN only) + one W sweep point.
+ *   mainArgs(1) halfWindow (smoke mode only) default 100.
+ *
+ * {{{
+ *   # full matrix (CI / committed results):
+ *   SPARK_GENERATE_BENCHMARK_FILES=1 build/sbt \
+ *     "sql/Test/runMain org.apache.spark.sql.execution.benchmark.WindowBenchmark"
+ *   # smoke (100k rows, W=201):
+ *   build/sbt "sql/Test/runMain \
+ *     org.apache.spark.sql.execution.benchmark.WindowBenchmark 100000 100"
+ * }}}
+ */
+object WindowBenchmark extends SqlBasedBenchmark {
+
+  // ---- Section A: per-case N (naive baseline ~3-5s/iter) ----
+  private val A_N_INT: Long = 256L * 1024              // MIN/MAX/SUM/COUNT @ W=1001
+  private val A_N_AVG: Long = 192L * 1024              // AVG  @ W=1001
+  private val A_N_STDDEV: Long = 2L * 1000L * 1000L    // STDDEV stress
+
+  // ---- Section B: W-sweep ----
+  private val B_N_W10: Long = 2L * 1000L * 1000L       // stress (Pareto loss)
+  private val B_N_W50: Long = 2L * 1000L * 1000L       // stress (Pareto loss)
+  private val B_N_W201: Long = 1L * 1000L * 1000L
+  private val B_N_W4001: Long = 2L * 1000L * 1000L     // stress O(W) cliff
+
+  // ---- Section F: String spill ----
+  private val SPILL_N: Long = 1L * 1000L * 1000L
+
+  // ---- Section C: N-sweep segtree-only ----
+  private val C_N_SMALL: Long = 2L * 1000L * 1000L
+  private val C_N_MID: Long = 8L * 1000L * 1000L
+  private val C_N_LARGE: Long = 16L * 1000L * 1000L
+  private val C_HALF_W: Int = 500                      // W=1001
+
+  private val MAIN_HALF_W: Int = 500                   // Section A W=1001
+
+  private val ITERS_NORMAL: Int = 5
+  private val ITERS_STRESS: Int = 3
+
+  override def runBenchmarkSuite(mainArgs: Array[String]): Unit = {
+    val smokeMode = mainArgs.nonEmpty
+    val smokeRowCount = if (smokeMode) mainArgs(0).toLong else 0L
+    val smokeHalfW = if (mainArgs.length > 1) mainArgs(1).toInt else 100
+
+    if (smokeMode) {
+      require(smokeRowCount >= 4096,
+        s"rowCount=$smokeRowCount too small; segtree may fallback. Use >= 4096.")
+    }
+
+    // Shared metrics listener: per-case peak mem + disk spill
+    val metrics = mutable.Map[String, (Long, Long)]()
+    @volatile var currentCase: String = ""
+    val listener = new SparkListener {
+      override def onTaskEnd(e: SparkListenerTaskEnd): Unit = {
+        val m = e.taskMetrics
+        val cc = currentCase
+        if (m != null && cc.nonEmpty) {
+          metrics.synchronized {
+            val (pm, ds) = metrics.getOrElse(cc, (0L, 0L))
+            metrics(cc) = (math.max(pm, m.peakExecutionMemory), ds + m.diskBytesSpilled)
+          }
+        }
+      }
+    }
+    spark.sparkContext.addSparkListener(listener)
+    val allCaseNames = mutable.ArrayBuffer[String]()
+
+    // ---- helpers ----
+    def setupIntTable(n: Long): Unit = {
+      spark.range(n)
+        .selectExpr("id", "cast(rand(42) * 1000000 as int) as v")
+        .coalesce(1)
+        .createOrReplaceTempView("t")
+    }
+
+    def setupStringTable(n: Long): Unit = {
+      // value is ~20-char string; variable-length, exercises spill path
+      spark.range(n)
+        .selectExpr("id", "repeat(cast(id as string), 5) as v")
+        .coalesce(1)
+        .createOrReplaceTempView("t")
+    }
+
+    def frameFor(halfW: Int): String =
+      s"OVER (ORDER BY id ROWS BETWEEN $halfW PRECEDING AND $halfW FOLLOWING)"
+
+    // Aggregates that produce Double (AVG/STDDEV/VAR) accumulate in
+    // floating-point. The segtree merge order differs from the row-by-row
+    // order used by SlidingWindowFunctionFrame, so the result differs at
+    // the bit (ULP) level even though it is mathematically equivalent.
+    //
+    // HASH(double) is bit-sensitive, and HASH(ROUND(m, k)) is a trap at
+    // scale: any row whose value sits within ~1 ULP of a rounding bin
+    // boundary rounds to a different k-decimal value across backends,
+    // producing two totally different HASH outputs that SUM propagates
+    // linearly. We hit this at N=2M on STDDEV_SAMP (0.2% digest diff even
+    // though per-row relative error is <1e-10). See
+    // spark-floating-point-digest-trap skill for details.

Review Comment:
   The reference to “spark-floating-point-digest-trap skill” isn’t a stable/public pointer for future maintainers. Please replace it with an in-repo doc link, a SPARK JIRA, or a brief self-contained explanation of the failure mode and why the chosen digest avoids it.
   ```suggestion
       // boundary can round to a different k-decimal value across backends.
       // Those rounded doubles then hash to unrelated values, and SUM of the
       // hashes turns tiny floating-point differences into large digest drift.
       // We hit this at N=2M on STDDEV_SAMP (0.2% digest diff even though
       // per-row relative error is <1e-10).
   ```



-- 
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@spark.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [WIP][SPARK-56546][SQL] Block-chunked segment-tree window frame for non-invertible sliding aggregates [spark]

Posted by "yaooqinn (via GitHub)" <gi...@apache.org>.
yaooqinn commented on code in PR #55422:
URL: https://github.com/apache/spark/pull/55422#discussion_r3115256683


##########
sql/core/src/test/scala/org/apache/spark/sql/execution/window/SegmentTreeWindowFunctionSuite.scala:
##########
@@ -0,0 +1,862 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.execution.window
+
+import org.apache.spark.sql.{DataFrame, Encoder, Encoders, QueryTest, Row}
+import org.apache.spark.sql.expressions.{Aggregator, MutableAggregationBuffer, Window}
+import org.apache.spark.sql.expressions.UserDefinedAggregateFunction
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.test.SharedSparkSession
+import org.apache.spark.sql.types.{DataType, LongType, StructType}
+
+/**
+ * End-to-end tests for the block-chunked segment-tree moving window frame.
+ *
+ * Coverage by section:
+ *   - Coverage: various cases (basic aggregates), various cases (frame boundaries),
+ *                min-partition-rows fallback, AggregateWindowFunction
+ *                regression.
+ *   - Coverage: various cases (NULL, NaN/Infinity), various cases
+ *                (numeric / string / date-timestamp types), various cases
+ *                (unsupported-merge / DISTINCT / feature-flag fallback).
+ *
+  */
+class SegmentTreeWindowFunctionSuite extends QueryTest with SharedSparkSession {
+
+  import testImplicits._
+
+  // Common config: force the segment-tree path regardless of partition size
+  // (we exercise the fallback explicitly below).
+  private val enableSegTree: Map[String, String] = Map(
+    SQLConf.WINDOW_SEGMENT_TREE_ENABLED.key -> "true",
+    SQLConf.WINDOW_SEGMENT_TREE_MIN_PARTITION_ROWS.key -> "1")
+
+  private val disableSegTree: Map[String, String] = Map(
+    SQLConf.WINDOW_SEGMENT_TREE_ENABLED.key -> "false")
+
+  /** Build `f(conf)` twice (enabled / disabled) and assert equal results. */
+  private def checkEquivalence(build: () => DataFrame): Unit = {
+    val baseline: Array[Row] = withSQLConf(disableSegTree.toSeq: _*) {
+      build().collect().sortBy(_.toString)
+    }
+    withSQLConf(enableSegTree.toSeq: _*) {
+      val actual = build().collect().sortBy(_.toString)
+      assert(actual.toSeq === baseline.toSeq,
+        s"segment-tree output differs from baseline.\nExpected: ${baseline.toSeq}\n" +
+          s"Actual:   ${actual.toSeq}")
+    }
+  }
+
+  /** Standard fixture: 3 partitions, sizes 40/40/40, values = row index. */
+  private def baseDF: DataFrame = {
+    spark.range(0, 120).selectExpr(
+      "id",
+      "(id % 3) AS pk",
+      "CAST(id AS INT) AS v")
+  }
+
+  private def winSpec(lo: Int, hi: Int) =
+    Window.partitionBy($"pk").orderBy($"id").rowsBetween(lo, hi)
+
+  // ---------------- A1: basic aggregate equivalence ----------------
+
+  test("MIN over ROWS BETWEEN 3 PRECEDING AND 3 FOLLOWING") {
+    checkEquivalence(() =>
+      baseDF.select($"id", $"pk", min($"v").over(winSpec(-3, 3)).as("agg")))
+  }
+
+  test("MAX over ROWS BETWEEN 3 PRECEDING AND 3 FOLLOWING") {
+    checkEquivalence(() =>
+      baseDF.select($"id", $"pk", max($"v").over(winSpec(-3, 3)).as("agg")))
+  }
+
+  test("SUM over ROWS BETWEEN 3 PRECEDING AND 3 FOLLOWING") {
+    checkEquivalence(() =>
+      baseDF.select($"id", $"pk", sum($"v").over(winSpec(-3, 3)).as("agg")))
+  }
+
+  test("COUNT over ROWS BETWEEN 3 PRECEDING AND 3 FOLLOWING") {
+    checkEquivalence(() =>
+      baseDF.select($"id", $"pk", count($"v").over(winSpec(-3, 3)).as("agg")))
+  }
+
+  test("AVG over ROWS BETWEEN 3 PRECEDING AND 3 FOLLOWING") {
+    checkEquivalence(() =>
+      baseDF.select($"id", $"pk", avg($"v").over(winSpec(-3, 3)).as("agg")))
+  }
+
+  test("MIN + MAX + SUM share a single window frame") {
+    checkEquivalence(() =>
+      baseDF.select(
+        $"id",
+        $"pk",
+        min($"v").over(winSpec(-3, 3)).as("mn"),
+        max($"v").over(winSpec(-3, 3)).as("mx"),
+        sum($"v").over(winSpec(-3, 3)).as("sm")))
+  }
+
+  // ---------------- A2: frame-size boundaries ----------------
+
+  test("frame size = 1 (CURRENT ROW only)") {
+    checkEquivalence(() =>
+      baseDF.select($"id", $"pk", sum($"v").over(winSpec(0, 0)).as("agg")))
+  }
+
+  test("frame spans full partition") {
+    // 40 rows per partition; use a wide symmetric window covering it.
+    checkEquivalence(() =>
+      baseDF.select($"id", $"pk", sum($"v").over(winSpec(-100, 100)).as("agg")))
+  }
+
+  test("frame extends past both partition edges") {
+    checkEquivalence(() =>
+      baseDF.select($"id", $"pk",
+        sum($"v").over(winSpec(-50, 50)).as("agg"),
+        min($"v").over(winSpec(-50, 50)).as("mn"),
+        max($"v").over(winSpec(-50, 50)).as("mx")))
+  }
+
+  
+  test("partition below minPartitionRows falls back to SlidingWindowFunctionFrame") {
+    // 5-row partition, min threshold = 10 -> must fall back.
+    val df = spark.range(0, 5).selectExpr(
+      "id", "0 AS pk", "CAST(id AS INT) AS v")
+    val enabledConf = Map(
+      SQLConf.WINDOW_SEGMENT_TREE_ENABLED.key -> "true",
+      SQLConf.WINDOW_SEGMENT_TREE_MIN_PARTITION_ROWS.key -> "10")
+
+    // 1. Result correctness against baseline.
+    val baseline = withSQLConf(disableSegTree.toSeq: _*) {
+      df.select($"id", sum($"v").over(winSpec(-1, 1)).as("s"))
+        .collect().sortBy(_.toString)
+    }
+    val actual = withSQLConf(enabledConf.toSeq: _*) {
+      df.select($"id", sum($"v").over(winSpec(-1, 1)).as("s"))
+        .collect().sortBy(_.toString)
+    }
+    assert(actual.toSeq === baseline.toSeq)
+
+    // 2. Directly exercise the frame to confirm the fallback flag flips.
+    withSQLConf(enabledConf.toSeq: _*) {
+      SegmentTreeWindowTestHelpers.withSmallPartitionFrame(
+        SQLConf.get, rows = 5) { frame =>
+        assert(frame.fallbackUsed,
+          "expected fallbackUsed=true for partition smaller than minPartitionRows")
+      }
+    }
+  }
+
+  
+  test("NTH_VALUE over ROWS frame falls back cleanly (no mergeExpressions crash)") {
+    // NthValue extends DeclarativeAggregate but its mergeExpressions throws
+    // mergeUnsupportedByWindowFunctionError. eligibleForSegTree must exclude it.
+    val df = baseDF
+    val withSegTree = withSQLConf(enableSegTree.toSeq: _*) {
+      df.selectExpr(
+        "id", "pk",
+        "nth_value(v, 3) OVER (PARTITION BY pk ORDER BY id " +
+          "ROWS BETWEEN 5 PRECEDING AND 5 FOLLOWING) AS n3")
+        .collect().sortBy(_.toString)
+    }
+    val baseline = withSQLConf(disableSegTree.toSeq: _*) {
+      df.selectExpr(
+        "id", "pk",
+        "nth_value(v, 3) OVER (PARTITION BY pk ORDER BY id " +
+          "ROWS BETWEEN 5 PRECEDING AND 5 FOLLOWING) AS n3")
+        .collect().sortBy(_.toString)
+    }
+    assert(withSegTree.toSeq === baseline.toSeq)
+  }
+
+  test("ROW_NUMBER over ROWS frame falls back cleanly (no mergeExpressions crash)") {
+    val df = baseDF
+    val withSegTree = withSQLConf(enableSegTree.toSeq: _*) {
+      df.selectExpr(
+        "id", "pk",
+        "row_number() OVER (PARTITION BY pk ORDER BY id) AS rn")
+        .collect().sortBy(_.toString)
+    }
+    val baseline = withSQLConf(disableSegTree.toSeq: _*) {
+      df.selectExpr(
+        "id", "pk",
+        "row_number() OVER (PARTITION BY pk ORDER BY id) AS rn")
+        .collect().sortBy(_.toString)
+    }
+    assert(withSegTree.toSeq === baseline.toSeq)
+  }
+
+    // A3.*: NULL / NaN / Infinity handling
+  // A4.*: numeric / string / date-timestamp types
+  // various cases: unsupported-merge / DISTINCT / feature-flag fallback
+  //
+  // All tests use the same oracle strategy as the frame integration: run with
+  // `segmentTree.enabled=true` (forced via min-rows=1) and with `=false`,
+  // then assert bit-for-bit equal Row sequences. That gives us:
+  //   - Correctness: seg-tree output matches SlidingWindowFunctionFrame
+  //     (the community-validated baseline).
+  //   - Fallback paths: various cases exercise the `eligibleForSegTree` filter,
+  //     which must decline to drive the seg-tree path and hand off to the
+  //     sliding frame; equal rows prove the hand-off preserves semantics.
+
+  // ---------------- A3: NULL / special values ----------------
+
+  test("all-NULL column: MIN/MAX/SUM/AVG/COUNT") {
+    val df = spark.range(0, 30).selectExpr(
+      "id", "(id % 3) AS pk", "CAST(NULL AS INT) AS v")
+    checkEquivalence(() =>
+      df.select($"id", $"pk",
+        min($"v").over(winSpec(-3, 3)).as("mn"),
+        max($"v").over(winSpec(-3, 3)).as("mx"),
+        sum($"v").over(winSpec(-3, 3)).as("sm"),
+        avg($"v").over(winSpec(-3, 3)).as("av"),
+        count($"v").over(winSpec(-3, 3)).as("cn")))
+  }
+
+  test("mixed NULL and non-NULL: NULLs must not leak into MIN/MAX") {
+    // Every 3rd value is NULL. Aggregates must skip them (NULL-agnostic merge).
+    val df = spark.range(0, 60).selectExpr(
+      "id",
+      "(id % 3) AS pk",
+      "CASE WHEN id % 3 = 0 THEN NULL ELSE CAST(id AS INT) END AS v")
+    checkEquivalence(() =>
+      df.select($"id", $"pk",
+        min($"v").over(winSpec(-4, 4)).as("mn"),
+        max($"v").over(winSpec(-4, 4)).as("mx"),
+        sum($"v").over(winSpec(-4, 4)).as("sm"),
+        count($"v").over(winSpec(-4, 4)).as("cn")))
+  }
+
+  test("Double NaN and +/-Infinity propagate correctly through MIN/MAX/SUM") {
+    // Spark's NaN ordering: NaN is treated as greater than +Inf for MIN/MAX.
+    // +Inf + -Inf = NaN for SUM. The seg-tree path uses DeclarativeAggregate's
+    // own merge, so behavior must match the baseline exactly.
+    val df = spark.range(0, 30).selectExpr(
+      "id",
+      "(id % 2) AS pk",
+      """CASE
+           WHEN id % 7 = 0 THEN double('NaN')
+           WHEN id % 7 = 1 THEN double('Infinity')
+           WHEN id % 7 = 2 THEN double('-Infinity')
+           ELSE CAST(id AS DOUBLE)
+         END AS v""")
+    checkEquivalence(() =>
+      df.select($"id", $"pk",
+        min($"v").over(winSpec(-3, 3)).as("mn"),
+        max($"v").over(winSpec(-3, 3)).as("mx"),
+        sum($"v").over(winSpec(-3, 3)).as("sm")))
+  }
+
+  // ---------------- A4: data types ----------------
+
+  test("numeric types: Int / Long / Double / Decimal") {
+    val df = spark.range(0, 60).selectExpr(
+      "id",
+      "(id % 3) AS pk",
+      "CAST(id AS INT)             AS vi",
+      "CAST(id * 1000000L AS LONG) AS vl",
+      "CAST(id AS DOUBLE) + 0.25   AS vd",
+      "CAST(id AS DECIMAL(20,4))   AS vdec")
+    checkEquivalence(() =>
+      df.select($"id", $"pk",
+        sum($"vi").over(winSpec(-2, 2)).as("si"),
+        min($"vl").over(winSpec(-2, 2)).as("ml"),
+        max($"vd").over(winSpec(-2, 2)).as("xd"),
+        sum($"vdec").over(winSpec(-2, 2)).as("sdec"),
+        avg($"vdec").over(winSpec(-2, 2)).as("adec")))
+  }
+
+  test("String lexicographic MIN/MAX") {
+    // Deliberately non-monotone string values so that MIN/MAX actually
+    // exercise segment-tree merge rather than trivially matching the edge.
+    val df = spark.range(0, 40).selectExpr(
+      "id",
+      "(id % 2) AS pk",
+      "CONCAT('s', LPAD(CAST((id * 37) % 97 AS STRING), 3, '0')) AS v")
+    checkEquivalence(() =>
+      df.select($"id", $"pk",
+        min($"v").over(winSpec(-3, 3)).as("mn"),
+        max($"v").over(winSpec(-3, 3)).as("mx")))
+  }
+
+  test("Date / Timestamp MIN/MAX") {
+    val df = spark.range(0, 40).selectExpr(
+      "id",
+      "(id % 2) AS pk",
+      "date_add(DATE'2020-01-01', CAST((id * 13) % 365 AS INT)) AS vd",
+      "CAST(TIMESTAMP'2020-01-01 00:00:00' + " +
+        "make_interval(0, 0, 0, 0, 0, 0, CAST(id AS DECIMAL(18,6))) AS TIMESTAMP) AS vt")
+    checkEquivalence(() =>
+      df.select($"id", $"pk",
+        min($"vd").over(winSpec(-3, 3)).as("mnd"),
+        max($"vd").over(winSpec(-3, 3)).as("mxd"),
+        min($"vt").over(winSpec(-3, 3)).as("mnt"),
+        max($"vt").over(winSpec(-3, 3)).as("mxt")))
+  }
+
+  
+  test("collect_list falls back cleanly (non-DeclarativeAggregate)") {
+    // collect_list is a Collect(TypedImperativeAggregate) -- not a
+    // DeclarativeAggregate, so eligibleForSegTree must decline and the
+    // sliding frame must take over.
+    checkEquivalence(() =>
+      baseDF.select($"id", $"pk",
+        collect_list($"v").over(winSpec(-2, 2)).as("lst")))
+  }
+
+  test("DISTINCT window aggregate is rejected by analyzer regardless of seg-tree flag") {
+    // Spark does not support DISTINCT window aggregates at all -- the analyzer
+    // throws DISTINCT_WINDOW_FUNCTION_UNSUPPORTED before we ever reach frame
+    // construction. The seg-tree feature flag must not alter this behavior.
+    def run(): Unit = {
+      baseDF.select($"id", $"pk",
+        count_distinct($"v").over(winSpec(-3, 3)).as("cd")).collect()
+    }
+    withSQLConf(disableSegTree.toSeq: _*) {
+      val e = intercept[org.apache.spark.sql.AnalysisException](run())
+      assert(e.getMessage.contains("DISTINCT_WINDOW_FUNCTION_UNSUPPORTED"))
+    }
+    withSQLConf(enableSegTree.toSeq: _*) {
+      val e = intercept[org.apache.spark.sql.AnalysisException](run())
+      assert(e.getMessage.contains("DISTINCT_WINDOW_FUNCTION_UNSUPPORTED"))
+    }
+  }
+
+  test("feature flag off: segmentTree.enabled=false yields baseline semantics") {
+    // Sanity check: disabling the flag on a workload the seg-tree path would
+    // otherwise handle (MIN, wide frame, partitions above the min-rows
+    // threshold) still produces the SlidingWindowFunctionFrame answer.
+    val df = baseDF
+    val expected = withSQLConf(disableSegTree.toSeq: _*) {
+      df.select($"id", $"pk", min($"v").over(winSpec(-3, 3)).as("mn"))
+        .collect().sortBy(_.toString).toSeq
+    }
+    // Explicit disable with the full-size partition config (no min-rows
+    // override). This exercises the flag-off branch of eligibleForSegTree.
+    withSQLConf(
+      SQLConf.WINDOW_SEGMENT_TREE_ENABLED.key -> "false",
+      SQLConf.WINDOW_SEGMENT_TREE_MIN_PARTITION_ROWS.key -> "1024") {
+      val actual = df.select($"id", $"pk", min($"v").over(winSpec(-3, 3)).as("mn"))
+        .collect().sortBy(_.toString).toSeq
+      assert(actual === expected)
+    }
+  }
+
+    // A5.*: RANGE frame equivalence between seg-tree path and sliding baseline.
+  //
+  // The factory (`eligibleForSegTree`) now admits RangeFrame when orderSpec
+  // has exactly one ordering expression. These tests exercise the
+  // frameType-aware admit/drop loops in SegmentTreeWindowFunctionFrame.
+  //
+  // All tests follow the same oracle pattern as NULL/NaN/collation coverage: run the same
+  // query twice (seg-tree on / off) and assert equal Row sequences.
+  // Aggregates are MIN/MAX (non-invertible) to guarantee the seg-tree
+  // code path is actually exercised rather than short-circuited.
+
+  /** Run `sql` twice (flag off / on) and checkAnswer equality. */
+  private def checkRangeEquivalence(df: DataFrame, query: String): Unit = {
+    df.createOrReplaceTempView("t")
+    try {
+      val baseline = withSQLConf(disableSegTree.toSeq: _*) {
+        spark.sql(query).collect().sortBy(_.toString)
+      }
+      withSQLConf(enableSegTree.toSeq: _*) {
+        val actual = spark.sql(query).collect().sortBy(_.toString)
+        assert(actual.toSeq === baseline.toSeq,
+          s"segment-tree output differs from baseline.\nExpected: ${baseline.toSeq}\n" +
+            s"Actual:   ${actual.toSeq}")
+      }
+    } finally {
+      spark.catalog.dropTempView("t")
+    }
+  }
+
+  test("-- RANGE INT offset basic (non-uniform gaps, MIN/MAX)") {
+    // Non-uniform k gaps (1, 3, 4, 4, 7, 10, 15, ...) so that the frame
+    // edges shift by variable amounts and admit/drop loops must consult
+    // the order-key comparator rather than just row count.
+    val df = spark.range(0, 40).selectExpr(
+      "CAST(id AS INT) AS id",
+      "(CAST(id AS INT) % 2) AS pk",
+      "CAST(CASE CAST(id AS INT) % 7 " +
+        "WHEN 0 THEN 1 WHEN 1 THEN 3 WHEN 2 THEN 4 WHEN 3 THEN 4 " +
+        "WHEN 4 THEN 7 WHEN 5 THEN 10 ELSE 15 END + (CAST(id AS INT) / 7) * 20 AS INT) AS k",
+      "CAST((id * 31) % 97 AS INT) AS v")
+    checkRangeEquivalence(df,
+      """SELECT id, pk,
+        |  MIN(v) OVER (PARTITION BY pk ORDER BY k
+        |    RANGE BETWEEN 2 PRECEDING AND 2 FOLLOWING) AS mn,
+        |  MAX(v) OVER (PARTITION BY pk ORDER BY k
+        |    RANGE BETWEEN 2 PRECEDING AND 2 FOLLOWING) AS mx
+        |FROM t""".stripMargin)
+  }
+
+  test("-- RANGE Timestamp with INTERVAL offset (MAX)") {
+    // Irregular gaps: 30min / 90min / 2h / 30min / ... so frame edges
+    // crossing the 1-hour bound must rely on the timestamp comparator.
+    val df = spark.range(0, 30).selectExpr(
+      "CAST(id AS INT) AS id",
+      "(CAST(id AS INT) % 2) AS pk",
+      "CAST(TIMESTAMP'2024-01-01 10:00:00' + " +
+        "make_interval(0, 0, 0, 0, 0, 30 * CAST(id AS INT) * " +
+        "(CASE CAST(id AS INT) % 3 WHEN 0 THEN 1 WHEN 1 THEN 3 ELSE 4 END), 0) " +
+        "AS TIMESTAMP) AS ts",
+      "CAST((id * 17) % 53 AS INT) AS v")
+    checkRangeEquivalence(df,
+      """SELECT id, pk,
+        |  MAX(v) OVER (PARTITION BY pk ORDER BY ts
+        |    RANGE BETWEEN INTERVAL '1' HOUR PRECEDING
+        |              AND INTERVAL '1' HOUR FOLLOWING) AS mx
+        |FROM t""".stripMargin)
+  }
+
+  test("-- RANGE with tie (duplicate order keys) inclusion at boundary") {
+    // k = [1, 2, 2, 2, 3, 4, 5] repeated across partitions. A frame of
+    // `0 PRECEDING AND 0 FOLLOWING` must include the FULL tie group at
+    // the current row's k, not just the current row itself. If the
+    // seg-tree path confuses RANGE with ROWS the tie group of k=2 would
+    // return a per-row MIN/MAX rather than a group-level one.
+    val rows = (0 until 40).map { i =>
+      val k = Seq(1, 2, 2, 2, 3, 4, 5)(i % 7)
+      (i, i % 2, k, (i * 13) % 41)
+    }
+    val df = rows.toDF("id", "pk", "k", "v")
+    checkRangeEquivalence(df,
+      """SELECT id, pk, k,
+        |  MIN(v) OVER (PARTITION BY pk ORDER BY k
+        |    RANGE BETWEEN 0 PRECEDING AND 0 FOLLOWING) AS mn,
+        |  MAX(v) OVER (PARTITION BY pk ORDER BY k
+        |    RANGE BETWEEN 0 PRECEDING AND 0 FOLLOWING) AS mx
+        |FROM t""".stripMargin)
+  }
+
+  test("-- RANGE frame wider than partition (C4: admit/drop loops no-op)") {
+    // Partition size 5 rows, frame covers everything. Once the first
+    // batch is admitted, the admit/drop loops in the seg-tree frame must
+    // detect the effective frame is unchanged and skip work.
+    val df = spark.range(0, 25).selectExpr(
+      "CAST(id AS INT) AS id",
+      "(CAST(id AS INT) / 5) AS pk",
+      "CAST((id * 7) % 23 AS INT) AS k",
+      "CAST((id * 19) % 101 AS INT) AS v")
+    checkRangeEquivalence(df,
+      """SELECT id, pk,
+        |  MIN(v) OVER (PARTITION BY pk ORDER BY k
+        |    RANGE BETWEEN 100 PRECEDING AND 100 FOLLOWING) AS mn,
+        |  MAX(v) OVER (PARTITION BY pk ORDER BY k
+        |    RANGE BETWEEN 100 PRECEDING AND 100 FOLLOWING) AS mx
+        |FROM t""".stripMargin)
+  }
+
+  test("-- RANGE with NULL order key (NULLS FIRST / NULLS LAST)") {
+    // k = [NULL, NULL, 1, 2, 3, NULL] repeated. Spark groups all NULLs
+    // into a single equivalence class at head (NULLS FIRST) or tail
+    // (NULLS LAST). The seg-tree admit/drop loops must treat NULL as a
+    // tie group identically to the sliding baseline.
+    val rows = (0 until 36).map { i =>
+      val kOpt: Option[Int] = (i % 6) match {
+        case 0 | 1 | 5 => None
+        case 2 => Some(1)
+        case 3 => Some(2)
+        case _ => Some(3)
+      }
+      (i, i % 2, kOpt, (i * 11) % 37)
+    }
+    val df = rows.toDF("id", "pk", "k", "v")
+    checkRangeEquivalence(df,
+      """SELECT id, pk,
+        |  MIN(v) OVER (PARTITION BY pk ORDER BY k ASC NULLS FIRST
+        |    RANGE BETWEEN 1 PRECEDING AND 1 FOLLOWING) AS mn_nf,
+        |  MAX(v) OVER (PARTITION BY pk ORDER BY k ASC NULLS FIRST
+        |    RANGE BETWEEN 1 PRECEDING AND 1 FOLLOWING) AS mx_nf,
+        |  MIN(v) OVER (PARTITION BY pk ORDER BY k ASC NULLS LAST
+        |    RANGE BETWEEN 1 PRECEDING AND 1 FOLLOWING) AS mn_nl,
+        |  MAX(v) OVER (PARTITION BY pk ORDER BY k ASC NULLS LAST
+        |    RANGE BETWEEN 1 PRECEDING AND 1 FOLLOWING) AS mx_nl
+        |FROM t""".stripMargin)
+  }
+
+    // Decimal overflow across seg-tree block merge
+  // BinaryType MIN/MAX across seg-tree block merge
+  // UDAF (ScalaUDAF / ScalaAggregator) fallback
+  //
+  // All Decimal/Binary tests force blockSize=16 (the minimum the config
+  // allows) + window size > blockSize so the seg-tree path crosses at
+  // least one block boundary (exercises `mergeExpressions` rather than
+  // only `update`). Design doc asked for blockSize=4 but the SQLConf
+  // validator rejects anything below 16; scaling data/frame up preserves
+  // the merge-path coverage the doc intended.
+
+  private val segTreeBlock: String = "16"
+  private val segTreeFramePrec: Int = 17
+  private val segTreeRows: Int = 20
+
+  private def withSegTreeBlock(conf: (String, String)*)(body: => Unit): Unit = {
+    val extra = Seq(SQLConf.WINDOW_SEGMENT_TREE_BLOCK_SIZE.key -> segTreeBlock) ++ conf
+    withSQLConf(extra: _*)(body)
+  }
+
+  
+  /**
+   * 20 rows in a single partition, Decimal(38, 0) values near the type's
+   * upper bound. Frame of `segTreeFramePrec` PRECEDING..CURRENT ROW means
+   * any window with >= 2 such rows overflows the widened Sum buffer
+   * (Decimal(38,0) widened to Decimal(38,0); any addition above 1e38
+   * overflows). Block size 16 + frame 17 forces cross-block merge.
+   */
+  private def decimalOverflowDF: DataFrame = {
+    // 9e37 -- below Decimal(38,0) MAX (~9.99e37), but 2x overflows.
+    val big = "90000000000000000000000000000000000000"  // 38 digits
+    spark.range(0, segTreeRows.toLong).selectExpr(
+      "CAST(id AS INT) AS id",
+      "0 AS pk",
+      s"CAST('$big' AS DECIMAL(38, 0)) AS v")
+  }
+
+  private val decimalOverflowSql: String =
+    s"""SELECT id, pk,
+       |  SUM(v) OVER (PARTITION BY pk ORDER BY id
+       |    ROWS BETWEEN $segTreeFramePrec PRECEDING AND CURRENT ROW) AS s
+       |FROM t""".stripMargin
+
+  test("a -- Decimal overflow ANSI on, seg-tree matches sliding (both throw)") {
+    val df = decimalOverflowDF
+    df.createOrReplaceTempView("t")
+    try {
+      withSegTreeBlock(SQLConf.ANSI_ENABLED.key -> "true") {
+        withSQLConf(disableSegTree.toSeq: _*) {
+          val e = intercept[Exception] {
+            spark.sql(decimalOverflowSql).collect()
+          }
+          assert(rootArithmeticCause(e).isDefined,
+            s"expected ArithmeticException root cause, got: ${e.getMessage}")
+        }
+        withSQLConf(enableSegTree.toSeq: _*) {
+          val e = intercept[Exception] {
+            spark.sql(decimalOverflowSql).collect()
+          }
+          assert(rootArithmeticCause(e).isDefined,
+            s"expected ArithmeticException root cause, got: ${e.getMessage}")
+        }
+      }
+    } finally {
+      spark.catalog.dropTempView("t")
+    }
+  }
+
+  test("b -- Decimal overflow ANSI off, seg-tree matches sliding (NULL on overflow)") {
+    val df = decimalOverflowDF
+    df.createOrReplaceTempView("t")
+    try {
+      withSegTreeBlock(SQLConf.ANSI_ENABLED.key -> "false") {
+        val baseline = withSQLConf(disableSegTree.toSeq: _*) {
+          spark.sql(decimalOverflowSql).collect().sortBy(_.toString)
+        }
+        // At least one row must be NULL so we know overflow actually fired.
+        assert(baseline.exists(_.isNullAt(2)),
+          "baseline should contain NULL overflow rows; test data may be too small")
+        withSQLConf(enableSegTree.toSeq: _*) {
+          val actual = spark.sql(decimalOverflowSql).collect().sortBy(_.toString)
+          assert(actual.toSeq === baseline.toSeq)
+        }
+      }
+    } finally {
+      spark.catalog.dropTempView("t")
+    }
+  }
+
+  test("c -- mid-window Decimal overflow slides past (seg-tree == sliding)") {
+    // 24 rows, blockSize=16. Frame ROWS BETWEEN 3 PRECEDING AND CURRENT ROW
+    // (size 4). Near-MAX values at ids 14,15,16,17 so any 4-row window
+    // containing >=2 of them overflows. Windows at:
+    //   id<14 or id>20   -> safe
+    //   id in [15..20]   -> overlaps >=2 big values -> NULL
+    // The big-value band (14..17) straddles the block boundary at id=16,
+    // guaranteeing cross-block merge paths see overflowing buffers.
+    val big = "90000000000000000000000000000000000000"
+    val df = spark.range(0, 24).selectExpr(
+      "CAST(id AS INT) AS id",
+      "0 AS pk",
+      s"""CASE WHEN id IN (14, 15, 16, 17)
+              THEN CAST('$big' AS DECIMAL(38, 0))
+              ELSE CAST(id AS DECIMAL(38, 0))
+         END AS v""")
+    df.createOrReplaceTempView("t")
+    try {
+      val sqlStr =
+        """SELECT id, pk,
+          |  SUM(v) OVER (PARTITION BY pk ORDER BY id
+          |    ROWS BETWEEN 3 PRECEDING AND CURRENT ROW) AS s
+          |FROM t""".stripMargin
+      withSegTreeBlock(SQLConf.ANSI_ENABLED.key -> "false") {
+        val baseline = withSQLConf(disableSegTree.toSeq: _*) {
+          spark.sql(sqlStr).collect().sortBy(_.toString)
+        }
+        // Sanity: overflow fired on some rows AND window slides past to
+        // recover non-NULL on the tail rows.
+        assert(baseline.exists(_.isNullAt(2)),
+          "baseline should contain NULL overflow rows")
+        assert(baseline.exists(r => r.getInt(0) >= 21 && !r.isNullAt(2)),
+          "rows with id>=21 should be non-NULL (window slid past big values)")
+        withSQLConf(enableSegTree.toSeq: _*) {
+          val actual = spark.sql(sqlStr).collect().sortBy(_.toString)
+          assert(actual.toSeq === baseline.toSeq)
+        }
+      }
+    } finally {
+      spark.catalog.dropTempView("t")
+    }
+  }
+
+  /** Walk a SparkException chain for an ArithmeticException (ANSI overflow). */
+  private def rootArithmeticCause(t: Throwable): Option[Throwable] = {
+    var cur: Throwable = t
+    while (cur != null) {
+      if (cur.isInstanceOf[ArithmeticException]) return Some(cur)
+      cur = cur.getCause
+    }
+    None
+  }

Review Comment:
   Let me close this since using `org.apache.commons.lang3.exception.ExceptionUtils` is explicitly forbidden via our linter 



-- 
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@spark.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-56546][SQL] Block-chunked segment-tree window frame for non-invertible sliding aggregates [spark]

Posted by "yaooqinn (via GitHub)" <gi...@apache.org>.
yaooqinn commented on code in PR #55422:
URL: https://github.com/apache/spark/pull/55422#discussion_r3124196492


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowSegmentTree.scala:
##########
@@ -0,0 +1,610 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.execution.window
+
+import java.util.{LinkedHashMap => JLinkedHashMap, Map => JMap}
+
+import scala.collection.mutable
+
+import org.apache.spark.{SparkEnv, SparkException, TaskContext}
+import org.apache.spark.memory.{MemoryConsumer, TaskMemoryManager}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.expressions.aggregate.DeclarativeAggregate
+import org.apache.spark.sql.errors.QueryExecutionErrors
+import org.apache.spark.sql.execution.ExternalAppendOnlyUnsafeRowArray
+import org.apache.spark.sql.types.DataType
+import org.apache.spark.util.ArrayImplicits._
+
+/**
+ * Block-chunked segment tree for range aggregate queries over window partitions.
+ *
+ * See `the class documentation`
+ * for the full design (API contract Section 2, block-chunked memory layout Section 3,
+ * DeclarativeAggregate binding Section 4, error handling Section 5, test hooks Section 6).
+ *
+ * initial implementation scope: correctness only. The data layer uses
+ * `ExternalAppendOnlyUnsafeRowArray` to hold input rows (spillable). Each
+ * block materializes its own small segment tree (levels 0..h). Internal
+ * nodes are cached in an LRU keyed by block index; block root aggregates
+ * (block pre-aggregates) stay resident for all blocks.
+ *
+ * Note: the design doc Section 3.3 specifies leaves are NOT materialized and
+ * recomputed from the spillable array on demand. For initial implementation simplicity
+ * we materialize leaves inside the per-block internal node arrays.
+ * // TODO(SPARK-XXXXX) re-assess after Frame integration.
+ *
+ * @note Instances are not thread-safe.
+ */
+private[window] class WindowSegmentTree(
+    functions: Array[DeclarativeAggregate],
+    inputSchema: Seq[Attribute],
+    newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
+    fanout: Int = WindowSegmentTree.DefaultFanout,
+    blockSize: Int = WindowSegmentTree.DefaultBlockSize,
+    maxCachedBlocks: Option[Int] = None,
+    spillThreshold: Int = Int.MaxValue,
+    inMemoryThreshold: Int = Int.MaxValue,
+    taskMemoryManager: TaskMemoryManager = null)
+  extends AutoCloseable {
+
+  require(fanout >= 2, s"fanout must be >= 2, got $fanout")
+  require(blockSize >= 1, s"blockSize must be >= 1, got $blockSize")
+  require(functions.nonEmpty, "WindowSegmentTree requires at least one aggregate function")
+  maxCachedBlocks.foreach { n =>
+    require(n >= 1, s"maxCachedBlocks must be >= 1 when specified, got $n")
+  }
+  require(taskMemoryManager != null,
+    "WindowSegmentTree requires a non-null TaskMemoryManager; " +
+      "in tests use `new TaskMemoryManager(new TestMemoryManager(conf), 0)`")
+
+  // ---------- Schemas & projections ----------
+
+  private val bufferAttrs: Seq[AttributeReference] =
+    functions.flatMap(_.aggBufferAttributes).toImmutableArraySeq
+  private val rightAttrs: Seq[AttributeReference] =
+    functions.flatMap(_.inputAggBufferAttributes).toImmutableArraySeq
+  private val bufferDataTypes: IndexedSeq[DataType] =
+    bufferAttrs.map(_.dataType).toIndexedSeq
+
+  private val initialValues: Seq[Expression] = functions.flatMap(_.initialValues).toIndexedSeq
+  private val updateExpressions: Seq[Expression] =
+    functions.flatMap(_.updateExpressions).toIndexedSeq
+  private val mergeExpressions: Seq[Expression] =
+    functions.flatMap(_.mergeExpressions).toIndexedSeq
+
+  private[this] val initProj: MutableProjection = newMutableProjection(initialValues, Nil)
+  private[this] val updateProj: MutableProjection =
+    newMutableProjection(updateExpressions, bufferAttrs ++ inputSchema)
+  private[this] val mergeProj: MutableProjection =
+    newMutableProjection(mergeExpressions, bufferAttrs ++ rightAttrs)
+
+  private val inputUnsafeProj: UnsafeProjection =
+    UnsafeProjection.create(inputSchema.map(_.dataType).toArray)
+
+  private[this] val joinedRow = new JoinedRow()
+
+  // ---------- State ----------
+
+  private var numRows: Int = 0
+  private var numBlocks: Int = 0
+  private var rowArray: ExternalAppendOnlyUnsafeRowArray = _
+  private var closed: Boolean = false
+
+  /** Always-resident per-block root aggregates. `blockAggregates(i)` =
+   *  merged buffer over all rows in block i. */
+  private var blockAggregates: Array[InternalRow] = Array.empty
+
+  /** Rough byte width of one aggregate buffer row. Chosen at 16 B/field as a
+   *  conservative heap-overhead-aware lower bound for a
+   *  `SpecificInternalRow` slot: primitive `MutableValue` is 8 B, boxed
+   *  references and object headers push the effective footprint higher.
+   *  Tighter per-type sizing (real boxing cost, variable-length fields) is
+   *  intentionally out of scope here; TaskMemoryManager remains the hard
+   *  backstop via spill / OOM.
+   *  TODO(SPARK-XXXXX): per-type width estimator keyed on
+   *  `bufferDataTypes` (primitive 16 B, String/Binary/Decimal wider). */
+  private val bufferWidthBytes: Long = {
+    val bytesPerField = 16L
+    math.max(1L, bufferDataTypes.size.toLong * bytesPerField)
+  }
+
+  /** Number of aggregate-buffer slots cached per block (contract I5).
+   *
+   *  Invariant: equals `sum over levels L of levels(L).length` for any
+   *  block materialized by [[buildBlockLevels]]. Level 0 holds `blockSize`
+   *  leaf buffers and each subsequent level holds `ceil(prev / fanout)`
+   *  parent buffers until a single root remains. The iterative ceiling
+   *  matches the allocation in [[buildBlockLevels]] for every
+   *  `(blockSize, fanout)` pair, including non-power-of-`fanout` cases.
+   *  For `blockSize == 1` the block is a single leaf with no parent
+   *  levels, so this returns 1.
+   *  TODO(SPARK-XXXXX): drop the leaf term when [[buildBlockLevels]]
+   *  switches to on-demand leaf recomputation. */
+  private val cachedSlotsPerBlock: Long = {
+    var n = blockSize.toLong
+    var sum = n
+    while (n > 1L) {
+      n = (n + fanout - 1) / fanout
+      sum += n
+    }
+    sum
+  }
+
+  /** Bytes accounted per cached block (contract I5). Conservative: assumes
+   *  every block is full; tail block (`numRows % blockSize != 0`) will
+   *  hold fewer leaves, giving a small headroom. */
+  private[this] val blockBytes: Long =
+    math.max(1L, cachedSlotsPerBlock * bufferWidthBytes)
+
+  /** `spans(L)` = number of leaves covered by a single node at level L. Depends
+   *  only on fanout + blockSize, so precomputed once. */
+  private val spans: Array[Int] = {
+    val maxLevel = {
+      var lvl = 0
+      var span = 1L
+      while (span < blockSize) { span *= fanout; lvl += 1 }
+      lvl
+    }
+    val arr = new Array[Int](maxLevel + 1)
+    var s = 1L
+    var i = 0
+    while (i <= maxLevel) {
+      arr(i) = if (s > Int.MaxValue) Int.MaxValue else s.toInt
+      s *= fanout
+      i += 1
+    }
+    arr
+  }
+
+  /** LRU cache of per-block internal node arrays. Key = blockIdx.
+   *  Value = `Array[Array[InternalRow]]` with levels(0..h). Auto-eviction via
+   *  `removeEldestEntry` is disabled (contract I3) -- eviction is driven
+   *  explicitly from [[ensureBlockLevels]] (capacity overflow) or
+   *  [[SegTreeSpiller.spill]] (TMM pressure). Each cache entry maps 1:1 to
+   *  one [[acquireBlockMemory]] accounting. Callers (e.g.
+   *  `SegmentTreeWindowFunctionFrame`) should pass a W-aware
+   *  value like `ceil(W / blockSize) + 2`. */
+  private val blockLevelsCache: JLinkedHashMap[Integer, Array[Array[InternalRow]]] =
+    new JLinkedHashMap[Integer, Array[Array[InternalRow]]](16, 0.75f, true) {
+      override def removeEldestEntry(
+          eldest: JMap.Entry[Integer, Array[Array[InternalRow]]]): Boolean = false
+    }
+
+  // ---------- Memory consumer (contract Section 2.2) ----------
+
+  /**
+   * Private MemoryConsumer tracking cached block levels under TMM.
+   *
+   * Heap accounting only (no Tungsten pages): uses
+   * [[MemoryConsumer.acquireMemory]] / [[MemoryConsumer.freeMemory]]. The
+   * [[MemoryConsumer]] base class records `used` via an `AtomicLong` when
+   * we call these -- so TMM's consumer-priority sort in
+   * `acquireExecutionMemory` sees our pressure accurately.
+   *
+   * @note `spill()` MUST NOT call `acquireMemory` (contract I1).
+   */
+  private final class SegTreeSpiller extends MemoryConsumer(
+      taskMemoryManager,
+      taskMemoryManager.pageSizeBytes(),
+      taskMemoryManager.getTungstenMemoryMode()) {

Review Comment:
   Addressed in `0dd8b9b20e0` — hardcoded `SegTreeSpiller` to `MemoryMode.ON_HEAP` (with scaladoc explaining why: cached state — `SpecificInternalRow` buffers, `Array[Array[InternalRow]]`, `ExternalAppendOnlyUnsafeRowArray` pages — is unambiguously on-heap regardless of Tungsten mode).
   
   T9 test flipped: `T9 OFF_HEAP Tungsten: spiller mode stays ON_HEAP (not OFF_HEAP)` now asserts the on-heap charge under `spark.memory.offHeap.enabled=true`. Benchmark refreshed in `0cdaffdbf50`.
   
   Happy to revisit the cross-pool spill-ordering concern as a follow-up if it ever shows up in practice. Thanks for catching this!



-- 
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@spark.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-56546][SQL] Block-chunked segment-tree window frame for non-invertible sliding aggregates [spark]

Posted by "LuciferYang (via GitHub)" <gi...@apache.org>.
LuciferYang commented on code in PR #55422:
URL: https://github.com/apache/spark/pull/55422#discussion_r3122403981


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowEvaluatorFactoryBase.scala:
##########
@@ -295,4 +342,58 @@ trait WindowEvaluatorFactoryBase {
     }
   }
 
+  /**
+   * Segment-tree path eligibility. The tree relies on
+   * `DeclarativeAggregate.mergeExpressions`, which [[AggregateWindowFunction]]s
+   * (NthValue, NTile, Rank, RowNumber, NullIndex) refuse via
+   * `mergeUnsupportedByWindowFunctionError`: they extend DeclarativeAggregate
+   * but are NOT merge-capable. Normal aggregate window expressions reach this
+   * code as the inner DeclarativeAggregate unwrapped from
+   * [[AggregateExpression]] (see `windowFrameExpressionFactoryPairs.collect`).
+   */
+  private def eligibleForSegTree(
+      functions: Array[Expression],
+      filters: Array[Option[Expression]],
+      frameType: FrameType): Boolean = {
+    // RANGE accepted only for single-column order specs. Multi-column RANGE
+    // with non-zero offset is already rejected by `createBoundOrdering`, so
+    // gating here on `orderSpec.size == 1` matches the Sliding-path invariant.
+    val frameTypeOk = frameType match {
+      case RowFrame => true
+      case RangeFrame => orderSpec.size == 1

Review Comment:
   1. Add explicit cases for ties at the endpoint (RANGE includes all rows with equal order-key), block-boundary frames at multiple `blockSize` values, and empty frames produced by RANGE semantics.
     2. Parameterize `WindowSegmentTreePropertySuite` over `FrameType` so random-shape generators exercise both `Row` and `Range`.
     3. `estimateMaxCachedBlocks` returns `Some(8)` for `RangeFrame`. At `W >> 8 · blockSize` this thrashes the LRU and triggers repeated `buildBlockLevels`. May need add a benchmark case at the thrash boundary and either raise the default or compute it from observed endpoint span.



-- 
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@spark.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-56546][SQL] Block-chunked segment-tree window frame for non-invertible sliding aggregates [spark]

Posted by "dongjoon-hyun (via GitHub)" <gi...@apache.org>.
dongjoon-hyun commented on code in PR #55422:
URL: https://github.com/apache/spark/pull/55422#discussion_r3148774740


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowSegmentTree.scala:
##########
@@ -0,0 +1,592 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.execution.window
+
+import java.util.{LinkedHashMap => JLinkedHashMap, Map => JMap}
+
+import scala.collection.mutable
+
+import org.apache.spark.SparkException
+import org.apache.spark.memory.{MemoryConsumer, MemoryMode, TaskMemoryManager}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.expressions.aggregate.{Average, Count, DeclarativeAggregate, Max, Min, StddevPop, StddevSamp, Sum, VariancePop, VarianceSamp}
+import org.apache.spark.sql.errors.QueryExecutionErrors
+import org.apache.spark.sql.execution.ExternalAppendOnlyUnsafeRowArray
+import org.apache.spark.sql.types.DataType
+import org.apache.spark.util.ArrayImplicits._
+
+/**
+ * Block-chunked segment tree for moving-frame window aggregates. Partitions are
+ * split into blocks of `blockSize` rows; each block has its own small segtree
+ * (fanout `F`, height `h`). Block roots stay resident; internal nodes are cached
+ * in an LRU keyed by block index. Queries cost O(log W).
+ *
+ * Memory accounting invariants:
+ *  - I1: `SegTreeSpiller.spill()` MUST NOT call `acquireMemory` on its own
+ *        consumer (would deadlock TMM's consumer-priority sort). All acquires
+ *        happen on the hot path ([[ensureBlockLevels]]).
+ *  - I2: `spill(_, trigger)` returns 0 when `trigger eq this` (self-trigger
+ *        short-circuit) to prevent re-entrant eviction.
+ *  - I3: LRU `removeEldestEntry` is disabled; eviction is driven explicitly
+ *        from [[ensureBlockLevels]] or [[SegTreeSpiller.spill]].
+ *  - I4: Every successful [[acquireBlockMemory]] is paired with exactly one
+ *        [[releaseBlockMemory]]. [[close]] is idempotent.
+ *  - I5: Per-block bytes are a conservative upper bound (full block, 16 B/field).
+ *  - I8: If `rowArray` already spilled to disk, `spill` returns 0 (rebuild
+ *        would O(blockStart)-scan the spill file).
+ *
+ * @note Instances are not thread-safe.
+ */
+private[window] class WindowSegmentTree(
+    functions: Array[DeclarativeAggregate],
+    inputSchema: Seq[Attribute],
+    newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
+    fanout: Int = WindowSegmentTree.DefaultFanout,
+    blockSize: Int = WindowSegmentTree.DefaultBlockSize,
+    maxCachedBlocks: Option[Int] = None,
+    taskMemoryManager: TaskMemoryManager = null)
+  extends AutoCloseable {
+
+  require(fanout >= 2, s"fanout must be >= 2, got $fanout")
+  require(blockSize >= 1, s"blockSize must be >= 1, got $blockSize")
+  require(functions.nonEmpty, "WindowSegmentTree requires at least one aggregate function")
+  maxCachedBlocks.foreach { n =>
+    require(n >= 1, s"maxCachedBlocks must be >= 1 when specified, got $n")
+  }
+  require(taskMemoryManager != null,
+    "WindowSegmentTree requires a non-null TaskMemoryManager; " +
+      "in tests use `new TaskMemoryManager(new TestMemoryManager(conf), 0)`")
+
+  // ---------- Schemas & projections ----------
+
+  private val bufferAttrs: Seq[AttributeReference] =
+    functions.flatMap(_.aggBufferAttributes).toImmutableArraySeq
+  private val rightAttrs: Seq[AttributeReference] =
+    functions.flatMap(_.inputAggBufferAttributes).toImmutableArraySeq
+  private val bufferDataTypes: IndexedSeq[DataType] =
+    bufferAttrs.map(_.dataType).toIndexedSeq
+
+  private val initialValues: Seq[Expression] = functions.flatMap(_.initialValues).toIndexedSeq
+  private val updateExpressions: Seq[Expression] =
+    functions.flatMap(_.updateExpressions).toIndexedSeq
+  private val mergeExpressions: Seq[Expression] =
+    functions.flatMap(_.mergeExpressions).toIndexedSeq
+
+  private[this] val initProj: MutableProjection = newMutableProjection(initialValues, Nil)
+  private[this] val updateProj: MutableProjection =
+    newMutableProjection(updateExpressions, bufferAttrs ++ inputSchema)
+  private[this] val mergeProj: MutableProjection =
+    newMutableProjection(mergeExpressions, bufferAttrs ++ rightAttrs)
+
+  private[this] val joinedRow = new JoinedRow()
+
+  // ---------- State ----------
+
+  private var numRows: Int = 0
+  private var numBlocks: Int = 0
+  private var rowArray: ExternalAppendOnlyUnsafeRowArray = _
+  private var closed: Boolean = false
+
+  /** Always-resident per-block root aggregates: `blockAggregates(i)` =
+   *  merged buffer over all rows in block i. */
+  private var blockAggregates: Array[InternalRow] = Array.empty
+
+  /** Conservative byte width of one aggregate buffer row at 16 B/field:
+   *  primitive `MutableValue` is 8 B, boxed references and object headers
+   *  push the effective footprint higher. Tighter per-type sizing is out
+   *  of scope; TaskMemoryManager remains the hard backstop via spill / OOM. */
+  private val bufferWidthBytes: Long = {
+    val bytesPerField = 16L
+    math.max(1L, bufferDataTypes.size.toLong * bytesPerField)
+  }
+
+  /** Number of aggregate-buffer slots cached per block (see I5).
+   *
+   *  Invariant: equals `sum over levels L of levels(L).length` for any block
+   *  built by [[buildBlockLevels]]: level 0 holds `blockSize` leaves and each
+   *  next level holds `ceil(prev / fanout)` parents until a single root
+   *  remains. For `blockSize == 1` this is 1 (single leaf, no parents). */
+  private val cachedSlotsPerBlock: Long = {
+    var n = blockSize.toLong
+    var sum = n
+    while (n > 1L) {
+      n = (n + fanout - 1) / fanout
+      sum += n
+    }
+    sum
+  }
+
+  /** Bytes accounted per cached block (see I5). Conservative: assumes every
+   *  block is full; tail block leaves a small headroom. */
+  private[this] val blockBytes: Long =
+    math.max(1L, cachedSlotsPerBlock * bufferWidthBytes)
+
+  /** `spans(L)` = number of leaves covered by a single node at level L. Depends
+   *  only on fanout + blockSize, so precomputed once. */
+  private val spans: Array[Int] = {
+    val maxLevel = {
+      var lvl = 0
+      var span = 1L
+      while (span < blockSize) { span *= fanout; lvl += 1 }
+      lvl
+    }
+    val arr = new Array[Int](maxLevel + 1)
+    var s = 1L
+    var i = 0
+    while (i <= maxLevel) {
+      arr(i) = if (s > Int.MaxValue) Int.MaxValue else s.toInt
+      s *= fanout
+      i += 1
+    }
+    arr
+  }
+
+  /** LRU cache of per-block internal node arrays. Key = blockIdx;
+   *  value = `Array[Array[InternalRow]]` with levels(0..h). Auto-eviction
+   *  via `removeEldestEntry` is disabled (I3) -- driven explicitly from
+   *  [[ensureBlockLevels]] or [[SegTreeSpiller.spill]]. Each entry maps 1:1
+   *  to one [[acquireBlockMemory]] accounting. Callers should pass a W-aware
+   *  `maxCachedBlocks` like `ceil(W / blockSize) + 2`. */
+  private val blockLevelsCache: JLinkedHashMap[Integer, Array[Array[InternalRow]]] =
+    new JLinkedHashMap[Integer, Array[Array[InternalRow]]](16, 0.75f, true) {
+      override def removeEldestEntry(
+          eldest: JMap.Entry[Integer, Array[Array[InternalRow]]]): Boolean = false
+    }
+
+  // ---------- Memory consumer ----------
+
+  /**
+   * Private MemoryConsumer tracking cached block levels under TMM. Heap-only
+   * (no Tungsten pages): uses [[MemoryConsumer.acquireMemory]] /
+   * [[MemoryConsumer.freeMemory]], which update the base class `used`
+   * AtomicLong so TMM's consumer-priority sort sees our pressure accurately.
+   *
+   * Hardcoded [[MemoryMode.ON_HEAP]] (not `tmm.getTungstenMemoryMode`): the
+   * cache holds plain JVM objects (`SpecificInternalRow` /
+   * `Array[Array[InternalRow]]`), never Tungsten pages. Under
+   * `spark.memory.offHeap.enabled=true`, enrolling as OFF_HEAP would let
+   * TMM pick us as a spill candidate for off-heap pressure; our `spill()`
+   * would then phantom-credit the off-heap pool without releasing any
+   * off-heap bytes, violating [[TaskMemoryManager#acquireExecutionMemory]]'s
+   * same-pool spill contract. Mirrors
+   * [[org.apache.spark.util.collection.Spillable]], which also hardcodes
+   * ON_HEAP for the same reason. Consequence under off-heap Tungsten: I8
+   * (below) degrades to a no-op because segtree and `rowArray` live in
+   * different pools -- a loss of optimization, not a correctness hazard.
+   *
+   * @note `spill()` MUST NOT call `acquireMemory` (see I1).
+   */
+  private final class SegTreeSpiller extends MemoryConsumer(
+      taskMemoryManager,
+      taskMemoryManager.pageSizeBytes(),
+      MemoryMode.ON_HEAP) {
+    override def spill(size: Long, trigger: MemoryConsumer): Long = {
+      // I2: self-trigger short-circuit (prevent re-entrant eviction).
+      if (trigger eq this) return 0L
+      // I8: rowArray already spilled -- evicting our cache is counter-productive
+      // (rebuild would O(blockStart)-scan the spill file). `spillSize > 0` is
+      // the available "has spilled" signal (UnsafeExternalSorter state is not
+      // public).
+      if (rowArray != null && rowArray.spillSize > 0) return 0L
+      evictUntil(size)
+    }
+  }
+
+  private[this] val spiller: SegTreeSpiller = new SegTreeSpiller
+
+  // ---------- Public API ----------
+
+  def size: Int = numRows
+
+  /**
+   * Build the tree against a caller-owned row array.
+   *
+   * Ownership: the tree holds a reference to `rows` for its lifetime but does
+   * NOT own it -- the caller (typically `WindowPartitionEvaluator.buffer`)
+   * manages `clear()` / lifetime at partition boundaries. `close()` drops
+   * the reference without mutating the array.
+   *
+   * Exception-safe: if aggregation throws, previously built state is preserved.
+   */
+  def build(rows: ExternalAppendOnlyUnsafeRowArray): Unit = {
+    // rows.length is Int by design; check guards against future widening.
+    val n = rows.length
+    if (n < 0) {
+      throw SparkException.internalError(
+        s"WindowSegmentTree cannot hold more than Int.MaxValue rows, got $n")
+    }
+    val nBlocks = if (n == 0) 0 else (n + blockSize - 1) / blockSize
+    val newBlockAggs = computeBlockAggregates(rows, n, nBlocks)
+
+    // Commit.
+    rowArray = rows
+    numRows = n
+    numBlocks = nBlocks
+    blockAggregates = newBlockAggs
+    // Rebuild invalidates cached block levels; release accounting first (I4).
+    releaseAllCachedBlocks()
+  }
+
+  /**
+   * Query [lo, hi) and directly evaluate the result via `processor.evaluate`
+   * into `target`. Uses an internal pre-allocated buffer so no per-call
+   * allocation is needed.
+   */
+  private[window] def queryInto(
+      lo: Int, hi: Int, processor: AggregateProcessor, target: InternalRow): Unit = {
+    query(lo, hi, internalQueryBuffer)
+    processor.evaluate(internalQueryBuffer, target)
+  }
+
+  private[this] val internalQueryBuffer: InternalRow = newBuffer()
+
+  def query(lo: Int, hi: Int, outBuffer: InternalRow): Unit = {
+    if (lo < 0 || hi > numRows || lo > hi) {
+      throw SparkException.internalError(
+        s"Invalid range [lo=$lo, hi=$hi) for size=$numRows")
+    }
+    // Reset outBuffer to identity only after bounds validation.
+    initProj.target(outBuffer)(InternalRow.empty)
+    if (lo == hi) return
+
+    val blo = lo / blockSize
+    val bhi = (hi - 1) / blockSize
+
+    if (blo == bhi) {
+      val blockStart = blo * blockSize
+      mergeBlockRange(blo, lo - blockStart, hi - blockStart, outBuffer)
+    } else {
+      // left partial
+      val loStart = blo * blockSize
+      val loBlockRows = math.min(blockSize, numRows - loStart)
+      mergeBlockRange(blo, lo - loStart, loBlockRows, outBuffer)
+      // full blocks
+      var b = blo + 1
+      while (b < bhi) {
+        mergeInto(outBuffer, blockAggregates(b))
+        b += 1
+      }
+      // right partial
+      val hiStart = bhi * blockSize
+      mergeBlockRange(bhi, 0, hi - hiStart, outBuffer)
+    }
+  }
+
+  /** Terminal: releases all state. Idempotent (I4). */
+  override def close(): Unit = {
+    if (closed) return
+    // Free all cached-block accounting before dropping references.
+    releaseAllCachedBlocks()
+    closeRowArray()
+    blockAggregates = Array.empty
+    numRows = 0
+    numBlocks = 0
+    closed = true
+  }
+
+  // ---------- Test hooks (package-private) ----------
+
+  private[window] def peekBlockCount: Int = numBlocks
+
+  private[window] def testOnlySpiller(): MemoryConsumer = spiller
+
+  /** Test-only accessor for the per-block memory accounting value. */
+  private[window] def peekBlockBytes: Long = blockBytes
+
+  /** NOTE: test-only; promotes block to MRU in the LRU cache as a side effect. */
+  private[window] def peekLevelSize(blockIdx: Int, level: Int): Int = {
+    val levels = ensureBlockLevels(blockIdx)
+    levels(level).length
+  }
+
+  /** NOTE: test-only; promotes block to MRU in the LRU cache as a side effect. */
+  private[window] def peekLevelCount(blockIdx: Int): Int = {
+    val levels = ensureBlockLevels(blockIdx)
+    levels.length
+  }
+
+  // ---------- Internals ----------
+
+  private def computeBlockAggregates(
+      array: ExternalAppendOnlyUnsafeRowArray,
+      n: Int,
+      nBlocks: Int): Array[InternalRow] = {
+    if (n == 0) return Array.empty
+    val result = new Array[InternalRow](nBlocks)
+    val iter = array.generateIterator()
+    var b = 0
+    while (b < nBlocks) {
+      val buf = newBuffer()
+      initProj.target(buf)(InternalRow.empty)
+      val start = b * blockSize
+      val end = math.min(start + blockSize, n)
+      var i = start
+      while (i < end) {
+        if (!iter.hasNext) {
+          throw SparkException.internalError("rowArray iterator exhausted unexpectedly")
+        }
+        val row = iter.next()
+        updateProj.target(buf)(joinedRow(buf, row))
+        i += 1
+      }
+      result(b) = buf
+      b += 1
+    }
+    result
+  }
+
+  /** Merge `src` buffer into `dst` buffer using mergeProj. */
+  private def mergeInto(dst: InternalRow, src: InternalRow): Unit = {
+    mergeProj.target(dst)(joinedRow(dst, src))
+  }
+
+  private def newBuffer(): InternalRow =
+    new SpecificInternalRow(bufferDataTypes)
+
+  /** Merge the given leaf range [lo, hi) inside `blockIdx` into `out`. */
+  private def mergeBlockRange(
+      blockIdx: Int, lo: Int, hi: Int, out: InternalRow): Unit = {
+    if (lo >= hi) return
+    val levels = ensureBlockLevels(blockIdx)
+    val blockRows = levels(0).length
+    val topLevel = levels.length - 1
+    queryDescend(levels, blockRows, topLevel, 0, lo, hi, out)
+  }
+
+  /** Descend the (per-block) segment tree merging any node fully contained
+   *  in [queryLo, queryHi) into `out`. A node at (level L, index idx) covers
+   *  leaves `[idx * span, min((idx+1)*span, blockRows))` where span = F^L. */

Review Comment:
   Oh, multi-line comments seem to break the coding style multiple times. Please check all of them, @yaooqinn .



-- 
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@spark.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-56546][SQL] Block-chunked segment-tree window frame for non-invertible sliding aggregates [spark]

Posted by "yaooqinn (via GitHub)" <gi...@apache.org>.
yaooqinn commented on code in PR #55422:
URL: https://github.com/apache/spark/pull/55422#discussion_r3123990134


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowEvaluatorFactoryBase.scala:
##########
@@ -295,4 +344,63 @@ trait WindowEvaluatorFactoryBase {
     }
   }
 
+  /**
+   * Segment-tree path eligibility. The tree relies on `DeclarativeAggregate.mergeExpressions`,
+   * which [[AggregateWindowFunction]]s (e.g. NthValue, NTile, Rank, RowNumber, NullIndex) refuse
+   * with `mergeUnsupportedByWindowFunctionError`. They extend DeclarativeAggregate but are
+   * NOT merge-capable, so we must exclude them here even though the base-class check passes.
+   * Normal aggregate window expressions reach this code as the inner DeclarativeAggregate
+   * unwrapped from [[AggregateExpression]] (see `windowFrameExpressionFactoryPairs.collect`).
+   */
+  private def eligibleForSegTree(
+      functions: Array[Expression],
+      filters: Array[Option[Expression]],
+      frameType: FrameType): Boolean = {
+    // RANGE is accepted only for single-column order specs. Multi-column
+    // RANGE with non-zero offset is already rejected by `createBoundOrdering`
+    // (see the `RangeFrame, _` internalError branch above), so gating here
+    // on `orderSpec.size == 1` matches the Sliding-path invariant exactly.
+    val frameTypeOk = frameType match {
+      case RowFrame => true
+      case RangeFrame => orderSpec.size == 1
+    }
+    SQLConf.get.windowSegmentTreeEnabled &&
+      frameTypeOk &&
+      filters.forall(_.isEmpty) &&
+      functions.forall { f =>
+        f.isInstanceOf[DeclarativeAggregate] && !f.isInstanceOf[AggregateWindowFunction]
+      } &&
+      !functions.exists {
+        case ae: AggregateExpression => ae.isDistinct
+        case _ => false
+      }

Review Comment:
        1|Good catch — verified this is indeed dead code. In `windowFrameExpressionFactoryPairs`:
        2|
        3|```scala
        4|case AggregateExpression(f, _, _, _, _) => collect("AGGREGATE", frame, e, f)
        5|```
        6|
        7|the inner aggregate function `f` is unwrapped, so `functions: Array[Expression]` never holds an `AggregateExpression` — the DISTINCT match arm is unreachable.
        8|
        9|Moreover, DISTINCT window aggregates are already hard-rejected in analysis by `WindowResolution.checkWindowFunction` (error class `DISTINCT_WINDOW_FUNCTION_UNSUPPORTED`), so no additional gate is needed at this physical-planning layer.
       10|
       11|Fixed in [e07dc6aa]: removed the dead match and added a scaladoc pointer to `WindowResolution`. Thanks.
       12|



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowEvaluatorFactoryBase.scala:
##########
@@ -295,4 +342,58 @@ trait WindowEvaluatorFactoryBase {
     }
   }
 
+  /**
+   * Segment-tree path eligibility. The tree relies on
+   * `DeclarativeAggregate.mergeExpressions`, which [[AggregateWindowFunction]]s
+   * (NthValue, NTile, Rank, RowNumber, NullIndex) refuse via
+   * `mergeUnsupportedByWindowFunctionError`: they extend DeclarativeAggregate
+   * but are NOT merge-capable. Normal aggregate window expressions reach this
+   * code as the inner DeclarativeAggregate unwrapped from
+   * [[AggregateExpression]] (see `windowFrameExpressionFactoryPairs.collect`).
+   */
+  private def eligibleForSegTree(
+      functions: Array[Expression],
+      filters: Array[Option[Expression]],
+      frameType: FrameType): Boolean = {
+    // RANGE accepted only for single-column order specs. Multi-column RANGE
+    // with non-zero offset is already rejected by `createBoundOrdering`, so
+    // gating here on `orderSpec.size == 1` matches the Sliding-path invariant.
+    val frameTypeOk = frameType match {
+      case RowFrame => true
+      case RangeFrame => orderSpec.size == 1
+    }
+    SQLConf.get.windowSegmentTreeEnabled &&
+      frameTypeOk &&
+      filters.forall(_.isEmpty) &&
+      functions.forall(WindowSegmentTree.isEligible) &&
+      !functions.exists {
+        case ae: AggregateExpression => ae.isDistinct
+        case _ => false
+      }
+  }

Review Comment:
        1|Good catch — verified this is indeed dead code. In `windowFrameExpressionFactoryPairs`:
        2|
        3|```scala
        4|case AggregateExpression(f, _, _, _, _) => collect("AGGREGATE", frame, e, f)
        5|```
        6|
        7|the inner aggregate function `f` is unwrapped, so `functions: Array[Expression]` never holds an `AggregateExpression` — the DISTINCT match arm is unreachable.
        8|
        9|Moreover, DISTINCT window aggregates are already hard-rejected in analysis by `WindowResolution.checkWindowFunction` (error class `DISTINCT_WINDOW_FUNCTION_UNSUPPORTED`), so no additional gate is needed at this physical-planning layer.
       10|
       11|Fixed in [e07dc6aa]: removed the dead match and added a scaladoc pointer to `WindowResolution`. Thanks.
       12|



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowSegmentTree.scala:
##########
@@ -0,0 +1,592 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.execution.window
+
+import java.util.{LinkedHashMap => JLinkedHashMap, Map => JMap}
+
+import scala.collection.mutable
+
+import org.apache.spark.SparkException
+import org.apache.spark.memory.{MemoryConsumer, MemoryMode, TaskMemoryManager}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.expressions.aggregate.{Average, Count, DeclarativeAggregate, Max, Min, StddevPop, StddevSamp, Sum, VariancePop, VarianceSamp}
+import org.apache.spark.sql.errors.QueryExecutionErrors
+import org.apache.spark.sql.execution.ExternalAppendOnlyUnsafeRowArray
+import org.apache.spark.sql.types.DataType
+import org.apache.spark.util.ArrayImplicits._
+
+/**
+ * Block-chunked segment tree for moving-frame window aggregates. Partitions are
+ * split into blocks of `blockSize` rows; each block has its own small segtree
+ * (fanout `F`, height `h`). Block roots stay resident; internal nodes are cached
+ * in an LRU keyed by block index. Queries cost O(log W).
+ *
+ * Memory accounting invariants:
+ *  - I1: `SegTreeSpiller.spill()` MUST NOT call `acquireMemory` on its own
+ *        consumer (would deadlock TMM's consumer-priority sort). All acquires
+ *        happen on the hot path ([[ensureBlockLevels]]).
+ *  - I2: `spill(_, trigger)` returns 0 when `trigger eq this` (self-trigger
+ *        short-circuit) to prevent re-entrant eviction.
+ *  - I3: LRU `removeEldestEntry` is disabled; eviction is driven explicitly
+ *        from [[ensureBlockLevels]] or [[SegTreeSpiller.spill]].
+ *  - I4: Every successful [[acquireBlockMemory]] is paired with exactly one
+ *        [[releaseBlockMemory]]. [[close]] is idempotent.
+ *  - I5: Per-block bytes are a conservative upper bound (full block, 16 B/field).
+ *  - I8: If `rowArray` already spilled to disk, `spill` returns 0 (rebuild
+ *        would O(blockStart)-scan the spill file).
+ *
+ * @note Instances are not thread-safe.
+ */
+private[window] class WindowSegmentTree(
+    functions: Array[DeclarativeAggregate],
+    inputSchema: Seq[Attribute],
+    newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
+    fanout: Int = WindowSegmentTree.DefaultFanout,
+    blockSize: Int = WindowSegmentTree.DefaultBlockSize,
+    maxCachedBlocks: Option[Int] = None,
+    taskMemoryManager: TaskMemoryManager = null)
+  extends AutoCloseable {
+
+  require(fanout >= 2, s"fanout must be >= 2, got $fanout")
+  require(blockSize >= 1, s"blockSize must be >= 1, got $blockSize")
+  require(functions.nonEmpty, "WindowSegmentTree requires at least one aggregate function")
+  maxCachedBlocks.foreach { n =>
+    require(n >= 1, s"maxCachedBlocks must be >= 1 when specified, got $n")
+  }
+  require(taskMemoryManager != null,
+    "WindowSegmentTree requires a non-null TaskMemoryManager; " +
+      "in tests use `new TaskMemoryManager(new TestMemoryManager(conf), 0)`")
+
+  // ---------- Schemas & projections ----------
+
+  private val bufferAttrs: Seq[AttributeReference] =
+    functions.flatMap(_.aggBufferAttributes).toImmutableArraySeq
+  private val rightAttrs: Seq[AttributeReference] =
+    functions.flatMap(_.inputAggBufferAttributes).toImmutableArraySeq
+  private val bufferDataTypes: IndexedSeq[DataType] =
+    bufferAttrs.map(_.dataType).toIndexedSeq
+
+  private val initialValues: Seq[Expression] = functions.flatMap(_.initialValues).toIndexedSeq
+  private val updateExpressions: Seq[Expression] =
+    functions.flatMap(_.updateExpressions).toIndexedSeq
+  private val mergeExpressions: Seq[Expression] =
+    functions.flatMap(_.mergeExpressions).toIndexedSeq
+
+  private[this] val initProj: MutableProjection = newMutableProjection(initialValues, Nil)
+  private[this] val updateProj: MutableProjection =
+    newMutableProjection(updateExpressions, bufferAttrs ++ inputSchema)
+  private[this] val mergeProj: MutableProjection =
+    newMutableProjection(mergeExpressions, bufferAttrs ++ rightAttrs)
+
+  private[this] val joinedRow = new JoinedRow()
+
+  // ---------- State ----------
+
+  private var numRows: Int = 0
+  private var numBlocks: Int = 0
+  private var rowArray: ExternalAppendOnlyUnsafeRowArray = _
+  private var closed: Boolean = false
+
+  /** Always-resident per-block root aggregates: `blockAggregates(i)` =
+   *  merged buffer over all rows in block i. */
+  private var blockAggregates: Array[InternalRow] = Array.empty
+
+  /** Conservative byte width of one aggregate buffer row at 16 B/field:
+   *  primitive `MutableValue` is 8 B, boxed references and object headers
+   *  push the effective footprint higher. Tighter per-type sizing is out
+   *  of scope; TaskMemoryManager remains the hard backstop via spill / OOM. */
+  private val bufferWidthBytes: Long = {
+    val bytesPerField = 16L
+    math.max(1L, bufferDataTypes.size.toLong * bytesPerField)
+  }
+
+  /** Number of aggregate-buffer slots cached per block (see I5).
+   *
+   *  Invariant: equals `sum over levels L of levels(L).length` for any block
+   *  built by [[buildBlockLevels]]: level 0 holds `blockSize` leaves and each
+   *  next level holds `ceil(prev / fanout)` parents until a single root
+   *  remains. For `blockSize == 1` this is 1 (single leaf, no parents). */
+  private val cachedSlotsPerBlock: Long = {
+    var n = blockSize.toLong
+    var sum = n
+    while (n > 1L) {
+      n = (n + fanout - 1) / fanout
+      sum += n
+    }
+    sum
+  }
+
+  /** Bytes accounted per cached block (see I5). Conservative: assumes every
+   *  block is full; tail block leaves a small headroom. */
+  private[this] val blockBytes: Long =
+    math.max(1L, cachedSlotsPerBlock * bufferWidthBytes)
+
+  /** `spans(L)` = number of leaves covered by a single node at level L. Depends
+   *  only on fanout + blockSize, so precomputed once. */
+  private val spans: Array[Int] = {
+    val maxLevel = {
+      var lvl = 0
+      var span = 1L
+      while (span < blockSize) { span *= fanout; lvl += 1 }
+      lvl
+    }
+    val arr = new Array[Int](maxLevel + 1)
+    var s = 1L
+    var i = 0
+    while (i <= maxLevel) {
+      arr(i) = if (s > Int.MaxValue) Int.MaxValue else s.toInt
+      s *= fanout
+      i += 1
+    }
+    arr
+  }
+
+  /** LRU cache of per-block internal node arrays. Key = blockIdx;
+   *  value = `Array[Array[InternalRow]]` with levels(0..h). Auto-eviction
+   *  via `removeEldestEntry` is disabled (I3) -- driven explicitly from
+   *  [[ensureBlockLevels]] or [[SegTreeSpiller.spill]]. Each entry maps 1:1
+   *  to one [[acquireBlockMemory]] accounting. Callers should pass a W-aware
+   *  `maxCachedBlocks` like `ceil(W / blockSize) + 2`. */
+  private val blockLevelsCache: JLinkedHashMap[Integer, Array[Array[InternalRow]]] =
+    new JLinkedHashMap[Integer, Array[Array[InternalRow]]](16, 0.75f, true) {
+      override def removeEldestEntry(
+          eldest: JMap.Entry[Integer, Array[Array[InternalRow]]]): Boolean = false
+    }
+
+  // ---------- Memory consumer ----------
+
+  /**
+   * Private MemoryConsumer tracking cached block levels under TMM. Heap-only
+   * (no Tungsten pages): uses [[MemoryConsumer.acquireMemory]] /
+   * [[MemoryConsumer.freeMemory]], which update the base class `used`
+   * AtomicLong so TMM's consumer-priority sort sees our pressure accurately.
+   *
+   * Hardcoded [[MemoryMode.ON_HEAP]] (not `tmm.getTungstenMemoryMode`): the
+   * cache holds plain JVM objects (`SpecificInternalRow` /
+   * `Array[Array[InternalRow]]`), never Tungsten pages. Under
+   * `spark.memory.offHeap.enabled=true`, enrolling as OFF_HEAP would let
+   * TMM pick us as a spill candidate for off-heap pressure; our `spill()`
+   * would then phantom-credit the off-heap pool without releasing any
+   * off-heap bytes, violating [[TaskMemoryManager#acquireExecutionMemory]]'s
+   * same-pool spill contract. Mirrors
+   * [[org.apache.spark.util.collection.Spillable]], which also hardcodes
+   * ON_HEAP for the same reason. Consequence under off-heap Tungsten: I8
+   * (below) degrades to a no-op because segtree and `rowArray` live in
+   * different pools -- a loss of optimization, not a correctness hazard.
+   *
+   * @note `spill()` MUST NOT call `acquireMemory` (see I1).
+   */
+  private final class SegTreeSpiller extends MemoryConsumer(
+      taskMemoryManager,
+      taskMemoryManager.pageSizeBytes(),
+      MemoryMode.ON_HEAP) {
+    override def spill(size: Long, trigger: MemoryConsumer): Long = {
+      // I2: self-trigger short-circuit (prevent re-entrant eviction).
+      if (trigger eq this) return 0L
+      // I8: rowArray already spilled -- evicting our cache is counter-productive
+      // (rebuild would O(blockStart)-scan the spill file). `spillSize > 0` is
+      // the available "has spilled" signal (UnsafeExternalSorter state is not
+      // public).
+      if (rowArray != null && rowArray.spillSize > 0) return 0L
+      evictUntil(size)
+    }
+  }
+
+  private[this] val spiller: SegTreeSpiller = new SegTreeSpiller
+
+  // ---------- Public API ----------
+
+  def size: Int = numRows
+
+  /**
+   * Build the tree against a caller-owned row array.
+   *
+   * Ownership: the tree holds a reference to `rows` for its lifetime but does
+   * NOT own it -- the caller (typically `WindowPartitionEvaluator.buffer`)
+   * manages `clear()` / lifetime at partition boundaries. `close()` drops
+   * the reference without mutating the array.
+   *
+   * Exception-safe: if aggregation throws, previously built state is preserved.
+   */
+  def build(rows: ExternalAppendOnlyUnsafeRowArray): Unit = {
+    // rows.length is Int by design; check guards against future widening.
+    val n = rows.length
+    if (n < 0) {
+      throw SparkException.internalError(
+        s"WindowSegmentTree cannot hold more than Int.MaxValue rows, got $n")
+    }
+    val nBlocks = if (n == 0) 0 else (n + blockSize - 1) / blockSize
+    val newBlockAggs = computeBlockAggregates(rows, n, nBlocks)
+
+    // Commit.
+    rowArray = rows
+    numRows = n
+    numBlocks = nBlocks
+    blockAggregates = newBlockAggs
+    // Rebuild invalidates cached block levels; release accounting first (I4).
+    releaseAllCachedBlocks()
+  }
+
+  /**
+   * Query [lo, hi) and directly evaluate the result via `processor.evaluate`
+   * into `target`. Uses an internal pre-allocated buffer so no per-call
+   * allocation is needed.
+   */
+  private[window] def queryInto(
+      lo: Int, hi: Int, processor: AggregateProcessor, target: InternalRow): Unit = {
+    query(lo, hi, internalQueryBuffer)
+    processor.evaluate(internalQueryBuffer, target)
+  }
+
+  private[this] val internalQueryBuffer: InternalRow = newBuffer()
+
+  def query(lo: Int, hi: Int, outBuffer: InternalRow): Unit = {
+    if (lo < 0 || hi > numRows || lo > hi) {
+      throw SparkException.internalError(
+        s"Invalid range [lo=$lo, hi=$hi) for size=$numRows")
+    }
+    // Reset outBuffer to identity only after bounds validation.
+    initProj.target(outBuffer)(InternalRow.empty)
+    if (lo == hi) return
+
+    val blo = lo / blockSize
+    val bhi = (hi - 1) / blockSize
+
+    if (blo == bhi) {
+      val blockStart = blo * blockSize
+      mergeBlockRange(blo, lo - blockStart, hi - blockStart, outBuffer)
+    } else {
+      // left partial
+      val loStart = blo * blockSize
+      val loBlockRows = math.min(blockSize, numRows - loStart)
+      mergeBlockRange(blo, lo - loStart, loBlockRows, outBuffer)
+      // full blocks
+      var b = blo + 1
+      while (b < bhi) {
+        mergeInto(outBuffer, blockAggregates(b))
+        b += 1
+      }
+      // right partial
+      val hiStart = bhi * blockSize
+      mergeBlockRange(bhi, 0, hi - hiStart, outBuffer)
+    }
+  }
+
+  /** Terminal: releases all state. Idempotent (I4). */
+  override def close(): Unit = {
+    if (closed) return
+    // Free all cached-block accounting before dropping references.
+    releaseAllCachedBlocks()
+    closeRowArray()
+    blockAggregates = Array.empty
+    numRows = 0
+    numBlocks = 0
+    closed = true
+  }
+
+  // ---------- Test hooks (package-private) ----------
+
+  private[window] def peekBlockCount: Int = numBlocks
+
+  private[window] def testOnlySpiller(): MemoryConsumer = spiller
+
+  /** Test-only accessor for the per-block memory accounting value. */
+  private[window] def peekBlockBytes: Long = blockBytes
+
+  /** NOTE: test-only; promotes block to MRU in the LRU cache as a side effect. */
+  private[window] def peekLevelSize(blockIdx: Int, level: Int): Int = {
+    val levels = ensureBlockLevels(blockIdx)
+    levels(level).length
+  }
+
+  /** NOTE: test-only; promotes block to MRU in the LRU cache as a side effect. */
+  private[window] def peekLevelCount(blockIdx: Int): Int = {
+    val levels = ensureBlockLevels(blockIdx)
+    levels.length
+  }
+
+  // ---------- Internals ----------
+
+  private def computeBlockAggregates(
+      array: ExternalAppendOnlyUnsafeRowArray,
+      n: Int,
+      nBlocks: Int): Array[InternalRow] = {
+    if (n == 0) return Array.empty
+    val result = new Array[InternalRow](nBlocks)
+    val iter = array.generateIterator()
+    var b = 0
+    while (b < nBlocks) {
+      val buf = newBuffer()
+      initProj.target(buf)(InternalRow.empty)
+      val start = b * blockSize
+      val end = math.min(start + blockSize, n)
+      var i = start
+      while (i < end) {
+        if (!iter.hasNext) {
+          throw SparkException.internalError("rowArray iterator exhausted unexpectedly")
+        }
+        val row = iter.next()
+        updateProj.target(buf)(joinedRow(buf, row))
+        i += 1
+      }
+      result(b) = buf
+      b += 1
+    }
+    result
+  }
+
+  /** Merge `src` buffer into `dst` buffer using mergeProj. */
+  private def mergeInto(dst: InternalRow, src: InternalRow): Unit = {
+    mergeProj.target(dst)(joinedRow(dst, src))
+  }
+
+  private def newBuffer(): InternalRow =
+    new SpecificInternalRow(bufferDataTypes)
+
+  /** Merge the given leaf range [lo, hi) inside `blockIdx` into `out`. */
+  private def mergeBlockRange(
+      blockIdx: Int, lo: Int, hi: Int, out: InternalRow): Unit = {
+    if (lo >= hi) return
+    val levels = ensureBlockLevels(blockIdx)
+    val blockRows = levels(0).length
+    val topLevel = levels.length - 1
+    queryDescend(levels, blockRows, topLevel, 0, lo, hi, out)
+  }
+
+  /** Descend the (per-block) segment tree merging any node fully contained
+   *  in [queryLo, queryHi) into `out`. A node at (level L, index idx) covers
+   *  leaves `[idx * span, min((idx+1)*span, blockRows))` where span = F^L. */
+  private def queryDescend(
+      levels: Array[Array[InternalRow]],
+      blockRows: Int,
+      level: Int,
+      idx: Int,
+      queryLo: Int,
+      queryHi: Int,
+      out: InternalRow): Unit = {
+    val span = spans(level)
+    val nodeLo = idx * span
+    val nodeHi = math.min(nodeLo + span, blockRows)
+    if (queryLo >= nodeHi || queryHi <= nodeLo) return
+    if (queryLo <= nodeLo && nodeHi <= queryHi) {
+      mergeInto(out, levels(level)(idx))
+      return
+    }
+    val childLevel = level - 1
+    val childLevelSize = levels(childLevel).length
+    var c = 0
+    while (c < fanout) {
+      val childIdx = idx * fanout + c
+      if (childIdx < childLevelSize) {
+        queryDescend(levels, blockRows, childLevel, childIdx, queryLo, queryHi, out)
+      }
+      c += 1
+    }
+  }
+
+  /** Build (or fetch from LRU) the full per-block levels array.
+   *  Protocol: acquire memory -> build -> cache. Eviction on capacity
+   *  overflow or on TMM spill request. */
+  private def ensureBlockLevels(blockIdx: Int): Array[Array[InternalRow]] = {
+    val cached = blockLevelsCache.get(Integer.valueOf(blockIdx))
+    if (cached != null) return cached
+
+    // Enforce LRU capacity before building a new entry (I3).
+    val cap = maxCachedBlocks.getOrElse(Int.MaxValue)
+    while (blockLevelsCache.size() >= cap) {
+      if (!evictEldest()) return throwCacheEvictFailed(blockIdx)
+    }
+
+    // Acquire accounting; on partial grant, try one manual evict-and-retry.
+    if (!acquireBlockMemory(blockIdx)) {
+      if (!evictEldest() || !acquireBlockMemory(blockIdx)) {
+        // scalastyle:off throwerror
+        throw QueryExecutionErrors.cannotAcquireMemoryForWindowAggregateError(
+          blockBytes, 0L)
+        // scalastyle:on throwerror

Review Comment:
   Thanks for the look. Re-checked and I don't think this is a bug:
   
   `acquireBlockMemory` rolls back any partial grant before returning `false`:
   
   ```scala
   private def acquireBlockMemory(blockIdx: Int): Boolean = {
     val granted = spiller.acquireMemory(blockBytes)
     if (granted < blockBytes) {
       if (granted > 0) spiller.freeMemory(granted)  // partial -> rolled back
       false
     } else true
   }
   ```
   
   So by the time we reach `cannotAcquireMemoryForWindowAggregateError`, the consumer's persisted received bytes is in fact `0` (both after the first attempt and after `evictEldest + retry`). The error-parameter contract is "bytes still held by this consumer at failure time", not "bytes ever transiently granted during the request".
   
   I'll leave the `0L` as is, but happy to add a comment at the throw site if that helps future readers. WDYT?
   



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/window/SegmentTreeWindowFunctionSuite.scala:
##########
@@ -0,0 +1,892 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.execution.window
+
+import org.apache.spark.sql.{DataFrame, Encoder, Encoders, QueryTest, Row}
+import org.apache.spark.sql.expressions.{Aggregator, MutableAggregationBuffer, Window}
+import org.apache.spark.sql.expressions.UserDefinedAggregateFunction
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.test.SharedSparkSession
+import org.apache.spark.sql.types.{DataType, LongType, StructType}
+import org.apache.spark.util.SparkErrorUtils
+
+/**
+ * End-to-end tests for the block-chunked segment-tree moving window frame.
+ * Covers basic aggregates, frame boundaries, min-rows fallback, NULL/NaN,
+ * numeric/string/date-timestamp types, RANGE, Decimal/Binary merge, UDAF
+ * fallback, and frame lifecycle.
+ */
+class SegmentTreeWindowFunctionSuite extends QueryTest with SharedSparkSession {
+
+  import testImplicits._
+
+  // Force seg-tree path regardless of partition size (fallback exercised explicitly).
+  private val enableSegTree: Map[String, String] = Map(
+    SQLConf.WINDOW_SEGMENT_TREE_ENABLED.key -> "true",
+    SQLConf.WINDOW_SEGMENT_TREE_MIN_PARTITION_ROWS.key -> "1")
+
+  private val disableSegTree: Map[String, String] = Map(
+    SQLConf.WINDOW_SEGMENT_TREE_ENABLED.key -> "false")
+
+  /** Build `f(conf)` twice (enabled / disabled) and assert equal results. */
+  private def checkEquivalence(build: () => DataFrame): Unit = {
+    val baseline: Array[Row] = withSQLConf(disableSegTree.toSeq: _*) {
+      build().collect().sortBy(_.toString)
+    }
+    withSQLConf(enableSegTree.toSeq: _*) {
+      val actual = build().collect().sortBy(_.toString)
+      assert(actual.toSeq === baseline.toSeq,

Review Comment:
   Good catch. Switched `checkEquivalence` to `QueryTest.sameRows(baseline, actual, isSorted = false)`, which normalizes `Array[_]` (and BigDecimal) via `prepareRow` *before* sorting, avoiding the address-based `Array[Byte].toString` ordering hazard. This also covers the BinaryType suites (B4) — fixed the three `a/b/c -- BinaryType ...` tests the same way. Thanks.
   



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/window/SegmentTreeWindowFunctionSuite.scala:
##########
@@ -0,0 +1,892 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.execution.window
+
+import org.apache.spark.sql.{DataFrame, Encoder, Encoders, QueryTest, Row}
+import org.apache.spark.sql.expressions.{Aggregator, MutableAggregationBuffer, Window}
+import org.apache.spark.sql.expressions.UserDefinedAggregateFunction
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.test.SharedSparkSession
+import org.apache.spark.sql.types.{DataType, LongType, StructType}
+import org.apache.spark.util.SparkErrorUtils
+
+/**
+ * End-to-end tests for the block-chunked segment-tree moving window frame.
+ * Covers basic aggregates, frame boundaries, min-rows fallback, NULL/NaN,
+ * numeric/string/date-timestamp types, RANGE, Decimal/Binary merge, UDAF
+ * fallback, and frame lifecycle.
+ */
+class SegmentTreeWindowFunctionSuite extends QueryTest with SharedSparkSession {
+
+  import testImplicits._
+
+  // Force seg-tree path regardless of partition size (fallback exercised explicitly).
+  private val enableSegTree: Map[String, String] = Map(
+    SQLConf.WINDOW_SEGMENT_TREE_ENABLED.key -> "true",
+    SQLConf.WINDOW_SEGMENT_TREE_MIN_PARTITION_ROWS.key -> "1")
+
+  private val disableSegTree: Map[String, String] = Map(
+    SQLConf.WINDOW_SEGMENT_TREE_ENABLED.key -> "false")
+
+  /** Build `f(conf)` twice (enabled / disabled) and assert equal results. */
+  private def checkEquivalence(build: () => DataFrame): Unit = {
+    val baseline: Array[Row] = withSQLConf(disableSegTree.toSeq: _*) {
+      build().collect().sortBy(_.toString)
+    }
+    withSQLConf(enableSegTree.toSeq: _*) {
+      val actual = build().collect().sortBy(_.toString)
+      assert(actual.toSeq === baseline.toSeq,
+        s"segment-tree output differs from baseline.\nExpected: ${baseline.toSeq}\n" +
+          s"Actual:   ${actual.toSeq}")
+    }
+  }
+
+  /** Standard fixture: 3 partitions, sizes 40/40/40, values = row index. */
+  private def baseDF: DataFrame = {
+    spark.range(0, 120).selectExpr(
+      "id",
+      "(id % 3) AS pk",
+      "CAST(id AS INT) AS v")
+  }
+
+  private def winSpec(lo: Int, hi: Int) =
+    Window.partitionBy($"pk").orderBy($"id").rowsBetween(lo, hi)
+
+  // A1: basic aggregate equivalence
+
+  test("MIN over ROWS BETWEEN 3 PRECEDING AND 3 FOLLOWING") {
+    checkEquivalence(() =>
+      baseDF.select($"id", $"pk", min($"v").over(winSpec(-3, 3)).as("agg")))
+  }
+
+  test("MAX over ROWS BETWEEN 3 PRECEDING AND 3 FOLLOWING") {
+    checkEquivalence(() =>
+      baseDF.select($"id", $"pk", max($"v").over(winSpec(-3, 3)).as("agg")))
+  }
+
+  test("SUM over ROWS BETWEEN 3 PRECEDING AND 3 FOLLOWING") {
+    checkEquivalence(() =>
+      baseDF.select($"id", $"pk", sum($"v").over(winSpec(-3, 3)).as("agg")))
+  }
+
+  test("COUNT over ROWS BETWEEN 3 PRECEDING AND 3 FOLLOWING") {
+    checkEquivalence(() =>
+      baseDF.select($"id", $"pk", count($"v").over(winSpec(-3, 3)).as("agg")))
+  }
+
+  test("AVG over ROWS BETWEEN 3 PRECEDING AND 3 FOLLOWING") {
+    checkEquivalence(() =>
+      baseDF.select($"id", $"pk", avg($"v").over(winSpec(-3, 3)).as("agg")))
+  }
+
+  test("MIN + MAX + SUM share a single window frame") {
+    checkEquivalence(() =>
+      baseDF.select(
+        $"id",
+        $"pk",
+        min($"v").over(winSpec(-3, 3)).as("mn"),
+        max($"v").over(winSpec(-3, 3)).as("mx"),
+        sum($"v").over(winSpec(-3, 3)).as("sm")))
+  }
+
+  // A2: frame-size boundaries
+
+  test("frame size = 1 (CURRENT ROW only)") {
+    checkEquivalence(() =>
+      baseDF.select($"id", $"pk", sum($"v").over(winSpec(0, 0)).as("agg")))
+  }
+
+  test("frame spans full partition") {
+    checkEquivalence(() =>
+      baseDF.select($"id", $"pk", sum($"v").over(winSpec(-100, 100)).as("agg")))
+  }
+
+  test("frame extends past both partition edges") {
+    checkEquivalence(() =>
+      baseDF.select($"id", $"pk",
+        sum($"v").over(winSpec(-50, 50)).as("agg"),
+        min($"v").over(winSpec(-50, 50)).as("mn"),
+        max($"v").over(winSpec(-50, 50)).as("mx")))
+  }
+
+
+  test("partition below minPartitionRows falls back to SlidingWindowFunctionFrame") {
+    // 5-row partition, min threshold = 10 -> must fall back.
+    val df = spark.range(0, 5).selectExpr(
+      "id", "0 AS pk", "CAST(id AS INT) AS v")
+    val enabledConf = Map(
+      SQLConf.WINDOW_SEGMENT_TREE_ENABLED.key -> "true",
+      SQLConf.WINDOW_SEGMENT_TREE_MIN_PARTITION_ROWS.key -> "10")
+
+    val baseline = withSQLConf(disableSegTree.toSeq: _*) {
+      df.select($"id", sum($"v").over(winSpec(-1, 1)).as("s"))
+        .collect().sortBy(_.toString)
+    }
+    val actual = withSQLConf(enabledConf.toSeq: _*) {
+      df.select($"id", sum($"v").over(winSpec(-1, 1)).as("s"))
+        .collect().sortBy(_.toString)
+    }
+    assert(actual.toSeq === baseline.toSeq)
+
+    // Confirm the fallback flag actually flipped.
+    withSQLConf(enabledConf.toSeq: _*) {
+      SegmentTreeWindowTestHelpers.withSmallPartitionFrame(
+        SQLConf.get, rows = 5) { frame =>
+        assert(frame.fallbackUsed,
+          "expected fallbackUsed=true for partition smaller than minPartitionRows")
+      }
+    }
+  }
+
+
+  test("NTH_VALUE over ROWS frame falls back cleanly (no mergeExpressions crash)") {
+    // NthValue extends DeclarativeAggregate but its mergeExpressions throws
+    // mergeUnsupportedByWindowFunctionError. eligibleForSegTree must exclude it.
+    val df = baseDF
+    val withSegTree = withSQLConf(enableSegTree.toSeq: _*) {
+      df.selectExpr(
+        "id", "pk",
+        "nth_value(v, 3) OVER (PARTITION BY pk ORDER BY id " +
+          "ROWS BETWEEN 5 PRECEDING AND 5 FOLLOWING) AS n3")
+        .collect().sortBy(_.toString)
+    }
+    val baseline = withSQLConf(disableSegTree.toSeq: _*) {
+      df.selectExpr(
+        "id", "pk",
+        "nth_value(v, 3) OVER (PARTITION BY pk ORDER BY id " +
+          "ROWS BETWEEN 5 PRECEDING AND 5 FOLLOWING) AS n3")
+        .collect().sortBy(_.toString)
+    }
+    assert(withSegTree.toSeq === baseline.toSeq)
+  }
+
+  test("ROW_NUMBER over ROWS frame falls back cleanly (no mergeExpressions crash)") {
+    val df = baseDF
+    val withSegTree = withSQLConf(enableSegTree.toSeq: _*) {
+      df.selectExpr(
+        "id", "pk",
+        "row_number() OVER (PARTITION BY pk ORDER BY id) AS rn")
+        .collect().sortBy(_.toString)
+    }
+    val baseline = withSQLConf(disableSegTree.toSeq: _*) {
+      df.selectExpr(
+        "id", "pk",
+        "row_number() OVER (PARTITION BY pk ORDER BY id) AS rn")
+        .collect().sortBy(_.toString)
+    }
+    assert(withSegTree.toSeq === baseline.toSeq)
+  }
+
+  // A3: NULL/NaN/Infinity; A4: numeric/string/date-timestamp types.
+  // Unsupported-merge / DISTINCT / feature-flag fallback.
+  // Oracle: run with seg-tree enabled and disabled, assert equal Row sequences.
+
+  // A3: NULL / special values
+
+  test("all-NULL column: MIN/MAX/SUM/AVG/COUNT") {
+    val df = spark.range(0, 30).selectExpr(
+      "id", "(id % 3) AS pk", "CAST(NULL AS INT) AS v")
+    checkEquivalence(() =>
+      df.select($"id", $"pk",
+        min($"v").over(winSpec(-3, 3)).as("mn"),
+        max($"v").over(winSpec(-3, 3)).as("mx"),
+        sum($"v").over(winSpec(-3, 3)).as("sm"),
+        avg($"v").over(winSpec(-3, 3)).as("av"),
+        count($"v").over(winSpec(-3, 3)).as("cn")))
+  }
+
+  test("mixed NULL and non-NULL: NULLs must not leak into MIN/MAX") {
+    // Every 3rd value is NULL. Aggregates must skip them (NULL-agnostic merge).
+    val df = spark.range(0, 60).selectExpr(
+      "id",
+      "(id % 3) AS pk",
+      "CASE WHEN id % 3 = 0 THEN NULL ELSE CAST(id AS INT) END AS v")
+    checkEquivalence(() =>
+      df.select($"id", $"pk",
+        min($"v").over(winSpec(-4, 4)).as("mn"),
+        max($"v").over(winSpec(-4, 4)).as("mx"),
+        sum($"v").over(winSpec(-4, 4)).as("sm"),
+        count($"v").over(winSpec(-4, 4)).as("cn")))
+  }
+
+  test("Double NaN and +/-Infinity propagate correctly through MIN/MAX/SUM") {
+    // Trap: NaN > +Inf in Spark's MIN/MAX ordering; +Inf + -Inf = NaN in SUM.
+    // Seg-tree uses DeclarativeAggregate.merge; behavior must match baseline.
+    val df = spark.range(0, 30).selectExpr(
+      "id",
+      "(id % 2) AS pk",
+      """CASE
+           WHEN id % 7 = 0 THEN double('NaN')
+           WHEN id % 7 = 1 THEN double('Infinity')
+           WHEN id % 7 = 2 THEN double('-Infinity')
+           ELSE CAST(id AS DOUBLE)
+         END AS v""")
+    checkEquivalence(() =>
+      df.select($"id", $"pk",
+        min($"v").over(winSpec(-3, 3)).as("mn"),
+        max($"v").over(winSpec(-3, 3)).as("mx"),
+        sum($"v").over(winSpec(-3, 3)).as("sm")))
+  }
+
+  // A4: data types
+
+  test("numeric types: Int / Long / Double / Decimal") {
+    val df = spark.range(0, 60).selectExpr(
+      "id",
+      "(id % 3) AS pk",
+      "CAST(id AS INT)             AS vi",
+      "CAST(id * 1000000L AS LONG) AS vl",
+      "CAST(id AS DOUBLE) + 0.25   AS vd",
+      "CAST(id AS DECIMAL(20,4))   AS vdec")
+    checkEquivalence(() =>
+      df.select($"id", $"pk",
+        sum($"vi").over(winSpec(-2, 2)).as("si"),
+        min($"vl").over(winSpec(-2, 2)).as("ml"),
+        max($"vd").over(winSpec(-2, 2)).as("xd"),
+        sum($"vdec").over(winSpec(-2, 2)).as("sdec"),
+        avg($"vdec").over(winSpec(-2, 2)).as("adec")))
+  }
+
+  test("String lexicographic MIN/MAX") {
+    // Non-monotone values so MIN/MAX exercise the seg-tree merge (not edge).
+    val df = spark.range(0, 40).selectExpr(
+      "id",
+      "(id % 2) AS pk",
+      "CONCAT('s', LPAD(CAST((id * 37) % 97 AS STRING), 3, '0')) AS v")
+    checkEquivalence(() =>
+      df.select($"id", $"pk",
+        min($"v").over(winSpec(-3, 3)).as("mn"),
+        max($"v").over(winSpec(-3, 3)).as("mx")))
+  }
+
+  test("Date / Timestamp MIN/MAX") {
+    val df = spark.range(0, 40).selectExpr(
+      "id",
+      "(id % 2) AS pk",
+      "date_add(DATE'2020-01-01', CAST((id * 13) % 365 AS INT)) AS vd",
+      "CAST(TIMESTAMP'2020-01-01 00:00:00' + " +
+        "make_interval(0, 0, 0, 0, 0, 0, CAST(id AS DECIMAL(18,6))) AS TIMESTAMP) AS vt")
+    checkEquivalence(() =>
+      df.select($"id", $"pk",
+        min($"vd").over(winSpec(-3, 3)).as("mnd"),
+        max($"vd").over(winSpec(-3, 3)).as("mxd"),
+        min($"vt").over(winSpec(-3, 3)).as("mnt"),
+        max($"vt").over(winSpec(-3, 3)).as("mxt")))
+  }
+
+
+  test("collect_list falls back cleanly (non-DeclarativeAggregate)") {
+    // collect_list is TypedImperativeAggregate; eligibleForSegTree must decline.
+    checkEquivalence(() =>
+      baseDF.select($"id", $"pk",
+        collect_list($"v").over(winSpec(-2, 2)).as("lst")))
+  }
+
+  test("DISTINCT window aggregate is rejected by analyzer regardless of seg-tree flag") {
+    // Analyzer throws DISTINCT_WINDOW_FUNCTION_UNSUPPORTED before frame
+    // construction; seg-tree flag must not alter this behavior.
+    def run(): Unit = {
+      baseDF.select($"id", $"pk",
+        count_distinct($"v").over(winSpec(-3, 3)).as("cd")).collect()
+    }
+    withSQLConf(disableSegTree.toSeq: _*) {
+      val e = intercept[org.apache.spark.sql.AnalysisException](run())
+      assert(e.getMessage.contains("DISTINCT_WINDOW_FUNCTION_UNSUPPORTED"))
+    }
+    withSQLConf(enableSegTree.toSeq: _*) {
+      val e = intercept[org.apache.spark.sql.AnalysisException](run())
+      assert(e.getMessage.contains("DISTINCT_WINDOW_FUNCTION_UNSUPPORTED"))
+    }
+  }
+
+  test("feature flag off: segmentTree.enabled=false yields baseline semantics") {
+    // Sanity: disabling the flag on a seg-tree-eligible workload still
+    // produces the SlidingWindowFunctionFrame answer.
+    val df = baseDF
+    val expected = withSQLConf(disableSegTree.toSeq: _*) {
+      df.select($"id", $"pk", min($"v").over(winSpec(-3, 3)).as("mn"))
+        .collect().sortBy(_.toString).toSeq
+    }
+    withSQLConf(
+      SQLConf.WINDOW_SEGMENT_TREE_ENABLED.key -> "false",
+      SQLConf.WINDOW_SEGMENT_TREE_MIN_PARTITION_ROWS.key -> "1024") {
+      val actual = df.select($"id", $"pk", min($"v").over(winSpec(-3, 3)).as("mn"))
+        .collect().sortBy(_.toString).toSeq
+      assert(actual === expected)
+    }
+  }
+
+    // A5: RANGE frame equivalence (single-order-expr admission).
+  // MIN/MAX non-invertible, guaranteeing seg-tree path is exercised.
+
+  /** Run `sql` twice (flag off / on) and checkAnswer equality. */
+  private def checkRangeEquivalence(df: DataFrame, query: String): Unit = {
+    df.createOrReplaceTempView("t")
+    try {
+      val baseline = withSQLConf(disableSegTree.toSeq: _*) {
+        spark.sql(query).collect().sortBy(_.toString)
+      }
+      withSQLConf(enableSegTree.toSeq: _*) {
+        val actual = spark.sql(query).collect().sortBy(_.toString)
+        assert(actual.toSeq === baseline.toSeq,
+          s"segment-tree output differs from baseline.\nExpected: ${baseline.toSeq}\n" +
+            s"Actual:   ${actual.toSeq}")
+      }
+    } finally {
+      spark.catalog.dropTempView("t")
+    }
+  }
+
+  test("-- RANGE INT offset basic (non-uniform gaps, MIN/MAX)") {
+    // Non-uniform gaps so admit/drop loops must consult the order-key comparator.
+    val df = spark.range(0, 40).selectExpr(
+      "CAST(id AS INT) AS id",
+      "(CAST(id AS INT) % 2) AS pk",
+      "CAST(CASE CAST(id AS INT) % 7 " +
+        "WHEN 0 THEN 1 WHEN 1 THEN 3 WHEN 2 THEN 4 WHEN 3 THEN 4 " +
+        "WHEN 4 THEN 7 WHEN 5 THEN 10 ELSE 15 END + (CAST(id AS INT) / 7) * 20 AS INT) AS k",
+      "CAST((id * 31) % 97 AS INT) AS v")
+    checkRangeEquivalence(df,
+      """SELECT id, pk,
+        |  MIN(v) OVER (PARTITION BY pk ORDER BY k
+        |    RANGE BETWEEN 2 PRECEDING AND 2 FOLLOWING) AS mn,
+        |  MAX(v) OVER (PARTITION BY pk ORDER BY k
+        |    RANGE BETWEEN 2 PRECEDING AND 2 FOLLOWING) AS mx
+        |FROM t""".stripMargin)
+  }
+
+  test("-- RANGE Timestamp with INTERVAL offset (MAX)") {
+    // Irregular gaps force the timestamp comparator at the 1-hour boundary.
+    val df = spark.range(0, 30).selectExpr(
+      "CAST(id AS INT) AS id",
+      "(CAST(id AS INT) % 2) AS pk",
+      "CAST(TIMESTAMP'2024-01-01 10:00:00' + " +
+        "make_interval(0, 0, 0, 0, 0, 30 * CAST(id AS INT) * " +
+        "(CASE CAST(id AS INT) % 3 WHEN 0 THEN 1 WHEN 1 THEN 3 ELSE 4 END), 0) " +
+        "AS TIMESTAMP) AS ts",
+      "CAST((id * 17) % 53 AS INT) AS v")
+    checkRangeEquivalence(df,
+      """SELECT id, pk,
+        |  MAX(v) OVER (PARTITION BY pk ORDER BY ts
+        |    RANGE BETWEEN INTERVAL '1' HOUR PRECEDING
+        |              AND INTERVAL '1' HOUR FOLLOWING) AS mx
+        |FROM t""".stripMargin)
+  }
+
+  test("-- RANGE with tie (duplicate order keys) inclusion at boundary") {
+    // Trap: RANGE `0 PRECEDING AND 0 FOLLOWING` must include the FULL tie
+    // group at the current row's key, not just the current row. A ROWS-vs-
+    // RANGE confusion would return per-row MIN/MAX instead of group-level.
+    val rows = (0 until 40).map { i =>
+      val k = Seq(1, 2, 2, 2, 3, 4, 5)(i % 7)
+      (i, i % 2, k, (i * 13) % 41)
+    }
+    val df = rows.toDF("id", "pk", "k", "v")
+    checkRangeEquivalence(df,
+      """SELECT id, pk, k,
+        |  MIN(v) OVER (PARTITION BY pk ORDER BY k
+        |    RANGE BETWEEN 0 PRECEDING AND 0 FOLLOWING) AS mn,
+        |  MAX(v) OVER (PARTITION BY pk ORDER BY k
+        |    RANGE BETWEEN 0 PRECEDING AND 0 FOLLOWING) AS mx
+        |FROM t""".stripMargin)
+  }
+
+  test("-- RANGE frame wider than partition (C4: admit/drop loops no-op)") {
+    // Once the first batch is admitted, admit/drop must detect no change
+    // and skip work.
+    val df = spark.range(0, 25).selectExpr(
+      "CAST(id AS INT) AS id",
+      "(CAST(id AS INT) / 5) AS pk",
+      "CAST((id * 7) % 23 AS INT) AS k",
+      "CAST((id * 19) % 101 AS INT) AS v")
+    checkRangeEquivalence(df,
+      """SELECT id, pk,
+        |  MIN(v) OVER (PARTITION BY pk ORDER BY k
+        |    RANGE BETWEEN 100 PRECEDING AND 100 FOLLOWING) AS mn,
+        |  MAX(v) OVER (PARTITION BY pk ORDER BY k
+        |    RANGE BETWEEN 100 PRECEDING AND 100 FOLLOWING) AS mx
+        |FROM t""".stripMargin)
+  }
+
+  test("-- RANGE with NULL order key (NULLS FIRST / NULLS LAST)") {
+    // Trap: Spark groups all NULLs into a single equivalence class at head
+    // (NULLS FIRST) or tail (NULLS LAST); seg-tree must treat NULL as a
+    // tie group identical to the sliding baseline.
+    val rows = (0 until 36).map { i =>
+      val kOpt: Option[Int] = (i % 6) match {
+        case 0 | 1 | 5 => None
+        case 2 => Some(1)
+        case 3 => Some(2)
+        case _ => Some(3)
+      }
+      (i, i % 2, kOpt, (i * 11) % 37)
+    }
+    val df = rows.toDF("id", "pk", "k", "v")
+    checkRangeEquivalence(df,
+      """SELECT id, pk,
+        |  MIN(v) OVER (PARTITION BY pk ORDER BY k ASC NULLS FIRST
+        |    RANGE BETWEEN 1 PRECEDING AND 1 FOLLOWING) AS mn_nf,
+        |  MAX(v) OVER (PARTITION BY pk ORDER BY k ASC NULLS FIRST
+        |    RANGE BETWEEN 1 PRECEDING AND 1 FOLLOWING) AS mx_nf,
+        |  MIN(v) OVER (PARTITION BY pk ORDER BY k ASC NULLS LAST
+        |    RANGE BETWEEN 1 PRECEDING AND 1 FOLLOWING) AS mn_nl,
+        |  MAX(v) OVER (PARTITION BY pk ORDER BY k ASC NULLS LAST
+        |    RANGE BETWEEN 1 PRECEDING AND 1 FOLLOWING) AS mx_nl
+        |FROM t""".stripMargin)
+  }
+
+    // Decimal overflow / BinaryType MIN/MAX across block merge; UDAF fallback.
+  // Trap: blockSize=16 is SQLConf minimum; frame > blockSize ensures the
+  // seg-tree merge path is actually crossed.
+
+  private val segTreeBlock: String = "16"
+  private val segTreeFramePrec: Int = 17
+  private val segTreeRows: Int = 20
+
+  private def withSegTreeBlock(conf: (String, String)*)(body: => Unit): Unit = {
+    val extra = Seq(SQLConf.WINDOW_SEGMENT_TREE_BLOCK_SIZE.key -> segTreeBlock) ++ conf
+    withSQLConf(extra: _*)(body)
+  }
+
+
+  /**
+   * 20 rows in one partition, Decimal(38, 0) values near the type's upper
+   * bound; frame of `segTreeFramePrec` PRECEDING..CURRENT ROW makes any
+   * >=2-row window overflow Sum. Block 16 + frame 17 forces cross-block merge.
+   */
+  private def decimalOverflowDF: DataFrame = {
+    // 9e37 -- below Decimal(38,0) MAX (~9.99e37), but 2x overflows.
+    val big = "90000000000000000000000000000000000000"  // 38 digits
+    spark.range(0, segTreeRows.toLong).selectExpr(
+      "CAST(id AS INT) AS id",
+      "0 AS pk",
+      s"CAST('$big' AS DECIMAL(38, 0)) AS v")
+  }
+
+  private val decimalOverflowSql: String =
+    s"""SELECT id, pk,
+       |  SUM(v) OVER (PARTITION BY pk ORDER BY id
+       |    ROWS BETWEEN $segTreeFramePrec PRECEDING AND CURRENT ROW) AS s
+       |FROM t""".stripMargin
+
+  test("a -- Decimal overflow ANSI on, seg-tree matches sliding (both throw)") {
+    val df = decimalOverflowDF
+    df.createOrReplaceTempView("t")
+    try {
+      withSegTreeBlock(SQLConf.ANSI_ENABLED.key -> "true") {
+        withSQLConf(disableSegTree.toSeq: _*) {
+          val e = intercept[Exception] {
+            spark.sql(decimalOverflowSql).collect()
+          }
+          assert(hasArithmeticCause(e),
+            s"expected ArithmeticException root cause, got: ${e.getMessage}")
+        }
+        withSQLConf(enableSegTree.toSeq: _*) {
+          val e = intercept[Exception] {
+            spark.sql(decimalOverflowSql).collect()
+          }
+          assert(hasArithmeticCause(e),
+            s"expected ArithmeticException root cause, got: ${e.getMessage}")
+        }
+      }
+    } finally {
+      spark.catalog.dropTempView("t")
+    }
+  }
+
+  test("b -- Decimal overflow ANSI off, seg-tree matches sliding (NULL on overflow)") {
+    val df = decimalOverflowDF
+    df.createOrReplaceTempView("t")
+    try {
+      withSegTreeBlock(SQLConf.ANSI_ENABLED.key -> "false") {
+        val baseline = withSQLConf(disableSegTree.toSeq: _*) {
+          spark.sql(decimalOverflowSql).collect().sortBy(_.toString)
+        }
+        // At least one row must be NULL so we know overflow actually fired.
+        assert(baseline.exists(_.isNullAt(2)),
+          "baseline should contain NULL overflow rows; test data may be too small")
+        withSQLConf(enableSegTree.toSeq: _*) {
+          val actual = spark.sql(decimalOverflowSql).collect().sortBy(_.toString)
+          assert(actual.toSeq === baseline.toSeq)
+        }
+      }
+    } finally {
+      spark.catalog.dropTempView("t")
+    }
+  }
+
+  test("c -- mid-window Decimal overflow slides past (seg-tree == sliding)") {
+    // Big values at ids 14..17 straddle block boundary at id=16, so any
+    // 4-row window overlapping >=2 of them overflows (-> NULL when ANSI off)
+    // and cross-block merge sees overflowing buffers. Rows past id=20 slide
+    // clear and recover non-NULL.
+    val big = "90000000000000000000000000000000000000"
+    val df = spark.range(0, 24).selectExpr(
+      "CAST(id AS INT) AS id",
+      "0 AS pk",
+      s"""CASE WHEN id IN (14, 15, 16, 17)
+              THEN CAST('$big' AS DECIMAL(38, 0))
+              ELSE CAST(id AS DECIMAL(38, 0))
+         END AS v""")
+    df.createOrReplaceTempView("t")
+    try {
+      val sqlStr =
+        """SELECT id, pk,
+          |  SUM(v) OVER (PARTITION BY pk ORDER BY id
+          |    ROWS BETWEEN 3 PRECEDING AND CURRENT ROW) AS s
+          |FROM t""".stripMargin
+      withSegTreeBlock(SQLConf.ANSI_ENABLED.key -> "false") {
+        val baseline = withSQLConf(disableSegTree.toSeq: _*) {
+          spark.sql(sqlStr).collect().sortBy(_.toString)
+        }
+        // Sanity: overflow fired AND later rows recover non-NULL.
+        assert(baseline.exists(_.isNullAt(2)),
+          "baseline should contain NULL overflow rows")
+        assert(baseline.exists(r => r.getInt(0) >= 21 && !r.isNullAt(2)),
+          "rows with id>=21 should be non-NULL (window slid past big values)")
+        withSQLConf(enableSegTree.toSeq: _*) {
+          val actual = spark.sql(sqlStr).collect().sortBy(_.toString)
+          assert(actual.toSeq === baseline.toSeq)
+        }
+      }
+    } finally {
+      spark.catalog.dropTempView("t")
+    }
+  }
+
+  /** True iff the root cause of `t` is an [[ArithmeticException]] (ANSI overflow). */
+  private def hasArithmeticCause(t: Throwable): Boolean =
+    Option(SparkErrorUtils.getRootCause(t)).exists(_.isInstanceOf[ArithmeticException])
+
+
+  /** Pattern of 20 Array[Byte] values used across a. */
+  private def binaryVariedRows: Seq[(Int, Array[Byte])] = {
+    (0 until 20).map { i =>
+      val arr: Array[Byte] = (i % 8) match {
+        case 0 => Array[Byte](0x01, 0x02)
+        case 1 => Array[Byte](0x00)
+        case 2 => Array[Byte](0x7f)
+        case 3 => Array[Byte](0x7f, 0x00)
+        case 4 => Array[Byte](0x10, 0x20, 0x30)
+        case 5 => Array[Byte](0x10, 0x20)
+        case 6 => Array[Byte](0x10)
+        case _ => Array[Byte](0x05, 0x05, 0x05, 0x05)
+      }
+      (i, arr)
+    }
+  }
+
+  test("a -- BinaryType MIN/MAX cross-block merge") {
+    // Varied lengths/content; frame > blockSize guarantees merge path hit.
+    val df = binaryVariedRows.toDF("id", "v").selectExpr("id", "0 AS pk", "v")
+    df.createOrReplaceTempView("t")
+    try {
+      withSegTreeBlock() {
+        val sqlStr =
+          s"""SELECT id, pk,
+             |  MIN(v) OVER (PARTITION BY pk ORDER BY id
+             |    ROWS BETWEEN $segTreeFramePrec PRECEDING AND CURRENT ROW) AS mn,
+             |  MAX(v) OVER (PARTITION BY pk ORDER BY id
+             |    ROWS BETWEEN $segTreeFramePrec PRECEDING AND CURRENT ROW) AS mx
+             |FROM t""".stripMargin
+        val baseline = withSQLConf(disableSegTree.toSeq: _*) {
+          spark.sql(sqlStr).collect().sortBy(_.toString)
+        }
+        withSQLConf(enableSegTree.toSeq: _*) {
+          val actual = spark.sql(sqlStr).collect().sortBy(_.toString)

Review Comment:
   Good catch — fixed along with the `checkEquivalence` helper change (see sibling comment). All three `a/b/c -- BinaryType ...` tests now use `QueryTest.sameRows(baseline, actual, isSorted = false)` which normalizes `Array[Byte]` via `prepareRow` before sorting, so the unstable `_.toString` ordering is gone. Thanks.
   



-- 
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@spark.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org