EnricoMi commented on a change in pull request #31905:
URL: https://github.com/apache/spark/pull/31905#discussion_r655909582



##########
File path: sql/core/src/main/scala/org/apache/spark/sql/Observation.scala
##########
@@ -0,0 +1,170 @@
+/*
+ * 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
+
+import java.util.UUID
+import java.util.concurrent.TimeUnit
+
+import org.apache.spark.sql.execution.QueryExecution
+import org.apache.spark.sql.util.QueryExecutionListener
+
+/**
+ * Helper class to simplify usage of [[Dataset.observe(String, Column, 
Column*)]]:
+ *
+ * {{{
+ *   // Observe row count (rows) and highest id (maxid) in the Dataset while 
writing it
+ *   val observation = Observation("my_metrics")
+ *   val observed_ds = ds.observe(observation, count(lit(1)).as("rows"), 
max($"id").as("maxid"))
+ *   observed_ds.write.parquet("ds.parquet")
+ *   val metrics = observation.get
+ * }}}
+ *
+ * This collects the metrics while the first action is executed on the 
obseerved dataset. Subsequent
+ * actions do not modify the metrics returned by 
[[org.apache.spark.sql.Observation.get]]. Retrieval
+ * of the metric via [[org.apache.spark.sql.Observation.get]] blocks until the 
first action has
+ * finished and metrics become available. You can add a timeout to that 
blocking via
+ * [[org.apache.spark.sql.Observation.waitCompleted]]:
+ *
+ * {{{
+ *   if (observation.waitCompleted(100, TimeUnit.MILLISECONDS)) {
+ *     observation.get
+ *   }
+ * }}}
+ *
+ * This class does not support streaming datasets.
+ *
+ * @param name name of the metric
+ * @since 3.2.0
+ */
+class Observation(name: String) {
+
+  private val listener: ObservationListener = ObservationListener(this)
+
+  private var sparkSession: Option[SparkSession] = None
+
+  @volatile private var row: Option[Row] = None
+
+  /**
+   * Attaches this observation to the given [[Dataset]] to observe aggregation 
expressions.
+   *
+   * @param ds dataset
+   * @param expr first aggregation expression
+   * @param exprs more aggregation expressions
+   * @tparam T dataset type
+   * @return observed dataset
+   * @throws IllegalArgumentException If this is a streaming Dataset 
(ds.isStreaming == true)
+   */
+  def on[T](ds: Dataset[T], expr: Column, exprs: Column*): Dataset[T] = {
+    if (ds.isStreaming) {
+      throw new IllegalArgumentException("Observation does not support 
streaming Datasets")
+    }
+    register(ds.sparkSession)
+    ds.observe(name, expr, exprs: _*)
+  }
+
+  /**
+   * Waits for the first action on the observed dataset to complete and 
returns true.
+   * The result is then available through the get method.
+   * This method times out after the given amount of time returning false.
+   *
+   * @param time timeout
+   * @param unit timeout time unit
+   * @return true if action completed within timeout, false otherwise
+   * @throws InterruptedException interrupted while waiting
+   */
+  def waitCompleted(time: Long, unit: TimeUnit): Boolean = 
waitCompleted(Some(unit.toMillis(time)))
+
+  /**
+   * Get the observed metrics. This waits until the observed dataset finishes 
its first action.
+   * If you want to wait for the result and provide a timeout, use 
[[waitCompleted]]. Only the
+   * result of the first action is available. Subsequent actions do not modify 
the result.
+   *
+   * @return the observed metrics as a [[Row]]
+   * @throws InterruptedException interrupted while waiting
+   */
+  def get: Row = {
+    assert(waitCompleted(None), "waitCompleted without timeout returned false")
+    row.get
+  }
+
+  private def waitCompleted(millis: Option[Long]): Boolean = {
+    synchronized {
+      if (row.isEmpty) {

Review comment:
       You are saying `wait` can return before the given time is up and without 
`notify` being called? Or do you refer to `notify` being called when `row` 
being `row.isEmpty`? We could guarantee that this is not happening if you would 
use a synchronization object other than `this`.

##########
File path: sql/core/src/main/scala/org/apache/spark/sql/Observation.scala
##########
@@ -0,0 +1,170 @@
+/*
+ * 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
+
+import java.util.UUID
+import java.util.concurrent.TimeUnit
+
+import org.apache.spark.sql.execution.QueryExecution
+import org.apache.spark.sql.util.QueryExecutionListener
+
+/**
+ * Helper class to simplify usage of [[Dataset.observe(String, Column, 
Column*)]]:
+ *
+ * {{{
+ *   // Observe row count (rows) and highest id (maxid) in the Dataset while 
writing it
+ *   val observation = Observation("my_metrics")
+ *   val observed_ds = ds.observe(observation, count(lit(1)).as("rows"), 
max($"id").as("maxid"))
+ *   observed_ds.write.parquet("ds.parquet")
+ *   val metrics = observation.get
+ * }}}
+ *
+ * This collects the metrics while the first action is executed on the 
obseerved dataset. Subsequent
+ * actions do not modify the metrics returned by 
[[org.apache.spark.sql.Observation.get]]. Retrieval
+ * of the metric via [[org.apache.spark.sql.Observation.get]] blocks until the 
first action has
+ * finished and metrics become available. You can add a timeout to that 
blocking via
+ * [[org.apache.spark.sql.Observation.waitCompleted]]:
+ *
+ * {{{
+ *   if (observation.waitCompleted(100, TimeUnit.MILLISECONDS)) {
+ *     observation.get
+ *   }
+ * }}}
+ *
+ * This class does not support streaming datasets.
+ *
+ * @param name name of the metric
+ * @since 3.2.0
+ */
+class Observation(name: String) {
+
+  private val listener: ObservationListener = ObservationListener(this)
+
+  private var sparkSession: Option[SparkSession] = None
+
+  @volatile private var row: Option[Row] = None
+
+  /**
+   * Attaches this observation to the given [[Dataset]] to observe aggregation 
expressions.
+   *
+   * @param ds dataset
+   * @param expr first aggregation expression
+   * @param exprs more aggregation expressions
+   * @tparam T dataset type
+   * @return observed dataset
+   * @throws IllegalArgumentException If this is a streaming Dataset 
(ds.isStreaming == true)
+   */
+  def on[T](ds: Dataset[T], expr: Column, exprs: Column*): Dataset[T] = {
+    if (ds.isStreaming) {
+      throw new IllegalArgumentException("Observation does not support 
streaming Datasets")
+    }
+    register(ds.sparkSession)
+    ds.observe(name, expr, exprs: _*)
+  }
+
+  /**
+   * Waits for the first action on the observed dataset to complete and 
returns true.
+   * The result is then available through the get method.
+   * This method times out after the given amount of time returning false.
+   *
+   * @param time timeout
+   * @param unit timeout time unit
+   * @return true if action completed within timeout, false otherwise
+   * @throws InterruptedException interrupted while waiting
+   */
+  def waitCompleted(time: Long, unit: TimeUnit): Boolean = 
waitCompleted(Some(unit.toMillis(time)))
+
+  /**
+   * Get the observed metrics. This waits until the observed dataset finishes 
its first action.
+   * If you want to wait for the result and provide a timeout, use 
[[waitCompleted]]. Only the
+   * result of the first action is available. Subsequent actions do not modify 
the result.
+   *
+   * @return the observed metrics as a [[Row]]
+   * @throws InterruptedException interrupted while waiting
+   */
+  def get: Row = {
+    assert(waitCompleted(None), "waitCompleted without timeout returned false")
+    row.get
+  }
+
+  private def waitCompleted(millis: Option[Long]): Boolean = {

Review comment:
       Why encoding this special semantics with a magic number when we have 
Scala `Option` to exactly express this? This is a private method anyway.
   
   I'll simplify this to:
   
       private def waitCompleted(millis: Option[Long]): Boolean = {
         synchronized {
           if (row.isEmpty) {
             this.wait(millis.getOrElse(0))
           }
           row.isDefined
         }
       }
   

##########
File path: sql/core/src/main/scala/org/apache/spark/sql/Observation.scala
##########
@@ -0,0 +1,170 @@
+/*
+ * 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
+
+import java.util.UUID
+import java.util.concurrent.TimeUnit
+
+import org.apache.spark.sql.execution.QueryExecution
+import org.apache.spark.sql.util.QueryExecutionListener
+
+/**
+ * Helper class to simplify usage of [[Dataset.observe(String, Column, 
Column*)]]:
+ *
+ * {{{
+ *   // Observe row count (rows) and highest id (maxid) in the Dataset while 
writing it
+ *   val observation = Observation("my_metrics")
+ *   val observed_ds = ds.observe(observation, count(lit(1)).as("rows"), 
max($"id").as("maxid"))
+ *   observed_ds.write.parquet("ds.parquet")
+ *   val metrics = observation.get
+ * }}}
+ *
+ * This collects the metrics while the first action is executed on the 
obseerved dataset. Subsequent
+ * actions do not modify the metrics returned by 
[[org.apache.spark.sql.Observation.get]]. Retrieval
+ * of the metric via [[org.apache.spark.sql.Observation.get]] blocks until the 
first action has
+ * finished and metrics become available. You can add a timeout to that 
blocking via
+ * [[org.apache.spark.sql.Observation.waitCompleted]]:
+ *
+ * {{{
+ *   if (observation.waitCompleted(100, TimeUnit.MILLISECONDS)) {
+ *     observation.get
+ *   }
+ * }}}
+ *
+ * This class does not support streaming datasets.
+ *
+ * @param name name of the metric
+ * @since 3.2.0
+ */
+class Observation(name: String) {
+
+  private val listener: ObservationListener = ObservationListener(this)
+
+  private var sparkSession: Option[SparkSession] = None
+
+  @volatile private var row: Option[Row] = None
+
+  /**
+   * Attaches this observation to the given [[Dataset]] to observe aggregation 
expressions.
+   *
+   * @param ds dataset
+   * @param expr first aggregation expression
+   * @param exprs more aggregation expressions
+   * @tparam T dataset type
+   * @return observed dataset
+   * @throws IllegalArgumentException If this is a streaming Dataset 
(ds.isStreaming == true)
+   */
+  def on[T](ds: Dataset[T], expr: Column, exprs: Column*): Dataset[T] = {
+    if (ds.isStreaming) {
+      throw new IllegalArgumentException("Observation does not support 
streaming Datasets")
+    }
+    register(ds.sparkSession)
+    ds.observe(name, expr, exprs: _*)
+  }
+
+  /**
+   * Waits for the first action on the observed dataset to complete and 
returns true.
+   * The result is then available through the get method.
+   * This method times out after the given amount of time returning false.
+   *
+   * @param time timeout
+   * @param unit timeout time unit
+   * @return true if action completed within timeout, false otherwise
+   * @throws InterruptedException interrupted while waiting
+   */
+  def waitCompleted(time: Long, unit: TimeUnit): Boolean = 
waitCompleted(Some(unit.toMillis(time)))
+
+  /**
+   * Get the observed metrics. This waits until the observed dataset finishes 
its first action.
+   * If you want to wait for the result and provide a timeout, use 
[[waitCompleted]]. Only the
+   * result of the first action is available. Subsequent actions do not modify 
the result.
+   *
+   * @return the observed metrics as a [[Row]]
+   * @throws InterruptedException interrupted while waiting
+   */
+  def get: Row = {
+    assert(waitCompleted(None), "waitCompleted without timeout returned false")
+    row.get
+  }
+
+  private def waitCompleted(millis: Option[Long]): Boolean = {
+    synchronized {
+      if (row.isEmpty) {
+        if (millis.isDefined) {
+          this.wait(millis.get)
+        } else {
+          this.wait()
+        }
+      }
+      row.isDefined
+    }
+  }
+
+  private def register(sparkSession: SparkSession): Unit = {
+    // makes this class thread-safe:
+    // only the first thread entering this block can set sparkSession
+    // all other threads will see the exception, because it is only allowed to 
do this once
+    synchronized {
+      if (this.sparkSession.isDefined) {
+        throw new IllegalStateException("An Observation can be used with a 
Dataset only once")
+      }
+      this.sparkSession = Some(sparkSession)
+    }
+
+    sparkSession.listenerManager.register(listener)
+  }
+
+  private def unregister(): Unit = {
+    this.sparkSession.foreach(_.listenerManager.unregister(listener))
+  }
+
+  private[spark] def onFinish(qe: QueryExecution): Unit = {
+    synchronized {
+      this.row = qe.observedMetrics.get(name)

Review comment:
       Good point! I have fixed that.
   
   Can there be the situation where an action running before we add our metric 
to the dataframe calls into our listener because we register the callback just 
before the action finishes? Would that cause a situation where our listener 
gets called but `qe.observedMetrics` does not contain our metric? Should we 
better be not so picky about ` assert(this.row.isDefined) here?

##########
File path: sql/core/src/main/scala/org/apache/spark/sql/Observation.scala
##########
@@ -0,0 +1,170 @@
+/*
+ * 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
+
+import java.util.UUID
+import java.util.concurrent.TimeUnit
+
+import org.apache.spark.sql.execution.QueryExecution
+import org.apache.spark.sql.util.QueryExecutionListener
+
+/**
+ * Helper class to simplify usage of [[Dataset.observe(String, Column, 
Column*)]]:
+ *
+ * {{{
+ *   // Observe row count (rows) and highest id (maxid) in the Dataset while 
writing it
+ *   val observation = Observation("my_metrics")
+ *   val observed_ds = ds.observe(observation, count(lit(1)).as("rows"), 
max($"id").as("maxid"))
+ *   observed_ds.write.parquet("ds.parquet")
+ *   val metrics = observation.get

Review comment:
       It does not really add something substantial to the API. I can make it 
`private[spark]`. It is more a convenient hook for `Dataset.observe`.

##########
File path: sql/core/src/main/scala/org/apache/spark/sql/Observation.scala
##########
@@ -0,0 +1,170 @@
+/*
+ * 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
+
+import java.util.UUID
+import java.util.concurrent.TimeUnit
+
+import org.apache.spark.sql.execution.QueryExecution
+import org.apache.spark.sql.util.QueryExecutionListener
+
+/**
+ * Helper class to simplify usage of [[Dataset.observe(String, Column, 
Column*)]]:
+ *
+ * {{{
+ *   // Observe row count (rows) and highest id (maxid) in the Dataset while 
writing it
+ *   val observation = Observation("my_metrics")
+ *   val observed_ds = ds.observe(observation, count(lit(1)).as("rows"), 
max($"id").as("maxid"))
+ *   observed_ds.write.parquet("ds.parquet")
+ *   val metrics = observation.get
+ * }}}
+ *
+ * This collects the metrics while the first action is executed on the 
obseerved dataset. Subsequent
+ * actions do not modify the metrics returned by 
[[org.apache.spark.sql.Observation.get]]. Retrieval
+ * of the metric via [[org.apache.spark.sql.Observation.get]] blocks until the 
first action has
+ * finished and metrics become available. You can add a timeout to that 
blocking via
+ * [[org.apache.spark.sql.Observation.waitCompleted]]:
+ *
+ * {{{
+ *   if (observation.waitCompleted(100, TimeUnit.MILLISECONDS)) {
+ *     observation.get
+ *   }
+ * }}}
+ *
+ * This class does not support streaming datasets.
+ *
+ * @param name name of the metric
+ * @since 3.2.0
+ */
+class Observation(name: String) {

Review comment:
       This `Observation` is trying hiding multi-threading from the user for 
use cases where they simply want a metric after they have called an action on a 
Dataset. Adding async notion to the API does not contribute to that goal.
   
   The `waitCompleted` is an edge case, usually you simply call 
`Observation.get`. If the user wanted a Future, they could wrap the 
`Observation.get` with one. What you are proposing would mean that everyone 
else who does not want a `Future` would get a `Future` and has to call `.value` 
to get an `Option[Try[Row]]` and deal with this result where `Observation.get` 
now returns the `Row`. I do not see where the Future simplifies the API.
   
   Maybe you can sketch this out a bit more on how it would look like for the 
user of `Observation` so the benefits become clearer.

##########
File path: sql/core/src/main/scala/org/apache/spark/sql/Observation.scala
##########
@@ -0,0 +1,139 @@
+/*
+ * 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
+
+import java.util.UUID
+import java.util.concurrent.TimeUnit
+
+import org.apache.spark.sql.execution.QueryExecution
+import org.apache.spark.sql.util.QueryExecutionListener
+
+/**
+ * Not thread-safe.
+ * @param name
+ * @param sparkSession
+ */
+class Observation(name: String) {
+
+  private val listener: ObservationListener = ObservationListener(this)
+
+  private var sparkSession: Option[SparkSession] = None
+
+  @volatile private var row: Option[Row] = None
+
+  /**
+   * Attach this observation to the given Dataset.
+   *
+   * @param ds dataset
+   * @tparam T dataset type
+   * @return observed dataset
+   */
+  def on[T](ds: Dataset[T])(expr: Column, exprs: Column*): Dataset[T] = {
+    if (ds.isStreaming) {
+      throw new IllegalArgumentException("Observation does not support 
streaming Datasets")
+    }
+    register(ds.sparkSession)
+    ds.observe(name, expr, exprs: _*)
+  }
+
+  /**
+   * Wait for the first action on the observed dataset to complete and returns 
true.
+   * This method times out after the given amount of time and returns false.
+   *
+   * @param time timeout
+   * @param unit timeout time unit
+   * @return true if action complete within timeout, false on timeout
+   */
+  def waitCompleted(time: Long, unit: TimeUnit): Boolean = 
waitCompleted(Some(time), unit)
+
+  /**
+   * Get the observation results. This waits until the observed dataset 
finishes its first action.
+   * If you want to wait for the result and provide a timeout, use 
waitCompleted.
+   * Only the result of the first action is available. Subsequent actions do 
not modify the result.
+   */
+  def get: Row = {
+    assert(waitCompleted(None, TimeUnit.SECONDS), "waitCompleted without 
timeout returned false")
+    row.get
+  }
+
+  private def waitCompleted(time: Option[Long], unit: TimeUnit): Boolean = {
+    synchronized {
+      if (row.isEmpty) {
+        if (time.isDefined) {
+          this.wait(unit.toMillis(time.get))
+        } else {
+          this.wait()
+        }
+      }
+      row.isDefined
+    }
+  }
+
+  private def register(sparkSession: SparkSession): Unit = {
+    // makes this class thread-safe:
+    // only the first thread entering this block can set sparkSession
+    // all other threads will see the exception, because it is only allowed to 
do this once
+    synchronized {
+      if (this.sparkSession.isDefined) {
+        throw new IllegalStateException("An Observation can be used with a 
Dataset only once")
+      }
+      this.sparkSession = Some(sparkSession)
+    }
+
+    sparkSession.listenerManager.register(listener)
+  }
+
+  private def unregister(): Unit = {
+    this.sparkSession.foreach(_.listenerManager.unregister(listener))
+  }
+
+  private[spark] def onFinish(qe: QueryExecution): Unit = {
+    synchronized {
+      this.row = qe.observedMetrics.get(name)
+      assert(this.row.isDefined, "No metric provided by 
QueryExecutionListener")
+      this.notifyAll()
+    }
+    unregister()

Review comment:
       You are saying making `sparkSession` needs to be `volatile` because it 
is written and read in different threads, even if not concurrently. That is 
right, I'l fix that.
   
   But reading and writing it does not need to be in a `synchronized` because 
that is not happening concurrently and thus cannot interfere.

##########
File path: sql/core/src/main/scala/org/apache/spark/sql/Observation.scala
##########
@@ -0,0 +1,139 @@
+/*
+ * 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
+
+import java.util.UUID
+import java.util.concurrent.TimeUnit
+
+import org.apache.spark.sql.execution.QueryExecution
+import org.apache.spark.sql.util.QueryExecutionListener
+
+/**
+ * Not thread-safe.
+ * @param name
+ * @param sparkSession
+ */
+class Observation(name: String) {
+
+  private val listener: ObservationListener = ObservationListener(this)
+
+  private var sparkSession: Option[SparkSession] = None
+
+  @volatile private var row: Option[Row] = None
+
+  /**
+   * Attach this observation to the given Dataset.
+   *
+   * @param ds dataset
+   * @tparam T dataset type
+   * @return observed dataset
+   */
+  def on[T](ds: Dataset[T])(expr: Column, exprs: Column*): Dataset[T] = {
+    if (ds.isStreaming) {
+      throw new IllegalArgumentException("Observation does not support 
streaming Datasets")
+    }
+    register(ds.sparkSession)
+    ds.observe(name, expr, exprs: _*)
+  }
+
+  /**
+   * Wait for the first action on the observed dataset to complete and returns 
true.
+   * This method times out after the given amount of time and returns false.
+   *
+   * @param time timeout
+   * @param unit timeout time unit
+   * @return true if action complete within timeout, false on timeout
+   */
+  def waitCompleted(time: Long, unit: TimeUnit): Boolean = 
waitCompleted(Some(time), unit)
+
+  /**
+   * Get the observation results. This waits until the observed dataset 
finishes its first action.
+   * If you want to wait for the result and provide a timeout, use 
waitCompleted.
+   * Only the result of the first action is available. Subsequent actions do 
not modify the result.
+   */
+  def get: Row = {
+    assert(waitCompleted(None, TimeUnit.SECONDS), "waitCompleted without 
timeout returned false")
+    row.get
+  }
+
+  private def waitCompleted(time: Option[Long], unit: TimeUnit): Boolean = {
+    synchronized {
+      if (row.isEmpty) {
+        if (time.isDefined) {
+          this.wait(unit.toMillis(time.get))
+        } else {
+          this.wait()
+        }
+      }
+      row.isDefined
+    }
+  }
+
+  private def register(sparkSession: SparkSession): Unit = {
+    // makes this class thread-safe:
+    // only the first thread entering this block can set sparkSession
+    // all other threads will see the exception, because it is only allowed to 
do this once
+    synchronized {
+      if (this.sparkSession.isDefined) {
+        throw new IllegalStateException("An Observation can be used with a 
Dataset only once")
+      }
+      this.sparkSession = Some(sparkSession)
+    }
+
+    sparkSession.listenerManager.register(listener)
+  }
+
+  private def unregister(): Unit = {
+    this.sparkSession.foreach(_.listenerManager.unregister(listener))
+  }
+
+  private[spark] def onFinish(qe: QueryExecution): Unit = {
+    synchronized {
+      this.row = qe.observedMetrics.get(name)
+      assert(this.row.isDefined, "No metric provided by 
QueryExecutionListener")
+      this.notifyAll()
+    }
+    unregister()

Review comment:
       You are saying making `sparkSession` needs to be `volatile` because it 
is written and read in different threads, even if not concurrently. That is 
right, I'll fix that.
   
   But reading and writing it does not need to be in a `synchronized` because 
that is not happening concurrently and thus cannot interfere.

##########
File path: sql/core/src/main/scala/org/apache/spark/sql/Observation.scala
##########
@@ -0,0 +1,139 @@
+/*
+ * 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
+
+import java.util.UUID
+import java.util.concurrent.TimeUnit
+
+import org.apache.spark.sql.execution.QueryExecution
+import org.apache.spark.sql.util.QueryExecutionListener
+
+/**
+ * Not thread-safe.
+ * @param name
+ * @param sparkSession
+ */
+class Observation(name: String) {
+
+  private val listener: ObservationListener = ObservationListener(this)
+
+  private var sparkSession: Option[SparkSession] = None
+
+  @volatile private var row: Option[Row] = None
+
+  /**
+   * Attach this observation to the given Dataset.
+   *
+   * @param ds dataset
+   * @tparam T dataset type
+   * @return observed dataset
+   */
+  def on[T](ds: Dataset[T])(expr: Column, exprs: Column*): Dataset[T] = {
+    if (ds.isStreaming) {
+      throw new IllegalArgumentException("Observation does not support 
streaming Datasets")
+    }
+    register(ds.sparkSession)
+    ds.observe(name, expr, exprs: _*)
+  }
+
+  /**
+   * Wait for the first action on the observed dataset to complete and returns 
true.
+   * This method times out after the given amount of time and returns false.
+   *
+   * @param time timeout
+   * @param unit timeout time unit
+   * @return true if action complete within timeout, false on timeout
+   */
+  def waitCompleted(time: Long, unit: TimeUnit): Boolean = 
waitCompleted(Some(time), unit)
+
+  /**
+   * Get the observation results. This waits until the observed dataset 
finishes its first action.
+   * If you want to wait for the result and provide a timeout, use 
waitCompleted.
+   * Only the result of the first action is available. Subsequent actions do 
not modify the result.
+   */
+  def get: Row = {
+    assert(waitCompleted(None, TimeUnit.SECONDS), "waitCompleted without 
timeout returned false")
+    row.get
+  }
+
+  private def waitCompleted(time: Option[Long], unit: TimeUnit): Boolean = {
+    synchronized {
+      if (row.isEmpty) {
+        if (time.isDefined) {
+          this.wait(unit.toMillis(time.get))
+        } else {
+          this.wait()
+        }
+      }
+      row.isDefined
+    }
+  }
+
+  private def register(sparkSession: SparkSession): Unit = {
+    // makes this class thread-safe:
+    // only the first thread entering this block can set sparkSession
+    // all other threads will see the exception, because it is only allowed to 
do this once
+    synchronized {
+      if (this.sparkSession.isDefined) {
+        throw new IllegalStateException("An Observation can be used with a 
Dataset only once")
+      }
+      this.sparkSession = Some(sparkSession)
+    }
+
+    sparkSession.listenerManager.register(listener)
+  }
+
+  private def unregister(): Unit = {
+    this.sparkSession.foreach(_.listenerManager.unregister(listener))
+  }
+
+  private[spark] def onFinish(qe: QueryExecution): Unit = {
+    synchronized {
+      this.row = qe.observedMetrics.get(name)
+      assert(this.row.isDefined, "No metric provided by 
QueryExecutionListener")
+      this.notifyAll()
+    }
+    unregister()

Review comment:
       You are saying making `sparkSession` needs to be `volatile` because it 
is written and read in different threads, even if not concurrently. That is 
right, I'll fix that.
   
   But reading (`unregister`) does not need to be in a `synchronized` because 
that is not happening concurrently with writing (`register`) and thus cannot 
interfere.




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

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



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

Reply via email to