Skip to content

An open-source, self-hostable PaaS alternative to Vercel, Heroku & Netlify that lets you easily deploy static sites, databases, full-stack applications and 360+ one-click services on your own servers.

fix(scheduler): read fresh server state in each job and log scheduling decisions

Andras Bacsaid28bc91ff52e
diff --git a/app/Jobs/DatabaseBackupJob.php b/app/Jobs/DatabaseBackupJob.php
index 2cafb8558b..31fa878f85 100644
--- a/app/Jobs/DatabaseBackupJob.php
+++ b/app/Jobs/DatabaseBackupJob.php
@@ -107,6 +107,7 @@ class DatabaseBackupJob implements ShouldBeEncrypted, ShouldQueue
$this->team = Team::find($this->backup->team_id);
if (! $this->team) {
+ $this->logSkippedRun('team_not_found');
$this->backup->delete();
return;
@@ -133,11 +134,7 @@ class DatabaseBackupJob implements ShouldBeEncrypted, ShouldQueue
$status = str(data_get($this->database, 'status'));
if (! $status->startsWith('running') && $this->database->id !== 0) {
- Log::info('DatabaseBackupJob skipped: database not running', [
- 'backup_id' => $this->backup->id,
- 'database_id' => $this->database->id,
- 'status' => (string) $status,
- ]);
+ $this->logSkippedRun('database_not_running', ['database_status' => (string) $status]);
return;
}
@@ -286,11 +283,15 @@ class DatabaseBackupJob implements ShouldBeEncrypted, ShouldQueue
} elseif ($this->database instanceof StandaloneSqlite) {
$databasesToBackup = $this->database->sqlite_databases;
} else {
+ $this->logSkippedRun('unsupported_database_type', ['service_database_type' => $databaseType]);
+
return;
}
}
$databasesToBackup = $this->databasesToBackup($databaseType, $databasesToBackup);
if ($databasesToBackup === []) {
+ $this->logSkippedRun('no_databases_selected');
+
return;
}
$this->backup_dir = backup_dir().'/databases/'.str($this->team->name)->slug().'-'.$this->team->id.'/'.$this->directory_name;
@@ -890,6 +891,24 @@ class DatabaseBackupJob implements ShouldBeEncrypted, ShouldQueue
return $dumpCommand.' | docker run --rm -i '.escapeshellarg($this->getFullImageName()).' sh -c '.escapeshellarg($script);
}
+ /**
+ * Log a run that ends without a backup execution, so it does not look like a missed schedule.
+ *
+ * @param array<string, mixed> $context
+ */
+ private function logSkippedRun(string $reason, array $context = []): void
+ {
+ Log::channel('scheduled')->warning('Database backup job ended without a backup', [
+ 'skip_reason' => $reason,
+ 'backup_id' => $this->backup->id,
+ 'database_id' => $this->backup->database_id,
+ 'database_type' => $this->backup->database_type,
+ 'team_id' => $this->backup->team_id,
+ 'occurrence_uuid' => $this->occurrenceUuid,
+ ...$context,
+ ]);
+ }
+
private function markStaleExecutionsAsFailed(): void
{
try {
diff --git a/app/Jobs/ScheduledJobManager.php b/app/Jobs/ScheduledJobManager.php
index 3bfb30c7c1..7a051345e3 100644
--- a/app/Jobs/ScheduledJobManager.php
+++ b/app/Jobs/ScheduledJobManager.php
@@ -8,6 +8,8 @@ use App\Models\ScheduledTask;
use App\Models\ScheduledVolumeBackup;
use App\Models\ScheduledVolumeBackupExecution;
use App\Models\Server;
+use App\Models\ServerSetting;
+use App\Models\Subscription;
use App\Models\Team;
use App\Services\ScheduledJobDeliveryService;
use Cron\CronExpression;
@@ -99,9 +101,7 @@ class ScheduledJobManager implements ShouldQueue
$this->dispatchedCount = 0;
$this->skippedCount = 0;
- Log::channel('scheduled')->info('ScheduledJobManager started', [
- 'execution_time' => $this->executionTime->toIso8601String(),
- ]);
+ $this->logStart();
app(ScheduledJobDeliveryService::class)->publishPending();
@@ -140,6 +140,11 @@ class ScheduledJobManager implements ShouldQueue
'duration_ms' => $this->executionTime->diffInMilliseconds(Carbon::now()),
'dispatched' => $this->dispatchedCount,
'skipped' => $this->skippedCount,
+ 'host' => gethostname(),
+ 'pid' => getmypid(),
+ 'memory_mb' => round(memory_get_usage(true) / 1048576, 1),
+ 'memory_peak_mb' => round(memory_get_peak_usage(true) / 1048576, 1),
+ 'open_occurrences_over_15_minutes' => rescue(fn () => app(ScheduledJobDeliveryService::class)->staleOpenOccurrenceCounts(), [], report: false),
]);
// Write heartbeat so the UI can detect when the scheduler has stopped
@@ -150,6 +155,33 @@ class ScheduledJobManager implements ShouldQueue
}
}
+ /**
+ * Log which worker runs the manager and how late it starts. The manager only catches up
+ * occurrences from the last CATCH_UP_WINDOW_MINUTES, so a larger delay skips them silently.
+ */
+ private function logStart(): void
+ {
+ $previousStartedAt = rescue(fn () => Cache::get('scheduled-job-manager:last-started-at'), report: false);
+ rescue(fn () => Cache::put('scheduled-job-manager:last-started-at', $this->executionTime->toIso8601String(), 86400), report: false);
+ $queuedAt = data_get($this->job?->payload(), 'createdAt');
+
+ $context = [
+ 'execution_time' => $this->executionTime->toIso8601String(),
+ 'host' => gethostname(),
+ 'pid' => getmypid(),
+ 'queue_wait_seconds' => $queuedAt ? $this->executionTime->timestamp - (int) $queuedAt : null,
+ 'seconds_since_previous_start' => $previousStartedAt ? (int) Carbon::parse($previousStartedAt)->diffInSeconds($this->executionTime) : null,
+ 'memory_mb' => round(memory_get_usage(true) / 1048576, 1),
+ ];
+
+ Log::channel('scheduled')->info('ScheduledJobManager started', $context);
+
+ $catchUpWindowSeconds = ScheduledJobDeliveryService::CATCH_UP_WINDOW_MINUTES * 60;
+ if ($context['queue_wait_seconds'] > $catchUpWindowSeconds || $context['seconds_since_previous_start'] > $catchUpWindowSeconds) {
+ Log::channel('scheduled-errors')->warning('ScheduledJobManager started late; occurrences due before the catch-up window were not run', $context);
+ }
+ }
+
private function processScheduledBackupsAndTasks(): void
{
$lastBackupId = null;
@@ -294,7 +326,7 @@ class ScheduledJobManager implements ShouldQueue
if ($skipReason !== null) {
if ($server === null || $this->recordSkippedOccurrence($backup->frequency, $server, "scheduled-backup:{$backup->id}")) {
$this->skippedCount++;
- $this->logBackupSkip($backup, $skipReason);
+ $this->logBackupSkip($backup, $skipReason, $server);
}
return;
@@ -449,7 +481,7 @@ class ScheduledJobManager implements ShouldQueue
$this->logSkip('volume_backup', 'server_not_functional', [
'backup_id' => $backup->id,
'team_id' => $backup->team_id,
- 'server_id' => $server->id,
+ ...$this->serverStateContext($server),
]);
}
@@ -462,7 +494,7 @@ class ScheduledJobManager implements ShouldQueue
$this->logSkip('volume_backup', 'subscription_unpaid', [
'backup_id' => $backup->id,
'team_id' => $backup->team_id,
- 'server_id' => $server->id,
+ ...$this->serverStateContext($server),
]);
}
@@ -712,13 +744,14 @@ class ScheduledJobManager implements ShouldQueue
return validate_timezone($timezone) ? $timezone : config('app.timezone');
}
- private function logBackupSkip(ScheduledDatabaseBackup $backup, string $reason): void
+ private function logBackupSkip(ScheduledDatabaseBackup $backup, string $reason, ?Server $server): void
{
$this->logSkip('backup', $reason, [
'backup_id' => $backup->id,
'database_id' => $backup->database_id,
'database_type' => $backup->database_type,
'team_id' => $backup->team_id ?? null,
+ ...$this->serverStateContext($server),
]);
}
@@ -728,6 +761,37 @@ class ScheduledJobManager implements ShouldQueue
'task_id' => $task->id,
'task_name' => $task->name,
'team_id' => $server?->team_id,
+ ...$this->serverStateContext($server),
]);
}
+
+ /**
+ * Compare the server state that decided the skip with the current database state.
+ * A difference shows that the worker used stale server data.
+ *
+ * @return array<string, mixed>
+ */
+ private function serverStateContext(?Server $server): array
+ {
+ if ($server === null) {
+ return [];
+ }
+
+ $settings = ServerSetting::query()
+ ->where('server_id', $server->id)
+ ->first(['is_reachable', 'is_usable', 'force_disabled']);
+
+ return [
+ 'server_id' => $server->id,
+ 'server_ip_is_placeholder' => $server->hasPlaceholderIp(),
+ 'used_is_reachable' => data_get($server->settings, 'is_reachable'),
+ 'used_is_usable' => data_get($server->settings, 'is_usable'),
+ 'used_force_disabled' => data_get($server->settings, 'force_disabled'),
+ 'used_invoice_paid' => data_get($server->team?->subscription, 'stripe_invoice_paid'),
+ 'db_is_reachable' => $settings?->is_reachable,
+ 'db_is_usable' => $settings?->is_usable,
+ 'db_force_disabled' => $settings?->force_disabled,
+ 'db_invoice_paid' => Subscription::query()->where('team_id', $server->team_id)->value('stripe_invoice_paid'),
+ ];
+ }
}
diff --git a/app/Jobs/ServerConnectionCheckJob.php b/app/Jobs/ServerConnectionCheckJob.php
index 97d211d247..182164b35e 100644
--- a/app/Jobs/ServerConnectionCheckJob.php
+++ b/app/Jobs/ServerConnectionCheckJob.php
@@ -16,6 +16,7 @@ use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\TimeoutExceededException;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Process;
+use Illuminate\Support\Str;
class ServerConnectionCheckJob implements ShouldBeEncrypted, ShouldQueue
{
@@ -25,6 +26,8 @@ class ServerConnectionCheckJob implements ShouldBeEncrypted, ShouldQueue
public $timeout = 15;
+ private ?string $connectionError = null;
+
public function __construct(
public Server $server,
public bool $disableMux = true
@@ -48,6 +51,7 @@ class ServerConnectionCheckJob implements ShouldBeEncrypted, ShouldQueue
}
$wasReachable = (bool) $this->server->settings->is_reachable;
+ $wasUsable = (bool) $this->server->settings->is_usable;
$wasNotified = (bool) $this->server->unreachable_notification_sent;
try {
@@ -61,6 +65,7 @@ class ServerConnectionCheckJob implements ShouldBeEncrypted, ShouldQueue
'server_id' => $this->server->id,
'server_name' => $this->server->name,
]);
+ $this->logConnectionStateChange($wasReachable, $wasUsable, false, false, 'force_disabled');
return;
}
@@ -85,6 +90,7 @@ class ServerConnectionCheckJob implements ShouldBeEncrypted, ShouldQueue
'server_name' => $this->server->name,
'server_ip' => $this->server->ip,
]);
+ $this->logConnectionStateChange($wasReachable, $wasUsable, false, false, $this->connectionError);
$this->dispatchReachabilityChangedIfNeeded($wasReachable, $wasNotified, false);
@@ -98,6 +104,7 @@ class ServerConnectionCheckJob implements ShouldBeEncrypted, ShouldQueue
'is_reachable' => true,
'is_usable' => $isUsable,
]);
+ $this->logConnectionStateChange($wasReachable, $wasUsable, true, $isUsable, $isUsable ? null : 'docker_not_available');
if ($this->server->unreachable_count > 0) {
// Direct assignment: unreachable_count is not mass-assignable,
@@ -119,6 +126,7 @@ class ServerConnectionCheckJob implements ShouldBeEncrypted, ShouldQueue
'is_usable' => false,
]);
$this->server->increment('unreachable_count');
+ $this->logConnectionStateChange($wasReachable, $wasUsable, false, false, $e->getMessage());
$this->dispatchReachabilityChangedIfNeeded($wasReachable, $wasNotified, false);
@@ -126,6 +134,29 @@ class ServerConnectionCheckJob implements ShouldBeEncrypted, ShouldQueue
}
}
+ /**
+ * Log a change of the state that scheduled jobs use to skip a server, with the node that ran
+ * the check. On a multi-node instance this shows when only one node cannot reach a server.
+ */
+ private function logConnectionStateChange(bool $wasReachable, bool $wasUsable, bool $isReachable, bool $isUsable, ?string $reason): void
+ {
+ if ($wasReachable === $isReachable && $wasUsable === $isUsable) {
+ return;
+ }
+
+ Log::channel('scheduled')->info('Server connection state changed', [
+ 'server_id' => $this->server->id,
+ 'is_reachable' => $isReachable,
+ 'is_usable' => $isUsable,
+ 'was_reachable' => $wasReachable,
+ 'was_usable' => $wasUsable,
+ 'unreachable_count' => $this->server->unreachable_count,
+ 'reason' => $reason,
+ 'host' => gethostname(),
+ 'pid' => getmypid(),
+ ]);
+ }
+
public function failed(?\Throwable $exception): void
{
if ($exception instanceof TimeoutExceededException) {
@@ -166,9 +197,13 @@ class ServerConnectionCheckJob implements ShouldBeEncrypted, ShouldQueue
$sshCommand = SshMultiplexingHelper::generateSshCommand($this->server, $commandString, true);
$process = Process::timeout(10)->run($sshCommand);
+ if ($process->exitCode() !== 0) {
+ $this->connectionError = 'ssh exit '.$process->exitCode().': '.Str::limit(trim($process->errorOutput()), 300);
+ }
return $process->exitCode() === 0;
} catch (\Throwable $e) {
+ $this->connectionError = $e->getMessage();
Log::debug('ServerConnectionCheck: Connection check failed', [
'server_id' => $this->server->id,
'error' => $e->getMessage(),
diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php
index 27f095ac45..1d41c94034 100644
--- a/app/Providers/AppServiceProvider.php
+++ b/app/Providers/AppServiceProvider.php
@@ -6,6 +6,7 @@ use App\Auth\Oidc\OidcDiscoveryService;
use App\Auth\Oidc\OidcTokenValidator;
use App\Auth\Oidc\Socialite\OidcProvider;
use App\Models\PersonalAccessToken;
+use App\Models\Server;
use App\Rules\SafeExternalUrl;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\App;
@@ -40,11 +41,15 @@ class AppServiceProvider extends ServiceProvider
/**
* Queue workers are long-running processes, so once() values (e.g. instanceSettings())
- * would stay stale across jobs. Flush them before each job, like a fresh web request.
+ * and the Server identity map would stay stale across jobs. Flush them before each job,
+ * like a fresh web request.
*/
private function configureQueue(): void
{
- Queue::before(fn () => Once::flush());
+ Queue::before(function (): void {
+ Once::flush();
+ Server::flushIdentityMap();
+ });
}
private function configureCommands(): void
diff --git a/app/Services/ScheduledJobDeliveryService.php b/app/Services/ScheduledJobDeliveryService.php
index 0bd4c031c5..3a8c09e5d4 100644
--- a/app/Services/ScheduledJobDeliveryService.php
+++ b/app/Services/ScheduledJobDeliveryService.php
@@ -15,6 +15,7 @@ use App\Models\Server;
use Cron\CronExpression;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Facades\Log;
class ScheduledJobDeliveryService
{
@@ -117,11 +118,38 @@ class ScheduledJobDeliveryService
->orderBy('id')
->chunkById(100, function ($occurrences): void {
foreach ($occurrences as $occurrence) {
- $this->publish($occurrence);
+ try {
+ $this->logOccurrence($occurrence, 'Scheduled occurrence publishing again', 'warning');
+ $this->publish($occurrence);
+ } catch (\Throwable $e) {
+ Log::channel('scheduled-errors')->error('Failed to publish pending scheduled occurrence', [
+ 'occurrence_uuid' => $occurrence->uuid,
+ 'schedule_key' => $occurrence->schedule_key,
+ 'error' => $e->getMessage(),
+ ]);
+ }
}
});
}
+ /**
+ * Count occurrences that are still open 15 minutes after they were created. Pending or
+ * enqueued rows here never started; claimed rows are still running or their worker died.
+ *
+ * @return array<string, int>
+ */
+ public function staleOpenOccurrenceCounts(): array
+ {
+ return ScheduledJobDelivery::query()
+ ->whereIn('status', ['pending', 'enqueued', 'claimed'])
+ ->where('created_at', '<', now()->subMinutes(15))
+ ->selectRaw('status, count(*) as aggregate')
+ ->groupBy('status')
+ ->pluck('aggregate', 'status')
+ ->map(fn ($count) => (int) $count)
+ ->all();
+ }
+
public function deleteOldOccurrences(): void
{
ScheduledJobDelivery::query()
@@ -150,21 +178,22 @@ class ScheduledJobDeliveryService
'claim_token' => $claimToken,
'started_at' => now(),
'updated_at' => now(),
- ]);
+ ]) === 1
+ || ScheduledJobDelivery::query()
+ ->where('uuid', $uuid)
+ ->where('status', 'claimed')
+ ->where('claim_token', $claimToken)
+ ->exists();
- if ($claimed === 1) {
- return true;
- }
+ $this->logOccurrence($uuid, $claimed ? 'Scheduled occurrence claimed' : 'Scheduled occurrence claim rejected', $claimed ? 'info' : 'warning');
- return ScheduledJobDelivery::query()
- ->where('uuid', $uuid)
- ->where('status', 'claimed')
- ->where('claim_token', $claimToken)
- ->exists();
+ return $claimed;
}
public function complete(string $uuid, string $claimToken): void
{
+ $this->logOccurrence($uuid, 'Scheduled occurrence completed', context: ['status' => 'completed']);
+
ScheduledJobDelivery::query()
->where('uuid', $uuid)
->where('claim_token', $claimToken)
@@ -180,6 +209,39 @@ class ScheduledJobDeliveryService
'status' => 'failed',
'updated_at' => now(),
]);
+
+ $this->logOccurrence($uuid, 'Scheduled occurrence failed', 'warning');
+ }
+
+ /**
+ * Log one step of an occurrence. Search scheduled.log for its schedule_key to see when it
+ * was due, when a worker started it, and how it ended.
+ *
+ * @param array<string, mixed> $context
+ */
+ private function logOccurrence(ScheduledJobDelivery|string $occurrence, string $message, string $level = 'info', array $context = []): void
+ {
+ try {
+ $uuid = is_string($occurrence) ? $occurrence : $occurrence->uuid;
+ if (is_string($occurrence)) {
+ $occurrence = ScheduledJobDelivery::query()->where('uuid', $uuid)->first();
+ }
+
+ Log::channel('scheduled')->log($level, $message, [
+ 'occurrence_uuid' => $uuid,
+ 'schedule_key' => $occurrence?->schedule_key,
+ 'status' => $occurrence?->status,
+ 'scheduled_for' => $occurrence?->scheduled_for?->toIso8601String(),
+ 'enqueued_at' => $occurrence?->enqueued_at?->toIso8601String(),
+ 'started_at' => $occurrence?->started_at?->toIso8601String(),
+ 'seconds_since_due' => $occurrence ? (int) $occurrence->scheduled_for->diffInSeconds(now()) : null,
+ 'host' => gethostname(),
+ 'pid' => getmypid(),
+ ...$context,
+ ]);
+ } catch (\Throwable) {
+ // Debug logging must never change the job result.
+ }
}
private function publish(ScheduledJobDelivery $occurrence): bool
@@ -212,10 +274,24 @@ class ScheduledJobDeliveryService
if ($job === null) {
ScheduledJobDelivery::query()->whereKey($occurrence->id)->update(['status' => 'skipped']);
+ Log::channel('scheduled')->warning('Scheduled occurrence skipped: resource not found', [
+ 'occurrence_uuid' => $occurrence->uuid,
+ 'schedule_key' => $occurrence->schedule_key,
+ 'scheduled_for' => $occurrence->scheduled_for->toIso8601String(),
+ ]);
return false;
}
+ // An open previous occurrence usually means the previous run is still running. Jobs with
+ // WithoutOverlapping(...)->dontRelease() then drop this one without running it.
+ $previousOpen = ScheduledJobDelivery::query()
+ ->where('schedule_key', $occurrence->schedule_key)
+ ->where('scheduled_for', '<', $occurrence->scheduled_for)
+ ->whereIn('status', ['pending', 'enqueued', 'claimed'])
+ ->orderByDesc('scheduled_for')
+ ->first(['uuid', 'status', 'scheduled_for']);
+
dispatch($job);
ScheduledJobDelivery::query()
@@ -227,6 +303,19 @@ class ScheduledJobDeliveryService
'updated_at' => now(),
]);
+ // Log from the loaded row: a fast worker can complete and delete the occurrence already.
+ $enqueued = ['status' => 'enqueued', 'enqueued_at' => now()->toIso8601String()];
+ if ($previousOpen) {
+ $this->logOccurrence($occurrence, 'Scheduled occurrence enqueued while the previous occurrence is still open', 'warning', [
+ ...$enqueued,
+ 'previous_occurrence_uuid' => $previousOpen->uuid,
+ 'previous_status' => $previousOpen->status,
+ 'previous_scheduled_for' => $previousOpen->scheduled_for->toIso8601String(),
+ ]);
+ } else {
+ $this->logOccurrence($occurrence, 'Scheduled occurrence enqueued', context: $enqueued);
+ }
+
return true;
}
}
diff --git a/tests/Feature/ScheduledJobManagerDispatchTest.php b/tests/Feature/ScheduledJobManagerDispatchTest.php
index 7ed396a641..ebb34bb8ff 100644
--- a/tests/Feature/ScheduledJobManagerDispatchTest.php
+++ b/tests/Feature/ScheduledJobManagerDispatchTest.php
@@ -1,5 +1,6 @@
<?php
+use App\Events\BackupCreated;
use App\Jobs\DatabaseBackupJob;
use App\Jobs\ScheduledJobManager;
use App\Jobs\ScheduledTaskJob;
@@ -12,17 +13,26 @@ use App\Models\ScheduledJobDelivery;
use App\Models\ScheduledJobState;
use App\Models\ScheduledTask;
use App\Models\Server;
+use App\Models\ServerSetting;
use App\Models\StandaloneDocker;
use App\Models\StandalonePostgresql;
use App\Models\Team;
use App\Services\ScheduledJobDeliveryService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Carbon;
+use Illuminate\Support\Facades\Bus;
+use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Facades\Event;
+use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Queue;
uses(RefreshDatabase::class);
+beforeEach(function () {
+ Server::flushIdentityMap();
+});
+
it('dispatches scheduled tasks across chunks', function () {
config(['constants.coolify.self_hosted' => true]);
Carbon::setTestNow(Carbon::create(2026, 5, 27, 0, 1, 0, 'UTC'));
@@ -341,6 +351,214 @@ it('does not query relationships when constructing scheduled task jobs', functio
->and($job->timeout)->toBe(300);
});
+it('reads current server settings in each queued manager run of the same worker', function () {
+ config(['constants.coolify.self_hosted' => true]);
+ Queue::fakeExcept(ScheduledJobManager::class);
+
+ $database = createScheduledBackupDatabase();
+ createScheduledDatabaseBackup($database, ['frequency' => 'daily']);
+ $serverId = $database->destination->server_id;
+ ServerSetting::query()->where('server_id', $serverId)->update(['is_reachable' => false]);
+
+ Carbon::setTestNow(Carbon::create(2026, 9, 16, 0, 5, 0, 'UTC'));
+ dispatch(new ScheduledJobManager);
+ Queue::assertNotPushed(DatabaseBackupJob::class);
+
+ // Another worker marks the server reachable again before the next daily run.
+ ServerSetting::query()->where('server_id', $serverId)->update(['is_reachable' => true]);
+
+ Carbon::setTestNow(Carbon::create(2026, 9, 17, 0, 5, 0, 'UTC'));
+ dispatch(new ScheduledJobManager);
+
+ Queue::assertPushed(DatabaseBackupJob::class, 1);
+});
+
+it('logs the current database server state when a backup is skipped', function () {
+ config(['constants.coolify.self_hosted' => true]);
+ Carbon::setTestNow(Carbon::create(2026, 9, 17, 0, 5, 0, 'UTC'));
+ Queue::fake();
+ $logPath = captureScheduledJobManagerTestLog('scheduled');
+
+ $database = createScheduledBackupDatabase();
+ $backup = createScheduledDatabaseBackup($database, ['frequency' => 'daily']);
+ ServerSetting::query()->where('server_id', $database->destination->server_id)->update(['is_reachable' => false]);
+
+ (new ScheduledJobManager)->handle();
+
+ $log = file_get_contents($logPath);
+ @unlink($logPath);
+
+ expect($log)->toContain('Backup skipped')
+ ->toContain('"skip_reason":"server_not_functional"')
+ ->toContain("\"backup_id\":{$backup->id}")
+ ->toContain('"db_is_reachable":false');
+});
+
+it('logs each step of a scheduled occurrence', function () {
+ config(['constants.coolify.self_hosted' => true]);
+ Carbon::setTestNow(Carbon::create(2026, 9, 17, 0, 5, 0, 'UTC'));
+ Queue::fake();
+ $logPath = captureScheduledJobManagerTestLog('scheduled');
+
+ $backup = createScheduledDatabaseBackup(createScheduledBackupDatabase(), ['frequency' => 'daily']);
+ (new ScheduledJobManager)->handle();
+ $occurrenceUuid = ScheduledJobDelivery::query()->where('schedule_key', "scheduled-backup:{$backup->id}")->value('uuid');
+ $service = app(ScheduledJobDeliveryService::class);
+
+ expect($service->claim($occurrenceUuid, 'worker-a'))->toBeTrue()
+ ->and($service->claim($occurrenceUuid, 'worker-b'))->toBeFalse();
+ $service->complete($occurrenceUuid, 'worker-a');
+
+ $log = file_get_contents($logPath);
+ @unlink($logPath);
+
+ expect($log)->toContain('Backup dispatched')
+ ->toContain('Scheduled occurrence enqueued')
+ ->toContain('"occurrence_uuid":"'.$occurrenceUuid.'"')
+ ->toContain('"host":"'.gethostname().'"')
+ ->toContain('Scheduled occurrence claimed')
+ ->toContain('Scheduled occurrence claim rejected')
+ ->toContain('Scheduled occurrence completed')
+ ->toContain("\"schedule_key\":\"scheduled-backup:{$backup->id}\"")
+ ->toContain('"seconds_since_due":300');
+});
+
+it('warns when the manager starts after the catch-up window', function (int $minutesSincePreviousStart, bool $expectWarning) {
+ config(['constants.coolify.self_hosted' => true]);
+ Carbon::setTestNow(Carbon::create(2026, 9, 17, 0, 30, 0, 'UTC'));
+ Queue::fake();
+ $logPath = captureScheduledJobManagerTestLog('scheduled-errors');
+ Cache::put('scheduled-job-manager:last-started-at', now()->subMinutes($minutesSincePreviousStart)->toIso8601String());
+
+ (new ScheduledJobManager)->handle();
+
+ $log = file_get_contents($logPath);
+ @unlink($logPath);
+
+ expect(str_contains($log, 'ScheduledJobManager started late'))->toBe($expectWarning);
+})->with([
+ 'normal one-minute interval' => [1, false],
+ 'twenty-minute gap' => [20, true],
+]);
+
+it('warns when an occurrence is enqueued while the previous one is still running', function () {
+ config(['constants.coolify.self_hosted' => true]);
+ Queue::fake();
+ $logPath = captureScheduledJobManagerTestLog('scheduled');
+ $backup = createScheduledDatabaseBackup(createScheduledBackupDatabase(), ['frequency' => 'daily']);
+
+ Carbon::setTestNow(Carbon::create(2026, 9, 16, 0, 5, 0, 'UTC'));
+ (new ScheduledJobManager)->handle();
+ $previousUuid = ScheduledJobDelivery::query()->where('schedule_key', "scheduled-backup:{$backup->id}")->value('uuid');
+ app(ScheduledJobDeliveryService::class)->claim($previousUuid, 'worker-a');
+
+ Carbon::setTestNow(Carbon::create(2026, 9, 17, 0, 5, 0, 'UTC'));
+ (new ScheduledJobManager)->handle();
+
+ $log = file_get_contents($logPath);
+ @unlink($logPath);
+
+ expect($log)->toContain('Scheduled occurrence enqueued while the previous occurrence is still open')
+ ->toContain('"previous_occurrence_uuid":"'.$previousUuid.'"')
+ ->toContain('"previous_status":"claimed"');
+});
+
+it('reports occurrences that stay open after fifteen minutes', function () {
+ config(['constants.coolify.self_hosted' => true]);
+ Carbon::setTestNow(Carbon::create(2026, 9, 17, 12, 30, 0, 'UTC'));
+ Queue::fake();
+ $logPath = captureScheduledJobManagerTestLog('scheduled');
+
+ foreach (['enqueued' => 20, 'claimed' => 20, 'failed' => 20] as $status => $minutesAgo) {
+ ScheduledJobDelivery::create([
+ 'schedule_key' => "scheduled-backup:{$status}",
+ 'scheduled_for' => now()->subMinutes($minutesAgo),
+ 'job_type' => 'database-backup',
+ 'resource_id' => 1,
+ 'status' => $status,
+ ])->forceFill(['created_at' => now()->subMinutes($minutesAgo)])->save();
+ }
+ ScheduledJobDelivery::create([
+ 'schedule_key' => 'scheduled-backup:recent',
+ 'scheduled_for' => now()->subMinutes(2),
+ 'job_type' => 'database-backup',
+ 'resource_id' => 1,
+ 'status' => 'enqueued',
+ ]);
+
+ (new ScheduledJobManager)->handle();
+
+ $log = file_get_contents($logPath);
+ @unlink($logPath);
+
+ expect($log)->toContain('"open_occurrences_over_15_minutes":{"claimed":1,"enqueued":1}');
+});
+
+it('keeps publishing pending occurrences after one of them fails', function () {
+ config(['constants.coolify.self_hosted' => true]);
+ Carbon::setTestNow(Carbon::create(2026, 9, 17, 0, 5, 0, 'UTC'));
+ $logPath = captureScheduledJobManagerTestLog('scheduled-errors');
+ $database = createScheduledBackupDatabase();
+ $occurrences = collect([createScheduledDatabaseBackup($database), createScheduledDatabaseBackup($database)])
+ ->map(fn (ScheduledDatabaseBackup $backup) => ScheduledJobDelivery::create([
+ 'schedule_key' => "scheduled-backup:{$backup->id}",
+ 'scheduled_for' => now()->startOfMinute(),
+ 'job_type' => 'database-backup',
+ 'resource_id' => $backup->id,
+ 'status' => 'pending',
+ ]));
+
+ $dispatchAttempts = 0;
+ Bus::shouldReceive('dispatch')->andReturnUsing(function () use (&$dispatchAttempts) {
+ if (++$dispatchAttempts === 1) {
+ throw new RuntimeException('queue connection lost');
+ }
+ });
+
+ app(ScheduledJobDeliveryService::class)->publishPending();
+
+ $log = file_get_contents($logPath);
+ @unlink($logPath);
+
+ expect($occurrences->first()->fresh()->status)->toBe('pending')
+ ->and($occurrences->last()->fresh()->status)->toBe('enqueued')
+ ->and($log)->toContain('Failed to publish pending scheduled occurrence')
+ ->toContain('queue connection lost');
+});
+
+it('logs a backup run that ends early, even when it completes before the enqueue log', function () {
+ config(['constants.coolify.self_hosted' => true]);
+ Carbon::setTestNow(Carbon::create(2026, 9, 17, 0, 5, 0, 'UTC'));
+ Event::fake([BackupCreated::class]);
+ Queue::fakeExcept([ScheduledJobManager::class, DatabaseBackupJob::class]);
+ $logPath = captureScheduledJobManagerTestLog('scheduled');
+
+ $database = createScheduledBackupDatabase();
+ $database->update(['status' => 'exited']);
+ $backup = createScheduledDatabaseBackup($database, ['frequency' => 'daily']);
+
+ dispatch(new ScheduledJobManager);
+
+ $log = file_get_contents($logPath);
+ @unlink($logPath);
+
+ expect($log)->toContain('Database backup job ended without a backup')
+ ->toContain('"skip_reason":"database_not_running"')
+ ->toContain('"database_status":"exited:unhealthy"')
+ ->toContain('Scheduled occurrence completed')
+ ->toMatch('/Scheduled occurrence enqueued \{[^\n]*"schedule_key":"scheduled-backup:'.$backup->id.'"[^\n]*"status":"enqueued"/')
+ ->and(ScheduledJobDelivery::query()->where('schedule_key', "scheduled-backup:{$backup->id}")->exists())->toBeFalse();
+});
+
+function captureScheduledJobManagerTestLog(string $channel): string
+{
+ $path = tempnam(sys_get_temp_dir(), 'coolify-scheduled-log-');
+ config(["logging.channels.{$channel}" => ['driver' => 'single', 'path' => $path, 'level' => 'debug']]);
+ Log::forgetChannel($channel);
+
+ return $path;
+}
+
function createScheduledTaskApplication(): Application
{
$team = Team::factory()->create();
diff --git a/tests/Feature/ServerConnectionCheckIsolationTest.php b/tests/Feature/ServerConnectionCheckIsolationTest.php
index 895304c7d1..e5431417c3 100644
--- a/tests/Feature/ServerConnectionCheckIsolationTest.php
+++ b/tests/Feature/ServerConnectionCheckIsolationTest.php
@@ -7,6 +7,7 @@ use App\Models\Server;
use App\Models\Team;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
+use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Process;
use Illuminate\Support\Facades\Storage;
@@ -96,3 +97,26 @@ it('resets unreachable_count after a successful connection check', function () {
expect($server->fresh()->unreachable_count)->toBe(0);
});
+
+it('logs the checking node and ssh error only when the connection state changes', function () {
+ $server = createServerForConnectionIsolationTest(['ip' => '203.0.113.10']);
+ $server->settings->update(['is_reachable' => true, 'is_usable' => true]);
+ $logPath = tempnam(sys_get_temp_dir(), 'coolify-scheduled-log-');
+ config(['logging.channels.scheduled' => ['driver' => 'single', 'path' => $logPath, 'level' => 'debug']]);
+ Log::forgetChannel('scheduled');
+ Process::fake([
+ '*' => Process::result(errorOutput: 'ssh: connect to host 203.0.113.10 port 22: Connection refused', exitCode: 255),
+ ]);
+
+ (new ServerConnectionCheckJob($server->fresh(), disableMux: false))->handle();
+ (new ServerConnectionCheckJob($server->fresh(), disableMux: false))->handle();
+
+ $log = file_get_contents($logPath);
+ @unlink($logPath);
+
+ expect(substr_count($log, 'Server connection state changed'))->toBe(1)
+ ->and($log)->toContain('"is_reachable":false')
+ ->toContain('"was_reachable":true')
+ ->toContain('ssh exit 255: ssh: connect to host 203.0.113.10 port 22: Connection refused')
+ ->toContain('"host":"'.gethostname().'"');
+});
diff --git a/tests/Unit/ServerBackoffTest.php b/tests/Unit/ServerBackoffTest.php
index 3bbf41b3a2..11a0c606af 100644
--- a/tests/Unit/ServerBackoffTest.php
+++ b/tests/Unit/ServerBackoffTest.php
@@ -132,6 +132,7 @@ describe('ServerConnectionCheckJob unreachable_count', function () {
$settings = Mockery::mock();
$settings->is_reachable = true;
+ $settings->is_usable = true;
$settings->force_disabled = false;
$settings->shouldReceive('update')
->with(['is_reachable' => false, 'is_usable' => false])