arjunashok commented on code in PR #359:
URL: https://github.com/apache/cassandra-sidecar/pull/359#discussion_r3553952714


##########
server/src/main/java/org/apache/cassandra/sidecar/job/DurableOperationalJobTracker.java:
##########
@@ -0,0 +1,231 @@
+/*
+ * 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.cassandra.sidecar.job;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.inject.Inject;
+import com.google.inject.Singleton;
+import org.apache.cassandra.sidecar.common.data.OperationalJobStatus;
+import org.apache.cassandra.sidecar.concurrent.TaskExecutorPool;
+import org.apache.cassandra.sidecar.config.ServiceConfiguration;
+import org.apache.cassandra.sidecar.job.storage.OperationalJobRecord;
+import org.apache.cassandra.sidecar.job.storage.StorageProvider;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+/**
+ * A durable implementation of {@link OperationalJobTracker} that persists job 
state
+ * via a {@link StorageProvider}. A local {@link ConcurrentHashMap} caches live
+ * {@link OperationalJob} references for the current process, since executing 
jobs
+ * with Vert.x promises cannot be reconstituted from storage. Once a job 
completes,
+ * it is removed from the local map, and subsequent lookups are served from 
storage.
+ */
+@Singleton
+public class DurableOperationalJobTracker implements OperationalJobTracker
+{
+    private static final Logger LOGGER = 
LoggerFactory.getLogger(DurableOperationalJobTracker.class);
+    private static final int MAX_STATUS_UPDATE_ATTEMPTS = 3;
+    private static final long RETRY_DELAY_MS = 100;
+
+    private final ConcurrentHashMap<UUID, OperationalJob> liveJobs;
+    private final StorageProvider storageProvider;
+    private final TaskExecutorPool executor;
+
+    @Inject
+    public DurableOperationalJobTracker(ServiceConfiguration 
serviceConfiguration,
+                                        StorageProvider storageProvider,
+                                        TaskExecutorPool executor)
+    {
+        this.liveJobs = new 
ConcurrentHashMap<>(serviceConfiguration.operationalJobTrackerSize());
+        this.storageProvider = storageProvider;
+        this.executor = executor;
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public OperationalJob computeIfAbsent(UUID jobId, Function<UUID, 
OperationalJob> mappingFunction)
+    {
+        if (!storageProvider.isAvailable())
+        {
+            throw new IllegalStateException("Storage provider is not 
available");
+        }
+
+        boolean[] created = {false};
+        OperationalJob job = liveJobs.computeIfAbsent(jobId, id -> {
+            created[0] = true;
+            return mappingFunction.apply(id);
+        });
+
+        if (created[0])
+        {
+            executor.executeBlocking(() -> {
+                
storageProvider.persistJob(OperationalJobRecord.fromOperationalJob(job));

Review Comment:
   Seems like this initial persist gets zero retries and gets removed from 
`liveJobs`
   
   Since `OperationalJobManager.trySubmitJob` already kicked off 
`job.execute()` on a separate executor before this callback runs, the job keeps 
running against Cassandra while the tracker has already forgotten it.
   
   Subsequently, `get(jobId)` returns null, and `inflightJobsByOperation()` no 
longer sees it, and could let a second decommission/move/repair job through 
while the first is still executing underneath. 
   
   Should this keep the job in liveJobs (serving it in a durability-degraded 
state) rather than dropping it entirely on persist failure?
   



##########
server/src/main/java/org/apache/cassandra/sidecar/job/DurableOperationalJobTracker.java:
##########
@@ -0,0 +1,231 @@
+/*
+ * 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.cassandra.sidecar.job;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.inject.Inject;
+import com.google.inject.Singleton;
+import org.apache.cassandra.sidecar.common.data.OperationalJobStatus;
+import org.apache.cassandra.sidecar.concurrent.TaskExecutorPool;
+import org.apache.cassandra.sidecar.config.ServiceConfiguration;
+import org.apache.cassandra.sidecar.job.storage.OperationalJobRecord;
+import org.apache.cassandra.sidecar.job.storage.StorageProvider;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+/**
+ * A durable implementation of {@link OperationalJobTracker} that persists job 
state
+ * via a {@link StorageProvider}. A local {@link ConcurrentHashMap} caches live
+ * {@link OperationalJob} references for the current process, since executing 
jobs
+ * with Vert.x promises cannot be reconstituted from storage. Once a job 
completes,
+ * it is removed from the local map, and subsequent lookups are served from 
storage.
+ */
+@Singleton
+public class DurableOperationalJobTracker implements OperationalJobTracker
+{
+    private static final Logger LOGGER = 
LoggerFactory.getLogger(DurableOperationalJobTracker.class);
+    private static final int MAX_STATUS_UPDATE_ATTEMPTS = 3;
+    private static final long RETRY_DELAY_MS = 100;
+
+    private final ConcurrentHashMap<UUID, OperationalJob> liveJobs;
+    private final StorageProvider storageProvider;
+    private final TaskExecutorPool executor;
+
+    @Inject
+    public DurableOperationalJobTracker(ServiceConfiguration 
serviceConfiguration,
+                                        StorageProvider storageProvider,
+                                        TaskExecutorPool executor)
+    {
+        this.liveJobs = new 
ConcurrentHashMap<>(serviceConfiguration.operationalJobTrackerSize());
+        this.storageProvider = storageProvider;
+        this.executor = executor;
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public OperationalJob computeIfAbsent(UUID jobId, Function<UUID, 
OperationalJob> mappingFunction)
+    {
+        if (!storageProvider.isAvailable())
+        {
+            throw new IllegalStateException("Storage provider is not 
available");
+        }
+
+        boolean[] created = {false};
+        OperationalJob job = liveJobs.computeIfAbsent(jobId, id -> {
+            created[0] = true;
+            return mappingFunction.apply(id);
+        });
+
+        if (created[0])
+        {
+            executor.executeBlocking(() -> {
+                
storageProvider.persistJob(OperationalJobRecord.fromOperationalJob(job));
+                return null;
+            }).onSuccess(v -> job.asyncResult().onComplete(ar -> {
+                updateTerminalStatus(job);
+                liveJobs.remove(job.jobId());
+            })).onFailure(e -> {
+                liveJobs.remove(jobId, job);
+                LOGGER.error("Failed to persist job {} to storage. Job will 
not be tracked durably.",
+                             jobId, e);
+            });
+        }
+
+        return job;
+    }
+
+    @Nullable
+    @Override
+    public OperationalJobInfo get(UUID jobId)
+    {
+        OperationalJob liveJob = liveJobs.get(jobId);
+        if (liveJob != null)
+        {
+            return liveJob;
+        }
+
+        OperationalJobRecord record = storageProvider.findJob(jobId);
+        if (record == null)
+        {
+            return null;
+        }
+        return enrichWithNodeStatuses(record);
+    }
+
+    @NotNull
+    @Override
+    public Map<UUID, OperationalJob> jobsView()
+    {
+        return Collections.unmodifiableMap(liveJobs);
+    }
+
+    @NotNull
+    @Override
+    public List<OperationalJob> inflightJobsByOperation(String operation)
+    {
+        return liveJobs.values()
+                       .stream()
+                       .filter(j -> j.name().equals(operation) &&
+                                    (j.status() == 
OperationalJobStatus.RUNNING ||
+                                     j.status() == 
OperationalJobStatus.CREATED))
+                       .collect(Collectors.toList());
+    }
+
+    /**
+     * Enriches an {@link OperationalJobRecord} with per-node status data from 
storage.
+     * If the record already has non-empty node lists (e.g. populated by a 
storage provider
+     * that joins the data in a single query), the record is returned as is.
+     */
+    private OperationalJobRecord enrichWithNodeStatuses(OperationalJobRecord 
record)
+    {
+        if (!record.nodesPending().isEmpty()
+            || !record.nodesExecuting().isEmpty()
+            || !record.nodesSucceeded().isEmpty()
+            || !record.nodesFailed().isEmpty())
+        {
+            return record;
+        }
+
+        Map<UUID, OperationalJobStatus> nodeStatuses =
+        storageProvider.getNodeStatusesForOperation(record.jobId());
+        if (nodeStatuses.isEmpty())
+        {
+            return record;
+        }
+
+        List<UUID> pending = new ArrayList<>();
+        List<UUID> executing = new ArrayList<>();
+        List<UUID> succeeded = new ArrayList<>();
+        List<UUID> failed = new ArrayList<>();
+
+        for (Map.Entry<UUID, OperationalJobStatus> entry : 
nodeStatuses.entrySet())
+        {
+            switch (entry.getValue())
+            {
+                case CREATED:
+                    pending.add(entry.getKey());
+                    break;
+                case RUNNING:
+                    executing.add(entry.getKey());
+                    break;
+                case SUCCEEDED:
+                    succeeded.add(entry.getKey());
+                    break;
+                case FAILED:
+                    failed.add(entry.getKey());
+                    break;
+                default:
+                    break;
+            }
+        }
+
+        return new OperationalJobRecord(record.jobId(), 
record.operationType(), record.status(),
+                                        record.startTime(), 
record.lastUpdate(), record.failureReason(),
+                                        record.nodeExecutionOrder(), 
record.operationMetadata(),
+                                        Collections.unmodifiableList(pending),
+                                        
Collections.unmodifiableList(executing),
+                                        
Collections.unmodifiableList(succeeded),
+                                        Collections.unmodifiableList(failed));
+    }
+
+    /**
+     * Attempts to update the terminal status in storage with retry.
+     * If all attempts fail, logs a warning and continues.
+     */
+    private void updateTerminalStatus(OperationalJob job)
+    {
+        updateTerminalStatus(job, 1);
+    }
+
+    private void updateTerminalStatus(OperationalJob job, int attempt)
+    {
+        try
+        {
+            storageProvider.updateJobStatus(job.jobId(), job.operationType(), 
job.status(), job.failureReason());
+        }
+        catch (RuntimeException e)

Review Comment:
   Now that retries are bumped to 3,  when all  exhaust, the storage record is 
left at the state it last successfully wrote (typically CREATED). There's no 
flag distinguishing 'this record's status is stale/unreliable' from 'this job 
genuinely hasn't started.' 
   
   A caller polling `GET /job/{id}` sees "not started yet" for a job that 
finished, which can either hang waiting for a terminal state that will never 
come, or time out and resubmit the same operation (which is not safe for 
decommission/move). It also blocks the periodic reconciliation sweep we want to 
add as we would need a way to tell "genuinely still CREATED" from "we know this 
finished but failed to record it".
   
   Couple of options: (a) a metadata field on OperationalJobRecord marking it 
durability-degraded, checked only by the reconciliation sweep (which can come 
later), or (b) a new OperationalJobStatus value (e.g. UNKNOWN) visible through 
the same field every existing caller already reads.



##########
server/src/main/java/org/apache/cassandra/sidecar/job/DurableOperationalJobTracker.java:
##########
@@ -0,0 +1,153 @@
+/*
+ * 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.cassandra.sidecar.job;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.inject.Inject;
+import com.google.inject.Singleton;
+import org.apache.cassandra.sidecar.common.data.OperationalJobStatus;
+import org.apache.cassandra.sidecar.concurrent.TaskExecutorPool;
+import org.apache.cassandra.sidecar.config.ServiceConfiguration;
+import org.apache.cassandra.sidecar.job.storage.OperationalJobRecord;
+import org.apache.cassandra.sidecar.job.storage.StorageProvider;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+/**
+ * A durable implementation of {@link OperationalJobTracker} that persists job 
state
+ * via a {@link StorageProvider}. A local {@link ConcurrentHashMap} caches live
+ * {@link OperationalJob} references for the current process, since executing 
jobs
+ * with Vert.x promises cannot be reconstituted from storage. Once a job 
completes,
+ * it is removed from the local map, and subsequent lookups are served from 
storage.
+ */
+@Singleton
+public class DurableOperationalJobTracker implements OperationalJobTracker
+{
+    private static final Logger LOGGER = 
LoggerFactory.getLogger(DurableOperationalJobTracker.class);
+    private static final int MAX_STATUS_UPDATE_ATTEMPTS = 2;
+    private static final long RETRY_DELAY_MS = 100;
+
+    private final ConcurrentHashMap<UUID, OperationalJob> liveJobs;
+    private final StorageProvider storageProvider;
+    private final TaskExecutorPool executor;
+
+    @Inject
+    public DurableOperationalJobTracker(ServiceConfiguration 
serviceConfiguration,
+                                        StorageProvider storageProvider,
+                                        TaskExecutorPool executor)
+    {
+        this.liveJobs = new 
ConcurrentHashMap<>(serviceConfiguration.operationalJobTrackerSize());
+        this.storageProvider = storageProvider;
+        this.executor = executor;
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public OperationalJob computeIfAbsent(UUID jobId, Function<UUID, 
OperationalJob> mappingFunction)
+    {
+        return liveJobs.computeIfAbsent(jobId, id -> {
+            OperationalJob job = mappingFunction.apply(id);
+
+            
storageProvider.persistJob(OperationalJobRecord.fromOperationalJob(job));
+
+            job.asyncResult().onComplete(ar -> {
+                liveJobs.remove(job.jobId());
+                updateTerminalStatus(job);
+            });
+
+            return job;
+        });
+    }
+
+    @Nullable
+    @Override
+    public OperationalJobInfo get(UUID jobId)
+    {
+        OperationalJob liveJob = liveJobs.get(jobId);
+        if (liveJob != null)
+        {
+            return liveJob;
+        }
+
+        return storageProvider.findJob(jobId);
+    }
+
+    @NotNull
+    @Override
+    public Map<UUID, OperationalJob> jobsView()
+    {
+        return Collections.unmodifiableMap(liveJobs);
+    }
+
+    @NotNull
+    @Override
+    public List<OperationalJob> inflightJobsByOperation(String operation)
+    {
+        return liveJobs.values()
+                       .stream()
+                       .filter(j -> j.name().equals(operation) &&
+                                    (j.status() == 
OperationalJobStatus.RUNNING ||
+                                     j.status() == 
OperationalJobStatus.CREATED))
+                       .collect(Collectors.toList());
+    }
+
+    /**
+     * Attempts to update the terminal status in storage with retry.
+     * If all attempts fail, logs a warning and continues.
+     */
+    private void updateTerminalStatus(OperationalJob job)
+    {
+        updateTerminalStatus(job, 1);
+    }
+
+    private void updateTerminalStatus(OperationalJob job, int attempt)
+    {
+        try
+        {
+            storageProvider.updateJobStatus(job.jobId(), job.operationType(), 
job.status(), job.failureReason());
+        }
+        catch (RuntimeException e)
+        {
+            LOGGER.warn("Failed to update terminal status for job {} (attempt 
{}/{}). error={}",
+                        job.jobId(), attempt, MAX_STATUS_UPDATE_ATTEMPTS, 
e.getMessage());
+            if (attempt < MAX_STATUS_UPDATE_ATTEMPTS)

Review Comment:
   For 3 attempts it's probably fine as-is, but consider adding jitter (see 
`ClusterLeaseClaimTask.initialDelay()` for existing precedent in this codebase) 
so that concurrent sidecar processes retrying against the same transient 
Cassandra blip don't all retry in lockstep.



-- 
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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to