Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |
Expand Down Expand Up @@ -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 `<cortex.assertionsLocation>/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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -78,6 +80,44 @@ JobDetail cortexBackupJobDetail() {
.build();
}

/**
* Creates the lifecycle that takes a final backup as the context closes.
*
* <p>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.
*
* <p>Matched by bean name for the same reason as the job detail and trigger.
*
* <p>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<Scheduler> schedulers,
JobDetail cortexBackupJobDetail,
BackupRunner backupRunner) {
return new BackupShutdownLifecycle(
schedulers::getIfAvailable, cortexBackupJobDetail, backupRunner);
}

/**
* Creates the trigger firing the backup job every {@code cortex.backup.interval}.
*
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
*
* <p>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.
*
* <p>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.
*
* <h2>Phase</h2>
*
* <p>{@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.
*
* <h2>Waiting</h2>
*
* <p>{@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.
*
* <p>Failures propagate out of {@link #stop()}, where {@code DefaultLifecycleProcessor} logs them
* and continues closing the context. That is the intended split: a backup that <em>fails</em> — bad
* credentials, a missing bucket — must not make the application impossible to restart, while a
* backup that is merely <em>slow</em> 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> 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> 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.
*
* <p>{@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.
*
* <p>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;
}
}
Loading
Loading