[SPARK-60736][CONNECT] Fix Arrow memory leak when driver-side result conversion fails or is interrupted #59945
All Vouch review confidence checks passed
Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)).
Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.52 · 650 lines diff across 8 files
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.17 · 1 substantive comment(s)
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size
diff_size
0.388
Shallow Review Depth
shallow_review_depth
0.289
Real PR Conversation Timeline
1 comments
"Review active on #59945"
general
weight: 0.35
HyukjinKwon
What changes were proposed in this pull request?
This PR fixes an Arrow memory leak in Spark Connect when the conversion of results to Arrow batches on the driver fails or is interrupted.
SparkConnectPlanExecution.processAsArrowBatchesconverts the results ofLocalTableScanExec,CollectLimitExecandCollectTailExecon the driver, andSparkConnectPlanner.handleSqlCommandconverts the results of commands and SQL scripts on the driver. Both useArrowConverters.toBatchWithSchemaIterator, whose iterator allocates a child allocator ofArrowUtils.rootAllocatorand the vectors of aVectorSchemaRoot. In a task, a task completion listener closes the iterator. On the driver, there is noTaskContext, so the iterator is closed only whenhasNextreaches the end of the rows. Ifnext()or sending a batch throws, nothing closes the iterator, and its memory stays inArrowUtils.rootAllocatoruntil the driver stops.This PR:
SparkConnectPlanExecution.rowToArrowConverterreturn aCloseableIteratorand closes it withUtils.tryWithSafeFinallywhen the rows are converted on the driver. Tasks still rely on the task completion listener.SparkConnectPlanner.handleSqlCommandin the same way.ArrowRecordBatchin afinallyblock inArrowBatchWithSchemaIterator.next(), asArrowBatchIterator.next()already does. Otherwise, whenMessageSerializer.serializethrows, the buffers that the batch retains stay allocated, and closing the iterator fails withIllegalStateException: Memory was leaked by queryinstead of releasing them.Utils.tryWithSafeFinallykeeps the original exception and adds a failure ofclose()to it as a suppressed exception. Closing the iterator again afterhasNexthas closed it is a no-op.Alternatives that were not taken:
next()fails: it does not cover a failure while sending a batch.ArrowBatchIteratorextendCloseableIteratorso thatmapkeepsclose(): it changes the type hierarchy of asql/coreclass that tasks also use, only for the driver-side paths of Spark Connect.Why are the changes needed?
To fix a memory leak in the Spark Connect server. The most common trigger is an interrupt.
ExecuteThreadRunner.interrupt()interrupts the execution thread, for example when the PySpark client sendsInterruptonKeyboardInterrupt(Ctrl-C), oninterruptAll,interruptTagandinterruptOperation, onReleaseExecutewithrelease_all(e.g. when a client closes the result iterator early), and when the session is closed.ArrowBatchWithSchemaIterator.next()writes to aWriteChanneloverChannels.newChannel(ByteArrayOutputStream), which is anAbstractInterruptibleChannel, so its next write throwsClosedByInterruptException. The execution thread spends most of its time filling a batch, so the exception usually comes fromMessageSerializer.serialize(writeChannel, batch)and also leaves theArrowRecordBatchopen.An error from
ArrowWriterleaks in the same way. For example, the following query fails withDATETIME_OVERFLOWbecause the microseconds of the interval do not fit in the int64 nanoseconds of Arrow, and it leaves 65536 bytes inArrowUtils.rootAllocatorof the driver.In a local test with the default
spark.sql.execution.arrow.maxRecordsPerBatch, each interrupt ofSELECT id, repeat('x', 200) AS s FROM range(0, 400000, 1, 1) LIMIT 300000leaked 2,293,760 bytes. A long-running Spark Connect server accumulates these leaks in direct memory. SPARK-45814 (#43691) fixed the same kind of leak inArrowConverters.createEmptyArrowBatch.By code reading, the conversion in
handleSqlCommandhas existed since Apache Spark 3.4.0 (SPARK-41725), theLocalTableScanExecpath since Apache Spark 3.5.0 (SPARK-43153), and theCollectLimitExecandCollectTailExecpaths since Apache Spark 4.2.0 (SPARK-55887).Does this PR introduce _any_ user-facing change?
No.
How was this patch tested?
Pass the CIs with the newly added
SparkConnectPlanExecutionArrowLeakSuite. Each test checks that notoArrowBatchWithSchemaIteratorallocator and no memory remain inArrowUtils.rootAllocator.LocalTableScanExec,CollectLimitExecandCollectTailExec: an interrupt after the first sent batch, a failure while sending the first batch, and a complete conversionLocalTableScanExec: an interrupt while filling a batch, anArrowWritererror, and an empty relationCollectLimitExec: anArrowWritererrorArrowBatchWithSchemaIterator: closing the iterator after a failure while serializing the batchArrowWritererror in a local relation and in a SQL script result (handleSqlCommand) throughSparkConnectService.executePlan, and anInterruptRPC that is raised in the conversion of aLocalRelationresultWithout this fix, all of them fail except the four tests of the complete conversions and the empty relation.
I also ran
ArrowConvertersSuite,SparkConnectServiceSuiteandSparkConnectPlannerSuitelocally, and all of them passed.Was this patch authored or co-authored using generative AI tooling?
Generated-by: Claude Opus 5.5