PostgreSQL backup tool with Point-In-Time-Recovery and restore verification
TypeScript backupbackupsdatabasedatabase-backupdevopsdockergolangkubernetesmariadbmongodbmysqlpgpostgrespostgresqls3self-hostedsystem-administrationtoolsweb-ui
FIX (verification): Handle missing extensions during backup verification (issue #619)
Rostislav Dugine0c76389db54
diff --git a/.github/workflows/ci-release.yml b/.github/workflows/ci-release.ymlindex 5c441056..51442c81 100644--- a/.github/workflows/ci-release.yml+++ b/.github/workflows/ci-release.yml@@ -117,7 +117,9 @@ jobs:sudo apt-get install -y trivy- name: Trivy Dockerfile misconfiguration scan- run: trivy config --severity HIGH,CRITICAL --exit-code 1 Dockerfile+ run: |+ trivy config --severity HIGH,CRITICAL --exit-code 1 Dockerfile+ trivy config --severity HIGH,CRITICAL --exit-code 1 agent/verification/images/postgres/Dockerfiletest-frontend:if: github.ref != 'refs/heads/develop'@@ -657,6 +659,32 @@ jobs:docker rmi databasus:smoke-${{ github.sha }} || truerm -rf /tmp/databasus-smoke-data || true+ build-verification-image:+ if: github.ref != 'refs/heads/develop'+ runs-on: ubuntu-latest+ needs: [lint-verification-agent, dockerfile-scan]+ permissions:+ contents: read+ steps:+ - name: Check out code+ uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1++ - name: Set up Docker Buildx+ uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3.12.0++ # Validate the extension Dockerfile builds (amd64, representative major) on+ # every PR; the full multi-arch matrix is built at release time below.+ - name: Build verification image (amd64, no push)+ uses: docker/build-push-action@ca052bb54ab0790a636c9b5f226502c73d547a25 # v5.4.0+ with:+ context: agent/verification/images/postgres+ push: false+ platforms: linux/amd64+ build-args: |+ PG_MAJOR=16+ cache-from: type=gha,scope=verification-postgres-16+ cache-to: type=gha,mode=min,scope=verification-postgres-16+determine-version:runs-on: self-hostedcontainer:@@ -793,6 +821,53 @@ jobs:databasus/databasus:v${{ needs.determine-version.outputs.new_version }}databasus/databasus:${{ github.sha }}+ push-verification-image:+ runs-on: ubuntu-latest+ needs: [determine-version, build-verification-image]+ if: ${{ needs.determine-version.outputs.should_release == 'true' }}+ permissions:+ contents: read+ strategy:+ fail-fast: false+ matrix:+ major: ["12", "13", "14", "15", "16", "17", "18"]+ steps:+ - name: Check out code+ uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1++ - name: Set up QEMU (enables multi-arch emulation)+ uses: docker/setup-qemu-action@c7c53464625b32c7a7e944ae62b3e17d2b600130 # v3.7.0++ - name: Set up Docker Buildx+ uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3.12.0++ - name: Log in to Docker Hub+ uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3.7.0+ with:+ username: ${{ secrets.DOCKERHUB_USERNAME }}+ password: ${{ secrets.DOCKERHUB_TOKEN }}++ # Pin the base to its current manifest digest so the published image is+ # reproducible rather than tracking a floating postgres:<major> tag.+ - name: Resolve digest-pinned base image+ id: base+ run: |+ DIGEST=$(docker buildx imagetools inspect postgres:${{ matrix.major }} --format '{{.Manifest.Digest}}')+ echo "image=postgres:${{ matrix.major }}@${DIGEST}" >> "$GITHUB_OUTPUT"++ - name: Build and push verification image+ uses: docker/build-push-action@ca052bb54ab0790a636c9b5f226502c73d547a25 # v5.4.0+ with:+ context: agent/verification/images/postgres+ push: true+ platforms: linux/amd64,linux/arm64+ build-args: |+ PG_MAJOR=${{ matrix.major }}+ BASE_IMAGE=${{ steps.base.outputs.image }}+ tags: |+ databasus/verification-postgres:${{ matrix.major }}+ databasus/verification-postgres:${{ matrix.major }}-v${{ needs.determine-version.outputs.new_version }}+release:runs-on: self-hostedcontainer:diff --git a/agent/verification/images/postgres/Dockerfile b/agent/verification/images/postgres/Dockerfilenew file mode 100644index 00000000..06443a0e--- /dev/null+++ b/agent/verification/images/postgres/Dockerfile@@ -0,0 +1,68 @@+# syntax=docker/dockerfile:1++# Databasus verification image: the official Postgres image plus a curated set of+# common extensions, so a dump's CREATE EXTENSION statements succeed when the+# agent restores a backup for verification (issue #619 PostGIS, plus auxiliary+# extensions like pg_stat_kcache / set_user). This mirrors how the agent already+# uses timescale/timescaledb for TimescaleDB. Built per PG major and published as+# databasus/verification-postgres:<major>.+#+# BASE_IMAGE is digest-pinned by CI (postgres:<major>@sha256:...). The tag-only+# default exists solely for local `docker build --build-arg PG_MAJOR=16` runs.+ARG PG_MAJOR=16+ARG BASE_IMAGE=postgres:${PG_MAJOR}++FROM ${BASE_IMAGE}++# ARGs declared before FROM are not visible in the build stage — redeclare it.+ARG PG_MAJOR++# Extensions whose CREATE EXTENSION works once the files are present, plus the+# Tier-2 monitoring extensions that additionally need shared_preload_libraries+# (set below). The official image already configures the apt.postgresql.org repo+# these packages come from. The list is overridable so the release matrix can+# trim a package PGDG does not build for a given major/arch — a missing package+# fails the build loudly rather than silently shipping a half-populated image.+ARG EXTENSION_PACKAGES="\+postgresql-${PG_MAJOR}-postgis-3 \+postgresql-${PG_MAJOR}-pgrouting \+postgresql-${PG_MAJOR}-h3 \+postgresql-${PG_MAJOR}-pgvector \+postgresql-${PG_MAJOR}-rum \+postgresql-${PG_MAJOR}-partman \+postgresql-${PG_MAJOR}-repack \+postgresql-${PG_MAJOR}-hypopg \+postgresql-${PG_MAJOR}-hll \+postgresql-${PG_MAJOR}-topn \+postgresql-${PG_MAJOR}-set-user \+postgresql-${PG_MAJOR}-pgaudit \+postgresql-${PG_MAJOR}-anonymizer \+postgresql-${PG_MAJOR}-ip4r \+postgresql-${PG_MAJOR}-semver \+postgresql-${PG_MAJOR}-pg-hashids \+postgresql-${PG_MAJOR}-http \+postgresql-${PG_MAJOR}-mysql-fdw \+postgresql-${PG_MAJOR}-tds-fdw \+postgresql-${PG_MAJOR}-pg-stat-kcache \+postgresql-${PG_MAJOR}-pg-qualstats \+postgresql-${PG_MAJOR}-pg-wait-sampling \+postgresql-${PG_MAJOR}-pg-stat-monitor \+postgresql-plpython3-${PG_MAJOR} \+postgresql-plperl-${PG_MAJOR} \+postgresql-pltcl-${PG_MAJOR}"++# Tier-2 extensions refuse to CREATE unless their library is preloaded. This list+# must match the packages installed above: a name whose library is absent makes+# Postgres refuse to start. Appending to the initdb sample means every fresh+# PGDATA (the verification container is ephemeral) inherits it; the agent does not+# pass -c shared_preload_libraries, so this value stands at runtime.+ARG PRELOAD_LIBRARIES="pg_stat_statements,pg_stat_kcache,pg_qualstats,pg_wait_sampling,pg_stat_monitor,pgaudit,set_user"++# Root is the base image's user; the official entrypoint still gosu-drops to the+# postgres user before exec, so the agent's hardened runtime is unchanged.+RUN set -eux; \+ apt-get update; \+ apt-get install -y --no-install-recommends ${EXTENSION_PACKAGES}; \+ rm -rf /var/lib/apt/lists/*; \+ printf "shared_preload_libraries = '%s'\n" "${PRELOAD_LIBRARIES}" \+ >> "/usr/share/postgresql/${PG_MAJOR}/postgresql.conf.sample"diff --git a/agent/verification/internal/config/config.go b/agent/verification/internal/config/config.goindex f3b59b38..5ac17e6d 100644--- a/agent/verification/internal/config/config.go+++ b/agent/verification/internal/config/config.go@@ -18,19 +18,33 @@ const configFileName = "databasus-verification.json"const minRAMMbPerJob = 512+// DefaultVerificationPgImageRepo bundles common extensions so a dump's CREATE+// EXTENSION statements succeed during verification; override via+// verificationPgImageRepo (e.g. a private registry, or "postgres" for stock).+const DefaultVerificationPgImageRepo = "databasus/verification-postgres"+type Config struct {- DatabasusHost string `json:"databasusHost"`- AgentID string `json:"agentId"`- Token string `json:"token"`- MaxCPU int `json:"maxCpu"`- MaxRAMMb int `json:"maxRamMb"`- MaxDiskGb int `json:"maxDiskGb"`- MaxConcurrentJobs int `json:"maxConcurrentJobs"`- AllowInsecureHTTP bool `json:"allowInsecureHttp"`+ DatabasusHost string `json:"databasusHost"`+ AgentID string `json:"agentId"`+ Token string `json:"token"`+ MaxCPU int `json:"maxCpu"`+ MaxRAMMb int `json:"maxRamMb"`+ MaxDiskGb int `json:"maxDiskGb"`+ MaxConcurrentJobs int `json:"maxConcurrentJobs"`+ AllowInsecureHTTP bool `json:"allowInsecureHttp"`+ VerificationPgImageRepo string `json:"verificationPgImageRepo"`flags parsedFlags}+func (c *Config) GetVerificationPgImageRepo() string {+ if c.VerificationPgImageRepo == "" {+ return DefaultVerificationPgImageRepo+ }++ return c.VerificationPgImageRepo+}+type Capacity struct {MaxCPU intMaxRAMMb int@@ -63,6 +77,12 @@ func (c *Config) LoadFromJSONAndArgs(fs *flag.FlagSet, args []string) {false,"Permit a plain http:// databasus-host (token and backup data sent unencrypted)",)+ c.flags.verificationPgImageRepo = fs.String(+ "verification-pg-image-repo",+ "",+ "Container image repo bundling PostgreSQL extensions for verification "++ "(default "+DefaultVerificationPgImageRepo+"; set to 'postgres' for the stock image)",+ )if err := fs.Parse(args); err != nil {os.Exit(1)@@ -199,14 +219,15 @@ func (c *Config) loadFromJSON() {func (c *Config) initSources() {c.flags.sources = map[string]string{- "databasus-host": "not configured",- "agent-id": "not configured",- "token": "not configured",- "max-cpu": "not configured",- "max-ram-mb": "not configured",- "max-disk-gb": "not configured",- "max-concurrent-jobs": "not configured",- "allow-insecure-http": "not configured",+ "databasus-host": "not configured",+ "agent-id": "not configured",+ "token": "not configured",+ "max-cpu": "not configured",+ "max-ram-mb": "not configured",+ "max-disk-gb": "not configured",+ "max-concurrent-jobs": "not configured",+ "allow-insecure-http": "not configured",+ "verification-pg-image-repo": "not configured",}if c.DatabasusHost != "" {@@ -240,6 +261,10 @@ func (c *Config) initSources() {if c.AllowInsecureHTTP {c.flags.sources["allow-insecure-http"] = configFileName}++ if c.VerificationPgImageRepo != "" {+ c.flags.sources["verification-pg-image-repo"] = configFileName+ }}func (c *Config) applyFlags() {@@ -285,6 +310,11 @@ func (c *Config) applyFlags() {c.AllowInsecureHTTP = truec.flags.sources["allow-insecure-http"] = "command line args"}++ if c.flags.verificationPgImageRepo != nil && *c.flags.verificationPgImageRepo != "" {+ c.VerificationPgImageRepo = *c.flags.verificationPgImageRepo+ c.flags.sources["verification-pg-image-repo"] = "command line args"+ }}func (c *Config) logConfigSources() {@@ -308,6 +338,13 @@ func (c *Config) logConfigSources() {"source",c.flags.sources["allow-insecure-http"],)+ log.Info(+ "verification-pg-image-repo",+ "value",+ c.GetVerificationPgImageRepo(),+ "source",+ c.flags.sources["verification-pg-image-repo"],+ )}func (c *Config) consentToInsecureHTTP(isStdinTTY bool, in *bufio.Reader) error {diff --git a/agent/verification/internal/config/config_test.go b/agent/verification/internal/config/config_test.goindex 39509280..4b82b20d 100644--- a/agent/verification/internal/config/config_test.go+++ b/agent/verification/internal/config/config_test.go@@ -173,3 +173,28 @@ func Test_MaskSensitive_WhenEmpty_ReturnsNotSet(t *testing.T) {func Test_MaskSensitive_WhenValue_RevealsQuarterThenMasks(t *testing.T) {assert.Equal(t, "ab***", maskSensitive("abcdefgh"))}++func Test_GetVerificationPgImageRepo_WhenUnset_ReturnsBundledDefault(t *testing.T) {+ cfg := &Config{}++ assert.Equal(t, DefaultVerificationPgImageRepo, cfg.GetVerificationPgImageRepo())+}++func Test_GetVerificationPgImageRepo_WhenSet_ReturnsConfiguredValue(t *testing.T) {+ cfg := &Config{VerificationPgImageRepo: "registry.internal/pg-verify"}++ assert.Equal(t, "registry.internal/pg-verify", cfg.GetVerificationPgImageRepo())+}++func Test_ApplyFlags_WhenImageRepoFlagSet_OverridesFileValue(t *testing.T) {+ cfg := &Config{VerificationPgImageRepo: "from-file"}+ cfg.initSources()++ flagValue := "from-flag"+ cfg.flags.verificationPgImageRepo = &flagValue++ cfg.applyFlags()++ assert.Equal(t, "from-flag", cfg.VerificationPgImageRepo)+ assert.Equal(t, "command line args", cfg.flags.sources["verification-pg-image-repo"])+}diff --git a/agent/verification/internal/config/dto.go b/agent/verification/internal/config/dto.goindex dab50b28..2b2c8148 100644--- a/agent/verification/internal/config/dto.go+++ b/agent/verification/internal/config/dto.go@@ -1,14 +1,15 @@package configtype parsedFlags struct {- databasusHost *string- agentID *string- token *string- maxCPU *int- maxRAMMb *int- maxDiskGb *int- maxConcurrentJobs *int- allowInsecureHTTP *bool+ databasusHost *string+ agentID *string+ token *string+ maxCPU *int+ maxRAMMb *int+ maxDiskGb *int+ maxConcurrentJobs *int+ allowInsecureHTTP *bool+ verificationPgImageRepo *stringsources map[string]string}diff --git a/agent/verification/internal/features/container/manager.go b/agent/verification/internal/features/container/manager.goindex 830eed4c..52f0225f 100644--- a/agent/verification/internal/features/container/manager.go+++ b/agent/verification/internal/features/container/manager.go@@ -18,9 +18,10 @@ const (containerReadyTimeout = 60 * time.SecondreadyPollInterval = 1 * time.Second- // engineImageRepo is the official Postgres image; the job's major version- // (from the backend assignment) is appended as the tag.- engineImageRepo = "postgres"+ // stockEngineImageRepo is the official Postgres image; the job's major version+ // (from the backend assignment) is appended as the tag. It is the fallback+ // when the configured (extension-bundling) repo can't be pulled.+ stockEngineImageRepo = "postgres"// timescaleImageRepo carries the timescaledb extension; the tag is// "<extversion>-pg<major>" so the engine matches the dump exactly@@ -51,20 +52,23 @@ var restoreTunedPostgresCmd = []string{}type Manager struct {- engine *dockerEngine- agentID string- log *slog.Logger+ engine *dockerEngine+ agentID string+ engineImageRepo string+ log *slog.Logger}func NewManager(engine *dockerEngine,agentID string,+ engineImageRepo string,log *slog.Logger,) *Manager {return &Manager{- engine: engine,- agentID: agentID,- log: log,+ engine: engine,+ agentID: agentID,+ engineImageRepo: engineImageRepo,+ log: log,}}@@ -99,10 +103,25 @@ func (m *Manager) PurgeContainers(ctx context.Context) {// Spawn's every failure is pre-pg_restore — the runner reports it with no exit// code (retryable AgentSetupFailed), never BackupRejected.func (m *Manager) Spawn(jobCtx context.Context, req SpawnRequest) (*PostgresContainer, error) {- image := imageForJob(req)+ image := imageForJob(req, m.engineImageRepo)if err := m.engine.EnsureImage(jobCtx, image); err != nil {- return nil, fmt.Errorf("ensure image: %w", err)+ fallbackImage, canFallBack := stockFallbackImage(req, image)+ if !canFallBack {+ return nil, fmt.Errorf("ensure image: %w", err)+ }++ // The extension-bundling image is unreachable (registry down, air-gapped,+ // not yet published). Fall back to the stock Postgres image; missing+ // extensions then surface as ignored pg_restore errors the runner tolerates.+ m.log.Warn("bundled verification image unavailable; falling back to stock postgres image",+ "bundled_image", image, "stock_image", fallbackImage, "error", err)++ image = fallbackImage++ if err := m.engine.EnsureImage(jobCtx, image); err != nil {+ return nil, fmt.Errorf("ensure stock image: %w", err)+ }}password, err := randomPassword()@@ -244,18 +263,35 @@ func pingOnce(ctx context.Context, conn dbconn.Conn) bool {return pgConn.Ping(pingCtx) == nil}-func imageForJob(req SpawnRequest) string {+func imageForJob(req SpawnRequest, engineImageRepo string) string {if req.TimescaledbVersion != "" {return fmt.Sprintf("%s:%s-pg%s", timescaleImageRepo, req.TimescaledbVersion, req.PgMajor)}- return imageForMajor(req.PgMajor)+ return imageForMajor(req.PgMajor, engineImageRepo)}-func imageForMajor(pgMajor string) string {+func imageForMajor(pgMajor, engineImageRepo string) string {return engineImageRepo + ":" + pgMajor}+// stockFallbackImage decides whether a failed pull of the configured image may+// retry against the official Postgres image. Timescale jobs need their exact+// version-matched image (pg_restore cannot cross extension versions), so they+// never fall back; nor does a job already targeting the stock repo.+func stockFallbackImage(req SpawnRequest, attemptedImage string) (string, bool) {+ if req.TimescaledbVersion != "" {+ return "", false+ }++ stockImage := imageForMajor(req.PgMajor, stockEngineImageRepo)+ if stockImage == attemptedImage {+ return "", false+ }++ return stockImage, true+}+func randomPassword() (string, error) {buf := make([]byte, 24)if _, err := rand.Read(buf); err != nil {diff --git a/agent/verification/internal/features/container/postgres_test.go b/agent/verification/internal/features/container/postgres_test.goindex 38330ac8..ac7ea55e 100644--- a/agent/verification/internal/features/container/postgres_test.go+++ b/agent/verification/internal/features/container/postgres_test.go@@ -11,7 +11,7 @@ import (func Test_BuildSpec_AppliesHardeningControls(t *testing.T) {// nil engine: buildSpec is pure and never calls the engine.- containerManager := NewManager(nil, "agent-1", testutil.DiscardLogger())+ containerManager := NewManager(nil, "agent-1", "databasus/verification-postgres", testutil.DiscardLogger())labels := map[string]string{LabelAgentID: "agent-1"}spec := containerManager.buildSpec(spawnPlan{@@ -35,7 +35,7 @@ func Test_BuildSpec_AppliesHardeningControls(t *testing.T) {}func Test_BuildSpec_SetsRestoreTunedPostgresCmd(t *testing.T) {- containerManager := NewManager(nil, "agent-1", testutil.DiscardLogger())+ containerManager := NewManager(nil, "agent-1", "databasus/verification-postgres", testutil.DiscardLogger())spec := containerManager.buildSpec(spawnPlan{verificationID: uuid.New(),@@ -75,35 +75,55 @@ func Test_GetVerifierConn_WhenSpawned_UsesResolvedHostPort(t *testing.T) {assert.Equal(t, "pw", conn.Password)}-func Test_ImageForMajor_ReturnsPostgresOfficialTagPerMajor(t *testing.T) {+func Test_ImageForMajor_AppendsMajorTagToConfiguredRepo(t *testing.T) {cases := []struct {major stringexpected string}{- {"12", "postgres:12"},- {"13", "postgres:13"},- {"14", "postgres:14"},- {"15", "postgres:15"},- {"16", "postgres:16"},- {"17", "postgres:17"},- {"18", "postgres:18"},+ {"12", "databasus/verification-postgres:12"},+ {"16", "databasus/verification-postgres:16"},+ {"18", "databasus/verification-postgres:18"},}for _, tc := range cases {t.Run(tc.major, func(t *testing.T) {- assert.Equal(t, tc.expected, imageForMajor(tc.major))+ assert.Equal(t, tc.expected, imageForMajor(tc.major, "databasus/verification-postgres"))})}}func Test_ImageForJob_WhenTimescaleVersionSet_ReturnsVersionMatchedTimescaleImage(t *testing.T) {- image := imageForJob(SpawnRequest{PgMajor: "17", TimescaledbVersion: "2.17.0"})+ image := imageForJob(+ SpawnRequest{PgMajor: "17", TimescaledbVersion: "2.17.0"}, "databasus/verification-postgres")- assert.Equal(t, "timescale/timescaledb:2.17.0-pg17", image)+ assert.Equal(t, "timescale/timescaledb:2.17.0-pg17", image,+ "timescale jobs ignore the engine repo and use the version-matched timescale image")}-func Test_ImageForJob_WhenNoTimescaleVersion_ReturnsStockPostgresImage(t *testing.T) {- image := imageForJob(SpawnRequest{PgMajor: "17"})+func Test_ImageForJob_WhenNoTimescaleVersion_UsesConfiguredEngineRepo(t *testing.T) {+ image := imageForJob(SpawnRequest{PgMajor: "17"}, "databasus/verification-postgres")- assert.Equal(t, "postgres:17", image)+ assert.Equal(t, "databasus/verification-postgres:17", image)+}++func Test_StockFallbackImage_WhenBundledEngineRepo_FallsBackToStockPostgres(t *testing.T) {+ fallbackImage, canFallBack := stockFallbackImage(+ SpawnRequest{PgMajor: "16"}, "databasus/verification-postgres:16")++ assert.True(t, canFallBack)+ assert.Equal(t, "postgres:16", fallbackImage)+}++func Test_StockFallbackImage_WhenAlreadyStockRepo_DoesNotFallBack(t *testing.T) {+ _, canFallBack := stockFallbackImage(SpawnRequest{PgMajor: "16"}, "postgres:16")++ assert.False(t, canFallBack, "a job already on the stock image has nothing to fall back to")+}++func Test_StockFallbackImage_WhenTimescaleJob_DoesNotFallBack(t *testing.T) {+ _, canFallBack := stockFallbackImage(+ SpawnRequest{PgMajor: "16", TimescaledbVersion: "2.17.0"}, "timescale/timescaledb:2.17.0-pg16")++ assert.False(t, canFallBack,+ "timescale needs its exact version-matched image; stock postgres cannot restore it")}diff --git a/agent/verification/internal/features/restore/missingextensions.go b/agent/verification/internal/features/restore/missingextensions.gonew file mode 100644index 00000000..07cbbbee--- /dev/null+++ b/agent/verification/internal/features/restore/missingextensions.go@@ -0,0 +1,112 @@+package restore++import (+ "regexp"+ "slices"+ "strconv"+ "strings"+)++const ignoredErrorsMarker = "errors ignored on restore:"++var extensionNamePattern = regexp.MustCompile(`extension "([^"]+)"`)++// IsMissingExtensionOnly reports whether a non-zero pg_restore exit is explained+// solely by extensions absent from this environment — i.e. the data itself+// restored. pg_restore runs without --exit-on-error, so it tails "errors ignored+// on restore: N"; this returns true only when every visible item error is+// extension-related and their count equals N. The count guard matters because+// StderrTail is capped at 8192 bytes: a truncated tail could hide a non-extension+// error, so when N can't be fully accounted for we refuse to tolerate.+func IsMissingExtensionOnly(stderrTail string) bool {+ ignoredCount, hasMarker := parseIgnoredErrorCount(stderrTail)+ if !hasMarker || ignoredCount < 1 {+ return false+ }++ itemErrors := queryErrorLines(stderrTail)+ if len(itemErrors) != ignoredCount {+ return false+ }++ for _, line := range itemErrors {+ if !isExtensionErrorLine(line) {+ return false+ }+ }++ return true+}++// ExtractUnavailableExtensions returns the de-duplicated, sorted names of the+// extensions pg_restore could not create, for an operator-facing log line.+func ExtractUnavailableExtensions(stderrTail string) []string {+ seen := map[string]struct{}{}++ var names []string++ for _, line := range queryErrorLines(stderrTail) {+ if !isExtensionErrorLine(line) {+ continue+ }++ for _, match := range extensionNamePattern.FindAllStringSubmatch(line, -1) {+ name := match[1]+ if _, isDup := seen[name]; isDup {+ continue+ }++ seen[name] = struct{}{}+ names = append(names, name)+ }+ }++ slices.Sort(names)++ return names+}++func parseIgnoredErrorCount(stderrTail string) (int, bool) {+ idx := strings.LastIndex(strings.ToLower(stderrTail), ignoredErrorsMarker)+ if idx < 0 {+ return 0, false+ }++ fields := strings.Fields(stderrTail[idx+len(ignoredErrorsMarker):])+ if len(fields) == 0 {+ return 0, false+ }++ count, err := strconv.Atoi(fields[0])+ if err != nil {+ return 0, false+ }++ return count, true+}++func queryErrorLines(stderrTail string) []string {+ var lines []string++ for line := range strings.SplitSeq(stderrTail, "\n") {+ if strings.Contains(strings.ToLower(line), "could not execute query: error:") {+ lines = append(lines, line)+ }+ }++ return lines+}++// isExtensionErrorLine matches the phrasings a missing extension produces — the+// failed CREATE EXTENSION and its cascading COMMENT ON EXTENSION. The "extension"+// guard keeps unrelated cascades (`type "..." does not exist`) out.+func isExtensionErrorLine(line string) bool {+ lowered := strings.ToLower(line)+ if !strings.Contains(lowered, "extension") {+ return false+ }++ return strings.Contains(lowered, "is not available") ||+ strings.Contains(lowered, "could not open extension control file") ||+ strings.Contains(lowered, "does not exist")+}diff --git a/agent/verification/internal/features/restore/missingextensions_test.go b/agent/verification/internal/features/restore/missingextensions_test.gonew file mode 100644index 00000000..932cd28d--- /dev/null+++ b/agent/verification/internal/features/restore/missingextensions_test.go@@ -0,0 +1,96 @@+package restore++import (+ "testing"++ "github.com/stretchr/testify/assert"+)++const missingAuxExtensionsStderr = `pg_restore: error: could not execute query: ERROR: extension "pg_stat_kcache" is not available+DETAIL: Could not open extension control file "/usr/share/postgresql/16/extension/pg_stat_kcache.control": No such file or directory.+HINT: The extension must first be installed on the system where PostgreSQL is running.+Command was: CREATE EXTENSION IF NOT EXISTS pg_stat_kcache WITH SCHEMA public;+++pg_restore: error: could not execute query: ERROR: extension "pg_stat_kcache" does not exist+Command was: COMMENT ON EXTENSION pg_stat_kcache IS 'Kernel statistics gathering';+++pg_restore: error: could not execute query: ERROR: extension "set_user" is not available+DETAIL: Could not open extension control file "/usr/share/postgresql/16/extension/set_user.control": No such file or directory.+HINT: The extension must first be installed on the system where PostgreSQL is running.+Command was: CREATE EXTENSION IF NOT EXISTS set_user WITH SCHEMA public;+++pg_restore: error: could not execute query: ERROR: extension "set_user" does not exist+Command was: COMMENT ON EXTENSION set_user IS 'similar to SET ROLE but with added logging';+++pg_restore: warning: errors ignored on restore: 4+`++// A missing data-bearing extension (PostGIS) cascades into type/relation errors+// that are NOT extension-related — the data did not restore, so this must not be+// tolerated.+const postgisCascadeStderr = `pg_restore: error: could not execute query: ERROR: extension "postgis" is not available+DETAIL: Could not open extension control file "/usr/share/postgresql/13/extension/postgis.control": No such file or directory.+Command was: CREATE EXTENSION IF NOT EXISTS postgis WITH SCHEMA public;+++pg_restore: error: could not execute query: ERROR: type "public.geometry" does not exist+Command was: CREATE TABLE public.places (geom public.geometry);+++pg_restore: error: could not execute query: ERROR: relation "public.places" does not exist+Command was: COPY public.places (geom) FROM stdin;+++pg_restore: warning: errors ignored on restore: 3+`++func Test_IsMissingExtensionOnly_WhenAllIgnoredErrorsAreMissingExtensions_ReturnsTrue(t *testing.T) {+ assert.True(t, IsMissingExtensionOnly(missingAuxExtensionsStderr))+}++func Test_IsMissingExtensionOnly_WhenCascadeDataErrorsPresent_ReturnsFalse(t *testing.T) {+ assert.False(t, IsMissingExtensionOnly(postgisCascadeStderr))+}++func Test_IsMissingExtensionOnly_WhenNoIgnoredErrorsMarker_ReturnsFalse(t *testing.T) {+ fatal := `pg_restore: error: could not execute query: ERROR: extension "set_user" is not available+Command was: CREATE EXTENSION IF NOT EXISTS set_user WITH SCHEMA public;+pg_restore: error: aborting because of errors`++ assert.False(t, IsMissingExtensionOnly(fatal))+}++func Test_IsMissingExtensionOnly_WhenVisibleErrorCountBelowMarker_ReturnsFalse(t *testing.T) {+ truncated := `pg_restore: error: could not execute query: ERROR: extension "set_user" is not available+Command was: CREATE EXTENSION IF NOT EXISTS set_user WITH SCHEMA public;+pg_restore: error: could not execute query: ERROR: extension "set_user" does not exist+Command was: COMMENT ON EXTENSION set_user IS 'x';+pg_restore: warning: errors ignored on restore: 5`++ assert.False(t, IsMissingExtensionOnly(truncated),+ "a truncated tail that cannot account for all N errors must not be tolerated")+}++func Test_IsMissingExtensionOnly_WhenNonExtensionErrorMixedIn_ReturnsFalse(t *testing.T) {+ mixed := `pg_restore: error: could not execute query: ERROR: extension "set_user" is not available+Command was: CREATE EXTENSION IF NOT EXISTS set_user WITH SCHEMA public;+pg_restore: error: could not execute query: ERROR: duplicate key value violates unique constraint "places_pkey"+Command was: COPY public.places (id) FROM stdin;+pg_restore: warning: errors ignored on restore: 2`++ assert.False(t, IsMissingExtensionOnly(mixed))+}++func Test_IsMissingExtensionOnly_WhenEmpty_ReturnsFalse(t *testing.T) {+ assert.False(t, IsMissingExtensionOnly(""))+}++func Test_ExtractUnavailableExtensions_ReturnsSortedDedupedNames(t *testing.T) {+ assert.Equal(t,+ []string{"pg_stat_kcache", "set_user"},+ ExtractUnavailableExtensions(missingAuxExtensionsStderr))+}diff --git a/agent/verification/internal/features/runner/runner.go b/agent/verification/internal/features/runner/runner.goindex da718650..7e3ab3ee 100644--- a/agent/verification/internal/features/runner/runner.go+++ b/agent/verification/internal/features/runner/runner.go@@ -6,6 +6,7 @@ import ("fmt""log/slog""slices"+ "strings""sync/atomic""time"@@ -269,17 +270,25 @@ func (r *Runner) executeJob(ctx context.Context, job *api.JobAssignment) {return}- if errors.Is(err, restore.ErrRestoreFailed) {- if restore.IsDiskExhausted(restoreResult.StderrTail) {- // Hitting the estimate-derived ceiling is agent infra, not- // proof the backup is corrupt — omit the exit code so the- // backend retries (AgentSetupFailed), never BackupRejected.- r.reportFailure(ctx, job.VerificationID, nil,- fmt.Sprintf("pg_restore hit job disk ceiling: %v", err), runLogger)+ if !errors.Is(err, restore.ErrRestoreFailed) {+ // Exec-infrastructure failure (no usable exit code).+ r.reportFailure(ctx, job.VerificationID, nil,+ fmt.Sprintf("pg_restore exec: %v", err), runLogger)- return- }+ return+ }++ if restore.IsDiskExhausted(restoreResult.StderrTail) {+ // Hitting the estimate-derived ceiling is agent infra, not proof the+ // backup is corrupt — omit the exit code so the backend retries+ // (AgentSetupFailed), never BackupRejected.+ r.reportFailure(ctx, job.VerificationID, nil,+ fmt.Sprintf("pg_restore hit job disk ceiling: %v", err), runLogger)++ return+ }+ if !restore.IsMissingExtensionOnly(restoreResult.StderrTail) {runLogger.Error("pg_restore failed","exit_code", restoreResult.PgRestoreExitCode,"stderr_tail", restoreResult.StderrTail)@@ -290,11 +299,16 @@ func (r *Runner) executeJob(ctx context.Context, job *api.JobAssignment) {return}- // Exec-infrastructure failure (no usable exit code).- r.reportFailure(ctx, job.VerificationID, nil,- fmt.Sprintf("pg_restore exec: %v", err), runLogger)-- return+ // The only items pg_restore skipped are CREATE/COMMENT EXTENSION for+ // extensions this verification environment lacks — the data restored.+ // Treat the backup as restorable and fall through to stats; the backend's+ // restored-size check is the remaining safety net.+ runLogger.Warn(+ "pg_restore completed with only missing-extension errors; treating backup as restorable",+ "exit_code", restoreResult.PgRestoreExitCode,+ "skipped_extensions",+ strings.Join(restore.ExtractUnavailableExtensions(restoreResult.StderrTail), ","),+ "stderr_tail", restoreResult.StderrTail)}if job.TimescaledbVersion != "" {diff --git a/agent/verification/internal/features/runner/runner_test.go b/agent/verification/internal/features/runner/runner_test.goindex 34d94e26..5596c4be 100644--- a/agent/verification/internal/features/runner/runner_test.go+++ b/agent/verification/internal/features/runner/runner_test.go@@ -199,6 +199,34 @@ func Test_ExecuteJob_WhenRestoreFailsNormally_ReportsFailedWithExitCode(t *testiassert.Equal(t, 1, *report.PgRestoreExitCode)}+func Test_ExecuteJob_WhenRestoreFailsWithOnlyMissingExtensions_ReportsCompleted(t *testing.T) {+ apiClient := &fakeAPI{downloadBody: []byte("ARCHIVE")}+ stderr := "pg_restore: error: could not execute query: ERROR: extension \"set_user\" is not available\n" ++ "Command was: CREATE EXTENSION IF NOT EXISTS set_user WITH SCHEMA public;\n" ++ "pg_restore: error: could not execute query: ERROR: extension \"set_user\" does not exist\n" ++ "Command was: COMMENT ON EXTENSION set_user IS 'x';\n" ++ "pg_restore: warning: errors ignored on restore: 2\n"+ restorer := &fakeRestorer{+ runErr: fmt.Errorf("restore: %w", restore.ErrRestoreFailed),+ runResult: restore.Result{PgRestoreExitCode: 1, DurationMs: 10, StderrTail: stderr},+ }+ stats := &fakeStats{stats: verifier.Stats{DBSizeBytes: 9_000_000, TableCount: 3}}+ r := newTestRunner(apiClient, okSpawner(), restorer, stats, newFakeRegistrar())+ r.connAlive = func(context.Context, dbconn.Conn) bool { return true }++ r.executeJob(t.Context(), postgresJob())++ report, ok := apiClient.lastReport()+ require.True(t, ok)+ assert.Equal(t, api.VerificationStatusCompleted, report.Status,+ "a restore whose only failures are missing extensions is restorable")+ require.NotNil(t, report.PgRestoreExitCode)+ assert.Equal(t, 1, *report.PgRestoreExitCode,+ "the real non-zero exit code is preserved on the success report")+ require.NotNil(t, report.DBSizeBytesAfterRestore)+ assert.Equal(t, int64(9_000_000), *report.DBSizeBytesAfterRestore)+}+func Test_ExecuteJob_WhenRestoreExecInfraFails_ReportsFailedWithoutExitCode(t *testing.T) {apiClient := &fakeAPI{downloadBody: []byte("ARCHIVE")}restorer := &fakeRestorer{runErr: errors.New("exec create failed")}diff --git a/agent/verification/internal/features/start/start.go b/agent/verification/internal/features/start/start.goindex 4de30639..c407045d 100644--- a/agent/verification/internal/features/start/start.go+++ b/agent/verification/internal/features/start/start.go@@ -73,7 +73,7 @@ func RunDaemon(cfg *config.Config, agentVersion string, isDev bool, log *slog.Loreturn err}- containerManager := container.NewManager(engine, cfg.AgentID, log)+ containerManager := container.NewManager(engine, cfg.AgentID, cfg.GetVerificationPgImageRepo(), log)if err := containerManager.StartupSelfCheck(ctx); err != nil {return err}diff --git a/backend/internal/features/verification/runs/agent_controller_test.go b/backend/internal/features/verification/runs/agent_controller_test.goindex 933ef2a9..5d64d9ab 100644--- a/backend/internal/features/verification/runs/agent_controller_test.go+++ b/backend/internal/features/verification/runs/agent_controller_test.go@@ -363,6 +363,67 @@ func Test_SubmitReport_WhenStatusCompleted_PersistsResultsAndTableStats(t *testi)}+func Test_SubmitReport_WhenCompletedWithNonZeroExitCode_MarksCompleted(t *testing.T) {+ router := createTestRouter()+ owner := users_testing.CreateTestUser(users_enums.UserRoleAdmin)+ workspace := workspaces_testing.CreateTestWorkspace("ws "+uuid.New().String(), owner, router)+ defer workspaces_testing.RemoveTestWorkspace(workspace, router)++ testStorage := storages.CreateTestStorage(workspace.ID)+ defer storages.RemoveTestStorage(testStorage.ID)++ notifier := notifiers.CreateTestNotifier(workspace.ID)+ defer notifiers.RemoveTestNotifier(notifier)++ database := databases.CreateTestDatabase(workspace.ID, testStorage, notifier)+ defer databases.RemoveTestDatabase(database)++ backup := backuping_logical.SeedTestBackup(t, database.ID, testStorage.ID, 100)+ agent := verification_agents.CreateTestVerificationAgent(t, router, owner.Token, "report-"+uuid.New().String())+ defer verification_agents.RemoveTestVerificationAgent(t, router, owner.Token, agent.Agent.ID)++ EnqueueManualVerificationViaAPI(t, router, owner.Token, backup.ID)+ assignment := ClaimVerificationViaAPI(+ t, router, agent.Agent.ID, agent.Token,+ AgentCapacity{MaxCPU: 4, MaxRAMMb: 4096, MaxDiskGb: 50, MaxConcurrentJobs: 2},+ )++ // When the agent tolerates a restore whose only failures were missing+ // extensions, it reports COMPLETED but carries the real non-zero pg_restore+ // exit code. The backend must accept that as success (the size guard, not the+ // exit code, is the arbiter on the COMPLETED path).+ pgRestoreExit := 1+ dbSize := int64(80_000_000)++ report := ReportRequest{+ Status: VerificationStatusCompleted,+ PgRestoreExitCode: &pgRestoreExit,+ DBSizeBytesAfterRestore: &dbSize,+ }++ test_utils.MakePostRequest(+ t, router,+ reportPathFor(agent.Agent.ID, assignment.VerificationID),+ "Bearer "+agent.Token,+ report,+ http.StatusNoContent,+ )++ final := GetVerificationByIDViaAPI(t, router, owner.Token, assignment.VerificationID)+ assert.Equal(t, VerificationStatusCompleted, final.Status,+ "a COMPLETED report with a non-zero pg_restore exit (tolerated missing extensions) must not be rejected")+ require.NotNil(t, final.PgRestoreExitCode)+ assert.Equal(t, 1, *final.PgRestoreExitCode)++ verifiedBackup := GetBackupViaAPI(t, router, owner.Token, database.ID, backup.ID)+ assert.Equal(+ t,+ backups_core_logical.RestoreVerificationStatusVerifiedSuccessful,+ verifiedBackup.RestoreVerificationStatus,+ "a tolerated missing-extension restore is a successful verification",+ )+}+func Test_SubmitReport_WhenRowWasReapedWhileAgentWasSilent_Returns410(t *testing.T) {router := createTestRouter()owner := users_testing.CreateTestUser(users_enums.UserRoleAdmin)