feat(jobs): add KILLED state for orphaned jobs with auto-retry

When the barn service is terminated unexpectedly (crash, SIGKILL), jobs
that were running are now marked as KILLED instead of FAILED. This
distinguishes between jobs that failed due to their own errors vs jobs
that were killed due to external factors.

Key changes:
- Add KILLED state to JobState enum
- Update JobStateMachine with KILLED transitions (RUNNING→KILLED, KILLED→QUEUED)
- CrashRecovery now marks orphaned jobs as KILLED and auto-retries them
- Add markKilled() method to JobRepository
- Add killed count to service status output
- Update HumanFormatter to display KILLED state in red

The auto-retry behavior uses exponential backoff (configurable) and
respects the maxRetries limit. Retry history is recorded in the
retry_history file.

Closes #25

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
Daniel SamsonandClaude Opus 4.5 committed 2026-01-22 01:08:05 +00:00
1 parent 27648a03a8
commit f916fc2f8b
11 files changed
+206 -44

No files matched your search

@@ -237,7 +237,7 @@ public class HumanFormatter implements OutputFormatter {
case QUEUED -> colorize(text, CYAN);
case RUNNING -> colorize(text, YELLOW);
case SUCCEEDED -> colorize(text, GREEN);
case FAILED -> colorize(text, RED);
case FAILED, KILLED -> colorize(text, RED);
case CANCELED -> text;
};
}
@@ -98,10 +98,11 @@ public class ServiceStatusCommand extends BaseCommand {
int succeeded = countJobsByState(effectiveBarnDir, JobState.SUCCEEDED);
int failed = countJobsByState(effectiveBarnDir, JobState.FAILED);
int canceled = countJobsByState(effectiveBarnDir, JobState.CANCELED);
int killed = countJobsByState(effectiveBarnDir, JobState.KILLED);
int total = countTotalJobs(effectiveBarnDir);
return ServiceStatus.running(pid, startTime, running, queued, succeeded, failed,
canceled, total, effectiveBarnDir, serviceManager);
canceled, killed, total, effectiveBarnDir, serviceManager);
}
} catch (IpcException e) {
LOG.debug("IPC failed, using basic status: {}", e.getMessage());
@@ -115,9 +116,10 @@ public class ServiceStatusCommand extends BaseCommand {
int succeeded = countJobsByState(effectiveBarnDir, JobState.SUCCEEDED);
int failed = countJobsByState(effectiveBarnDir, JobState.FAILED);
int canceled = countJobsByState(effectiveBarnDir, JobState.CANCELED);
int killed = countJobsByState(effectiveBarnDir, JobState.KILLED);
return ServiceStatus.running(pid, startTime, running, queued, succeeded, failed, canceled,
total, effectiveBarnDir, serviceManager);
killed, total, effectiveBarnDir, serviceManager);
}
private int getIntValue(Map<String, Object> map, String key, int defaultValue) {
@@ -182,6 +184,7 @@ public class ServiceStatusCommand extends BaseCommand {
sb.append(String.format(" Succeeded: %d%n", status.succeededJobs));
sb.append(String.format(" Failed: %d%n", status.failedJobs));
sb.append(String.format(" Canceled: %d%n", status.canceledJobs));
sb.append(String.format(" Killed: %d%n", status.killedJobs));
sb.append(String.format(" Total: %d%n", status.totalJobs));
}
@@ -254,13 +257,14 @@ public class ServiceStatusCommand extends BaseCommand {
final int succeededJobs;
final int failedJobs;
final int canceledJobs;
final int killedJobs;
final int totalJobs;
final Path dataDir;
final String serviceManager;
private ServiceStatus(boolean running, long pid, Instant startedAt, long uptimeSeconds,
int runningJobs, int queuedJobs, int succeededJobs, int failedJobs, int canceledJobs,
int totalJobs, Path dataDir, String serviceManager) {
int killedJobs, int totalJobs, Path dataDir, String serviceManager) {
this.running = running;
this.pid = pid;
this.startedAt = startedAt;
@@ -270,21 +274,22 @@ public class ServiceStatusCommand extends BaseCommand {
this.succeededJobs = succeededJobs;
this.failedJobs = failedJobs;
this.canceledJobs = canceledJobs;
this.killedJobs = killedJobs;
this.totalJobs = totalJobs;
this.dataDir = dataDir;
this.serviceManager = serviceManager;
}
static ServiceStatus stopped(Path dataDir, String serviceManager) {
return new ServiceStatus(false, 0, null, 0, 0, 0, 0, 0, 0, 0, dataDir, serviceManager);
return new ServiceStatus(false, 0, null, 0, 0, 0, 0, 0, 0, 0, 0, dataDir, serviceManager);
}
static ServiceStatus running(long pid, Instant startedAt, int runningJobs, int queuedJobs,
int succeededJobs, int failedJobs, int canceledJobs, int totalJobs,
int succeededJobs, int failedJobs, int canceledJobs, int killedJobs, int totalJobs,
Path dataDir, String serviceManager) {
long uptime = Duration.between(startedAt, Instant.now()).getSeconds();
return new ServiceStatus(true, pid, startedAt, uptime, runningJobs, queuedJobs,
succeededJobs, failedJobs, canceledJobs, totalJobs, dataDir, serviceManager);
succeededJobs, failedJobs, canceledJobs, killedJobs, totalJobs, dataDir, serviceManager);
}
Map<String, Object> toMap() {
@@ -303,6 +308,7 @@ public class ServiceStatusCommand extends BaseCommand {
jobs.put("succeeded", succeededJobs);
jobs.put("failed", failedJobs);
jobs.put("canceled", canceledJobs);
jobs.put("killed", killedJobs);
jobs.put("total", totalJobs);
map.put("jobs", jobs);
}
@@ -1,6 +1,7 @@
package com.samsonmedia.barn.execution;
import java.io.IOException;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
@@ -8,8 +9,10 @@ import java.util.Objects;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.samsonmedia.barn.config.Config;
import com.samsonmedia.barn.jobs.Job;
import com.samsonmedia.barn.jobs.JobRepository;
import com.samsonmedia.barn.jobs.RetryCalculator;
import com.samsonmedia.barn.state.BarnDirectories;
import com.samsonmedia.barn.state.JobState;
@@ -23,17 +26,19 @@ import com.samsonmedia.barn.state.JobState;
* <li>Its process is no longer alive (or PID is unknown)</li>
* </ul>
*
* <p>Orphaned jobs are marked as failed with a symbolic exit code.
* <p>Orphaned jobs are marked as KILLED and automatically scheduled for retry
* if retries are configured and not exhausted.
*/
public class CrashRecovery {
private static final Logger LOG = LoggerFactory.getLogger(CrashRecovery.class);
private static final String ORPHANED_EXIT_CODE = "orphaned_process";
private static final String ORPHANED_ERROR = "Process orphaned - daemon restarted";
private static final String KILLED_ERROR = "Process killed - daemon restarted";
private final JobRepository repository;
private final HeartbeatChecker heartbeatChecker;
private final BarnDirectories dirs;
private final RetryCalculator retryCalculator;
private final int maxRetries;
/**
* Creates a CrashRecovery instance.
@@ -41,11 +46,16 @@ public class CrashRecovery {
* @param repository the job repository
* @param heartbeatChecker the heartbeat checker
* @param dirs the directory manager
* @param config the configuration
*/
public CrashRecovery(JobRepository repository, HeartbeatChecker heartbeatChecker, BarnDirectories dirs) {
public CrashRecovery(JobRepository repository, HeartbeatChecker heartbeatChecker, BarnDirectories dirs,
Config config) {
this.repository = Objects.requireNonNull(repository, "repository must not be null");
this.heartbeatChecker = Objects.requireNonNull(heartbeatChecker, "heartbeatChecker must not be null");
this.dirs = Objects.requireNonNull(dirs, "dirs must not be null");
Objects.requireNonNull(config, "config must not be null");
this.retryCalculator = new RetryCalculator(config.jobs());
this.maxRetries = config.jobs().maxRetries();
}
/**
@@ -128,6 +138,18 @@ public class CrashRecovery {
private void recoverJob(Job job) throws IOException {
LOG.info("Recovering orphaned job: {} (PID: {})", job.id(), job.pid());
repository.markFailed(job.id(), ORPHANED_EXIT_CODE, ORPHANED_ERROR);
// Mark the job as killed
repository.markKilled(job.id(), KILLED_ERROR);
// Check if we should auto-retry
if (maxRetries > 0 && job.retryCount() < maxRetries) {
// Schedule retry with exponential backoff
Instant retryAt = Instant.now().plus(retryCalculator.calculateDelay(job.retryCount()));
repository.scheduleRetry(job.id(), retryAt, null, KILLED_ERROR);
LOG.info("Job {} scheduled for auto-retry at {} (attempt {})",
job.id(), retryAt, job.retryCount() + 1);
} else {
LOG.info("Job {} will not be retried (retries exhausted or disabled)", job.id());
}
}
}
@@ -257,6 +257,27 @@ public class JobRepository {
LOG.info("Job {} failed: {}", id, symbolicCode);
}
/**
* Marks a job as killed (orphaned when service was terminated).
*
* @param id the job ID
* @param error the error message
* @throws IOException if update fails
*/
public void markKilled(String id, String error) throws IOException {
Objects.requireNonNull(id, "id must not be null");
StateFiles stateFiles = new StateFiles(dirs.getJobDir(id));
updateState(id, JobState.KILLED);
stateFiles.writeFinishedAt(Instant.now());
if (error != null) {
stateFiles.writeError(error);
}
LOG.info("Job {} killed: {}", id, error);
}
/**
* Schedules a job for retry.
*
@@ -13,20 +13,22 @@ import com.samsonmedia.barn.state.JobState;
* <p>Valid transitions:
* <ul>
* <li>QUEUED → RUNNING, FAILED, CANCELED</li>
* <li>RUNNING → SUCCEEDED, FAILED, CANCELED</li>
* <li>RUNNING → SUCCEEDED, FAILED, CANCELED, KILLED</li>
* <li>FAILED → QUEUED (for retry)</li>
* <li>SUCCEEDED → (none, terminal)</li>
* <li>CANCELED → (none, terminal)</li>
* <li>KILLED → QUEUED (for retry)</li>
* </ul>
*/
public final class JobStateMachine {
private static final Map<JobState, Set<JobState>> VALID_TRANSITIONS = Map.of(
JobState.QUEUED, Set.of(JobState.RUNNING, JobState.FAILED, JobState.CANCELED),
JobState.RUNNING, Set.of(JobState.SUCCEEDED, JobState.FAILED, JobState.CANCELED),
JobState.RUNNING, Set.of(JobState.SUCCEEDED, JobState.FAILED, JobState.CANCELED, JobState.KILLED),
JobState.FAILED, Set.of(JobState.QUEUED), // For retry
JobState.SUCCEEDED, Set.of(),
JobState.CANCELED, Set.of()
JobState.CANCELED, Set.of(),
JobState.KILLED, Set.of(JobState.QUEUED) // For retry
);
private JobStateMachine() {
@@ -69,7 +69,7 @@ public class BarnService {
Duration heartbeatThreshold = Duration.ofSeconds(config.service().staleHeartbeatThresholdSeconds());
HeartbeatChecker heartbeatChecker = new HeartbeatChecker(heartbeatThreshold);
this.crashRecovery = new CrashRecovery(repository, heartbeatChecker, dirs);
this.crashRecovery = new CrashRecovery(repository, heartbeatChecker, dirs, config);
this.shutdownLatch = new CountDownLatch(1);
this.running = new AtomicBoolean(false);
@@ -17,7 +17,10 @@ public enum JobState {
FAILED,
/** Job was manually canceled. */
CANCELED;
CANCELED,
/** Job was killed when the service was terminated unexpectedly. */
KILLED;
/**
* Parses a job state from a string (case-insensitive).
@@ -33,8 +36,8 @@ public enum JobState {
try {
return valueOf(value.trim().toUpperCase());
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(
"Invalid job state: '" + value + "'. Valid values are: queued, running, succeeded, failed, canceled");
throw new IllegalArgumentException("Invalid job state: '" + value
+ "'. Valid values are: queued, running, succeeded, failed, canceled, killed");
}
}
@@ -53,7 +56,7 @@ public enum JobState {
* @return true if the job is in a terminal state
*/
public boolean isTerminal() {
return this == SUCCEEDED || this == FAILED || this == CANCELED;
return this == SUCCEEDED || this == FAILED || this == CANCELED || this == KILLED;
}
/**