Spark AQE 导致的 Driver OOM问题

server/2024/10/21 7:27:02/

背景

最近在做Spark 3.1 升级 Spark 3.5的过程中,遇到了一批SQL在运行的过程中 Driver OOM的情况,排查到是AQE开启导致的问题,再次分析记录一下,顺便了解一下Spark中指标的事件处理情况

结论

SQLAppStatusListener 类在内存中存放着 一个整个SQL查询链的所有stage以及stage的指标信息,在AQE中 一个job会被拆分成很多job,甚至几百上千的job,这个时候 stageMetrics的数据就会成百上倍的被存储在内存中,从而导致Driver OOM
解决方法:

  1. 关闭AQE spark.sql.adaptive.enabled false
  2. 合并对应的PR-SPARK-45439

分析

背景知识:对于一个完整链接的sql语句来说(比如说从 读取数据源,到 数据处理操作,再到插入hive表),这可以称其为一个最小的SQL执行单元,这最小的数据执行单元在Spark内部是可以跟踪的,也就是用executionId来进行跟踪的。
对于一个sql,举例来说 :

insert into  TableA select * from TableB;

在生成 物理计划的过程中会调用 QueryExecution.assertOptimized 方法,该方法会触发eagerlyExecuteCommands调用,最终会到SQLExecution.withNewExecutionId方法:

  def assertOptimized(): Unit = optimizedPlan...lazy val commandExecuted: LogicalPlan = mode match {case CommandExecutionMode.NON_ROOT => analyzed.mapChildren(eagerlyExecuteCommands)case CommandExecutionMode.ALL => eagerlyExecuteCommands(analyzed)case CommandExecutionMode.SKIP => analyzed}...lazy val optimizedPlan: LogicalPlan = {// We need to materialize the commandExecuted here because optimizedPlan is also tracked under// the optimizing phaseassertCommandExecuted()executePhase(QueryPlanningTracker.OPTIMIZATION) {// clone the plan to avoid sharing the plan instance between different stages like analyzing,// optimizing and planning.val plan =sparkSession.sessionState.optimizer.executeAndTrack(withCachedData.clone(), tracker)// We do not want optimized plans to be re-analyzed as literals that have been constant// folded and such can cause issues during analysis. While `clone` should maintain the// `analyzed` state of the LogicalPlan, we set the plan as analyzed here as well out of// paranoia.plan.setAnalyzed()plan}def assertCommandExecuted(): Unit = commandExecuted...private def eagerlyExecuteCommands(p: LogicalPlan) = p transformDown {case c: Command =>// Since Command execution will eagerly take place here,// and in most cases be the bulk of time and effort,// with the rest of processing of the root plan being just outputting command results,// for eagerly executed commands we mark this place as beginning of execution.tracker.setReadyForExecution()val qe = sparkSession.sessionState.executePlan(c, CommandExecutionMode.NON_ROOT)val name = commandExecutionName(c)val result = QueryExecution.withInternalError(s"Eagerly executed $name failed.") {SQLExecution.withNewExecutionId(qe, Some(name)) {qe.executedPlan.executeCollect()}}  

SQLExecution.withNewExecutionId主要的作用是设置当前计划的所属的executionId:

    val executionId = SQLExecution.nextExecutionIdsc.setLocalProperty(EXECUTION_ID_KEY, executionId.toString)

EXECUTION_ID_KEY的值会在JobStart的时候传递给Event,以便记录跟踪整个执行过程中的指标信息。
同时我们在方法中eagerlyExecuteCommands看到qe.executedPlan.executeCollect()这是具体的执行方法,针对于insert into 操作来说,物理计划就是
InsertIntoHadoopFsRelationCommand,这里的run方法最终会流转到DAGScheduler.submitJob方法:

    eventProcessLoop.post(JobSubmitted(jobId, rdd, func2, partitions.toArray, callSite, waiter,JobArtifactSet.getActiveOrDefault(sc),Utils.cloneProperties(properties)))

最终会被DAGScheduler.handleJobSubmitted处理,其中会发送SparkListenerJobStart事件:

    listenerBus.post(SparkListenerJobStart(job.jobId, jobSubmissionTime, stageInfos,Utils.cloneProperties(properties)))

该事件会被SQLAppStatusListener捕获,从而转到onJobStart处理,这里有会涉及到指标信息的存储,这里我们截图出dump的内存占用情况:
在这里插入图片描述

可以看到 SQLAppStatusListener 的 LiveStageMetrics 占用很大,也就是 accumIdsToMetricType占用很大

那在AQE中是怎么回事呢?
我们知道再AQE中,任务会从source节点按照shuffle进行分割,从而形成单独的job,从而生成对应的shuffle指标,具体的分割以及执行代码在AdaptiveSparkPlanExec.getFinalPhysicalPlan中,如下:

      var result = createQueryStages(currentPhysicalPlan)val events = new LinkedBlockingQueue[StageMaterializationEvent]()val errors = new mutable.ArrayBuffer[Throwable]()var stagesToReplace = Seq.empty[QueryStageExec]while (!result.allChildStagesMaterialized) {currentPhysicalPlan = result.newPlanif (result.newStages.nonEmpty) {stagesToReplace = result.newStages ++ stagesToReplaceexecutionId.foreach(onUpdatePlan(_, result.newStages.map(_.plan)))// SPARK-33933: we should submit tasks of broadcast stages first, to avoid waiting// for tasks to be scheduled and leading to broadcast timeout.// This partial fix only guarantees the start of materialization for BroadcastQueryStage// is prior to others, but because the submission of collect job for broadcasting is// running in another thread, the issue is not completely resolved.val reorderedNewStages = result.newStages.sortWith {case (_: BroadcastQueryStageExec, _: BroadcastQueryStageExec) => falsecase (_: BroadcastQueryStageExec, _) => truecase _ => false}// Start materialization of all new stages and fail fast if any stages failed eagerlyreorderedNewStages.foreach { stage =>try {stage.materialize().onComplete { res =>if (res.isSuccess) {events.offer(StageSuccess(stage, res.get))} else {events.offer(StageFailure(stage, res.failed.get))}// explicitly clean up the resources in this stagestage.cleanupResources()}(AdaptiveSparkPlanExec.executionContext)

这里就是得看stage.materialize()这个方法,这两个stage只有两类:BroadcastQueryStageExec 和 ShuffleQueryStageExec
这两个物理计划稍微分析一下如下:

  • BroadcastQueryStageExec
    数据流如下:
    broadcast.submitBroadcastJob||\/
    promise.future||\/
    relationFuture||\/
    child.executeCollectIterator()
    其中 promise的设置在relationFuture方法中,而relationFuture 会被doPrepare调用,而submitBroadcastJob会调用executeQuery,从而调用doPrepare,executeCollectIterator()最终也会发送JobSubmitted事件,分析和上面的一样
  • ShuffleQueryStageExec
     shuffle.submitShuffleJob||\/sparkContext.submitMapStage(shuffleDependency)||\/dagScheduler.submitMapStage

submitMapStage会发送MapStageSubmitted事件:

    eventProcessLoop.post(MapStageSubmitted(jobId, dependency, callSite, waiter, JobArtifactSet.getActiveOrDefault(sc),Utils.cloneProperties(properties)))

最终会被DAGScheduler.handleMapStageSubmitted处理,其中会发送SparkListenerJobStart事件:

    listenerBus.post(SparkListenerJobStart(job.jobId, jobSubmissionTime, stageInfos,Utils.cloneProperties(properties)))

该事件会被SQLAppStatusListener捕获,从而转到onJobStart处理:

  private val liveExecutions = new ConcurrentHashMap[Long, LiveExecutionData]()private val stageMetrics = new ConcurrentHashMap[Int, LiveStageMetrics]()...override def onJobStart(event: SparkListenerJobStart): Unit = {val executionIdString = event.properties.getProperty(SQLExecution.EXECUTION_ID_KEY)if (executionIdString == null) {// This is not a job created by SQLreturn}val executionId = executionIdString.toLongval jobId = event.jobIdval exec = Option(liveExecutions.get(executionId))

该方法会获取事件中的executionId,在AQE中,同一个执行单元的executionId是一样的,所以stageMetrics内存占用会越来越大。
而这里指标的更新是在AdaptiveSparkPlanExec.onUpdatePlan等方法中。

这样整个事件的数据流以及问题的产生原因就应该很清楚了。

其他

为啥AQE以后多个Job还是共享一个executionId呢?因为原则上来说,如果没有开启AQE之前,一个SQL执行单元的是属于同一个Job的,开启了AQE之后,因为AQE的原因,一个Job被拆成了了多个Job,但是从逻辑上来说,还是属于同一个SQL处理单元的所以还是得归属到一次执行中。


http://www.ppmy.cn/server/18132.html

相关文章

科技论文网站:中国科技论文在线

文章目录 1. Intro2. Main3. Cons Evaluation彩蛋:科学素质 这是作者最后一次发 这种类型的宣传 科普文章 1. Intro 中国科技论文在线是经教育部批准,由教育部科技发展中心主办, 利用现代信息技术手段,打破传统出版物的概念&…

LeetCode 每日一题 ---- 【2739.总行驶距离】

LeetCode 每日一题 ---- 【2739.总行驶距离】 2739.总行驶距离解题方法:模拟 2739.总行驶距离 解题方法:模拟 根据题意进行模拟,主邮箱每减少 5 升油,汽车就可以行驶 10 公里,同时副油箱需要向主油箱注入 1 升油&…

ThingsBoard处理设备上报的属性并转换为可读属性

一、前言 二、案例 1、AI生成JSON数据体 2、将json数据体直接通过遥测topic发送查看效果 3、可查看目前整个数据都在一起 ​编辑 4、配置附规则链路 5、对msg的消息值,进行数据的转换,并从新进行赋值。 6、规则链路关联关系 7、再次通过MQTT发送遥…

Linux线程池

目录 1.模型样貌 2.代码模拟 1.模型样貌 2.代码模拟 pthread_pool.hpp 里面有很有多余的打印,就是因为59行初始化和60行是一样的,没有初始化_cond,所以就一直拍错,展示就保存下来吧,提醒自己! Task.hpp main.cc 运行…

Flutter 上架如何解决 ITMS-91053 问题

最近,我的 Flutter App 发布到 TestFlight 后,就会收到一封邮件:The uploaded build for YOUR APP has one or more issues. 上面的邮件主要是说,我的 App 缺少了调用 API 的声明,以前从来没看到过,上网一查…

Unity 数据持久化——persistentDataPath储存路径

Unity中: StreamingAssets的文件夹,特点是:只能读,不能写. persistentDataPath可读可写(但是,此文件夹在Editor阶段没有,手机安装App后自动生成) 可以将一些必需的文件先放在StreamingAssets,在App安装后Copy到persistentDataP…

C# 面向对象编程(一)——类 第三篇

总目录 C# 语法总目录 系列链接 C# 面向对象编程(一) 类 第一篇 C# 面向对象编程(一) 类 第二篇 C# 面向对象编程(一) 类 第三篇 C# 面向对象编程 一 ——类 第三篇 简介面向对象编程类 第三篇9. 重载运算符10. 分部方法** nameof方法 **** GetType 方法和 typeof方…

Unity和iOS 原生专题一 unity打包设置C#设置 Xcode添加OTHER_LDFLAGS和Info.plist设置

一、 获取 PBXProject PBXProject的很多操作都是通过guid的 var pbxProject new PBXProject(); 二 、获取projectPath var projectPath PBXProject.GetPBXProjectPath(iosProjectPath); 三 、读取pbxProject 文件 pbxProject.ReadFromFile(projectPath); 四 、 读取Uni…