# PostgreSQL, as one StatefulSet we own.
#
# The same published db image every compose mode pulls (official postgres
# Alpine + pg_cron + wal-g + a baked /etc/postgresql/postgresql.conf, built
# once from docker/postgres-walg in the vibecarbon repo), started with the
# same flags as compose's db `command:` (carbon/docker-compose.yml). WAL
# archiving is therefore on from the first boot: there is no ALTER SYSTEM step
# and no restart to enable it.
#
# Placeholders. The double-brace tokens below are rendered at DEPLOY time by
# applyK3sManifests (renderK8sBase in src/lib/deploy/k8s/k3s.js), which applies
# a rendered temp copy of k8s/base and refuses to apply one that still carries
# any of them. They are quoted so this file stays valid YAML and
# `kubectl kustomize k8s/base` builds. Never apply k8s/base by hand: a literal
# StorageClass token is accepted by the API server, and a StatefulSet's
# volumeClaimTemplates cannot be changed afterwards.
#
#   DB_IMAGE / DB_IMAGE_TAG   the db image (resolveDbImage, src/lib/images.js)
#   WALG_S3_PREFIX_BASE       s3://<backup bucket>/backups/<project>/<env>/walg,
#                             one prefix per environment, shared by primary
#                             and standby. Each database lineage archives in
#                             its own folder under it, named by its system
#                             identifier: walg-env.sh (vibecarbon-wal-archive
#                             ConfigMap) exports WALG_S3_PREFIX from it, and
#                             every wal-g caller sources that file first
#   S3_ENDPOINT / S3_REGION   the backup bucket's endpoint
#   K8S_STORAGE_CLASS         the provider's CSI class (never the cluster
#                             default, which can be k3s' node-local local-path)
#
# Names other code relies on (src/lib/deploy/k8s/db-workload.js): StatefulSet
# `db`, pod `db-0`, container `db`, PVC `data-db-0`, pod label
# `app: vibecarbon-db` (also read by the admin Infrastructure page).
#
# The db volume stays attached for the life of the pod. A k8s-ha standby
# reseed (cold deploy, failover, restore) never scales this StatefulSet to
# zero and never mounts data-db-0 in another pod: reseedStandbyInPlace
# (src/lib/deploy/replication.js) stages a pg_basebackup into
# $PGDATA/.vc-reseed in the running container, stops postgres there, and the
# kubelet restarts the container in the same pod, where db-guard.sh (the db
# container's command below) swaps the staged tree in before postgres starts.
# The wal-g role is a file on this volume (subPath vibecarbon-role), never
# env, so a role move is one write with no restart either.
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: db
  labels:
    app: vibecarbon-db
    component: database
  # The vibecarbon CLI's deploy owns this object; Flux strips it from its
  # base build (flux/clusters/*). prune: disabled keeps Flux's garbage
  # collection from deleting the live one in either handoff order.
  annotations:
    kustomize.toolkit.fluxcd.io/prune: disabled
spec:
  serviceName: db-headless
  replicas: 1
  selector:
    matchLabels:
      app: vibecarbon-db
  template:
    metadata:
      labels:
        app: vibecarbon-db
        component: database
      annotations:
        # `kubectl exec statefulset/db` (the backup CronJob) and every
        # `kubectl exec db-0` land in the postgres container, never an init.
        kubectl.kubernetes.io/default-container: db
        # sha of the wal-archive ConfigMap this pod template was rendered
        # with. The script is mounted with subPath, and the kubelet never
        # updates a subPath ConfigMap mount in place, so a changed script only
        # reaches postgres when the pod is recreated. A changed sha changes the
        # template, which rolls the pod on the next apply.
        vibecarbon.dev/wal-archive-sha: "{{WAL_ARCHIVE_SHA}}"
    spec:
      # Nothing in this pod talks to the Kubernetes API.
      automountServiceAccountToken: false
      # The image sets STOPSIGNAL SIGINT (fast shutdown). 60s covers a
      # checkpoint on a busy database before the kubelet escalates to SIGKILL.
      terminationGracePeriodSeconds: 60
      # The entrypoint starts as root so it can chown PGDATA to the image's
      # postgres user (uid/gid 70 on Alpine), then drops to it with gosu, the
      # same way compose runs it. No fsGroup on purpose: the kubelet would
      # re-group every file and set g+rwx on PGDATA, and postgres refuses a
      # data directory that is not 0700 or 0750.
      securityContext:
        seccompProfile:
          type: RuntimeDefault
      # Pin postgres to the dedicated database node: cloud-init labels it
      # dedicated=db and taints it dedicated=db:NoSchedule
      # (carbon/cloud-init/k3s/db-init.sh, do-db-init.sh), so the selector
      # attracts this pod and the toleration lets it through the taint.
      nodeSelector:
        dedicated: db
      tolerations:
        - key: dedicated
          operator: Equal
          value: db
          effect: NoSchedule
      initContainers:
        # Restore, and the interrupted-restore guard. Runs on EVERY boot.
        #
        # Normal boot (RESTORE_BACKUP empty): exit 0, unless a restore's
        # in-progress marker is in PGDATA (a swap this init left half done);
        # then exit 1 with "restore interrupted; rerun vibecarbon restore".
        # It never sources walg-env.sh: a fresh volume has no system
        # identifier to read.
        #
        # Restore (RESTORE_BACKUP set by `vibecarbon restore` on
        # vibecarbon-infra-secrets, with RESTORE_RECOVERY_CONF rendered by the
        # CLI and RESTORE_LINEAGE naming the archive folder, sourced through
        # walg-env.sh): fetch exactly that base backup into $PGDATA/.vc-restore,
        # write the recovery config and recovery.signal into it, then swap it
        # in under the marker, the live cluster moving to $PGDATA/.vc-prev
        # (or, when a surviving .vc-prev says PGDATA holds an unproven copy,
        # that copy moving to $PGDATA/.vc-discard). Nothing touches the live
        # cluster until the fetch is complete, and nothing here removes
        # .vc-prev: the CLI renames it to .vc-discard and removes it once the
        # restored database promoted and proved writable. Staging and .vc-prev live
        # inside PGDATA because PGDATA is a mount point and cannot be
        # renamed. The same steps as the compose restore script
        # (composeRestoreScript, src/lib/deploy/compose/index.js); the census
        # in tests/unit/deploy/restore-destroy-before-verify-census.test.ts
        # holds both. Runs before postgres, so the app's migrations always
        # see the restored database. A PGDATA left mid-way by an in-place
        # reseed swap (db-guard.sh) is an unproven copy: it moves to
        # .vc-discard, never to the .vc-prev fallback. Under its own marker
        # the restore swap removes every in-place reseed staging dir and
        # marker ($PGDATA/.vc-reseed*), so a reseed left pending can never
        # swap over the restored cluster on a later start.
        - name: walg-restore
          image: "{{DB_IMAGE}}:{{DB_IMAGE_TAG}}"
          imagePullPolicy: IfNotPresent
          command:
            - /bin/bash
            - -c
            - |
              set -euo pipefail
              VC_MARKER="$PGDATA/.vc-restore-in-progress"
              if [ -z "${RESTORE_BACKUP:-}" ]; then
                # Every boot: a swap this init left half done must not boot. Rerunning
                # the restore settles it (see the settle step below).
                if [ -e "$VC_MARKER" ]; then
                  echo "restore interrupted; rerun vibecarbon restore" >&2
                  exit 1
                fi
                echo "walg-restore: no restore requested, normal boot."
                exit 0
              fi
              case "$RESTORE_BACKUP" in
                base_*) ;;
                *) echo "walg-restore: RESTORE_BACKUP=${RESTORE_BACKUP} is not a wal-g backup name" >&2; exit 1 ;;
              esac
              if [ -z "${RESTORE_RECOVERY_CONF:-}" ]; then
                echo "walg-restore: RESTORE_BACKUP is set without RESTORE_RECOVERY_CONF; rerun vibecarbon restore" >&2
                exit 1
              fi
              # This init runs on EVERY boot while the marker is set. A completed swap
              # of this same ATTEMPT (RESTORE_ATTEMPT, a new id per restore, recorded in
              # .vc-restored-from; no swap in progress) means the CLI has not cleared the
              # marker yet: boot it, never move the live cluster aside and restore it
              # again. A new attempt of the same base (another target, or a record an
              # earlier attempt left) has another id, so it restores. A marker with no
              # attempt id always restores.
              if [ -n "${RESTORE_ATTEMPT:-}" ] && [ ! -e "$VC_MARKER" ] && \
                 [ -f "$PGDATA/.vc-restored-from" ] && \
                 [ "$(cat "$PGDATA/.vc-restored-from")" = "$RESTORE_BACKUP $RESTORE_ATTEMPT" ]; then
                echo "walg-restore: ${RESTORE_BACKUP} is already restored on this volume (marker not cleared yet), normal boot."
                exit 0
              fi
              # The archive folder of the lineage being restored (walg-env.sh). PGDATA
              # does not hold that database yet, so the marker names it. Only a restore that
              # fetches sources it: a normal boot (a fresh volume included) has no wal-g call
              # and nothing to read a system identifier from.
              if [ -z "${RESTORE_LINEAGE:-}" ]; then
                echo "walg-restore: RESTORE_BACKUP is set without RESTORE_LINEAGE; rerun vibecarbon restore" >&2
                exit 1
              fi
              . /etc/postgresql/walg-env.sh
              echo "walg-restore: restoring ${RESTORE_BACKUP} (target ${RESTORE_TARGET:-latest})."
              VC_RECOVERY_CONF_FILE=/tmp/vc-recovery.conf
              printf '%s\n' "$RESTORE_RECOVERY_CONF" > "$VC_RECOVERY_CONF_FILE"

              # --- prelude ---
              VC_MARKER="$PGDATA/.vc-restore-in-progress"
              # 1. One restore at a time on this volume. This runs as root in the postgres
              #    user's PGDATA: the files it writes are never opened through a symlink.
              if [ -L "$PGDATA/.vc-restore.lock" ]; then
                echo "restore: $PGDATA/.vc-restore.lock is a symlink; refusing" >&2
                exit 1
              fi
              exec 9>"$PGDATA/.vc-restore.lock"
              if ! flock -n 9; then
                echo "restore: another restore holds $PGDATA/.vc-restore.lock; refusing" >&2
                exit 75
              fi
              # The marker is only ever replaced by rename, so a crash mid-write leaves
              # the previous state, never a torn one.
              vc_mark() {
                rm -f "$VC_MARKER.tmp"
                printf '%s' "$1" > "$VC_MARKER.tmp"
                mv -f "$VC_MARKER.tmp" "$VC_MARKER"
              }
              # The cluster's own entries in PGDATA: everything but the restore's .vc-*.
              vc_cluster_entries() {
                find "$PGDATA" -mindepth 1 -maxdepth 1 ! -name '.vc-*'
              }
              # --- end prelude ---

              # 2. Fetch the named base backup into staging. The live cluster is untouched.
              #
              # Bounded retry over Hetzner Object Storage read-after-write staleness
              # (quarantined in docs/mitigations.yml): a frontend that has not caught
              # up 404s a bucket/object that provably exists (NoSuchBucket / NoSuchKey /
              # status code: 404 / wal-g's own "object '…' not found in storage"
              # wording), which is how a compose scale died on 2026-07-31 seconds after
              # a successful base-backup push, and again on 2026-08-06. Bash mirror of
              # the compose path's JS retry (src/lib/deploy/walg-staleness.js): same
              # signatures, same 5-attempt 2/4/8/16s budget. It exists separately
              # because the kubelet runs this, with no JS seam. Each retry clears the
              # staging dir, never PGDATA. Anything that is not a storage 404 fails on
              # attempt 1.
              WALG_FETCH_ATTEMPTS=5
              WALG_FETCH_LOG=/tmp/walg-restore-fetch.log
              walg_attempt=1
              walg_delay=2
              rm -rf "$PGDATA/.vc-restore"
              mkdir -p "$PGDATA/.vc-restore"
              while :; do
                if wal-g backup-fetch "$PGDATA/.vc-restore" "$RESTORE_BACKUP" 2>&1 | tee "${WALG_FETCH_LOG}"; then
                  break
                fi
                if [ "${walg_attempt}" -ge "${WALG_FETCH_ATTEMPTS}" ] || \
                   ! grep -qE "NoSuchBucket|NoSuchKey|status code: 404|object '[^']*' not found in storage" "${WALG_FETCH_LOG}"; then
                  rm -rf "$PGDATA/.vc-restore"
                  echo "walg-restore: backup-fetch of ${RESTORE_BACKUP} FAILED on attempt ${walg_attempt}/${WALG_FETCH_ATTEMPTS}, see the output above; nothing was moved." >&2
                  exit 1
                fi
                echo "[walg] backup-fetch hit a stale storage frontend (attempt ${walg_attempt}/${WALG_FETCH_ATTEMPTS}), retrying in ${walg_delay}s"
                rm -rf "$PGDATA/.vc-restore"
                mkdir -p "$PGDATA/.vc-restore"
                sleep "${walg_delay}"
                walg_attempt=$((walg_attempt + 1))
                walg_delay=$((walg_delay * 2))
              done
              # --- staged ---
              if [ ! -f "$PGDATA/.vc-restore/PG_VERSION" ]; then
                rm -rf "$PGDATA/.vc-restore"
                echo "restore: $RESTORE_BACKUP fetched no PG_VERSION; nothing was moved" >&2
                exit 1
              fi
              # 3. A base pushed while a restore or a reseed left its .vc-* entries in
              #    PGDATA carries them: drop every one from the staged tree, by glob, so
              #    none can wedge the swap. The source database's WAL gap record goes
              #    too: the restored one has its own.
              find "$PGDATA/.vc-restore" -mindepth 1 -maxdepth 1 -name '.vc-*' -exec rm -rf {} +
              rm -rf "$PGDATA/.vc-restore/vibecarbon-wal-gap" "$PGDATA/.vc-restore/vibecarbon-wal-gap.clearing"
              # Recovery config into staging: strip the settings it rewrites, append the
              # new ones (rendered by the CLI, the same text on both tiers).
              VC_AUTO_CONF="$PGDATA/.vc-restore/postgresql.auto.conf"
              # These writes run as root inside a tree fetched from the bucket: a
              # symlink the base carries at either path is removed, never followed.
              [ -L "$VC_AUTO_CONF" ] && rm -f "$VC_AUTO_CONF"
              touch "$VC_AUTO_CONF"
              while IFS= read -r vc_line; do
                case "$vc_line" in
                  -*) sed -i "/^[[:space:]]*${vc_line#-}[[:space:]]*=/d" "$VC_AUTO_CONF" ;;
                  ?*) printf '%s\n' "$vc_line" >> "$VC_AUTO_CONF" ;;
                esac
              done < "$VC_RECOVERY_CONF_FILE"
              [ -L "$PGDATA/.vc-restore/recovery.signal" ] && rm -f "$PGDATA/.vc-restore/recovery.signal"
              touch "$PGDATA/.vc-restore/recovery.signal"
              chown -R postgres:postgres "$PGDATA/.vc-restore"

              # --- swap ---
              # 4. Settle what PGDATA holds, then swap under the in-progress marker.
              #    .vc-discard is only ever an unproven copy or a proven restore's old
              #    cluster the CLI was removing: garbage.
              rm -rf "$PGDATA/.vc-discard"
              if [ -f "$VC_MARKER" ] && [ "$(cat "$VC_MARKER")" = in ]; then
                vc_root=unproven
              elif [ -f "$VC_MARKER" ]; then
                vc_root=half-out
              elif [ -d "$PGDATA/.vc-prev" ]; then
                vc_root=unproven
              elif [ -e "$PGDATA/.vc-reseed-in-progress" ] || [ -L "$PGDATA/.vc-reseed-in-progress" ]; then
                # An in-place reseed stopped mid-swap (db-guard.sh): PGDATA holds part
                # of a tree, and the reseed's old one was garbage (D9). No fallback.
                vc_root=unproven
              else
                vc_root=live
              fi
              case "$vc_root" in
                unproven)
                  # .vc-prev (if any) holds the database from before; PGDATA an unproven
                  # copy or a reseed's partial tree.
                  vc_mark in
                  mkdir -p "$PGDATA/.vc-discard"
                  vc_cluster_entries | while IFS= read -r vc_entry; do mv "$vc_entry" "$PGDATA/.vc-discard/"; done
                  ;;
                half-out)
                  mkdir -p "$PGDATA/.vc-prev"
                  vc_cluster_entries | while IFS= read -r vc_entry; do mv "$vc_entry" "$PGDATA/.vc-prev/"; done
                  vc_mark in
                  ;;
                live)
                  if [ -n "$(vc_cluster_entries)" ]; then
                    vc_mark out
                    mkdir -p "$PGDATA/.vc-prev"
                    vc_cluster_entries | while IFS= read -r vc_entry; do mv "$vc_entry" "$PGDATA/.vc-prev/"; done
                  fi
                  vc_mark in
                  ;;
              esac
              # A stale in-place reseed (db-guard.sh) must not survive onto the restored
              # cluster: a later start would otherwise swap an old staged tree over it.
              # Cleared only now, under this swap's marker, so a crash before it still
              # finds the reseed state that rules PGDATA out as a fallback.
              rm -rf "$PGDATA/.vc-reseed" "$PGDATA/.vc-reseed-ready" "$PGDATA/.vc-reseed-ready.tmp" "$PGDATA/.vc-reseed-in-progress" "$PGDATA/.vc-reseed-in-progress.tmp"
              find "$PGDATA/.vc-restore" -mindepth 1 -maxdepth 1 | while IFS= read -r vc_entry; do mv "$vc_entry" "$PGDATA/"; done
              rmdir "$PGDATA/.vc-restore"
              # The slow removal goes before the marker: once the marker is gone, the
              # only thing in PGDATA that says "swapped, not proven" is recovery.signal,
              # and nothing slow may follow.
              rm -rf "$PGDATA/.vc-discard"
              # Record the attempt PGDATA now holds (renamed in, never torn), before the
              # marker goes: a k8s pod start during this same attempt boots it instead of
              # restoring it again.
              rm -f "$PGDATA/.vc-restored-from.tmp"
              printf '%s %s' "$RESTORE_BACKUP" "${RESTORE_ATTEMPT:-}" > "$PGDATA/.vc-restored-from.tmp"
              mv -f "$PGDATA/.vc-restored-from.tmp" "$PGDATA/.vc-restored-from"
              rm -f "$VC_MARKER"
              echo "restore: $RESTORE_BACKUP staged and swapped in"
              # --- end swap ---
          env:
            - name: PGDATA
              value: /var/lib/postgresql/data
            - name: RESTORE_TARGET
              valueFrom:
                secretKeyRef:
                  name: vibecarbon-infra-secrets
                  key: RESTORE_TARGET
                  optional: true
            - name: RESTORE_BACKUP
              valueFrom:
                secretKeyRef:
                  name: vibecarbon-infra-secrets
                  key: RESTORE_BACKUP
                  optional: true
            - name: RESTORE_RECOVERY_CONF
              valueFrom:
                secretKeyRef:
                  name: vibecarbon-infra-secrets
                  key: RESTORE_RECOVERY_CONF
                  optional: true
            - name: RESTORE_ATTEMPT
              valueFrom:
                secretKeyRef:
                  name: vibecarbon-infra-secrets
                  key: RESTORE_ATTEMPT
                  optional: true
            - name: RESTORE_LINEAGE
              valueFrom:
                secretKeyRef:
                  name: vibecarbon-infra-secrets
                  key: RESTORE_LINEAGE
                  optional: true
            - name: WALG_S3_PREFIX_BASE
              value: "{{WALG_S3_PREFIX_BASE}}"
            - name: WALG_PREVENT_WAL_OVERWRITE
              value: "true"
            - name: WALG_COMPRESSION_METHOD
              value: lz4
            - name: AWS_ENDPOINT
              value: "{{S3_ENDPOINT}}"
            - name: AWS_REGION
              value: "{{S3_REGION}}"
            - name: AWS_SHARED_CREDENTIALS_FILE
              value: /etc/walg/credentials
          volumeMounts:
            - name: data
              mountPath: /var/lib/postgresql/data
              subPath: postgres-data
            - name: walg-s3-creds
              mountPath: /etc/walg
              readOnly: true
            - name: wal-archive-script
              mountPath: /etc/postgresql/walg-env.sh
              subPath: walg-env.sh
              readOnly: true
      containers:
        - name: db
          image: "{{DB_IMAGE}}:{{DB_IMAGE_TAG}}"
          imagePullPolicy: IfNotPresent
          # db-guard.sh wraps the image's entrypoint, exactly like compose
          # (carbon/docker-compose.yml): it refuses to boot over an
          # interrupted restore, applies the wal-g role intent below to the
          # role file, finishes a pending in-place standby reseed (only when
          # the intent is standby and the staged tree's attempt id matches the
          # ready marker), then execs db-entrypoint.sh with these args.
          # Mounted from the vibecarbon-wal-archive ConfigMap and run through
          # sh, so it needs no exec bit. The CLI stops postgres in place
          # (SIGINT to PID 1) only after it has read this command and the
          # mounted file's reseed protocol marker in the RUNNING pod.
          command: ["sh", "/usr/local/bin/db-guard.sh"]
          # The same flags as compose's db `command:` (carbon/docker-compose.yml),
          # where each one's reasoning lives. The image's entrypoint keeps
          # archiving off on its init-time temporary server
          # (docker/postgres-walg/db-entrypoint.sh), so a fresh volume never
          # waits on S3 during initdb.
          args:
            - postgres
            - -c
            - config_file=/etc/postgresql/postgresql.conf
            - -c
            - wal_level=replica
            - -c
            - archive_mode=on
            - -c
            # Fault-tolerant wrapper around `wal-g wal-push` (vibecarbon-wal-archive
            # ConfigMap, k8s/base/backup/configmap-walg.yaml): retries, then
            # logs WAL_ARCHIVE_FAILED and exits 0 so a persistent S3 outage
            # cannot pin pg_wal and fill the disk. Invoked through bash so the
            # mounted file needs no exec bit.
            - archive_command=bash /etc/postgresql/wal-archive.sh %p
            - -c
            - archive_timeout=900
            - -c
            # Lets the k8s-ha standby (in recovery) accept the read-only psql
            # connection failover's pg_promote() needs.
            - hot_standby=on
            - -c
            - max_connections=200
            # Replication slot WAL cap, so a long-gone HA standby cannot fill
            # the primary's volume (past it the slot goes `lost` and the next
            # deploy reseeds), the floor a briefly disconnected standby catches
            # up from, and room for the standby plus a reseed's basebackup.
            - -c
            - max_slot_wal_keep_size=4GB
            - -c
            - wal_keep_size=512MB
            - -c
            - max_wal_senders=10
          ports:
            - name: postgres
              containerPort: 5432
              protocol: TCP
          env:
            # The official image's superuser. Only the db and the app's
            # migrate init container use it; the app connects as app_service.
            - name: POSTGRES_USER
              value: postgres
            - name: POSTGRES_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: vibecarbon-infra-secrets
                  key: DB_PASSWORD
            - name: PGPASSWORD
              valueFrom:
                secretKeyRef:
                  name: vibecarbon-infra-secrets
                  key: DB_PASSWORD
            - name: POSTGRES_DB
              value: postgres
            - name: PGDATABASE
              value: postgres
            - name: POSTGRES_HOST
              value: /var/run/postgresql
            - name: PGPORT
              value: "5432"
            - name: POSTGRES_PORT
              value: "5432"
            # Non-secret wal-g env: continuous WAL archiving (archive_command)
            # and the backup CronJob's `kubectl exec` (which inherits this env)
            # both read it. The S3 keys are a mounted file (walg-s3-creds), not
            # env, so rotating them never needs a template change.
            # WALG_S3_PREFIX_BASE is the environment's prefix; walg-env.sh
            # (sourced by every wal-g caller) appends this database's lineage
            # folder. A segment name already archived with other bytes is
            # refused, never overwritten.
            - name: WALG_S3_PREFIX_BASE
              value: "{{WALG_S3_PREFIX_BASE}}"
            - name: WALG_PREVENT_WAL_OVERWRITE
              value: "true"
            # The durable wal-g role intent, held in the CLI-owned ConfigMap
            # vibecarbon-db-role (never in this base, so Flux never sees it;
            # src/lib/deploy/walg-role.js). db-guard.sh writes it to the role
            # file on every container start. Optional: a cluster before its
            # first deploy, or with the ConfigMap gone, starts with the file
            # as it was.
            - name: VC_WALG_ROLE_INTENT
              valueFrom:
                configMapKeyRef:
                  name: vibecarbon-db-role
                  key: VC_WALG_ROLE_INTENT
                  optional: true
            - name: WALG_COMPRESSION_METHOD
              value: lz4
            # The nightly base backup runs inside this container's cgroup, so
            # it is kept at 2 (compose uses the wal-g default of 4) to bound
            # the burst against the limits below.
            - name: WALG_UPLOAD_CONCURRENCY
              value: "2"
            - name: AWS_ENDPOINT
              value: "{{S3_ENDPOINT}}"
            - name: AWS_REGION
              value: "{{S3_REGION}}"
            - name: AWS_SHARED_CREDENTIALS_FILE
              value: /etc/walg/credentials
          # Ready means the REAL server accepts TCP. The entrypoint's
          # first-boot temporary server listens on the socket only, so a TCP
          # pg_isready cannot mistake it for the real one (the d4 run-2 RCA in
          # awaitPostgresAccepting, src/lib/deploy/k8s/readiness.js). A hot
          # standby in recovery also answers, so the k8s-ha standby goes Ready
          # too. No liveness probe: a long WAL replay after a restore must not
          # be killed half way.
          # Startup uses the same check every second, so Ready lands within a
          # second of the server accepting. The probe stops at its first
          # success, so a large failureThreshold costs nothing. The 30-day
          # ceiling exists only because a startup probe must have one; a
          # recovering database must never be killed by a probe.
          startupProbe:
            exec:
              command: ["pg_isready", "-h", "127.0.0.1", "-p", "5432", "-U", "postgres"]
            periodSeconds: 1
            timeoutSeconds: 5
            failureThreshold: 2592000
          readinessProbe:
            exec:
              command: ["pg_isready", "-h", "127.0.0.1", "-p", "5432", "-U", "postgres"]
            periodSeconds: 5
            timeoutSeconds: 5
            failureThreshold: 3
          # Headroom for the daily wal-g base backup, which runs INSIDE this
          # container's cgroup (via `kubectl exec`, see k8s/base/backup/cronjob.yaml).
          # backup-push streams PGDATA → lz4 → S3; the limit is sized for the
          # backup window, not steady state, or it throttles postgres too.
          resources:
            requests:
              cpu: 250m
              memory: 512Mi
            limits:
              cpu: "2"
              memory: 2Gi
          volumeMounts:
            # subPath keeps PGDATA one level below the volume root: a freshly
            # formatted ext4 volume carries lost+found, and initdb refuses a
            # non-empty directory.
            - name: data
              mountPath: /var/lib/postgresql/data
              subPath: postgres-data
            - name: wal-archive-script
              mountPath: /etc/postgresql/wal-archive.sh
              subPath: wal-archive.sh
              readOnly: true
            - name: wal-archive-script
              mountPath: /etc/postgresql/walg-env.sh
              subPath: walg-env.sh
              readOnly: true
            - name: wal-archive-script
              mountPath: /usr/local/bin/db-guard.sh
              subPath: db-guard.sh
              readOnly: true
            # The wal-g role file (walg-role: primary or standby), a sibling
            # of postgres-data on the same volume and never inside PGDATA, so
            # pg_basebackup never copies it. Writable: db-guard.sh and the
            # CLI's live role write (setK8sWalgRole) write it in place.
            - name: data
              mountPath: /var/lib/vibecarbon/role
              subPath: vibecarbon-role
            - name: walg-s3-creds
              mountPath: /etc/walg
              readOnly: true
      volumes:
        - name: wal-archive-script
          configMap:
            # Invoked as `bash /etc/postgresql/wal-archive.sh` (archive_command),
            # so no exec bit is required on the mounted file.
            name: vibecarbon-wal-archive
        - name: walg-s3-creds
          secret:
            secretName: vibecarbon-infra-secrets
            # Optional so a no-S3 deploy still schedules the db pod; wal-g is
            # simply unconfigured then. items maps the INI key → credentials.
            optional: true
            items:
              - key: S3_CREDENTIALS_INI
                path: credentials
  volumeClaimTemplates:
    - metadata:
        name: data
        labels:
          app: vibecarbon-db
      spec:
        accessModes:
          - ReadWriteOnce
        # The provider's CSI class, pinned at deploy time. Left to the
        # cluster default this can bind k3s' node-local local-path, which
        # silently breaks replication, failover and wal-g restore (RCA: kept
        # k8s-ha rig e4, 2026-08-05). Immutable once the PVC exists.
        storageClassName: "{{K8S_STORAGE_CLASS}}"
        resources:
          requests:
            storage: 10Gi
