Skip to content

SQLite backup, recovery and health checks

A useful backup must let your application recover a saved execution. For the SQLite-backed API, that means preserving a consistent database and the compatible graph catalogue and service version needed to interpret it. A copied file is only the beginning of that check: the restored service must open the database and return the expected state for a known session.

This procedure uses the separate Nginx and PHP-FPM service from Docker deployment, with a sessions volume and a known demo-flow execution saved at node 2. That guide defines OPS_DIR, ekcompose and the private curl header file. For another installation, substitute its project, configuration and known session while keeping the backup and restored data separate from the live database.

The underlying storage role is the one introduced in Session stores: after an accepted operation, the store retains the execution’s state so a later request can retrieve it. Here the API’s PdoSessionStore writes that state and its language to SQLite.

Include the database and its interpretation

Section titled “Include the database and its interpretation”
Item What it preserves How this procedure handles it
sessions.sqlite Sessions, serialized context and history, timestamps, write versions, optional signatures and migration records. A consistent SQLite backup into a new snapshot file.
sessions.sqlite-wal, sessions.sqlite-shm while running Working files used by SQLite’s WAL mode. Let SQLite read them through its backup API; do not copy them independently.
Configured graph catalogue Definitions and identities needed to load saved executions. Archive the matching catalogue while deployments and catalogue changes are paused.
API/engine versions, image IDs and configuration Code, migration checksums, paths and lifetime policy used with that database. Keep the image IDs, API revision, Composer lock and deployment environment file with the snapshot.
Service credential Access to the restored API. Recover it through your secret-management process or configure a new credential.

A session snapshot is not the graph definition itself. The API reloads that definition when recovering an execution. Keep catalogue identities stable, and do not assume that any later image or graph revision can interpret an earlier database.

The deployment enables SQLite write-ahead logging, or WAL. Committed changes may still be in sessions.sqlite-wal rather than the main file. Copying only a live sessions.sqlite with a filesystem copy can therefore omit committed state. Copying the main file and WAL at different times is not a consistent snapshot either. Use SQLite’s database-aware backup operation, which reads the committed database through SQLite. The SQLite WAL documentation explains why the main file alone is insufficient during operation.

The running service writes a database and WAL. SQLite’s backup operation produces a separate consistent snapshot. A different API instance opens restored data and checks database integrity, service readiness and the saved session.

Keep backups private: the database contains application context and execution history. A local rehearsal backup in the commands below must still be copied to the durable backup location and retention policy chosen for your service. A snapshot on the same host is not protection against loss of that host.

Create a consistent snapshot with PHP’s SQLite support

Section titled “Create a consistent snapshot with PHP’s SQLite support”

The API image includes PHP’s SQLite3 extension. The complete backup example uses its SQLite3::backup() method; it is an operator script, not an ExecKernel CLI command.

The central operation opens the running source read-only and a separate, new destination:

$source = new SQLite3($sourcePath, SQLITE3_OPEN_READONLY);
$snapshot = new SQLite3($snapshotPath, SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE);
if (!$source->backup($snapshot)) {
throw new RuntimeException('SQLite backup did not complete.');
}

The backup method reads the source database consistently, including committed pages reached through WAL. It does not merge three independently copied files. The full script refuses an existing destination, applies a busy timeout, checks the backup result and validates the snapshot with PRAGMA integrity_check. It then puts the destination in DELETE journal mode and closes both connections before hashing the exported file. This produces a completed snapshot without a pending destination WAL.

Download the script to the private operator directory, then run it as the API container’s normal user. The temporary destination is in the writable session volume; the running database remains the source:

Terminal window
set -euo pipefail
curl --fail --location --silent --show-error \
https://docs.execkernel.org/examples/production/sqlite-backup.php \
--output "$OPS_DIR/sqlite-backup.php"
BACKUP_LABEL="$(date -u +%Y%m%dT%H%M%SZ)"
export BACKUP_DIR="$OPS_DIR/backups/$BACKUP_LABEL"
SNAPSHOT_IN_CONTAINER="/var/lib/execkernel/backup-$BACKUP_LABEL.sqlite"
mkdir -p "$BACKUP_DIR"
chmod 700 "$BACKUP_DIR"
ekcompose exec -T api php /dev/stdin \
/var/lib/execkernel/sessions.sqlite "$SNAPSHOT_IN_CONTAINER" \
< "$OPS_DIR/sqlite-backup.php" > "$BACKUP_DIR/report.json"
ekcompose cp "api:$SNAPSHOT_IN_CONTAINER" "$BACKUP_DIR/sessions.sqlite"
chmod 600 "$BACKUP_DIR/sessions.sqlite"

The report contains integrity_check: "ok", the session and migration counts, and the snapshot’s SHA-256. A failure exits nonzero; do not export a partial file as a successful backup. If the operation fails because of contention or storage problems, diagnose that condition and repeat with a new destination name after resolving it.

Verify the exported bytes against the hash produced after SQLite closed the snapshot:

Terminal window
python3 - <<'PY'
import hashlib, json, os
from pathlib import Path
backup = Path(os.environ["BACKUP_DIR"])
report = json.loads((backup / "report.json").read_text())
actual = hashlib.sha256((backup / "sessions.sqlite").read_bytes()).hexdigest()
if actual != report["sha256"]:
raise SystemExit("Exported snapshot hash does not match")
print("Snapshot integrity and exported hash verified")
PY

Pause catalogue/configuration deployments while collecting the matching files. The following commands use the default catalogue from the image’s source checkout. If your service mounts a different catalogue, set GRAPH_SOURCE to that actual directory instead:

Terminal window
GRAPH_SOURCE="$PWD/resources/graphs"
tar -C "$GRAPH_SOURCE" -czf "$BACKUP_DIR/graphs.tar.gz" .
git rev-parse HEAD > "$BACKUP_DIR/api-revision.txt"
cp composer.lock "$BACKUP_DIR/api-composer.lock"
cp "$OPS_DIR/deployment.env" "$BACKUP_DIR/deployment.env"
chmod 600 "$BACKUP_DIR/"*
ekcompose exec -T api rm "$SNAPSHOT_IN_CONTAINER"

The environment file records image IDs and the token file’s path, not its contents. Keep the required images available independently of their local tags. Capture any additional Compose overrides used by your installation as well. The SQLite backup is consistent for the database; it does not make concurrent graph or configuration edits part of the same transaction.

Restore into separate data before starting PHP

Section titled “Restore into separate data before starting PHP”

Use an unused project name and port. The rehearsal below restores to project execkernel-restore-check on 127.0.0.1:4322, with a different session volume. Keep the same compatible images recorded with the backup and recover the archived catalogue into a new directory:

Terminal window
export RESTORE_DIR="$OPS_DIR/restore-$BACKUP_LABEL"
mkdir -p "$RESTORE_DIR/graphs"
chmod 700 "$RESTORE_DIR"
tar -xzf "$BACKUP_DIR/graphs.tar.gz" -C "$RESTORE_DIR/graphs"
chmod 755 "$RESTORE_DIR/graphs"
chmod 644 "$RESTORE_DIR/graphs/"*.json
python3 - <<'PY'
import os
from pathlib import Path
source = Path(os.environ["BACKUP_DIR"]) / "deployment.env"
settings = dict(line.split("=", 1) for line in source.read_text().splitlines())
settings["EXECKERNEL_BIND"] = "127.0.0.1"
settings["EXECKERNEL_PORT"] = "4322"
target = Path(os.environ["RESTORE_DIR"]) / "restore.env"
target.write_text("".join(f"{key}={value}\n" for key, value in settings.items()))
target.chmod(0o600)
PY
export EXECKERNEL_GRAPH_HOST_DIR="$RESTORE_DIR/graphs"
restorecompose() {
docker compose --env-file "$RESTORE_DIR/restore.env" \
-p execkernel-restore-check \
-f compose.yaml -f deploy/compose.graphs.yaml "$@"
}

The token file referenced by restore.env must still be available and readable. This local rehearsal can reuse the existing private file. In disaster recovery, restore it through your secret-management process or configure a new token and update the calling application. The service token is an access credential, not an encryption key for SQLite.

Seed the fresh volume before the normal entry point runs. This command uses the image’s normal runtime user, refuses a nonempty destination directory and bypasses startup only for the copy:

Terminal window
restorecompose run --rm --no-deps --entrypoint sh api -eu -c '
entries="$(ls -A /var/lib/execkernel)"
test -z "$entries"
umask 077
cat > /var/lib/execkernel/sessions.sqlite
' < "$BACKUP_DIR/sessions.sqlite"
restorecompose up -d --no-build --pull never --wait

Do not run the seed step against an existing service volume. The empty-directory guard also prevents mixing a restored main file with old WAL files. On normal startup, the preflight validates the catalogue, opens the restored database, checks migrations and enables WAL for service operation again.

Check the database, the service and the execution

Section titled “Check the database, the service and the execution”

Perform three different checks; each answers a different recovery question.

1. Can SQLite read the restored database, and does its schema match this API? Run a database check inside the restored API container:

Terminal window
restorecompose exec -T api php -r '
require "/app/vendor/autoload.php";
$pdo = ExecKernelApi\Infrastructure\Deployment\SqliteDatabase::connect(
"/var/lib/execkernel/sessions.sqlite"
);
ExecKernelApi\Infrastructure\Deployment\SqliteDatabase::assertReady(
$pdo, "/app/database/migrations"
);
echo json_encode([
"schema_ready" => true,
"integrity_check" => $pdo->query("PRAGMA integrity_check")->fetchAll(PDO::FETCH_COLUMN)
], JSON_THROW_ON_ERROR), PHP_EOL;
'

The expected result is {"schema_ready":true,"integrity_check":["ok"]}. assertReady() checks the required session columns and the migration ledger against the SQL files in the image, including their checksums. An integrity result alone does not establish that the database belongs to the expected API version.

2. Can the deployed HTTP service initialize its dependencies?

Terminal window
curl --fail --silent --show-error http://127.0.0.1:4322/healthz

Expect HTTP 200 and "status":"ok". This goes through Nginx and PHP, with the runtime’s database/schema checks and catalogue validation. It does not run PRAGMA integrity_check, test every saved session or prove that a new session write will succeed.

3. Can your application recover the known execution? The deployment guide saved confirmed.json after choosing edge 10 of demo-flow. Recover that identifier from the restored instance:

Terminal window
SESSION_ID="$(python3 -c \
'import json,sys; print(json.load(open(sys.argv[1]))["session_id"])' \
"$OPS_DIR/confirmed.json")"
curl --fail-with-body --silent --show-error \
http://127.0.0.1:4322/execkernel/session/resume \
--header "@$OPS_DIR/auth.header" \
--header 'Content-Type: application/json' \
--data "{\"session_id\":\"$SESSION_ID\"}" \
--output "$RESTORE_DIR/recovered.json"
python3 -m json.tool "$RESTORE_DIR/recovered.json"

The response must contain the same session identifier, state.current_node: 2 and payload.type: "terminal". The successful check connects storage to application behavior: the restored service can return the screen corresponding to the confirmed choice without executing that choice again.

The session used for this check must have been saved before the backup started and still be within its configured lifetime. Keep its expected position with the recovery record. Data written after the snapshot is outside that backup; measure the age of your recovery point and the time needed for this exercise against your own service requirements.

Observation What to check next
API container will not start, or /healthz returns 503. Token readability, database directory permissions, migration ledger and catalogue validation; inspect restorecompose logs --tail 50 api web.
Integrity check reports an error. Preserve the failed snapshot for diagnosis and test another validated backup. A healthy port does not repair database corruption.
/healthz is 200, but the known session returns 400 / EK-INPUT-400 with Session not found. Confirm the identifier and snapshot date, then check whether the session was deleted or expired.
A saved execution cannot load its graph. Check that the restored catalogue contains the compatible graph identity and definition used by that execution.
Restored position is older than expected. Compare the expected operation’s confirmation with the snapshot’s capture point; later writes are not included.

Restoration preserves session timestamps. The configured store lifetime uses the later of updated_at and last_transition_at; restoring a backup does not reset that clock. Loading an expired record can remove it and return “not found.” This is storage expiry behavior, not a scheduled cleanup job, and deleting expired sessions is not a substitute for taking backups.

After recording the rehearsal’s image IDs, snapshot hash, health result and known-session result, stop its separate services:

Terminal window
restorecompose down

The restored volume is retained until you deliberately remove it under your rehearsal retention policy. The source deployment continues to use its original volume. Keep that separation when testing other snapshots or a candidate API version; successful recovery of one snapshot does not establish compatibility for every future version.