From fd0b9a61b9adba74cf7c8b68160ecfbf5a452890 Mon Sep 17 00:00:00 2001 From: Ajay Viswanathan Date: Sun, 19 Jul 2026 09:18:30 +0700 Subject: [PATCH] Adds shutdown hook to perform a final backup --- CLAUDE.md | 21 ++ README.md | 9 + .../cortex/spring/CortexProperties.java | 6 +- .../spring/backup/BackupJobConfiguration.java | 40 +++ .../backup/BackupShutdownLifecycle.java | 170 +++++++++++++ .../backup/BackupShutdownLifecycleTests.java | 232 ++++++++++++++++++ .../CortexBackupAutoConfigurationTests.java | 88 +++++++ site/configuration.html | 27 +- 8 files changed, 591 insertions(+), 2 deletions(-) create mode 100644 cortex-spring-boot-autoconfigure/src/main/java/ai/chatur/cortex/spring/backup/BackupShutdownLifecycle.java create mode 100644 cortex-spring-boot-autoconfigure/src/test/java/ai/chatur/cortex/spring/backup/BackupShutdownLifecycleTests.java diff --git a/CLAUDE.md b/CLAUDE.md index d5bd1ab..1e4f826 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -110,6 +110,27 @@ a consumer who explicitly asked for backups — the failure it produces is an ap and never backs anything up. `BackupServiceTests` pins the `TDBException`; `CortexBackupAutoConfigurationTests` pins each fail-fast. +**The shutdown backup's lifecycle phase is load-bearing.** `BackupShutdownLifecycle` takes one last +backup as the context closes and blocks until it uploads — otherwise a restart discards up to a full +`cortex.backup.interval` (24h) of approvals. `PHASE` is `Integer.MAX_VALUE - 4096`, below every phase +Boot stops before it: `SchedulerFactoryBean` at `Integer.MAX_VALUE`, graceful shutdown at +`- 1024`, the web server at `- 2048`. Raise it and the snapshot races approvals still arriving over +HTTP — silently losing the writes it exists to preserve. It also resolves the `Scheduler` through an +`ObjectProvider` **lazily, at stop time**: injecting it outright makes the bean uncreatable without +`QuartzAutoConfiguration` (which `CortexBackupAutoConfigurationTests`' runner does not register) and +forces the `SchedulerFactoryBean` to initialize while `BackupJobConfiguration` is still defining the +`JobDetail` beans it collects. + +**The shutdown backup's wait is unbounded, and that requires `stop()` to stay synchronous.** Spring's +`DefaultLifecycleProcessor` calls `SmartLifecycle.stop(Runnable)`, whose default implementation runs +`stop()` on the calling thread and then the callback — so the latch it awaits is already counted down +and `spring.lifecycle.timeout-per-shutdown-phase` never applies. Moving the upload to an executor and +counting the latch down on completion looks equivalent and silently caps it at that timeout (30s), +killing a large store's backup mid-upload on every restart. Failures, by contrast, propagate out of +`stop()`, where the processor logs them and continues closing: a bad bucket must not make the app +impossible to restart. `CortexBackupAutoConfigurationTests.shouldActuallyBackUpWhenTheContextCloses` +closes a real context and pins that a real TDB2 snapshot is uploaded. + **`CortexBackupAutoConfiguration` must not name a Quartz or AWS type in a method signature.** They're `compileOnly`, so a missing one would surface as a `NoClassDefFoundError` while Spring introspects the class, pre-empting the constructor's explanation. That's why `BackupJobConfiguration` is a separate diff --git a/README.md b/README.md index 556c76c..316fba7 100644 --- a/README.md +++ b/README.md @@ -67,6 +67,7 @@ All properties are bound under the `cortex` prefix. `ontologies`, `shapes`, and | `cortex.backup.enabled` | `false` | Whether the scheduled backup job is registered. See [Scheduled backups](#scheduled-backups) — enabling it requires `cortex.persistent=true`, an enabled S3 client, and two extra dependencies. | | `cortex.backup.interval` | `24h` | How often a backup is taken. The first runs one interval **after** startup, not at startup, so restarts do not each leave a backup behind. | | `cortex.backup.keyPrefix` | `cortex/` | Prepended verbatim to the backup's file name to form the S3 object key. Include a trailing `/` to group the objects under a folder. | +| `cortex.backup.onShutdown` | `true` | Whether a final backup is taken as the application shuts down, blocking shutdown until it has uploaded. Only applies when `cortex.backup.enabled=true`. | | `cortex.restore.enabled` | `false` | Whether the latest backup under `cortex.restore.keyPrefix` is downloaded and loaded into the store at startup. See [Restore on startup](#restore-on-startup) — enabling it requires `cortex.persistent=true`, an enabled S3 client, and the same two extra dependencies as backups. | | `cortex.restore.keyPrefix` | `cortex/` | The S3 key prefix to look for backups under. Defaults to the same value as `cortex.backup.keyPrefix`; set it to match if you customize that. | | `cortex.s3.enabled` | `false` | Whether the `S3Client` bean is registered. Independent of `cortex.backup.enabled` and `cortex.restore.enabled`, though both require it. | @@ -124,6 +125,14 @@ cortex: > **Backups require `cortex.persistent=true`.** A TDB2 backup is an admin operation on an on-disk store; the in-memory store used by default has no location to write a backup beside. Enabling backups without persistence **fails at startup** rather than booting an application that reports healthy and never backs anything up. The same is true of a missing bucket, missing static credentials, a non-positive interval, and the dependencies above. +### Backup on shutdown + +Backups are scheduled, so a restart discards every approval made since the last one — up to a full `cortex.backup.interval`, 24 hours by default. Cortex therefore takes one final backup as the context closes and **blocks shutdown until it has uploaded**. It is on by default whenever backups are enabled; set `cortex.backup.onShutdown=false` to turn it off without giving up scheduled backups. + +The final backup runs after the web server has stopped accepting requests and after the scheduler has quiesced, so it snapshots a store nothing is still writing to — including waiting out a scheduled backup that happens to be in flight. It is an ordinary backup under the same key prefix, so a restore picks it up as the most recent object with no extra configuration. + +> **The wait is deliberately unbounded.** A large store on a slow link takes as long as it takes, and a bounded wait would kill the upload partway through on exactly the stores that most need it. A backup that *fails* — bad credentials, a missing bucket — is logged and shutdown continues, so a misconfigured bucket can never make the application impossible to restart; only a genuinely slow upload holds shutdown open. If your orchestrator sends `SIGKILL` after a grace period, size that grace period against how long a backup of your store actually takes. + Backup files accumulate under `/Backups/` and are never deleted: the upload is a copy, not a move, so a bucket misconfiguration can never destroy data. Pruning them is left to whatever manages that volume — or to an S3 lifecycle rule for the uploaded copies. ## Restore on startup diff --git a/cortex-spring-boot-autoconfigure/src/main/java/ai/chatur/cortex/spring/CortexProperties.java b/cortex-spring-boot-autoconfigure/src/main/java/ai/chatur/cortex/spring/CortexProperties.java index 2e0f1eb..8e0702c 100644 --- a/cortex-spring-boot-autoconfigure/src/main/java/ai/chatur/cortex/spring/CortexProperties.java +++ b/cortex-spring-boot-autoconfigure/src/main/java/ai/chatur/cortex/spring/CortexProperties.java @@ -169,11 +169,15 @@ public record Proxy( * startup, so a restart loop does not upload a backup per restart * @param keyPrefix prepended verbatim to the backup's file name to form the S3 object key; * include a trailing {@code /} to group the objects under a folder + * @param onShutdown whether a final backup is taken while the context closes, blocking shutdown + * until it has uploaded; on by default, since the alternative is discarding up to a full + * {@code interval} of approved work on every deliberate restart */ public record Backup( @DefaultValue("false") boolean enabled, @DefaultValue("24h") Duration interval, - @DefaultValue("cortex/") String keyPrefix) {} + @DefaultValue("cortex/") String keyPrefix, + @DefaultValue("true") boolean onShutdown) {} /** * Settings for the restore-on-startup step auto-configured by {@link diff --git a/cortex-spring-boot-autoconfigure/src/main/java/ai/chatur/cortex/spring/backup/BackupJobConfiguration.java b/cortex-spring-boot-autoconfigure/src/main/java/ai/chatur/cortex/spring/backup/BackupJobConfiguration.java index beab69b..19c8032 100644 --- a/cortex-spring-boot-autoconfigure/src/main/java/ai/chatur/cortex/spring/backup/BackupJobConfiguration.java +++ b/cortex-spring-boot-autoconfigure/src/main/java/ai/chatur/cortex/spring/backup/BackupJobConfiguration.java @@ -12,8 +12,10 @@ import org.quartz.SimpleScheduleBuilder; import org.quartz.Trigger; import org.quartz.TriggerBuilder; +import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.quartz.SchedulerFactoryBean; @@ -78,6 +80,44 @@ JobDetail cortexBackupJobDetail() { .build(); } + /** + * Creates the lifecycle that takes a final backup as the context closes. + * + *

Gated on {@code cortex.backup.on-shutdown}, defaulting to on: a consumer who asked for + * backups is not expecting a deliberate restart to discard up to a full interval of approved + * work. It is a separate switch rather than part of {@code cortex.backup.enabled} because it is + * the one part of the feature that makes shutdown wait on the network — see {@link + * BackupShutdownLifecycle} for why that wait is deliberately unbounded. + * + *

Matched by bean name for the same reason as the job detail and trigger. + * + *

The scheduler is taken as an {@link ObjectProvider} and resolved only at shutdown, which is + * what keeps the promise in this class's own documentation that nothing here touches the {@link + * Scheduler} directly. Injecting it outright would make this bean uncreatable in any context + * without {@code QuartzAutoConfiguration}, and would force the {@code SchedulerFactoryBean} to + * initialize partway through building this configuration — while it is still collecting the + * {@link JobDetail} beans defined here. + * + * @param schedulers resolves the scheduler at shutdown, quiesced before the final backup is taken + * @param cortexBackupJobDetail the backup job, so an in-flight run can be recognized + * @param backupRunner the runner that takes and uploads the backup + * @return the shutdown lifecycle + */ + @Bean + @ConditionalOnMissingBean(name = "cortexBackupShutdownLifecycle") + @ConditionalOnProperty( + prefix = "cortex.backup", + name = "on-shutdown", + havingValue = "true", + matchIfMissing = true) + BackupShutdownLifecycle cortexBackupShutdownLifecycle( + ObjectProvider schedulers, + JobDetail cortexBackupJobDetail, + BackupRunner backupRunner) { + return new BackupShutdownLifecycle( + schedulers::getIfAvailable, cortexBackupJobDetail, backupRunner); + } + /** * Creates the trigger firing the backup job every {@code cortex.backup.interval}. * diff --git a/cortex-spring-boot-autoconfigure/src/main/java/ai/chatur/cortex/spring/backup/BackupShutdownLifecycle.java b/cortex-spring-boot-autoconfigure/src/main/java/ai/chatur/cortex/spring/backup/BackupShutdownLifecycle.java new file mode 100644 index 0000000..df20248 --- /dev/null +++ b/cortex-spring-boot-autoconfigure/src/main/java/ai/chatur/cortex/spring/backup/BackupShutdownLifecycle.java @@ -0,0 +1,170 @@ +package ai.chatur.cortex.spring.backup; + +import java.util.function.Supplier; +import org.quartz.JobDetail; +import org.quartz.JobExecutionContext; +import org.quartz.JobKey; +import org.quartz.Scheduler; +import org.quartz.SchedulerException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.SmartLifecycle; + +/** + * Takes one last backup while the context closes, and blocks shutdown until it has uploaded. + * + *

Without this, a deliberate restart discards every approval made since the last scheduled fire + * — up to a full {@code cortex.backup.interval}, which defaults to 24 hours. The scheduled job + * covers the process dying; this covers the process being stopped, which is the far more common + * case and the only one where waiting is possible at all. + * + *

Holds no backup logic of its own — {@link BackupRunner} is shared verbatim with {@link + * BackupJob}, so the shutdown snapshot and the scheduled one are the same operation producing the + * same kind of object under the same key prefix. There is deliberately nothing that marks an upload + * as a shutdown backup: {@link RestoreRunner} restores the most recent object under the prefix, and + * a shutdown backup is only interesting because it is the most recent. + * + *

Phase

+ * + *

{@link #PHASE} is below every phase Boot stops before it, so by the time the snapshot is taken + * nothing can still be writing: Spring's {@code SchedulerFactoryBean} stops at {@link + * Integer#MAX_VALUE}, graceful shutdown drains in-flight requests at {@code MAX_VALUE - 1024}, and + * the web server stops accepting connections at {@code MAX_VALUE - 2048}. Raising it above any of + * those would snapshot a store still taking approvals over HTTP, quietly losing exactly the writes + * this class exists to preserve. + * + *

Waiting

+ * + *

{@link #stop()} runs on the calling thread, which is what makes the wait unbounded. Spring's + * {@code DefaultLifecycleProcessor} invokes {@link SmartLifecycle#stop(Runnable)}, whose default + * implementation calls {@link #stop()} and then the callback, so the latch it waits on is already + * counted down and {@code spring.lifecycle.timeout-per-shutdown-phase} never applies. Handing the + * work to an executor and counting the latch down on completion would look equivalent and silently + * cap the upload at that timeout (30s by default) — a large store would then be killed mid-upload + * on every restart. Don't. + * + *

Failures propagate out of {@link #stop()}, where {@code DefaultLifecycleProcessor} logs them + * and continues closing the context. That is the intended split: a backup that fails — bad + * credentials, a missing bucket — must not make the application impossible to restart, while a + * backup that is merely slow is waited on however long it takes. + */ +class BackupShutdownLifecycle implements SmartLifecycle { + + /** + * The lifecycle phase this stops in, below Boot's Quartz, graceful-shutdown, and web-server + * phases so the final snapshot sees a store nothing is still writing to. + */ + static final int PHASE = Integer.MAX_VALUE - 4096; + + private static final long POLL_MILLIS = 100; + + private static final Logger log = LoggerFactory.getLogger(BackupShutdownLifecycle.class); + + private final Supplier scheduler; + private final JobKey jobKey; + private final BackupRunner runner; + + private volatile boolean running; + + /** + * Creates the lifecycle. + * + * @param scheduler resolves the scheduler the backup job runs on, or {@code null} if there is + * none; resolved lazily, and only at shutdown + * @param jobDetail the backup job, named only to recognize it among the currently executing jobs + * @param runner the runner that takes and uploads the backup + */ + BackupShutdownLifecycle(Supplier scheduler, JobDetail jobDetail, BackupRunner runner) { + this.scheduler = scheduler; + this.jobKey = jobDetail.getKey(); + this.runner = runner; + } + + /** Marks this running, so that {@link #stop()} is called when the context closes. */ + @Override + public void start() { + running = true; + } + + /** + * Quiesces the scheduler and takes the final backup, blocking until it has uploaded. + * + * @throws RuntimeException if the backup cannot be taken or the upload fails + */ + @Override + public void stop() { + if (!running) { + return; + } + running = false; + quiesce(); + log.info("Taking a final Cortex backup before shutdown"); + runner.run(); + } + + /** + * Reports whether the final backup is still pending. + * + * @return {@code true} until {@link #stop()} has run + */ + @Override + public boolean isRunning() { + return running; + } + + /** + * Returns {@link #PHASE}. + * + * @return the lifecycle phase this stops in + */ + @Override + public int getPhase() { + return PHASE; + } + + /** + * Stops new backups firing and waits for any already in flight. + * + *

{@link Scheduler#standby()} alone is not enough: it prevents further fires but lets a + * running job finish, so without the wait a scheduled backup and the shutdown backup could + * snapshot the same store at once. That is not corrupting — TDB2 serializes them inside read + * transactions — but it doubles the disk and upload cost of a shutdown, which is the moment least + * able to afford it. + * + *

The scheduler is resolved lazily and may be absent: this bean must not force a {@code + * SchedulerFactoryBean} into existence just to hold a reference to it, and a context that somehow + * has no scheduler still wants its final backup. Scheduler faults are logged rather than thrown + * for the same reason — a scheduler that cannot be quiesced is a reason to take the backup + * carefully, not a reason to skip it. + */ + private void quiesce() { + Scheduler scheduler = this.scheduler.get(); + if (scheduler == null) { + return; + } + try { + if (scheduler.isShutdown()) { + return; + } + scheduler.standby(); + while (isBackupExecuting(scheduler)) { + log.info("Waiting for the in-flight Cortex backup to finish before shutting down"); + Thread.sleep(POLL_MILLIS); + } + } catch (SchedulerException e) { + log.warn("Could not quiesce the scheduler before the final backup; taking it anyway", e); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + log.warn("Interrupted waiting for the in-flight Cortex backup; taking the final one anyway"); + } + } + + private boolean isBackupExecuting(Scheduler scheduler) throws SchedulerException { + for (JobExecutionContext executing : scheduler.getCurrentlyExecutingJobs()) { + if (jobKey.equals(executing.getJobDetail().getKey())) { + return true; + } + } + return false; + } +} diff --git a/cortex-spring-boot-autoconfigure/src/test/java/ai/chatur/cortex/spring/backup/BackupShutdownLifecycleTests.java b/cortex-spring-boot-autoconfigure/src/test/java/ai/chatur/cortex/spring/backup/BackupShutdownLifecycleTests.java new file mode 100644 index 0000000..a27a076 --- /dev/null +++ b/cortex-spring-boot-autoconfigure/src/test/java/ai/chatur/cortex/spring/backup/BackupShutdownLifecycleTests.java @@ -0,0 +1,232 @@ +package ai.chatur.cortex.spring.backup; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.description; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import ai.chatur.cortex.core.store.BackupService; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.InOrder; +import org.quartz.JobBuilder; +import org.quartz.JobDetail; +import org.quartz.JobExecutionContext; +import org.quartz.Scheduler; +import org.quartz.SchedulerException; +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; + +/** + * Plain JUnit tests for {@link BackupShutdownLifecycle}, against a mocked {@link Scheduler} and a + * {@link BackupRunner} over mocks — no Spring context, no scheduler thread pool, no network. + */ +class BackupShutdownLifecycleTests { + + private static final JobDetail JOB = + JobBuilder.newJob(BackupJob.class).withIdentity("cortexBackupJob", "cortex").build(); + + private static BackupRunner runner(S3Client s3Client, Path backup) { + BackupService backupService = mock(BackupService.class); + when(backupService.backup()).thenReturn(backup.toString()); + return new BackupRunner(backupService, s3Client, "cortex-backups", "cortex/"); + } + + private static Path backupFile(Path dir) throws IOException { + return Files.writeString(dir.resolve("backup_2026-07-19_020000.nq.gz"), "gzip-bytes"); + } + + @Test + void stopShouldTakeAndUploadAFinalBackup(@TempDir Path dir) throws IOException { + S3Client s3Client = mock(S3Client.class); + BackupShutdownLifecycle lifecycle = + new BackupShutdownLifecycle( + () -> mock(Scheduler.class), JOB, runner(s3Client, backupFile(dir))); + + lifecycle.start(); + lifecycle.stop(); + + verify(s3Client).putObject(any(PutObjectRequest.class), any(RequestBody.class)); + } + + @Test + void stopShouldPutTheSchedulerInStandbyBeforeBackingUp(@TempDir Path dir) throws Exception { + Scheduler scheduler = mock(Scheduler.class); + S3Client s3Client = mock(S3Client.class); + BackupShutdownLifecycle lifecycle = + new BackupShutdownLifecycle(() -> scheduler, JOB, runner(s3Client, backupFile(dir))); + + lifecycle.start(); + lifecycle.stop(); + + InOrder order = inOrder(scheduler, s3Client); + order.verify(scheduler).standby(); + order.verify(s3Client).putObject(any(PutObjectRequest.class), any(RequestBody.class)); + } + + @Test + void stopShouldWaitForAnInFlightBackupBeforeTakingItsOwn(@TempDir Path dir) throws Exception { + Scheduler scheduler = mock(Scheduler.class); + JobExecutionContext executing = mock(JobExecutionContext.class); + when(executing.getJobDetail()).thenReturn(JOB); + AtomicInteger polls = new AtomicInteger(); + when(scheduler.getCurrentlyExecutingJobs()) + .thenAnswer( + invocation -> + polls.incrementAndGet() < 3 ? List.of(executing) : List.of()); + S3Client s3Client = mock(S3Client.class); + BackupShutdownLifecycle lifecycle = + new BackupShutdownLifecycle(() -> scheduler, JOB, runner(s3Client, backupFile(dir))); + + lifecycle.start(); + lifecycle.stop(); + + assertThat(polls.get()) + .as("the scheduled backup is polled until it drains, so the two never run at once") + .isGreaterThanOrEqualTo(3); + verify(s3Client).putObject(any(PutObjectRequest.class), any(RequestBody.class)); + } + + @Test + void stopShouldIgnoreOtherJobsStillExecuting(@TempDir Path dir) throws Exception { + Scheduler scheduler = mock(Scheduler.class); + JobExecutionContext other = mock(JobExecutionContext.class); + when(other.getJobDetail()) + .thenReturn(JobBuilder.newJob(BackupJob.class).withIdentity("someOtherJob", "app").build()); + when(scheduler.getCurrentlyExecutingJobs()).thenReturn(List.of(other)); + S3Client s3Client = mock(S3Client.class); + BackupShutdownLifecycle lifecycle = + new BackupShutdownLifecycle(() -> scheduler, JOB, runner(s3Client, backupFile(dir))); + + lifecycle.start(); + lifecycle.stop(); + + verify(s3Client).putObject(any(PutObjectRequest.class), any(RequestBody.class)); + } + + @Test + void stopShouldSkipQuiescingAnAlreadyShutDownScheduler(@TempDir Path dir) throws Exception { + Scheduler scheduler = mock(Scheduler.class); + when(scheduler.isShutdown()).thenReturn(true); + S3Client s3Client = mock(S3Client.class); + BackupShutdownLifecycle lifecycle = + new BackupShutdownLifecycle(() -> scheduler, JOB, runner(s3Client, backupFile(dir))); + + lifecycle.start(); + lifecycle.stop(); + + verify(scheduler, never()).standby(); + verify(s3Client, description("a scheduler already down is no reason to skip the final backup")) + .putObject(any(PutObjectRequest.class), any(RequestBody.class)); + } + + @Test + void stopShouldStillBackUpWhenTheSchedulerCannotBeQuiesced(@TempDir Path dir) throws Exception { + Scheduler scheduler = mock(Scheduler.class); + doThrow(new SchedulerException("scheduler is broken")).when(scheduler).standby(); + S3Client s3Client = mock(S3Client.class); + BackupShutdownLifecycle lifecycle = + new BackupShutdownLifecycle(() -> scheduler, JOB, runner(s3Client, backupFile(dir))); + + lifecycle.start(); + lifecycle.stop(); + + verify(s3Client, description("a scheduler that cannot be quiesced is not a reason to skip it")) + .putObject(any(PutObjectRequest.class), any(RequestBody.class)); + } + + @Test + void stopShouldStillBackUpWhenThereIsNoScheduler(@TempDir Path dir) throws IOException { + S3Client s3Client = mock(S3Client.class); + BackupShutdownLifecycle lifecycle = + new BackupShutdownLifecycle(() -> null, JOB, runner(s3Client, backupFile(dir))); + + lifecycle.start(); + lifecycle.stop(); + + verify(s3Client, description("the scheduler is optional; the final backup is not")) + .putObject(any(PutObjectRequest.class), any(RequestBody.class)); + } + + @Test + void stopShouldPropagateBackupFailures(@TempDir Path dir) throws IOException { + S3Client s3Client = mock(S3Client.class); + doThrow(new IllegalStateException("no such bucket")) + .when(s3Client) + .putObject(any(PutObjectRequest.class), any(RequestBody.class)); + BackupShutdownLifecycle lifecycle = + new BackupShutdownLifecycle( + () -> mock(Scheduler.class), JOB, runner(s3Client, backupFile(dir))); + + lifecycle.start(); + + assertThatThrownBy(lifecycle::stop) + .as( + "Spring's lifecycle processor logs this and continues, so a failing backup cannot make" + + " the application impossible to restart") + .isInstanceOf(IllegalStateException.class); + } + + @Test + void stopShouldBeIdempotent(@TempDir Path dir) throws IOException { + S3Client s3Client = mock(S3Client.class); + BackupShutdownLifecycle lifecycle = + new BackupShutdownLifecycle( + () -> mock(Scheduler.class), JOB, runner(s3Client, backupFile(dir))); + + lifecycle.start(); + lifecycle.stop(); + lifecycle.stop(); + + verify(s3Client).putObject(any(PutObjectRequest.class), any(RequestBody.class)); + } + + @Test + void stopShouldDoNothingWhenNeverStarted(@TempDir Path dir) throws IOException { + S3Client s3Client = mock(S3Client.class); + BackupShutdownLifecycle lifecycle = + new BackupShutdownLifecycle( + () -> mock(Scheduler.class), JOB, runner(s3Client, backupFile(dir))); + + lifecycle.stop(); + + verify(s3Client, never()).putObject(any(PutObjectRequest.class), any(RequestBody.class)); + } + + @Test + void isRunningShouldTrackWhetherTheFinalBackupIsStillPending(@TempDir Path dir) + throws IOException { + BackupShutdownLifecycle lifecycle = + new BackupShutdownLifecycle( + () -> mock(Scheduler.class), JOB, runner(mock(S3Client.class), backupFile(dir))); + + assertThat(lifecycle.isRunning()).isFalse(); + lifecycle.start(); + assertThat(lifecycle.isRunning()).isTrue(); + lifecycle.stop(); + assertThat(lifecycle.isRunning()).isFalse(); + } + + @Test + void phaseShouldStopAfterEveryPhaseThatCanStillWriteToTheStore() { + assertThat(BackupShutdownLifecycle.PHASE) + .as( + "phases stop in descending order, so a phase at or above Boot's web server" + + " (Integer.MAX_VALUE - 2048), its graceful shutdown (- 1024), or" + + " SchedulerFactoryBean (Integer.MAX_VALUE) would snapshot a store still being" + + " written to") + .isLessThan(Integer.MAX_VALUE - 2048); + } +} diff --git a/cortex-spring-boot-autoconfigure/src/test/java/ai/chatur/cortex/spring/backup/CortexBackupAutoConfigurationTests.java b/cortex-spring-boot-autoconfigure/src/test/java/ai/chatur/cortex/spring/backup/CortexBackupAutoConfigurationTests.java index 35fc706..4502604 100644 --- a/cortex-spring-boot-autoconfigure/src/test/java/ai/chatur/cortex/spring/backup/CortexBackupAutoConfigurationTests.java +++ b/cortex-spring-boot-autoconfigure/src/test/java/ai/chatur/cortex/spring/backup/CortexBackupAutoConfigurationTests.java @@ -1,17 +1,25 @@ package ai.chatur.cortex.spring.backup; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.description; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; import ai.chatur.cortex.core.store.BackupService; import ai.chatur.cortex.spring.CortexAutoConfiguration; import java.nio.file.Path; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import org.mockito.ArgumentCaptor; import org.quartz.JobDetail; import org.quartz.Trigger; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; /** * Tests for {@link CortexBackupAutoConfiguration}, driven by {@link ApplicationContextRunner} @@ -89,6 +97,86 @@ void shouldRegisterTheBackupJobWhenEnabledAndConfigured() { assertThat(context).hasSingleBean(S3Client.class); assertThat(context).hasBean("cortexBackupJobDetail"); assertThat(context).hasBean("cortexBackupTrigger"); + assertThat(context).hasBean("cortexBackupShutdownLifecycle"); + }); + } + + @Test + void shouldTakeAFinalBackupOnShutdownByDefault() { + // Backups are scheduled at cortex.backup.interval, 24h by default, so without this a deliberate + // restart discards up to a day of approvals. Enabling backups is enough to opt in. + enabledRunner() + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context).hasSingleBean(BackupShutdownLifecycle.class); + }); + } + + @Test + void shouldNotTakeAFinalBackupOnShutdownWhenDisabled() { + // The one part of the feature that makes shutdown block on the network, so it is switchable + // without giving up scheduled backups. + enabledRunner() + .withPropertyValues("cortex.backup.on-shutdown=false") + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context).doesNotHaveBean(BackupShutdownLifecycle.class); + assertThat(context) + .as("disabling the shutdown backup leaves the scheduled one alone") + .hasBean("cortexBackupTrigger"); + }); + } + + @Test + void shouldActuallyBackUpWhenTheContextCloses() { + // The one case here that closes a real context rather than inspecting bean definitions: it + // proves Spring invokes the lifecycle on shutdown at all, which no amount of wiring assertions + // can. The snapshot is a real TDB2 backup of the temp store; only the upload is mocked. + S3Client s3Client = mock(S3Client.class); + + enabledRunner() + .withBean("cortexS3Client", S3Client.class, () -> s3Client) + .run( + context -> { + assertThat(context).hasNotFailed(); + verify(s3Client, never()) + .putObject(any(PutObjectRequest.class), any(RequestBody.class)); + }); + + // ApplicationContextRunner closes the context once the callback returns. + ArgumentCaptor request = ArgumentCaptor.forClass(PutObjectRequest.class); + verify(s3Client, description("closing the context must upload a final backup")) + .putObject(request.capture(), any(RequestBody.class)); + assertThat(request.getValue().bucket()).isEqualTo("cortex-backups"); + assertThat(request.getValue().key()) + .as("the shutdown backup is an ordinary backup under the same prefix, so restore finds it") + .startsWith("cortex/backup_"); + } + + @Test + void shouldNotBackUpOnCloseWhenTheShutdownBackupIsDisabled() { + S3Client s3Client = mock(S3Client.class); + + enabledRunner() + .withPropertyValues("cortex.backup.on-shutdown=false") + .withBean("cortexS3Client", S3Client.class, () -> s3Client) + .run(context -> assertThat(context).hasNotFailed()); + + verify(s3Client, never()).putObject(any(PutObjectRequest.class), any(RequestBody.class)); + } + + @Test + void shouldStopTheShutdownLifecycleAfterTheWebServerAndScheduler() { + // Lifecycle phases stop in descending order. At or above Boot's web server phase the final + // snapshot would race approvals still arriving over HTTP -- the writes it exists to preserve. + enabledRunner() + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context.getBean(BackupShutdownLifecycle.class).getPhase()) + .isLessThan(Integer.MAX_VALUE - 2048); }); } diff --git a/site/configuration.html b/site/configuration.html index 57c1db4..e7d25cd 100644 --- a/site/configuration.html +++ b/site/configuration.html @@ -95,6 +95,7 @@

Scheduled backups

cortex.backup.enabledfalseRegister the scheduled backup job. cortex.backup.interval24hHow often a backup is taken. The first runs one interval after startup, not at startup. cortex.backup.keyPrefixcortex/Prepended to the backup file name to form the S3 object key. Include a trailing / to group under a folder. + cortex.backup.onShutdowntrueTake a final backup as the application shuts down, blocking shutdown until it has uploaded. Applies only when backups are enabled. @@ -135,6 +136,27 @@

Scheduled backups

copy, not a move, so a bucket misconfiguration can never destroy data. Pruning is left to the volume, or to an S3 lifecycle rule.

+

Backup on shutdown

+

Backups are scheduled, so a restart would otherwise discard every approval made since + the last one — up to a full cortex.backup.interval, 24 hours by default. Cortex + therefore takes one final backup as the application shuts down and blocks shutdown until + it has uploaded. It is on whenever backups are enabled; set + cortex.backup.onShutdown=false to turn it off without giving up scheduled + backups.

+

The final backup runs after the web server has stopped accepting requests and after the + scheduler has quiesced — including waiting out a scheduled backup that happens to be in flight — + so it snapshots a store nothing is still writing to. It is an ordinary backup under the same key + prefix, so a restore picks it up as the most recent object with no extra + configuration.

+
+ The wait is deliberately unbounded. A large store on a slow link takes as long + as it takes, and a bounded wait would kill the upload partway through on exactly the stores that + most need it. A backup that fails — bad credentials, a missing bucket — is logged and + shutdown continues, so a misconfiguration can never make the application impossible to restart; + only a genuinely slow upload holds shutdown open. If your orchestrator sends SIGKILL + after a grace period, size that period against how long a backup of your store actually takes. +
+

Restore on startup

The inverse of a backup: on boot, download the most recent backup from S3 and load it into the store before the application serves traffic, so an instance whose local disk was @@ -169,7 +191,10 @@

Restore on startup

A restore is destructive by design. It is a wipe-and-load that runs on every boot — it clears the local store and loads the latest backup over it, restoring approved assertions, staged branches, and provenance at full fidelity. Any local writes not yet captured - by a backup are lost on the next boot. An empty bucket (a first-ever deploy) is not an + by a backup are lost on the next boot — which is most of what + backup on shutdown is for, since it closes that window for + every clean stop, leaving only a crash or a SIGKILL able to lose work. An empty + bucket (a first-ever deploy) is not an error — it logs and starts empty; every other misconfiguration fails the context. Leave it false if S3 is not your source of truth.