PostgreSQL backup tool with Point-In-Time-Recovery and restore verification
TypeScript backupbackupsdatabasedatabase-backupdevopsdockergolangkubernetesmariadbmongodbmysqlpgpostgrespostgresqls3self-hostedsystem-administrationtoolsweb-ui
FIX (docker): Keep the startup script as a non-root process 1 that stops the application first and then shuts the embedded PostgreSQL down in fast mode, so docker stop leaves a cleanly shut down cluster and the next start needs no crash recovery
Rostislav Dugind89d966b0558
diff --git a/.trivyignore.yaml b/.trivyignore.yamlindex f6be187e..37f17824 100644--- a/.trivyignore.yaml+++ b/.trivyignore.yaml@@ -3,7 +3,8 @@ misconfigurations:paths:- Dockerfilestatement: >-- The final image creates postgres and databasus users, then start.sh drops- the application process to databasus with gosu. The entrypoint must start- as root to remap PUID and PGID values, prepare the mounted data directory,- and initialize PostgreSQL. A Dockerfile USER directive would break startup.+ The final image runs every service as the databasus user. start.sh starts+ as root only to remap PUID and PGID values and prepare the mounted data+ directory, then re-executes itself as databasus with gosu, and that+ non-root process initializes PostgreSQL and runs the application. A+ Dockerfile USER directive would break startup.diff --git a/docker/start.sh b/docker/start.shindex 5c804dbb..9a28472c 100755--- a/docker/start.sh+++ b/docker/start.sh@@ -12,9 +12,13 @@ readonly postgres_binary_directory="/usr/lib/postgresql/17/bin"# rotation of the next start. backend/internal/config/config.go reads the same path.readonly published_database_dsn_path="/dev/shm/databasus-database-dsn"+readonly runtime_phase_argument="--as-databasus"+runtime_uid=""runtime_gid=""postgres_pid=""+postgresql_step_pid=""+application_pid=""internal_postgres_password=""reject_legacy_postgresus_volume() {@@ -353,7 +357,7 @@ initialize_postgresql_cluster() {fiecho "Initializing PostgreSQL database..."- gosu databasus "${postgres_binary_directory}/initdb" \+ "${postgres_binary_directory}/initdb" \-D /databasus-data/pgdata \--encoding=UTF8 \--locale=C.UTF-8 \@@ -370,9 +374,9 @@ initialize_postgresql_cluster() {install_postgresql_configuration_file() {local configuration_file="/databasus-data/pgdata/$1"- gosu databasus tee "${configuration_file}.new" >/dev/null- gosu databasus chmod 0600 "${configuration_file}.new"- gosu databasus mv "${configuration_file}.new" "${configuration_file}"+ tee "${configuration_file}.new" >/dev/null+ chmod 0600 "${configuration_file}.new"+ mv "${configuration_file}.new" "${configuration_file}"}write_postgresql_authentication() {@@ -386,25 +390,40 @@ PG_HBA}# Single-user mode listens on nothing, so the cluster can be administered before any client can-# connect. The database name must be the last argument.+# connect. The database name must be the last argument. Docker delivers a stop signal to process 1+# alone, and Bash runs a trap only after a foreground command returns, so the step runs in the+# background where the stop trap can end it.run_postgresql_single_user() {- gosu databasus "${postgres_binary_directory}/postgres" \+ local single_user_input="$1"+ local single_user_output_path="$2"+ local single_user_status=0+ shift 2++ "${postgres_binary_directory}/postgres" \--single \-D /databasus-data/pgdata \"$@" \- postgres+ postgres <<<"${single_user_input}" >"${single_user_output_path}" 2>&1 &+ postgresql_step_pid=$!+ wait "${postgresql_step_pid}" || single_user_status=$?+ postgresql_step_pid=""++ return "${single_user_status}"}# Opening the cluster replays the write-ahead log, so a failure here is the only sign of a log that# cannot be recovered without a reset.open_postgresql_cluster() {- local single_user_output+ local single_user_output_path- if single_user_output="$(run_postgresql_single_user </dev/null 2>&1)"; then+ single_user_output_path="$(mktemp)"+ if run_postgresql_single_user "" "${single_user_output_path}"; then+ rm -f "${single_user_output_path}"returnfi- printf '%s\n' "${single_user_output}"+ cat "${single_user_output_path}"+ rm -f "${single_user_output_path}"return 1}@@ -435,10 +454,10 @@ open_postgresql_cluster_with_recovery() {# A single-user backend that panics leaves its lock file behind, and pg_resetwal refuses to run# while one exists. No PostgreSQL process runs at this point, so the file is stale.- gosu databasus rm -f /databasus-data/pgdata/postmaster.pid+ rm -f /databasus-data/pgdata/postmaster.pidecho "Running pg_resetwal to reset WAL..."- if ! gosu databasus "${postgres_binary_directory}/pg_resetwal" \+ if ! "${postgres_binary_directory}/pg_resetwal" \-f /databasus-data/pgdata ||! open_postgresql_cluster; thenreport_postgresql_recovery_failure@@ -448,31 +467,35 @@ open_postgresql_cluster_with_recovery() {echo "PostgreSQL recovered successfully after WAL reset!"}-# printf is a shell builtin, so the password reaches PostgreSQL through a pipe and never through-# the arguments of a process. log_min_error_statement=panic keeps a failing statement, and the-# password inside it, out of the output.+# The statement reaches PostgreSQL as standard input, so the password never appears in the+# arguments of a process. log_min_error_statement=panic keeps a failing statement, and the password+# inside it, out of the output.rotate_internal_postgres_password() {- local single_user_output+ local single_user_output_pathinternal_postgres_password="$(od -An -N32 -tx1 /dev/urandom | tr -d '[:space:]')"echo "Setting the internal PostgreSQL password..."- if single_user_output="$(printf "ALTER ROLE postgres WITH PASSWORD '%s'\n" "${internal_postgres_password}" |- run_postgresql_single_user \- -c exit_on_error=on \- -c log_min_error_statement=panic \- -c password_encryption=scram-sha-256 2>&1)"; then+ single_user_output_path="$(mktemp)"+ if run_postgresql_single_user \+ "ALTER ROLE postgres WITH PASSWORD '${internal_postgres_password}'" \+ "${single_user_output_path}" \+ -c exit_on_error=on \+ -c log_min_error_statement=panic \+ -c password_encryption=scram-sha-256; then+ rm -f "${single_user_output_path}"returnfi- printf '%s\n' "${single_user_output}" >&2+ cat "${single_user_output_path}" >&2+ rm -f "${single_user_output_path}"echo "ERROR: PostgreSQL rejected the internal password change." >&2return 1}start_postgresql() {echo "Starting PostgreSQL..."- gosu databasus "${postgres_binary_directory}/postgres" \+ "${postgres_binary_directory}/postgres" \-D /databasus-data/pgdata \-p 5437 \-c unix_socket_directories='' \@@ -483,7 +506,7 @@ start_postgresql() {echo "Waiting for PostgreSQL to be ready..."local postgres_readiness_attemptfor ((postgres_readiness_attempt = 1; postgres_readiness_attempt <= 30; postgres_readiness_attempt++)); do- if gosu databasus "${postgres_binary_directory}/pg_isready" \+ if "${postgres_binary_directory}/pg_isready" \-h localhost -p 5437 >/dev/null 2>&1; thenecho "PostgreSQL is ready!"return@@ -500,7 +523,7 @@ start_postgresql() {create_metadata_database() {echo "Setting up database..."- PGPASSWORD="${internal_postgres_password}" gosu databasus "${postgres_binary_directory}/psql" \+ PGPASSWORD="${internal_postgres_password}" "${postgres_binary_directory}/psql" \-v ON_ERROR_STOP=1 \-h localhost \-p 5437 \@@ -513,7 +536,7 @@ SQL}verify_postgresql_runtime_authentication() {- if ! PGPASSWORD="${internal_postgres_password}" gosu databasus "${postgres_binary_directory}/psql" \+ if ! PGPASSWORD="${internal_postgres_password}" "${postgres_binary_directory}/psql" \-h localhost \-p 5437 \-U postgres \@@ -531,9 +554,7 @@ configure_application_database_dsn() {export DATABASE_DSN="host=localhost user=postgres password=${internal_postgres_password} dbname=databasus port=5437 sslmode=disable"- # The runtime user creates the file itself, so startup needs no CHOWN capability.- printf '%s\n' "${DATABASE_DSN}" \- | gosu databasus /bin/sh -c 'umask 077 && cat > "$1"' sh "${published_database_dsn_path}"+ (umask 077 && printf '%s\n' "${DATABASE_DSN}" > "${published_database_dsn_path}")}bootstrap_postgresql() {@@ -553,7 +574,7 @@ reject_legacy_wal_configuration() {echo "Checking for legacy WAL backup configuration..."has_backup_type_column="$(PGPASSWORD="${internal_postgres_password}" \- gosu databasus "${postgres_binary_directory}/psql" \+ "${postgres_binary_directory}/psql" \-h localhost -p 5437 -U postgres -d databasus -tA \-c "SELECT 1 FROM information_schema.columns WHERE table_name='postgresql_databases' AND column_name='backup_type' LIMIT 1" \2>/dev/null || true)"@@ -564,7 +585,7 @@ reject_legacy_wal_configuration() {fihas_legacy_wal_database="$(PGPASSWORD="${internal_postgres_password}" \- gosu databasus "${postgres_binary_directory}/psql" \+ "${postgres_binary_directory}/psql" \-h localhost -p 5437 -U postgres -d databasus -tA \-c "SELECT 1 FROM postgresql_databases WHERE backup_type='WAL_V1' LIMIT 1" \2>/dev/null || true)"@@ -587,16 +608,109 @@ reject_legacy_wal_configuration() {return 1}-main() {+wait_for_process_exit() {+ local process_id="$1"++ # A trapped signal interrupts wait before the process has exited.+ while kill -0 "${process_id}" 2>/dev/null; do+ wait "${process_id}" 2>/dev/null || true+ done+}++# A fast shutdown disconnects remaining sessions and writes a shutdown checkpoint, so the next+# start needs no crash recovery.+stop_postgresql_server() {+ kill -INT "${postgres_pid}" 2>/dev/null || true+ wait_for_process_exit "${postgres_pid}"+}++get_signal_exit_status() {+ local signal_name="$1"++ echo "$((128 + $(kill -l "${signal_name}")))"+}++# Exiting before the PostgreSQL process has ended would let the kernel kill it together with+# process 1, possibly during its shutdown checkpoint.+stop_startup() {+ local signal_name="$1"++ trap '' TERM INT+ echo "Stop requested during startup"+ if [ -n "${postgres_pid}" ]; then+ stop_postgresql_server+ elif [ -n "${postgresql_step_pid}" ]; then+ kill -TERM "${postgresql_step_pid}" 2>/dev/null || true+ wait_for_process_exit "${postgresql_step_pid}"+ fi+ exit "$(get_signal_exit_status "${signal_name}")"+}++handle_stop_signal() {+ local signal_name="$1"++ if [ -z "${application_pid}" ]; then+ stop_startup "${signal_name}"+ fi++ kill -s "${signal_name}" "${application_pid}" 2>/dev/null || true+}++install_stop_trap() {+ trap 'handle_stop_signal TERM' TERM+ trap 'handle_stop_signal INT' INT+}++# The application shuts down first, because it records interrupted backups in the metadata+# database while it stops.+supervise_application() {+ local exited_process_id=""+ local exit_status=0++ echo "Starting Databasus application..."+ ./main &+ application_pid=$!++ while [ -z "${exited_process_id}" ]; do+ exit_status=0+ wait -n -p exited_process_id "${application_pid}" "${postgres_pid}" || exit_status=$?+ done++ if [ "${exited_process_id}" = "${postgres_pid}" ]; then+ echo "ERROR: PostgreSQL exited with status ${exit_status} while Databasus was running." >&2+ kill -TERM "${application_pid}" 2>/dev/null || true+ wait_for_process_exit "${application_pid}"+ exit 1+ fi++ echo "Databasus application exited with status ${exit_status}"+ stop_postgresql_server+ exit "${exit_status}"+}++prepare_container_as_root() {reject_legacy_postgresus_volumeconfigure_runtime_identitygenerate_frontend_runtime_configurationprepare_and_verify_storage++ exec gosu databasus "$0" "${runtime_phase_argument}"+}++run_as_databasus() {bootstrap_postgresqlreject_legacy_wal_configuration+ supervise_application+}- echo "Starting Databasus application..."- exec gosu databasus ./main+main() {+ install_stop_trap++ if [ "${1:-}" = "${runtime_phase_argument}" ]; then+ run_as_databasus+ else+ prepare_container_as_root+ fi}main "$@"diff --git a/e2e/docker-storage/run.sh b/e2e/docker-storage/run.shindex 76ae94e6..b07c31b7 100755--- a/e2e/docker-storage/run.sh+++ b/e2e/docker-storage/run.sh@@ -107,12 +107,11 @@ wait_for_log() {return 1}-wait_for_exit() {+wait_for_stop() {local container_name="$1"for ((exit_attempt = 1; exit_attempt <= 100; exit_attempt++)); doif [[ "$(docker inspect --format '{{.State.Running}}' "${container_name}")" != "true" ]]; then- [[ "$(docker inspect --format '{{.State.ExitCode}}' "${container_name}")" != "0" ]]returnfisleep 0.1@@ -122,6 +121,19 @@ wait_for_exit() {return 1}+get_exit_code() {+ local container_name="$1"++ docker inspect --format '{{.State.ExitCode}}' "${container_name}"+}++wait_for_exit() {+ local container_name="$1"++ wait_for_stop "${container_name}"+ [[ "$(get_exit_code "${container_name}")" != "0" ]]+}+start_databasus() {local container_name="$1"shift@@ -668,7 +680,10 @@ get_application_database_dsn() {local container_name="$1"docker exec --user databasus "${container_name}" /bin/sh -eu -c '- database_dsn="$(tr "\0" "\n" < /proc/1/environ | sed -n "s/^DATABASE_DSN=//p")"+ database_dsn="$(cat /dev/shm/databasus-database-dsn 2>/dev/null || true)"+ if [ -z "${database_dsn}" ]; then+ database_dsn="$(tr "\0" "\n" < /proc/1/environ | sed -n "s/^DATABASE_DSN=//p")"+ fiif [ -z "${database_dsn}" ]; thenset -a. /.env@@ -940,6 +955,284 @@ run_postgresql_recovery() {fi}+get_cluster_state() {+ local volume_name="$1"++ docker run --rm --label "${harness_label}" \+ --entrypoint /usr/lib/postgresql/17/bin/pg_controldata \+ --volume "${volume_name}:/databasus-data" "${databasus_image}" \+ /databasus-data/pgdata | sed -n 's/^Database cluster state: *//p'+}++assert_cluster_shut_down() {+ local volume_name="$1"+ local cluster_state++ cluster_state="$(get_cluster_state "${volume_name}")"+ if [[ "${cluster_state}" != "shut down" ]]; then+ echo "The stopped cluster reports the state '${cluster_state}', not 'shut down'" >&2+ return 1+ fi+}++assert_exit_code() {+ local container_name="$1"+ local required_exit_code="$2"+ local exit_code++ exit_code="$(get_exit_code "${container_name}")"+ if [[ "${exit_code}" != "${required_exit_code}" ]]; then+ docker logs "${container_name}" >&2+ echo "The container exited with status ${exit_code}, not ${required_exit_code}" >&2+ return 1+ fi+}++start_databasus_on_new_volume() {+ local container_name="$1"++ docker volume create --label "${harness_label}" "${container_name}" >/dev/null+ start_databasus "${container_name}" --volume "${container_name}:/databasus-data"+}++check_docker_stop_shuts_down_cleanly() {+ local container_name="databasus-storage-clean-stop-${run_id}"+ local stop_started_at_ms+ local stop_duration_ms++ start_databasus_on_new_volume "${container_name}"+ stop_started_at_ms="$(date +%s%3N)"+ docker stop "${container_name}" >/dev/null+ stop_duration_ms="$(($(date +%s%3N) - stop_started_at_ms))"++ if ((stop_duration_ms >= 10000)); then+ echo "docker stop took ${stop_duration_ms} ms, so the stop timeout ended the container" >&2+ return 1+ fi+ assert_exit_code "${container_name}" 0+ assert_cluster_shut_down "${container_name}"+ assert_application_exit_precedes_postgresql_shutdown "${container_name}"+}++get_first_log_line_number() {+ local container_name="$1"+ local searched_log_line="$2"++ docker logs "${container_name}" 2>&1 | grep -nF "${searched_log_line}" | head -1 | cut -d: -f1+}++assert_application_exit_precedes_postgresql_shutdown() {+ local container_name="$1"+ local application_exit_line_number+ local postgresql_shutdown_line_number++ application_exit_line_number="$(get_first_log_line_number "${container_name}" \+ "Databasus application exited with status 0")"+ postgresql_shutdown_line_number="$(get_first_log_line_number "${container_name}" \+ "received fast shutdown request")"+ if [[ -z "${application_exit_line_number}" || -z "${postgresql_shutdown_line_number}" ]] ||+ ((application_exit_line_number > postgresql_shutdown_line_number)); then+ docker logs "${container_name}" >&2+ echo "The application exit is not logged before the PostgreSQL shutdown request" >&2+ return 1+ fi+}++check_interrupt_shuts_down_cleanly() {+ local container_name="databasus-storage-clean-interrupt-${run_id}"++ start_databasus_on_new_volume "${container_name}"+ docker kill --signal INT "${container_name}" >/dev/null+ wait_for_stop "${container_name}"+ assert_cluster_shut_down "${container_name}"+}++check_application_exit_shuts_down_cleanly() {+ local container_name="databasus-storage-clean-application-exit-${run_id}"++ start_databasus_on_new_volume "${container_name}"+ send_signal_in_container "${container_name}" TERM "$(docker exec "${container_name}" pidof main)"+ wait_for_stop "${container_name}"+ assert_exit_code "${container_name}" 0+ assert_cluster_shut_down "${container_name}"+}++check_postgresql_exit_stops_container() {+ local container_name="databasus-storage-clean-postgresql-exit-${run_id}"++ start_databasus_on_new_volume "${container_name}"+ send_signal_in_container "${container_name}" KILL \+ "$(docker exec "${container_name}" head -1 /databasus-data/pgdata/postmaster.pid)"+ wait_for_exit "${container_name}"+ assert_log_contains "${container_name}" "ERROR: PostgreSQL exited with status"+ assert_log_lacks "${container_name}" "Databasus application exited with status"+}++run_clean_shutdown() {+ check_docker_stop_shuts_down_cleanly+ check_interrupt_shuts_down_cleanly+ check_application_exit_shuts_down_cleanly+ check_postgresql_exit_stops_container+}++# The loop polls without a delay, because the open step of a clean cluster lasts about 0.1 seconds.+# A single-user step started by initdb works on template1, so matching the final postgres argument+# skips it.+readonly postgresql_freeze_script='+ target_kind="$1"+ while :; do+ for process_directory in /proc/[0-9]*; do+ mapfile -d "" -t process_arguments < "${process_directory}/cmdline" 2>/dev/null || continue+ [[ "${process_arguments[0]:-}" == /usr/lib/postgresql/17/bin/postgres ]] || continue+ process_id="${process_directory#/proc/}"+ case "${target_kind}" in+ single-user)+ [[ "${process_arguments[1]:-}" == --single &&+ "${process_arguments[-1]}" == postgres ]] || continue+ ;;+ regular-server)+ [[ "${process_arguments[1]:-}" != --single ]] || continue+ IFS= read -r postmaster_pid < /databasus-data/pgdata/postmaster.pid 2>/dev/null || continue+ [[ "${postmaster_pid}" == "${process_id}" ]] || continue+ ;;+ esac+ kill -STOP "${process_id}"+ printf "%s" "${process_id}" > /tmp/frozen-postgresql-pid+ exit 0+ done+ done+'++start_databasus_with_frozen_postgresql() {+ local container_name="$1"+ local target_kind="$2"+ local frozen_pid++ docker volume create --label "${harness_label}" "${container_name}" >/dev/null+ docker run --detach \+ --name "${container_name}" \+ --label "${harness_label}" \+ --volume "${container_name}:/databasus-data" \+ "${databasus_image}" >/dev/null+ docker exec --detach "${container_name}" \+ /bin/bash -c "${postgresql_freeze_script}" freeze-postgresql "${target_kind}"++ for ((freeze_attempt = 1; freeze_attempt <= 300; freeze_attempt++)); do+ if frozen_pid="$(docker exec "${container_name}" cat /tmp/frozen-postgresql-pid 2>/dev/null)"; then+ echo "${frozen_pid}"+ return+ fi+ sleep 0.1+ done++ docker logs "${container_name}" >&2+ echo "No ${target_kind} PostgreSQL process appeared to freeze" >&2+ return 1+}++send_signal_in_container() {+ local container_name="$1"+ local signal_name="$2"+ local process_id="$3"++ docker exec "${container_name}" /bin/bash -c 'kill -"$1" "$2"' send-signal "${signal_name}" "${process_id}"+}++is_process_stopped() {+ local container_name="$1"+ local process_id="$2"++ [[ "$(docker exec "${container_name}" awk '/^State:/ { print $2 }' "/proc/${process_id}/status")" == "T" ]]+}++wait_for_log_within_two_seconds() {+ local container_name="$1"+ local required_log_line="$2"++ for ((log_attempt = 1; log_attempt <= 20; log_attempt++)); do+ if docker logs "${container_name}" 2>&1 | grep -F "${required_log_line}" >/dev/null; then+ return+ fi+ sleep 0.1+ done++ docker logs "${container_name}" >&2+ echo "The container did not log within two seconds: ${required_log_line}" >&2+ return 1+}++wait_for_kill_event() {+ local container_name="$1"+ local container_created_at++ container_created_at="$(docker inspect --format '{{.Created}}' "${container_name}")"+ for ((event_attempt = 1; event_attempt <= 50; event_attempt++)); do+ if docker events \+ --since "${container_created_at}" \+ --until "$(date +%s.%N)" \+ --filter "container=${container_name}" \+ --filter event=kill \+ --format '{{.Action}}' | grep -q .; then+ return+ fi+ sleep 0.1+ done++ echo "Docker did not report sending the stop signal" >&2+ return 1+}++# Status 143 comes from the startup stop handler, while a kill by the stop timeout gives 137.+assert_startup_ended_without_application() {+ local container_name="$1"++ assert_exit_code "${container_name}" 143+ assert_log_lacks "${container_name}" "Starting Databasus application..."+}++check_stop_during_single_user_step() {+ local container_name="databasus-storage-startup-stop-single-user-${run_id}"+ local frozen_pid+ local stop_pid++ frozen_pid="$(start_databasus_with_frozen_postgresql "${container_name}" single-user)"+ docker stop "${container_name}" >/dev/null &+ stop_pid=$!++ wait_for_log_within_two_seconds "${container_name}" "Stop requested during startup"+ if ! is_process_stopped "${container_name}" "${frozen_pid}"; then+ echo "The single-user step ended before the container reported the stop" >&2+ return 1+ fi++ send_signal_in_container "${container_name}" CONT "${frozen_pid}"+ wait "${stop_pid}"+ assert_startup_ended_without_application "${container_name}"+}++# The script may be waiting in pg_isready or psql on the frozen server, and Bash runs a trap only+# after that call returns, so this part cannot see the stop before the server resumes.+check_stop_while_regular_server_starts() {+ local container_name="databasus-storage-startup-stop-regular-server-${run_id}"+ local frozen_pid+ local stop_pid++ frozen_pid="$(start_databasus_with_frozen_postgresql "${container_name}" regular-server)"+ docker stop "${container_name}" >/dev/null &+ stop_pid=$!++ wait_for_kill_event "${container_name}"+ send_signal_in_container "${container_name}" CONT "${frozen_pid}"+ wait "${stop_pid}"+ assert_startup_ended_without_application "${container_name}"+ assert_cluster_shut_down "${container_name}"+}++run_startup_stop() {+ check_stop_during_single_user_step+ check_stop_while_regular_server_starts+}+run_legacy_directory_guard() {local container_name="databasus-storage-legacy-directory-${run_id}"local volume_name="databasus-storage-legacy-directory-${run_id}"@@ -978,6 +1271,8 @@ run_case() {nfs-root-squash) run_nfs_root_squash ;;upgrades) run_upgrades ;;postgresql-recovery) run_postgresql_recovery ;;+ clean-shutdown) run_clean_shutdown ;;+ startup-stop) run_startup_stop ;;legacy-directory-guard) run_legacy_directory_guard ;;*)echo "unknown Docker filesystem case: ${case_name}" >&2@@ -991,7 +1286,7 @@ if [[ "${selected_case}" == all ]]; thenbuild-only default-ids custom-ids maximum-ids automatic-ids empty-pgdata-ids partial-ids invalid-ids \bind-root named-volume split-mounts no-unix-sockets metadata-changes-denied read-only wrong-owner \unwritable-data-root \- cifs nfs-root-squash upgrades postgresql-recovery legacy-directory-guard; do+ cifs nfs-root-squash upgrades postgresql-recovery clean-shutdown startup-stop legacy-directory-guard; dorun_case "${case_name}"cleanupcase_root="$(mktemp -d /tmp/databasus-storage-test.XXXXXXXX)"diff --git a/openspec/changes/archive/2026-10-21-stop-embedded-postgresql-cleanly/.openspec.yaml b/openspec/changes/archive/2026-10-21-stop-embedded-postgresql-cleanly/.openspec.yamlnew file mode 100644index 00000000..dc36fb1b--- /dev/null+++ b/openspec/changes/archive/2026-10-21-stop-embedded-postgresql-cleanly/.openspec.yaml@@ -0,0 +1,2 @@+schema: spec-driven+created: 2026-10-21diff --git a/openspec/changes/archive/2026-10-21-stop-embedded-postgresql-cleanly/design.md b/openspec/changes/archive/2026-10-21-stop-embedded-postgresql-cleanly/design.mdnew file mode 100644index 00000000..b33bc8a3--- /dev/null+++ b/openspec/changes/archive/2026-10-21-stop-embedded-postgresql-cleanly/design.md@@ -0,0 +1,100 @@+## Context++See `proposal.md` for the motivation. `main` in `docker/start.sh` ends with `exec gosu databasus ./main` (`docker/start.sh:603`). `gosu` replaces itself with the application, so the application takes over process ID 1. The PostgreSQL server was started in the background earlier (`start_postgresql`, `docker/start.sh:398-419`) and becomes a child of the application. The image declares no `STOPSIGNAL`, so `docker stop` sends `SIGTERM` to process 1 only. The application handles it (`backend/cmd/main.go:345`), drains HTTP requests for up to 10 seconds and returns. When process 1 exits, the kernel kills every remaining process in the PID namespace with `SIGKILL`, PostgreSQL included.++A spike with `postgres:17` reproduced the current pattern. A stand-in application ran as process 1 and PostgreSQL as its child. After `docker stop`, the next start logged `database system was not properly shut down; automatic recovery in progress`. With the supervisor described below, the same stop took 1.7 seconds and the container exited with `0`. The stand-in application still queried the database from its own `SIGTERM` handler, and the next start logged `database system was shut down at ...` with no recovery.++`docker/start.sh` runs with `set -e` (`docker/start.sh:2`).++The approach answers to the root `AGENTS.md`: no compatibility shims and refactoring of the touched startup code within the change. ADR-0003 embeds PostgreSQL as a process in the application container. This change keeps that topology and only orders its shutdown. No module `AGENTS.md` governs `docker/` or `e2e/`.++## Goals / Non-Goals++**Goals:**++- A stop within the timeout leaves the cluster cleanly shut down.+- The application keeps database access for its whole shutdown.+- The container's exit status reflects the application's outcome, and an unexpected PostgreSQL exit is visible to a restart policy.++**Non-Goals:**++- Guaranteeing a clean shutdown when the stop timeout expires first. That case stays a `SIGKILL`, as today.+- Supervising processes started with `docker exec`.++## Decisions++### 1. Keep the startup script as process 1 and supervise both services++The script runs in two phases. The root phase checks for a legacy volume, sets the runtime identity, writes the frontend configuration and prepares storage, because these steps change ownership, modes and accounts. It ends with `exec gosu databasus /app/start.sh` and a phase argument. The runtime phase runs under `databasus` in the same process 1. It runs every PostgreSQL step, starts the application in the background as `./main &` and records its process ID beside `postgres_pid`. It then waits with `wait -n` on both IDs. The script stays process 1, the process that receives the stop signal.++Process 1 therefore stays non-root, as `docker-storage-compatibility` requires and `assert_single_runtime_identity` checks through `/proc/1`. PostgreSQL and the application are started by the runtime phase itself, so they are real children of its shell and `wait` can collect them. The PostgreSQL steps no longer need a `gosu databasus` prefix.++Alternatives rejected:++- Keep the whole script under root as process 1. A root process would then live for the life of the container, which breaks the single non-root identity of all bundled services.+- Bootstrap PostgreSQL under root and `exec gosu databasus` into supervision afterwards. The running server would not be a child of the new shell, so `wait` and `wait -n` could not collect it.++Other alternatives rejected:++- Install `tini` or `dumb-init` as the entrypoint. With signal forwarding to the whole process group, PostgreSQL would receive `SIGTERM` at the same moment as the application. `SIGTERM` starts a smart shutdown, which refuses new connections while the application may still need one to finish. The entrypoint would also gain a dependency that solves only half of the problem, because the ordering logic still has to live in a script.+- Let the application stop PostgreSQL after its own shutdown. The backend also runs against an external metadata database in development and in deployments that set `DATABASE_DSN`. It would need to know whether the database is the embedded one and where its data directory lives, which couples it to the image layout.+- Rely on `docker run --init`. It is the operator's choice, not the image's, and it has the same ordering problem as `tini`.++### 2. Stop the application first, then PostgreSQL in fast mode++A `trap` on `TERM` and `INT` sends the received signal to the application. The supervisor then waits for the application to exit and logs `Databasus application exited with status <n>`. Next it sends `SIGINT` to the postmaster, which requests a fast shutdown. PostgreSQL disconnects remaining sessions and writes a shutdown checkpoint, and the supervisor waits until the postmaster process has exited. The supervisor signals its own child instead of calling `pg_ctl stop -m fast -w`, because `pg_ctl` finds the server through `postmaster.pid`, which a server that has just started may not have written yet. The container exits with the application's status.++Alternatives rejected:++- Smart shutdown (`SIGTERM` to the postmaster). It waits for every session to end. A session left by an application that was killed would hold the container until the stop timeout.+- Immediate shutdown (`-m immediate`). It skips the checkpoint, so the next start runs crash recovery, which is the behavior this change removes.+- Stop both services in parallel. The application's shutdown records interrupted backups (`openspec/specs/logical-backup-outcome/spec.md`, scenario "Application shuts down during a backup") and needs the database for that.++### 3. Survive interrupted waits and `set -e`++In Bash, a trapped signal interrupts `wait` immediately with a status above 128, before the awaited process has exited. The spike's first version stopped PostgreSQL while the application was still running because of this. The supervisor therefore repeats `wait -n -p exited_process_id` on both process IDs until Bash names the process that exited, and other waits repeat `wait` while `kill -0` succeeds. Every `wait` collects its status as `wait ... || status=$?`, so `set -e` does not end the script on a non-zero child status.++Alternative rejected: drop `set -e` for the whole script. The startup steps before supervision rely on it to stop at the first failure.++### 4. Install the stop trap at the start of `main`++Each phase sets the trap first. In the root phase no PostgreSQL process exists, so the handler only logs `Stop requested during startup` and exits. Between the `exec` and the runtime phase's trap, Bash briefly ignores a stop signal, because the kernel drops signals to process 1 that it does not handle. No PostgreSQL process runs in that moment, and Docker's stop timeout ends the container at worst. In the runtime phase, while no application runs, the handler first logs `Stop requested during startup`. It then stops the PostgreSQL process running at that moment and waits for it to exit, repeating `wait` while `kill -0` succeeds as in decision 3. The regular server receives `SIGINT` for a fast shutdown as in decision 2, a single-user step `SIGTERM`. Finally the handler exits with status `143` for `SIGTERM` or `130` for `SIGINT`. Exiting before the PostgreSQL process has ended would let the kernel kill it as soon as process 1 is gone, possibly during its shutdown checkpoint.++Docker delivers the stop signal to process 1 only, and Bash runs a trap only after the current foreground command returns. The single-user steps from `remove-embedded-postgresql-socket` therefore run in the background, followed by `wait` on their process ID. The handler sends them `SIGTERM`. In a spike, `SIGTERM` ended a single-user backend waiting for input within a second, while `SIGINT` did not. Recovery that was interrupted this way runs again on the next start, because the write-ahead log is unchanged.++Alternatives rejected:++- Ignore signals until the application runs. A stop during a long crash recovery would then wait for the full stop timeout and end in `SIGKILL`.+- Keep the single-user steps in the foreground. The trap would wait for a recovery of unbounded length.++### 5. Report an unexpected PostgreSQL exit by stopping the container++When `wait -n` returns because PostgreSQL ended first, the supervisor logs the event, sends `SIGTERM` to the application, waits for it and exits with status `1`. Nothing restarts PostgreSQL in place. A restart policy or the operator then starts a fresh container, which runs the normal recovery path.++Alternative rejected: restart PostgreSQL inside the running container. The application would see a database that disappeared and returned under it, and the supervisor would turn into a process manager.++### 6. Test shutdown in the filesystem suite++Two cases drive the real image.++`clean-shutdown` stops a healthy container with `docker stop` and with `docker kill --signal INT`, sends `SIGTERM` to the application process alone and kills the postmaster with `SIGKILL`. It checks exit status and duration. After each stop it reads the cluster state with `pg_controldata` from a helper container on the stopped volume. `Database cluster state: shut down` proves a clean stop, and `in production` proves a kill. The log of the next start cannot tell the two apart. The open step from `remove-embedded-postgresql-socket` replays the log, writes a shutdown checkpoint and discards its output, so the regular server always reports a clean previous shutdown. For the order of events, the supervisor logs `Databasus application exited with status <n>`, and the case asserts that this line precedes PostgreSQL's `received fast shutdown request`.++`startup-stop` holds the container inside a startup step without depending on timing. A `docker exec` loop inside the container waits for the target process and sends it `SIGSTOP`. The target is a `postgres --single` process in one part and the postmaster of the regular server in the other. With the step frozen, the case runs `docker stop` in the background. In the single-user part it asserts that `Stop requested during startup` appears while the target is still stopped. A foreground implementation would print that line only after the step had ended, so this part proves the background execution. The regular-server part skips that assertion. There the script may be waiting in a foreground `pg_isready` or `psql` call on the frozen postmaster, and Bash runs the trap only when that call returns. Both parts then send `SIGCONT`, so the pending signal reaches the target, and assert the exit status and the missing application start. The regular-server part also asserts the cluster state `shut down`.++Alternative rejected: a shell unit test with stand-in processes. It would test a copy of the supervision logic instead of the image the operator runs.++## Risks / Trade-offs++- [The application's HTTP drain takes up to 10 seconds, which equals Docker's default stop timeout, so PostgreSQL can still be killed] -> An idle application drains at once, and the spike's fast shutdown took about 0.1 seconds. Under load the result is no worse than today. Raising the timeout is out of scope.+- [The startup script now reaps orphaned processes as process 1] -> Bash collects any terminated child while it waits. Today the Go application is process 1 and does not reap processes it did not start.+- [A stop signal that arrives between the `exec` into the runtime phase and its trap is ignored] -> The window lasts until Bash has parsed the script, and no PostgreSQL process runs in it. Docker's stop timeout then kills a container that holds no database process.+- [`docker exec` sessions started during shutdown see the database disappear] -> They see the same thing today, earlier and without a checkpoint.+- [A single-user backend in the middle of write-ahead log replay may not act on `SIGTERM` at once; the spike only covered a backend waiting for input] -> The stop timeout then ends it with `SIGKILL`. The log stays unchanged, and the next start repeats the replay.+- [The open step of a clean cluster lasts about 0.1 seconds, so the `docker exec` loop could miss it] -> The loop starts as soon as the container runs and polls inside the container without a delay. Storage validation and `--test-storage` run before the first PostgreSQL step and take longer than the loop needs to start.++## Migration Plan++1. Apply after `remove-embedded-postgresql-socket`.+2. Build the image and run the `clean-shutdown` and `startup-stop` cases locally.+3. Publish. The first stop of an existing container still uses the old image's behavior. Its next start runs crash recovery once, and every later stop is clean.+4. Rollback restores the old behavior with no data change.diff --git a/openspec/changes/archive/2026-10-21-stop-embedded-postgresql-cleanly/proposal.md b/openspec/changes/archive/2026-10-21-stop-embedded-postgresql-cleanly/proposal.mdnew file mode 100644index 00000000..05333d3f--- /dev/null+++ b/openspec/changes/archive/2026-10-21-stop-embedded-postgresql-cleanly/proposal.md@@ -0,0 +1,43 @@+## Why++Every `docker stop` kills the embedded PostgreSQL server instead of shutting it down. Startup ends with `exec gosu databasus ./main`, so the Databasus application becomes process 1 and the only receiver of the stop signal. When it exits, the kernel kills every other process in the container, the PostgreSQL server included. Each following start therefore runs crash recovery. A long recovery used to run into the 30-second readiness limit, and the startup script then reset the write-ahead log of a healthy cluster. The open step of `remove-embedded-postgresql-socket` removes that limit, but every restart still depends on recovery, and the automatic reset stays reserved for real damage such as a full disk or a power loss.++## Governing docs++This change answers to [`AGENTS.md`](../../../AGENTS.md). It changes `docker/start.sh` and the Docker filesystem suite in `e2e/docker-storage/`. It changes no code under `backend/`, `frontend/`, `agent/` or `website/`.++It builds on `remove-embedded-postgresql-socket`, which rewrites the same startup functions, and is applied after that change.++## What Changes++- The startup script stays process 1 for the life of the container instead of replacing itself with the application. After the steps that need root, it replaces itself with a copy running under the `databasus` account, so process 1 stays non-root. That copy runs PostgreSQL and the application as child processes.+- On `SIGTERM` or `SIGINT`, the script forwards the signal to the application and waits until the application exits. It then shuts the embedded PostgreSQL server down in fast mode and waits for that shutdown. The container exits with the application's exit status.+- The application can still write to the metadata database while it shuts down, because PostgreSQL stops only after the application has exited.+- When the application exits on its own, the script shuts PostgreSQL down cleanly and the container exits with the application's status.+- When the PostgreSQL server exits while the application runs, the script stops the application and the container exits with a non-zero status, so a restart policy can start it again.+- A stop signal during startup ends startup. A PostgreSQL process that is already running is shut down, the application never starts, and the container exits with a non-zero status.+- The Docker filesystem suite gains two cases. They stop and break the container in these ways and read the cluster state of the stopped volume to prove a clean shutdown.++## Capabilities++### New Capabilities++- `container-shutdown`: how the container stops its application and the embedded PostgreSQL server, in which order, and with which exit status.++### Modified Capabilities++None.++## Impact++- `docker/start.sh`: `main` splits into a root phase and a runtime phase under `databasus`, entered with `--as-databasus`. The PostgreSQL steps drop their `gosu databasus` prefix, the single-user steps run in the background, and a new supervision step with signal handling replaces the final `exec`.+- `.trivyignore.yaml`: the justification for the root entrypoint describes the two-phase start.+- `e2e/docker-storage/run.sh`: two new cases for shutdown behavior.+- No backend, frontend, API, database migration, configuration variable or dependency change.++## Out of scope++- Raising the stop timeout. Docker's default of 10 seconds and the Helm chart's pod termination period stay as they are, and the installation documentation does not change. When the timeout runs out, the container is killed as it is today.+- Making the application wait for its background tasks after a stop signal. Today it exits once the HTTP server has drained (`backend/cmd/main.go:330-361`).+- Adding an init process such as `tini` to the image.+- Changing the automatic write-ahead log reset.diff --git a/openspec/changes/archive/2026-10-21-stop-embedded-postgresql-cleanly/specs/container-shutdown/spec.md b/openspec/changes/archive/2026-10-21-stop-embedded-postgresql-cleanly/specs/container-shutdown/spec.mdnew file mode 100644index 00000000..7b7108e2--- /dev/null+++ b/openspec/changes/archive/2026-10-21-stop-embedded-postgresql-cleanly/specs/container-shutdown/spec.md@@ -0,0 +1,59 @@+## Purpose++Defines how the Databasus container stops its application and its embedded PostgreSQL server, so that a normal stop leaves the metadata database cleanly shut down and the next start needs no crash recovery.++## ADDED Requirements++### Requirement: A stop signal shuts the application down before the embedded database++When the container receives `SIGTERM` or `SIGINT` while the application runs, the container SHALL pass the signal to the application and wait for the application process to exit. The embedded PostgreSQL server SHALL receive its shutdown request only after that exit. The container SHALL then shut the server down cleanly, wait for that shutdown to finish and exit with the application's exit status.++#### Scenario: Operator stops the container++- **WHEN** an operator stops a healthy container with the default stop timeout+- **THEN** the container exits with status `0` before the timeout+- **AND** the stopped data directory reports the cluster state `shut down`, not `in production`++#### Scenario: Interrupt signal++- **WHEN** a healthy container receives `SIGINT`+- **THEN** the container exits before the stop timeout+- **AND** the stopped data directory reports the cluster state `shut down`++#### Scenario: Database shutdown follows the application's exit++- **WHEN** the container stops after a stop signal+- **THEN** the log line in which the container reports the application's exit comes before the line in which PostgreSQL reports its shutdown request++### Requirement: The container ends when either service ends++When the application exits without a stop signal, the container SHALL shut the embedded PostgreSQL server down cleanly and exit with the application's exit status. When the embedded PostgreSQL server exits while the application runs, the container SHALL stop the application and exit with a non-zero status.++#### Scenario: Application exits on its own++- **WHEN** the application process exits while the container has received no stop signal+- **THEN** the container exits with the application's exit status+- **AND** the stopped data directory reports the cluster state `shut down`++#### Scenario: Embedded database exits unexpectedly++- **WHEN** the embedded PostgreSQL server exits while the application runs+- **THEN** the application process stops+- **AND** the container exits with a non-zero status++### Requirement: A stop signal during startup ends startup++When the container receives `SIGTERM` or `SIGINT` before the application has started, it SHALL NOT start the application. It SHALL stop the PostgreSQL process that is running at that moment, wait for it to exit and exit with a non-zero status. The container SHALL act on the signal while a PostgreSQL startup step is still running, not only after that step has finished.++#### Scenario: Stop while the regular server starts++- **WHEN** the container receives a stop signal after the regular PostgreSQL server has started and before the application starts+- **THEN** the container exits with a non-zero status before the stop timeout+- **AND** the log has no line that the application starts+- **AND** the stopped data directory reports the cluster state `shut down`++#### Scenario: Stop during a long startup step++- **WHEN** the container receives a stop signal while a PostgreSQL startup administration step is still running+- **THEN** the container logs that it is stopping startup before that step has ended+- **AND** the container exits with a non-zero status, and the application never startsdiff --git a/openspec/changes/archive/2026-10-21-stop-embedded-postgresql-cleanly/tasks.md b/openspec/changes/archive/2026-10-21-stop-embedded-postgresql-cleanly/tasks.mdnew file mode 100644index 00000000..0d5ddc72--- /dev/null+++ b/openspec/changes/archive/2026-10-21-stop-embedded-postgresql-cleanly/tasks.md@@ -0,0 +1,25 @@+## 1. Reproduce the unclean stop++- [x] 1.1 Add a `clean-shutdown` case to `e2e/docker-storage/run.sh` and to its `all` list. Add a helper that reads `Database cluster state` with `pg_controldata` from a helper container on a stopped volume. The first part of the case starts the candidate on a named volume and waits for health. It stops the container with `docker stop` and the default timeout, then asserts three things: the stop took less than 10 seconds, the exit status is `0` and the cluster state is `shut down`. Verify that `docker build --tag databasus-storage-test:local .` succeeds and that `CASE=clean-shutdown DATABASUS_IMAGE=databasus-storage-test:local bash e2e/docker-storage/run.sh` fails, because the current image leaves the state `in production`.+- [x] 1.2 Add a `startup-stop` case and add it to the `all` list. Each of its two parts starts the candidate on a fresh volume and runs a `docker exec` loop inside the container. The loop waits for the target process and sends it `SIGSTOP`. In the first part the target is a `postgres --single` process. In the second part it is the postmaster of the regular server, a `postgres` process without `--single` whose PID matches `postmaster.pid`. With the target frozen, the case starts `docker stop` in the background. In the first part only, it asserts that `Stop requested during startup` appears in the log within 2 seconds while the target is still stopped. In the second part, a foreground `pg_isready` or `psql` call can wait on the frozen postmaster, so the case sends `SIGCONT` without that assertion. In both parts, the case then sends `SIGCONT` to the target where not yet sent and asserts that the container exits with status `143`, which rules out a kill by the stop timeout, and that the log has no `Starting Databasus application...` line. In the second part it also asserts that the cluster state is `shut down`. Verify that `CASE=startup-stop DATABASUS_IMAGE=databasus-storage-test:local bash e2e/docker-storage/run.sh` fails against the current image.++## 2. Supervise the services++- [x] 2.1 In `docker/start.sh`, split `main` into a root phase and a runtime phase under `databasus`, following design decision 1. The root phase ends with `exec gosu databasus /app/start.sh` and a phase argument, and the PostgreSQL steps drop their `gosu databasus` prefix. Install a `TERM` and `INT` trap at the start of each phase, following design decision 4. Before the application starts, the handler logs `Stop requested during startup` and stops the PostgreSQL process running at that moment. The regular server receives `SIGINT` for a fast shutdown, a single-user step `SIGTERM`. The handler waits in a loop while `kill -0` succeeds and then exits with `143` or `130`. Run the single-user steps in the background, followed by `wait` on their process ID. Verify that `docker build --tag databasus-storage-test:local .` succeeds and that `CASE=startup-stop DATABASUS_IMAGE=databasus-storage-test:local bash e2e/docker-storage/run.sh` passes.+- [x] 2.2 Replace `exec gosu databasus ./main` with a supervision function that follows design decisions 1, 2, 3 and 5. It starts the application in the background, waits on both process IDs with `wait -n` and forwards a stop signal to the application. It repeats `wait -n -p` until Bash names the process that exited, collects every status with `|| status=$?` and logs `Databasus application exited with status <n>`. Afterwards it sends the postmaster `SIGINT` for a fast shutdown, waits for it to exit and exits with the application's status. When PostgreSQL ends first, it stops the application and exits with `1`. Verify that `docker build --tag databasus-storage-test:local .` succeeds and that `CASE=clean-shutdown DATABASUS_IMAGE=databasus-storage-test:local bash e2e/docker-storage/run.sh` passes.++## 3. Cover the remaining stop paths++- [x] 3.1 Extend the first part of `clean-shutdown`. Assert that `Databasus application exited with status 0` comes before PostgreSQL's `received fast shutdown request` line in `docker logs`. Verify that `CASE=clean-shutdown DATABASUS_IMAGE=databasus-storage-test:local bash e2e/docker-storage/run.sh` passes.+- [x] 3.2 Add three parts to `clean-shutdown`, each on a fresh volume.+ - Interrupt: send `docker kill --signal INT` to a healthy container. Assert that it exits within 10 seconds and that the cluster state is `shut down`.+ - Application exit: send `SIGTERM` to the application process alone with `docker exec <container> /bin/bash -c 'kill -TERM <pid of ./main>'`, because the image ships no `kill` executable. Assert that the container exits with `0` and that the cluster state is `shut down`.+ - PostgreSQL exit: send `SIGKILL` to the postmaster from `head -1 /databasus-data/pgdata/postmaster.pid`. Assert that the container exits with a non-zero status, that the log has the supervisor's `ERROR: PostgreSQL exited with status` line and that it lacks the `Databasus application exited with status` line of a normal application exit.++ Verify that `CASE=clean-shutdown DATABASUS_IMAGE=databasus-storage-test:local bash e2e/docker-storage/run.sh` passes.+- [x] 3.3 Verify that the `bind-root`, `upgrades` and `postgresql-recovery` cases still pass one at a time through `CASE=<case> DATABASUS_IMAGE=databasus-storage-test:local bash e2e/docker-storage/run.sh`.++## 4. Specs and review++- [x] 4.1 Verify that `openspec validate stop-embedded-postgresql-cleanly --strict` passes.+- [x] 4.2 Run the mandatory full implementation review from `AGENTS.md` and resolve its blocking findings. Then rebuild the image and verify that the `clean-shutdown` and `startup-stop` cases pass.diff --git a/openspec/specs/container-shutdown/spec.md b/openspec/specs/container-shutdown/spec.mdnew file mode 100644index 00000000..0514531c--- /dev/null+++ b/openspec/specs/container-shutdown/spec.md@@ -0,0 +1,61 @@+# Container Shutdown Specification++## Purpose++Defines how the Databasus container stops its application and its embedded PostgreSQL server, so that a normal stop leaves the metadata database cleanly shut down and the next start needs no crash recovery.++## Requirements++### Requirement: A stop signal shuts the application down before the embedded database++When the container receives `SIGTERM` or `SIGINT` while the application runs, the container SHALL pass the signal to the application and wait for the application process to exit. The embedded PostgreSQL server SHALL receive its shutdown request only after that exit. The container SHALL then shut the server down cleanly, wait for that shutdown to finish and exit with the application's exit status.++#### Scenario: Operator stops the container++- **WHEN** an operator stops a healthy container with the default stop timeout+- **THEN** the container exits with status `0` before the timeout+- **AND** the stopped data directory reports the cluster state `shut down`, not `in production`++#### Scenario: Interrupt signal++- **WHEN** a healthy container receives `SIGINT`+- **THEN** the container exits before the stop timeout+- **AND** the stopped data directory reports the cluster state `shut down`++#### Scenario: Database shutdown follows the application's exit++- **WHEN** the container stops after a stop signal+- **THEN** the log line in which the container reports the application's exit comes before the line in which PostgreSQL reports its shutdown request++### Requirement: The container ends when either service ends++When the application exits without a stop signal, the container SHALL shut the embedded PostgreSQL server down cleanly and exit with the application's exit status. When the embedded PostgreSQL server exits while the application runs, the container SHALL stop the application and exit with a non-zero status.++#### Scenario: Application exits on its own++- **WHEN** the application process exits while the container has received no stop signal+- **THEN** the container exits with the application's exit status+- **AND** the stopped data directory reports the cluster state `shut down`++#### Scenario: Embedded database exits unexpectedly++- **WHEN** the embedded PostgreSQL server exits while the application runs+- **THEN** the application process stops+- **AND** the container exits with a non-zero status++### Requirement: A stop signal during startup ends startup++When the container receives `SIGTERM` or `SIGINT` before the application has started, it SHALL NOT start the application. It SHALL stop the PostgreSQL process that is running at that moment, wait for it to exit and exit with a non-zero status. The container SHALL act on the signal while a PostgreSQL startup step is still running, not only after that step has finished.++#### Scenario: Stop while the regular server starts++- **WHEN** the container receives a stop signal after the regular PostgreSQL server has started and before the application starts+- **THEN** the container exits with a non-zero status before the stop timeout+- **AND** the log has no line that the application starts+- **AND** the stopped data directory reports the cluster state `shut down`++#### Scenario: Stop during a long startup step++- **WHEN** the container receives a stop signal while a PostgreSQL startup administration step is still running+- **THEN** the container logs that it is stopping startup before that step has ended+- **AND** the container exits with a non-zero status, and the application never starts