You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@spark.apache.org by "dongjoon-hyun (via GitHub)" <gi...@apache.org> on 2026/09/25 20:59:14 UTC

[PR] [SPARK-59790] Bound the wait for the terminating pods of a suspended `SparkCluster` [spark-kubernetes-operator]

dongjoon-hyun opened a new pull request, #889:
URL: https://github.com/apache/spark-kubernetes-operator/pull/889

   ### What changes were proposed in this pull request?
   
   This PR aims to stop a master or worker pod from holding the Kueue `Workload` of a suspended `SparkCluster` once that pod has been terminating for 5 minutes, measured from its `deletionTimestamp`. A resumed cluster still waits until such pods are gone, since they keep the names of the new pods.
   
   ### Why are the changes needed?
   
   A pod on a lost node can stay `Terminating` forever, so the `Workload` and its quota were never released. SPARK-59771 bounds the same wait for `SparkApplication` with `forceTerminationGracePeriodMillis` (5 minutes by default).
   
   ### Does this PR introduce _any_ user-facing change?
   
   No for the released versions, because `spec.suspend` for a running `SparkCluster` is not released yet.
   
   ### How was this patch tested?
   
   Pass the CIs with the newly added test cases.
   
   ### Was this patch authored or co-authored using generative AI tooling?
   
   Generated-by: Claude Opus 5.5


-- 
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-59790] Bound the wait for the terminating pods of a suspended `SparkCluster` [spark-kubernetes-operator]

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


##########
spark-operator/src/main/java/org/apache/spark/k8s/operator/reconciler/reconcilesteps/ClusterSuspendStep.java:
##########
@@ -156,19 +185,56 @@ private boolean releaseResources(SparkClusterContext context) {
           .inNamespace(namespace)
           .withName(getWorkerPodDisruptionBudgetName(name))
           .delete();
-      if (ReconcilerUtils.hasPods(
-          client,
-          namespace,
-          LABEL_SPARK_CLUSTER_NAME,
-          name,
-          LABEL_SPARK_ROLE_MASTER_VALUE,
-          LABEL_SPARK_ROLE_WORKER_VALUE)) {
-        // The deletion of each pod is observed by the pod informer, which reconciles again.
+      List<Pod> pods =
+          ReconcilerUtils.podsOf(
+                  client,
+                  namespace,
+                  LABEL_SPARK_CLUSTER_NAME,
+                  name,
+                  LABEL_SPARK_ROLE_MASTER_VALUE,
+                  LABEL_SPARK_ROLE_WORKER_VALUE)
+              .list()
+              .getItems();
+      Instant now = Instant.now();
+      Instant podReleaseDeadline =
+          pods.stream()
+              .map(ClusterSuspendStep::getPodReleaseDeadline)
+              .max(Comparator.naturalOrder())
+              .orElse(now);
+      if (now.isBefore(podReleaseDeadline)) {
+        // The deletion of each pod is observed by the pod informer, which reconciles again, while
+        // the timeout of a pod which may send no more events is observed by the requeue.
         log.debug("Waiting for the pods of the suspended cluster to be deleted.");
-        return false;
+        ReconcileProgress defaultRequeue = completeAndDefaultRequeue();
+        Duration remaining = Duration.between(now, podReleaseDeadline);
+        return Optional.of(
+            remaining.compareTo(defaultRequeue.getRequeueAfterDuration()) < 0
+                ? completeAndRequeueAfter(remaining)
+                : defaultRequeue);
       }
       // A Workload admitted before the queue label was removed is released as well.
       KueueWorkloadUtils.deleteWorkloadOf(client, cluster);
+      if (!suspend && !pods.isEmpty()) {
+        log.debug("Waiting for the stuck pods of the resumed cluster to be deleted.");
+        // This may last until a lost node is deleted, so the state says why, once per set of pods
+        String message =
+            String.format(
+                CLUSTER_SUSPENDED_BY_STUCK_PODS_MESSAGE,
+                pods.stream()
+                    .map(pod -> pod.getMetadata().getName())
+                    .sorted()
+                    .collect(Collectors.joining(", ")));
+        ReconcileProgress defaultRequeue = completeAndDefaultRequeue();

Review Comment:
   Thank you, @peter-toth. You're right. The deletion of the stuck pods arrives as a watch event of the Pod informer, so this unbounded branch now requeues with `SUSPEND_HOLD_REQUEUE_INTERVAL_SECONDS`. The bounded wait before the deadline keeps the fine-grained interval.



##########
spark-operator/src/main/java/org/apache/spark/k8s/operator/reconciler/reconcilesteps/ClusterSuspendStep.java:
##########
@@ -64,6 +71,14 @@
  */
 @Slf4j
 public final class ClusterSuspendStep extends ClusterReconcileStep {
+  /**
+   * How long a suspended cluster waits for a terminating master or worker pod past the end of its
+   * grace period, i.e. its deletionTimestamp, before it releases its Kueue Workload anyway. It is
+   * the same as the default `forceTerminationGracePeriodMillis` of an application. A pod on a lost

Review Comment:
   Thank you for the suggestion. I'd like to keep it fixed in this PR, the same as the default `forceTerminationGracePeriodMillis`, to avoid adding a new configuration before there is a real need. We can make it configurable later via `SparkOperatorConf` if needed.



-- 
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-59790] Bound the wait for the terminating pods of a suspended `SparkCluster` [spark-kubernetes-operator]

Posted by "dongjoon-hyun (via GitHub)" <gi...@apache.org>.
dongjoon-hyun commented on PR #889:
URL: https://github.com/apache/spark-kubernetes-operator/pull/889#issuecomment-5844523016

   Thank you, @MaxGekk and @peter-toth . I'm going to merge 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-59790] Bound the wait for the terminating pods of a suspended `SparkCluster` [spark-kubernetes-operator]

Posted by "dongjoon-hyun (via GitHub)" <gi...@apache.org>.
dongjoon-hyun closed pull request #889: [SPARK-59790] Bound the wait for the terminating pods of a suspended `SparkCluster`
URL: https://github.com/apache/spark-kubernetes-operator/pull/889


-- 
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-59790] Bound the wait for the terminating pods of a suspended `SparkCluster` [spark-kubernetes-operator]

Posted by "MaxGekk (via GitHub)" <gi...@apache.org>.
MaxGekk commented on code in PR #889:
URL: https://github.com/apache/spark-kubernetes-operator/pull/889#discussion_r4110251918


##########
spark-operator/src/main/java/org/apache/spark/k8s/operator/reconciler/reconcilesteps/ClusterSuspendStep.java:
##########
@@ -179,8 +221,22 @@ private boolean releaseResources(SparkClusterContext context) {
                 + "cluster, will retry. "
                 + EventUtils.describe(e));
       }
-      return false;
+      return Optional.of(completeAndDefaultRequeue());
     }
-    return true;
+    return Optional.empty();
+  }
+
+  /**
+   * Returns when a master or worker pod stops holding the Kueue Workload of a suspended cluster.
+   *
+   * @param pod The master or worker pod.
+   * @return {@link #POD_RELEASE_TIMEOUT} after its deletion started, or Instant.MAX while it is not
+   *     being deleted yet.
+   */
+  private static Instant getPodReleaseDeadline(Pod pod) {
+    String deletionTimestamp = pod.getMetadata().getDeletionTimestamp();
+    return deletionTimestamp == null
+        ? Instant.MAX
+        : Instant.parse(deletionTimestamp).plus(POD_RELEASE_TIMEOUT);

Review Comment:
   `deletionTimestamp` is not when the deletion started. For a graceful delete the API server sets it to the request time plus the grace period (`BeforeDelete` in `k8s.io/apiserver/pkg/registry/rest/delete.go`), and the field's doc calls it the time "at which this resource will be deleted". So this deadline is `request + terminationGracePeriodSeconds + 5 minutes`: 5m30s for a default pod, and 65 minutes for a worker with a one-hour grace period for decommissioning. The Javadoc ("after its deletion started") and the docs ("has been terminating for 5 minutes", lines 583 and 686) promise 5 minutes.
   
   Subtracting the grace period gives the request time back, and it stays correct when a later delete shortens the grace, since the API server moves both fields together:
   
   ```java
   ObjectMeta meta = pod.getMetadata();
   long grace = Optional.ofNullable(meta.getDeletionGracePeriodSeconds()).orElse(0L);
   return Instant.parse(meta.getDeletionTimestamp()).minusSeconds(grace).plus(POD_RELEASE_TIMEOUT);
   ```
   
   Alternatively, keep the code and say "5 minutes after the pod's grace period ends" in the Javadoc and the docs.



##########
spark-operator/src/main/java/org/apache/spark/k8s/operator/reconciler/reconcilesteps/ClusterSuspendStep.java:
##########
@@ -64,6 +69,14 @@
  */
 @Slf4j
 public final class ClusterSuspendStep extends ClusterReconcileStep {
+  /**
+   * How long a suspended cluster waits for each terminating master or worker pod to go before it
+   * releases its Kueue Workload anyway. It is the same as the default
+   * `forceTerminationGracePeriodMillis` of an application. A pod on a lost node stays terminating
+   * until the node is deleted, which could otherwise hold the quota forever.
+   */
+  private static final Duration POD_RELEASE_TIMEOUT = Duration.ofMinutes(5);

Review Comment:
   A design question, not a request. Past the timeout, the application path force-deletes (`AppCleanUpStep.enableForceDelete`, grace 0), which frees both the quota and the pod names, so there it needs no resume special case. Here the cluster releases the `Workload` but leaves the pods, and so needs the branch at line 210. I'd guess that is deliberate: force-deleting a StatefulSet pod on a partitioned node can leave its container running while a resume creates a new pod with the same identity, which is the at-most-one risk the Kubernetes docs warn about for StatefulSets. If so, a sentence in the Javadoc saying why the cluster does not force-delete like an application would save the next reader the question.



##########
spark-operator/src/main/java/org/apache/spark/k8s/operator/reconciler/reconcilesteps/ClusterSuspendStep.java:
##########
@@ -156,19 +178,39 @@ private boolean releaseResources(SparkClusterContext context) {
           .inNamespace(namespace)
           .withName(getWorkerPodDisruptionBudgetName(name))
           .delete();
-      if (ReconcilerUtils.hasPods(
-          client,
-          namespace,
-          LABEL_SPARK_CLUSTER_NAME,
-          name,
-          LABEL_SPARK_ROLE_MASTER_VALUE,
-          LABEL_SPARK_ROLE_WORKER_VALUE)) {
-        // The deletion of each pod is observed by the pod informer, which reconciles again.
+      List<Pod> pods =
+          ReconcilerUtils.podsOf(
+                  client,
+                  namespace,
+                  LABEL_SPARK_CLUSTER_NAME,
+                  name,
+                  LABEL_SPARK_ROLE_MASTER_VALUE,
+                  LABEL_SPARK_ROLE_WORKER_VALUE)
+              .list()
+              .getItems();
+      Instant now = Instant.now();
+      Instant podReleaseDeadline =
+          pods.stream()
+              .map(ClusterSuspendStep::getPodReleaseDeadline)
+              .max(Comparator.naturalOrder())
+              .orElse(now);
+      if (now.isBefore(podReleaseDeadline)) {
+        // The deletion of each pod is observed by the pod informer, which reconciles again, while
+        // the timeout of a pod which may send no more events is observed by the requeue.
         log.debug("Waiting for the pods of the suspended cluster to be deleted.");
-        return false;
+        ReconcileProgress defaultRequeue = completeAndDefaultRequeue();
+        Duration remaining = Duration.between(now, podReleaseDeadline);
+        return Optional.of(
+            remaining.compareTo(defaultRequeue.getRequeueAfterDuration()) < 0
+                ? completeAndRequeueAfter(remaining)
+                : defaultRequeue);
       }
       // A Workload admitted before the queue label was removed is released as well.
       KueueWorkloadUtils.deleteWorkloadOf(client, cluster);
+      if (!suspend && !pods.isEmpty()) {

Review Comment:
   The docs say the resumed cluster stays `Suspended` until a stuck pod is gone, which makes sense since the pod still holds the name. But the only trace of it is a debug log. The user clears `spec.suspend`, the `Workload` is already gone, and the cluster sits in `Suspended` with nothing in its status or events to say why. On a lost node that can last until someone deletes the node. Could this report it, for example a warning `Event` naming the pods, or a message on the `Suspended` state such as "waiting for pods ... stuck terminating"? A status message avoids repeating an `Event` on every requeue.



-- 
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-59790] Bound the wait for the terminating pods of a suspended `SparkCluster` [spark-kubernetes-operator]

Posted by "dongjoon-hyun (via GitHub)" <gi...@apache.org>.
dongjoon-hyun commented on PR #889:
URL: https://github.com/apache/spark-kubernetes-operator/pull/889#issuecomment-5843616392

   Thank you so much for the thorough review, @MaxGekk. I addressed all comments in 1e7698b4.
   
   - **`deletionTimestamp` semantics**: I kept the deadline as `deletionTimestamp + 5 minutes` and fixed the Javadoc and the docs to say "5 minutes after its grace period ends", since a pod within its grace period still occupies the quota.
   - **Visibility of a blocked resume**: A resumed cluster blocked by stuck pods now appends a `Suspended` state whose message names those pods. It is appended only when the message changes.
   - **No force deletion**: I added a sentence to the Javadoc explaining why the cluster does not force-delete its pods, unlike an application.
   
   In addition, I will respect a user-specified `terminationGracePeriodSeconds` for the master and worker pods in a follow-up PR.


-- 
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-59790] Bound the wait for the terminating pods of a suspended `SparkCluster` [spark-kubernetes-operator]

Posted by "dongjoon-hyun (via GitHub)" <gi...@apache.org>.
dongjoon-hyun commented on PR #889:
URL: https://github.com/apache/spark-kubernetes-operator/pull/889#issuecomment-5844515385

   Thank you for the review, @peter-toth. I addressed the comments in f1b262e5.
   
   - **1.** The blocked steady state now requeues with `SUSPEND_HOLD_REQUEUE_INTERVAL_SECONDS`, since the pods' disappearance arrives as a watch event.
   - **2.** I kept the timeout fixed in this PR, and we can make it configurable later if needed.
   - **3.** I removed the `!suspend` condition, so a cluster which stays suspended also names its stuck pods in its `Suspended` state. The message was reworded to cover both cases.


-- 
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-59790] Bound the wait for the terminating pods of a suspended `SparkCluster` [spark-kubernetes-operator]

Posted by "dongjoon-hyun (via GitHub)" <gi...@apache.org>.
dongjoon-hyun commented on PR #889:
URL: https://github.com/apache/spark-kubernetes-operator/pull/889#issuecomment-5844527857

   Merged to main


-- 
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-59790] Bound the wait for the terminating pods of a suspended `SparkCluster` [spark-kubernetes-operator]

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


##########
spark-operator/src/main/java/org/apache/spark/k8s/operator/reconciler/reconcilesteps/ClusterSuspendStep.java:
##########
@@ -179,8 +221,22 @@ private boolean releaseResources(SparkClusterContext context) {
                 + "cluster, will retry. "
                 + EventUtils.describe(e));
       }
-      return false;
+      return Optional.of(completeAndDefaultRequeue());
     }
-    return true;
+    return Optional.empty();
+  }
+
+  /**
+   * Returns when a master or worker pod stops holding the Kueue Workload of a suspended cluster.
+   *
+   * @param pod The master or worker pod.
+   * @return {@link #POD_RELEASE_TIMEOUT} after its deletion started, or Instant.MAX while it is not
+   *     being deleted yet.
+   */
+  private static Instant getPodReleaseDeadline(Pod pod) {
+    String deletionTimestamp = pod.getMetadata().getDeletionTimestamp();
+    return deletionTimestamp == null
+        ? Instant.MAX
+        : Instant.parse(deletionTimestamp).plus(POD_RELEASE_TIMEOUT);

Review Comment:
   Thank you for the precise pointer, @MaxGekk. I kept the code and fixed the Javadoc and the docs to say "5 minutes after its grace period ends". A pod within its grace period is still shutting down and still occupies the quota, e.g. a worker with a long grace period for decommissioning, so the `Workload` should not be released before the grace period ends.
   
   As a side note, `SparkClusterResourceSpec` currently overrides `terminationGracePeriodSeconds` to `0` for the master and worker pods. That is only a default for faster deletion, so a user-specified value should be respected. I'll handle it in a follow-up PR.



##########
spark-operator/src/main/java/org/apache/spark/k8s/operator/reconciler/reconcilesteps/ClusterSuspendStep.java:
##########
@@ -156,19 +178,39 @@ private boolean releaseResources(SparkClusterContext context) {
           .inNamespace(namespace)
           .withName(getWorkerPodDisruptionBudgetName(name))
           .delete();
-      if (ReconcilerUtils.hasPods(
-          client,
-          namespace,
-          LABEL_SPARK_CLUSTER_NAME,
-          name,
-          LABEL_SPARK_ROLE_MASTER_VALUE,
-          LABEL_SPARK_ROLE_WORKER_VALUE)) {
-        // The deletion of each pod is observed by the pod informer, which reconciles again.
+      List<Pod> pods =
+          ReconcilerUtils.podsOf(
+                  client,
+                  namespace,
+                  LABEL_SPARK_CLUSTER_NAME,
+                  name,
+                  LABEL_SPARK_ROLE_MASTER_VALUE,
+                  LABEL_SPARK_ROLE_WORKER_VALUE)
+              .list()
+              .getItems();
+      Instant now = Instant.now();
+      Instant podReleaseDeadline =
+          pods.stream()
+              .map(ClusterSuspendStep::getPodReleaseDeadline)
+              .max(Comparator.naturalOrder())
+              .orElse(now);
+      if (now.isBefore(podReleaseDeadline)) {
+        // The deletion of each pod is observed by the pod informer, which reconciles again, while
+        // the timeout of a pod which may send no more events is observed by the requeue.
         log.debug("Waiting for the pods of the suspended cluster to be deleted.");
-        return false;
+        ReconcileProgress defaultRequeue = completeAndDefaultRequeue();
+        Duration remaining = Duration.between(now, podReleaseDeadline);
+        return Optional.of(
+            remaining.compareTo(defaultRequeue.getRequeueAfterDuration()) < 0
+                ? completeAndRequeueAfter(remaining)
+                : defaultRequeue);
       }
       // A Workload admitted before the queue label was removed is released as well.
       KueueWorkloadUtils.deleteWorkloadOf(client, cluster);
+      if (!suspend && !pods.isEmpty()) {

Review Comment:
   Good point. A resumed cluster blocked by stuck pods now appends a `Suspended` state whose message names those pods. It is appended only when the message changes, so it is not repeated on every requeue.



##########
spark-operator/src/main/java/org/apache/spark/k8s/operator/reconciler/reconcilesteps/ClusterSuspendStep.java:
##########
@@ -64,6 +69,14 @@
  */
 @Slf4j
 public final class ClusterSuspendStep extends ClusterReconcileStep {
+  /**
+   * How long a suspended cluster waits for each terminating master or worker pod to go before it
+   * releases its Kueue Workload anyway. It is the same as the default
+   * `forceTerminationGracePeriodMillis` of an application. A pod on a lost node stays terminating
+   * until the node is deleted, which could otherwise hold the quota forever.
+   */
+  private static final Duration POD_RELEASE_TIMEOUT = Duration.ofMinutes(5);

Review Comment:
   Yes, it is deliberate. Force-deleting a StatefulSet pod on a partitioned node can leave its container running while a pod with the same identity is created again. I added a sentence about it to the Javadoc.



-- 
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-59790] Bound the wait for the terminating pods of a suspended `SparkCluster` [spark-kubernetes-operator]

Posted by "dongjoon-hyun (via GitHub)" <gi...@apache.org>.
dongjoon-hyun commented on PR #889:
URL: https://github.com/apache/spark-kubernetes-operator/pull/889#issuecomment-5839836036

   Could you review this PR when you have some time, @MaxGekk ?


-- 
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-59790] Bound the wait for the terminating pods of a suspended `SparkCluster` [spark-kubernetes-operator]

Posted by "peter-toth (via GitHub)" <gi...@apache.org>.
peter-toth commented on code in PR #889:
URL: https://github.com/apache/spark-kubernetes-operator/pull/889#discussion_r4110633009


##########
spark-operator/src/main/java/org/apache/spark/k8s/operator/reconciler/reconcilesteps/ClusterSuspendStep.java:
##########
@@ -64,6 +71,14 @@
  */
 @Slf4j
 public final class ClusterSuspendStep extends ClusterReconcileStep {
+  /**
+   * How long a suspended cluster waits for a terminating master or worker pod past the end of its
+   * grace period, i.e. its deletionTimestamp, before it releases its Kueue Workload anyway. It is
+   * the same as the default `forceTerminationGracePeriodMillis` of an application. A pod on a lost

Review Comment:
   **Finding 2.** The counterpart named in this sentence is a per-resource field; this one cannot be changed at all.
   
   `ApplicationTimeoutConfig.java:65` is `@Builder.Default protected Long forceTerminationGracePeriodMillis = 300 * 1000L`, a CRD field, so an application whose pods need longer or shorter sets it. `POD_RELEASE_TIMEOUT` is a `private static final Duration`, so the only way to change it is editing the operator.
   
   There is no cluster-side spec home for it today, since `ClusterTolerations` carries only `instanceConfig`. But this step already reads one tunable from `SparkOperatorConf`, `SUSPEND_HOLD_REQUEUE_INTERVAL_SECONDS` with `enableDynamicOverride(true)`, and the reason to change this one is a property of the cluster rather than of one `SparkCluster`: how long a lost node takes to be reclaimed. So an operator config looks like the right home.
   
   ```java
     public static final ConfigOption<Long> SUSPENDED_POD_RELEASE_TIMEOUT_SECONDS =
         ConfigOption.<Long>builder()
             .key("spark.kubernetes.operator.reconciler.suspendedPodReleaseTimeoutSeconds")
             .enableDynamicOverride(true)
             .description(
                 "How long a suspended SparkCluster waits for a terminating master or worker pod "
                     + "past the end of its grace period, i.e. its deletionTimestamp, before it "
                     + "releases its Kueue Workload anyway. ...")
             .typeParameterClass(Long.class)
             .defaultValue(300L)
             .build();
   ```
   
   Worth separating this from the "unpinned constant" complaint, which does not apply: the new tests bracket the value from both sides. With a 4-minute timeout the 270-second pod in `podsAreWaitedForSinceTheirDeletionRatherThanSinceSuspended` would be past its deadline and `assertNotNull(getWorkload())` would fail; with a 10-minute one the 6-minute pods in `stubStuckPods` would still be waiting and `assertNull(getWorkload())` in `suspendedClusterReleasesKueueWorkloadOfPodsTerminatingForTimeout` would fail. So this is only about whether an operator can reach it.
   



##########
spark-operator/src/main/java/org/apache/spark/k8s/operator/reconciler/reconcilesteps/ClusterSuspendStep.java:
##########
@@ -156,19 +185,56 @@ private boolean releaseResources(SparkClusterContext context) {
           .inNamespace(namespace)
           .withName(getWorkerPodDisruptionBudgetName(name))
           .delete();
-      if (ReconcilerUtils.hasPods(
-          client,
-          namespace,
-          LABEL_SPARK_CLUSTER_NAME,
-          name,
-          LABEL_SPARK_ROLE_MASTER_VALUE,
-          LABEL_SPARK_ROLE_WORKER_VALUE)) {
-        // The deletion of each pod is observed by the pod informer, which reconciles again.
+      List<Pod> pods =
+          ReconcilerUtils.podsOf(
+                  client,
+                  namespace,
+                  LABEL_SPARK_CLUSTER_NAME,
+                  name,
+                  LABEL_SPARK_ROLE_MASTER_VALUE,
+                  LABEL_SPARK_ROLE_WORKER_VALUE)
+              .list()
+              .getItems();
+      Instant now = Instant.now();
+      Instant podReleaseDeadline =
+          pods.stream()
+              .map(ClusterSuspendStep::getPodReleaseDeadline)
+              .max(Comparator.naturalOrder())
+              .orElse(now);
+      if (now.isBefore(podReleaseDeadline)) {
+        // The deletion of each pod is observed by the pod informer, which reconciles again, while
+        // the timeout of a pod which may send no more events is observed by the requeue.
         log.debug("Waiting for the pods of the suspended cluster to be deleted.");
-        return false;
+        ReconcileProgress defaultRequeue = completeAndDefaultRequeue();
+        Duration remaining = Duration.between(now, podReleaseDeadline);
+        return Optional.of(
+            remaining.compareTo(defaultRequeue.getRequeueAfterDuration()) < 0
+                ? completeAndRequeueAfter(remaining)
+                : defaultRequeue);
       }
       // A Workload admitted before the queue label was removed is released as well.
       KueueWorkloadUtils.deleteWorkloadOf(client, cluster);
+      if (!suspend && !pods.isEmpty()) {
+        log.debug("Waiting for the stuck pods of the resumed cluster to be deleted.");
+        // This may last until a lost node is deleted, so the state says why, once per set of pods
+        String message =
+            String.format(
+                CLUSTER_SUSPENDED_BY_STUCK_PODS_MESSAGE,
+                pods.stream()
+                    .map(pod -> pod.getMetadata().getName())
+                    .sorted()
+                    .collect(Collectors.joining(", ")));
+        ReconcileProgress defaultRequeue = completeAndDefaultRequeue();

Review Comment:
   **Finding 1.** This is the one steady state here that can last indefinitely, and it is the one that requeues most often.
   
   Measured on this head, with a resumed cluster whose master and worker pods have been terminating for 6 minutes, two reconciles through the probe:
   
   ```
   first requeueAfter=PT2M
   steady requeueAfter=PT2M
   suspendHoldInterval=1800s
   per reconcile: 2 apps(), 1 pods(), 5 resources() on the spied client
   ```
   
   So the loop runs every 120 seconds while the comment two lines up says "This may last until a lost node is deleted". That is 15 times more often than the hold at `ClusterSuspendStep.java:119-120`, which this same step uses for a cluster that has finished releasing and has nothing left to do. `SUSPEND_HOLD_REQUEUE_INTERVAL_SECONDS`'s own description is written for exactly this shape: "deliberately much coarser than `spark.kubernetes.operator.reconciler.intervalSeconds`, since a suspended resource has nothing to observe while each republish costs a read and a write on the API server."
   
   Slowing it down costs nothing, because the pods' disappearance arrives as a watch event rather than on the requeue. The master and worker pod templates carry `LABEL_SPARK_CLUSTER_NAME` (`SparkClusterResourceSpec.java:236` and `:318`), the cluster's Pod informer selects on that label (`SparkClusterReconciler.java:158`), and it has no delete filter. That is the same mechanism the javadoc already relies on for the pods which are not stuck.
   
   ```java
           ReconcileProgress holdRequeue =
               completeAndRequeueAfter(
                   Duration.ofSeconds(SUSPEND_HOLD_REQUEUE_INTERVAL_SECONDS.getValue()));
           if (message.equals(cluster.getStatus().getCurrentState().getMessage())) {
             return Optional.of(holdRequeue);
           }
           return Optional.of(
               appendStateAndRequeueAfter(
                   context, statusRecorder, new ClusterState(ClusterStateSummary.Suspended, message),
                   holdRequeue.getRequeueAfterDuration()));
   ```
   
   The `now.isBefore(podReleaseDeadline)` branch above should keep the fine-grained interval, since its wait is bounded and the `min` is what makes it end exactly at the deadline. Only this branch is unbounded.
   



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