Mark timed out and stale imports as failed in the prune command

The job's failed() handler can not mark a timed out import as failed, since
the timeout handler runs while the import transaction is still open and the
change is rolled back when the worker is killed. It also must not mark the
import as failed when the queue hands out the job a second time after
retry_after, while the first attempt is still running.

Running imports are now considered stale shortly after the job timeout and
the prune command runs every five minutes.
This commit is contained in:
Constantin Graf
2026-11-11 18:26:48 +01:00
committed by Constantin Graf
parent cecaa429c9
commit a440687a41
6 changed files with 82 additions and 18 deletions

View File

@@ -4,9 +4,11 @@ declare(strict_types=1);
namespace App\Console\Commands\Import;
use App\Enums\ImportStatus;
use App\Models\Import;
use App\Service\Import\ImportService;
use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Storage;
@@ -14,10 +16,18 @@ use Illuminate\Support\Facades\Storage;
class ImportPruneCommand extends Command
{
/**
* Time in seconds an active import can exceed the job timeout before it is considered stale,
* Time in seconds a running import can exceed the job timeout before it is considered stale.
* The queue worker kills the job after the timeout, so this only needs to cover small delays.
* Note: The job itself can not mark a timed out import as failed, since the timeout handler runs while the
* import transaction is still open and the change is rolled back when the worker is killed.
*/
private const int RUNNING_STALE_BUFFER_SECONDS = 300;
/**
* Time in seconds a pending import can exceed the job timeout before it is considered stale,
* this covers the time the job waits in the queue.
*/
private const int STALE_BUFFER_SECONDS = 3600;
private const int PENDING_STALE_BUFFER_SECONDS = 3600;
/**
* The name and signature of the console command.
@@ -44,11 +54,20 @@ class ImportPruneCommand extends Command
$this->comment('Running in dry-run mode. Nothing will be saved or deleted.');
}
$staleBefore = Carbon::now()->subSeconds((int) config('import.job_timeout') + self::STALE_BUFFER_SECONDS);
$jobTimeout = (int) config('import.job_timeout');
$runningStaleBefore = Carbon::now()->subSeconds($jobTimeout + self::RUNNING_STALE_BUFFER_SECONDS);
$pendingStaleBefore = Carbon::now()->subSeconds($jobTimeout + self::PENDING_STALE_BUFFER_SECONDS);
$staleImports = 0;
Import::query()
->active()
->where('updated_at', '<', $staleBefore)
->where(function (Builder $query) use ($runningStaleBefore, $pendingStaleBefore): void {
$query->where(function (Builder $query) use ($runningStaleBefore): void {
$query->where('status', ImportStatus::Running)
->where('started_at', '<', $runningStaleBefore);
})->orWhere(function (Builder $query) use ($pendingStaleBefore): void {
$query->where('status', ImportStatus::Pending)
->where('created_at', '<', $pendingStaleBefore);
});
})
->orderBy('created_at', 'asc')
->chunkById(500, function (Collection $imports) use ($dryRun, $importService, &$staleImports): void {
/** @var Collection<int, Import> $imports */

View File

@@ -46,7 +46,7 @@ class Kernel extends ConsoleKernel
$schedule->command('import:prune')
->when(fn (): bool => config('scheduling.tasks.import_prune'))
->hourly();
->everyFiveMinutes();
$schedule->command('self-host:database-consistency')
->when(fn (): bool => config('scheduling.tasks.self_hosting_database_consistency'))

View File

@@ -11,6 +11,7 @@ use Illuminate\Contracts\Events\ShouldDispatchAfterCommit;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\MaxAttemptsExceededException;
use Illuminate\Queue\SerializesModels;
use Throwable;
@@ -28,8 +29,6 @@ class ProcessImport implements ShouldDispatchAfterCommit, ShouldQueue
/**
* Imports are not retried, since a failed import is rolled back and the user has to fix the import data.
* Note: The "retry_after" of the queue connection needs to be higher than the timeout,
* otherwise a long-running import is started a second time.
*/
public int $tries = 1;
@@ -56,10 +55,20 @@ class ProcessImport implements ShouldDispatchAfterCommit, ShouldQueue
}
/**
* Handle a job failure, for example a timeout.
* Handle a job failure.
*/
public function failed(?Throwable $exception): void
{
// A MaxAttemptsExceededException is thrown in two cases where the import must not be marked as failed here:
// - The import runs longer than the "retry_after" of the queue connection and the queue hands out the job
// a second time, while the first attempt is still running.
// - The import timed out (TimeoutExceededException). The timeout handler runs while the import transaction
// is still open, so the change would be rolled back when the worker is killed.
// In both cases the import:prune command marks the import as failed if it is really stale.
if ($exception instanceof MaxAttemptsExceededException) {
return;
}
$this->import->refresh();
if ($this->import->status->isActive()) {
app(ImportService::class)->markAsFailed($this->import, 'Import could not be finished');

View File

@@ -50,10 +50,9 @@ return [
| Import job
|--------------------------------------------------------------------------
|
| Imports are processed by a queued job. The timeout is in seconds, the
| "retry_after" of the queue connection needs to be higher than the
| timeout. The queue is the queue name the job is pushed to, null
| means the default queue of the connection.
| Imports are processed by a queued job. The timeout is in seconds. The
| queue is the queue name the job is pushed to, null means the default
| queue of the connection.
|
*/

View File

@@ -30,16 +30,20 @@ class ImportPruneCommandTest extends TestCaseWithDatabase
{
// Arrange
$stalePending = Import::factory()->create([
'updated_at' => now()->subHours(3),
'created_at' => now()->subHours(3),
]);
$recentPending = Import::factory()->create([
'created_at' => now()->subMinutes(90),
]);
$staleRunning = Import::factory()->running()->create([
'updated_at' => now()->subHours(3),
'started_at' => now()->subMinutes(70),
]);
$recentRunning = Import::factory()->running()->create([
'updated_at' => now()->subHour(),
'started_at' => now()->subMinutes(50),
]);
$oldCompleted = Import::factory()->completed()->create([
'updated_at' => now()->subHours(3),
'created_at' => now()->subHours(3),
'started_at' => now()->subHours(3),
]);
// Act
@@ -50,6 +54,7 @@ class ImportPruneCommandTest extends TestCaseWithDatabase
$this->assertStringContainsString('Marked 2 stale imports as failed and deleted 0 import files.', Artisan::output());
$this->assertSame(ImportStatus::Failed, $stalePending->refresh()->status);
$this->assertSame('Import could not be finished', $stalePending->error_message);
$this->assertSame(ImportStatus::Pending, $recentPending->refresh()->status);
$this->assertSame(ImportStatus::Failed, $staleRunning->refresh()->status);
$this->assertSame(ImportStatus::Running, $recentRunning->refresh()->status);
$this->assertSame(ImportStatus::Completed, $oldCompleted->refresh()->status);
@@ -88,7 +93,7 @@ class ImportPruneCommandTest extends TestCaseWithDatabase
$disk = Storage::disk(config('filesystems.private'));
$disk->put('import/old', 'old');
$staleImport = Import::factory()->running()->create([
'updated_at' => now()->subHours(3),
'started_at' => now()->subHours(3),
]);
$oldImport = Import::factory()->completed()->create([
'file_path' => 'import/old',

View File

@@ -8,6 +8,8 @@ use App\Enums\ImportStatus;
use App\Jobs\ProcessImport;
use App\Models\Import;
use App\Service\Import\ImportService;
use Illuminate\Queue\MaxAttemptsExceededException;
use Illuminate\Queue\TimeoutExceededException;
use Mockery\MockInterface;
use PHPUnit\Framework\Attributes\CoversClass;
use RuntimeException;
@@ -77,4 +79,34 @@ class ProcessImportTest extends TestCaseWithDatabase
$this->assertSame(ImportStatus::Completed, $import->status);
$this->assertNull($import->error_message);
}
public function test_failed_does_not_mark_import_as_failed_if_job_was_handed_out_again_while_still_running(): void
{
// Arrange
$import = Import::factory()->running()->create();
$job = new ProcessImport($import);
// Act
$job->failed(new MaxAttemptsExceededException('App\\Jobs\\ProcessImport has been attempted too many times.'));
// Assert
$import->refresh();
$this->assertSame(ImportStatus::Running, $import->status);
$this->assertNull($import->error_message);
}
public function test_failed_does_not_mark_import_as_failed_on_timeout(): void
{
// Arrange
$import = Import::factory()->running()->create();
$job = new ProcessImport($import);
// Act
$job->failed(new TimeoutExceededException('App\\Jobs\\ProcessImport has timed out.'));
// Assert
$import->refresh();
$this->assertSame(ImportStatus::Running, $import->status);
$this->assertNull($import->error_message);
}
}