PostgreSQL backup tool with Point-In-Time-Recovery and restore verification
TypeScript backupbackupsdatabasedatabase-backupdevopsdockergolangkubernetesmariadbmongodbmysqlpgpostgrespostgresqls3self-hostedsystem-administrationtoolsweb-ui
FIX (restore): Accept a pre-existing public schema when restoring an include-schemas backup (issue #726)
Rostislav Dugin9147e828eab0
diff --git a/.claude/hooks/require-implementation-review.sh b/.claude/hooks/require-stop-review.shsimilarity index 59%rename from .claude/hooks/require-implementation-review.shrename to .claude/hooks/require-stop-review.shindex a1b012df..b783f55d 100755--- a/.claude/hooks/require-implementation-review.sh+++ b/.claude/hooks/require-stop-review.sh@@ -1,14 +1,24 @@#!/usr/bin/env bash-# Stop hook: blocks once per distinct working-tree state until claude-md-reviewer has audited it.+# Stop hook: blocks once per distinct working-tree state until the review round named by $1 has run.#-# Blocking is guarded by a marker file keyed on session id + a hash of the diff. Claude Code does-# not document a `stop_hook_active` field, so the marker is the only thing standing between this-# hook and an infinite stop loop. Any git failure exits 0 — never block on a broken repo.+# usage: require-stop-review.sh <marker-prefix> <reason>+#+# Blocking is guarded by a marker file keyed on marker prefix + session id + a hash of the diff.+# Claude Code does not document a `stop_hook_active` field, so the marker is the only thing standing+# between this hook and an infinite stop loop. Any git failure exits 0 — never block on a broken repo.+#+# Several rounds can share this script: each gets its own marker prefix, so they block together on+# the same tree state and clear together, costing one stop round rather than one per round.set -uo pipefailREVIEWED_SOURCE_DIRS=(backend agent frontend)+marker_prefix=${1:-}+reason=${2:-}+[ -n "$marker_prefix" ] || exit 0+[ -n "$reason" ] || exit 0+hook_input=$(cat)project_dir=${CLAUDE_PROJECT_DIR:-$(git rev-parse --show-toplevel 2>/dev/null)} || exit 0@@ -37,12 +47,9 @@ session_id=${session_id//[^a-zA-Z0-9_-]/}marker_dir="${TMPDIR:-/tmp}/databasus-claude-review"mkdir -p "$marker_dir" 2>/dev/null || exit 0-marker="$marker_dir/$session_id-$tree_hash"+marker="$marker_dir/$marker_prefix-$session_id-$tree_hash"[ -e "$marker" ] && exit 0: >"$marker" 2>/dev/null || exit 0-jq -n '{- decision: "block",- reason: "The working tree has unreviewed changes under backend/, agent/ or frontend/. Invoke the claude-md-reviewer subagent in implementation mode, then resolve every CHANGES REQUIRED finding before stopping. If it returns PASS, stop as normal."-}'+jq -n --arg reason "$reason" '{decision: "block", reason: $reason}'diff --git a/.claude/settings.json b/.claude/settings.jsonindex ff97ff25..df9bc9de 100644--- a/.claude/settings.json+++ b/.claude/settings.json@@ -16,7 +16,11 @@"hooks": [{"type": "command",- "command": "\"$CLAUDE_PROJECT_DIR/.claude/hooks/require-implementation-review.sh\""+ "command": "\"$CLAUDE_PROJECT_DIR/.claude/hooks/require-stop-review.sh\" compliance \"The working tree has unreviewed changes under backend/, agent/ or frontend/. Invoke the claude-md-reviewer subagent in implementation mode, then resolve every CHANGES REQUIRED finding before stopping. If it returns PASS, stop as normal.\""+ },+ {+ "type": "command",+ "command": "\"$CLAUDE_PROJECT_DIR/.claude/hooks/require-stop-review.sh\" solution \"Re-audit the finished change end to end before stopping, with fresh eyes and no attachment to what you already built. Does it remove the root cause the user actually asked about, or only the symptom they happened to see? Would a reviewer who never saw the plan choose this approach, or a simpler or more complete one? Did the plan itself get something wrong — wrong layer, wrong scope, a case it never considered, a break it did not flag? Confirm every test and lint command you claimed actually ran and passed, and that new tests fail when the fix is reverted. If any of that does not hold, say so plainly and fix it, reworking the approach or replanning if that is what it takes — do not defend the implemented solution or narrow the scope to fit it. If the change holds up, stop as normal.\""}]}diff --git a/agent/verification/e2e/fixture-gen/entrypoint.sh b/agent/verification/e2e/fixture-gen/entrypoint.shindex 23742505..6768d88e 100644--- a/agent/verification/e2e/fixture-gen/entrypoint.sh+++ b/agent/verification/e2e/fixture-gen/entrypoint.sh@@ -1,5 +1,6 @@#!/bin/bash# Produces /artifacts/good-pgN.dump for each supported Postgres major, one+# /artifacts/good-pg18-public-schema.dump (dumped with -n public), one# /artifacts/good-timescale-pg17.dump (a hypertable dump), and a single# /artifacts/broken.dump sentinel. For each fixture: spawn a sibling container# against the host daemon, wait for pg_isready, seed the schema, pg_dump -Fc to@@ -55,6 +56,15 @@ SQLOUT="$ARTIFACTS/good-pg${V}.dump"docker exec "$CID" pg_dump -Fc -U postgres postgres > "$OUT"+ # An include-schemas backup selects public explicitly, which makes pg_dump emit the schema+ # definition too — and every restore target already owns public (issue #726). Only the newest+ # major is covered; the archive shape does not vary by version.+ if [ "$V" = "18" ]; then+ PUBLIC_OUT="$ARTIFACTS/good-pg${V}-public-schema.dump"+ docker exec "$CID" pg_dump -Fc -n public -U postgres postgres > "$PUBLIC_OUT"+ echo "fixture: good-pg${V}-public-schema.dump=$(stat -c%s "$PUBLIC_OUT")B"+ fi+docker rm -f "$CID" >/dev/nullCID=""diff --git a/agent/verification/e2e/scripts/run-all.sh b/agent/verification/e2e/scripts/run-all.shindex d200aefb..f4299ee0 100644--- a/agent/verification/e2e/scripts/run-all.sh+++ b/agent/verification/e2e/scripts/run-all.sh@@ -10,6 +10,7 @@ TESTS=("test-restore-broken.sh""test-restore-disk-budget.sh""test-restore-timescale.sh"+ "test-restore-include-public-schema.sh")PG_VERSIONS=(12 13 14 15 16 17 18)diff --git a/agent/verification/e2e/scripts/test-restore-include-public-schema.sh b/agent/verification/e2e/scripts/test-restore-include-public-schema.shnew file mode 100644index 00000000..d093a5c6--- /dev/null+++ b/agent/verification/e2e/scripts/test-restore-include-public-schema.sh@@ -0,0 +1,53 @@+#!/bin/bash+# Restore e2e for an include-schemas backup (issue #726): the archive was dumped with -n public, so+# it carries CREATE SCHEMA public, and the spawned target already owns that schema from initdb. The+# agent must still report COMPLETED with pgRestoreExitCode==0 — --clean --if-exists drops the target+# schema before the archive recreates it.+set -euo pipefail++source "$(dirname "$0")/lib.sh"++PG_VERSION=18++WORK="/tmp/agent-work-restore-include-public-schema"+AGENT_ID="49494949-4949-4949-4949-494949494949"+VERIFICATION_ID="49494949-aaaa-aaaa-aaaa-494949494949"+BACKUP_ID="49494949-bbbb-bbbb-bbbb-494949494949"++rm -rf "$WORK"+mkdir -p "$WORK"+cd "$WORK"++reset_mock_state+reset_mock_version++cp "$ARTIFACTS/agent-v1" ./databasus-verification-agent+chmod +x ./databasus-verification-agent++start_agent "$AGENT_ID"++curl -sf -X POST "$MOCK/mock/set-backup-fixture" \+ -H 'Content-Type: application/json' \+ -d "{\"path\":\"/artifacts/good-pg${PG_VERSION}-public-schema.dump\"}"++curl -sf -X POST "$MOCK/mock/set-claim" \+ -H 'Content-Type: application/json' \+ -d "{\"verificationId\":\"$VERIFICATION_ID\",\"backupId\":\"$BACKUP_ID\",\"backupSizeMb\":1,\"maxContainerDiskMb\":2048,\"database\":{\"type\":\"POSTGRES_LOGICAL\",\"postgresqlLogical\":{\"version\":\"${PG_VERSION}\"}}}"++wait_for_report '"status":"COMPLETED"' 240 '"status":"FAILED"'++assert_report "$VERIFICATION_ID" '.pgRestoreExitCode == 0'+assert_report "$VERIFICATION_ID" '.tableCount == 2'+assert_report "$VERIFICATION_ID" '(.tableStats | map(.name) | sort) == ["t_a","t_b"]'++echo "Include-public-schema report OK: COMPLETED with exit code 0 and t_a+t_b present"++stop_agent++if ! leak_check "$AGENT_ID"; then+ echo "---- agent.out ----"+ cat agent.out+ exit 1+fi++echo "Verification agent restore include-public-schema e2e passed"diff --git a/agent/verification/internal/features/restore/dto.go b/agent/verification/internal/features/restore/dto.goindex fe13add1..9d794166 100644--- a/agent/verification/internal/features/restore/dto.go+++ b/agent/verification/internal/features/restore/dto.go@@ -1,5 +1,7 @@package restore+import "databasus-verification-agent/internal/features/dbconn"+// A non-zero ExitCode is not a Go error here — only failing to create, start,// or attach the exec is.type ExecResult struct {@@ -8,6 +10,13 @@ type ExecResult struct {Stderr string}+type PgRestoreSpec struct {+ ArchivePath string+ Conn dbconn.Conn+ ParallelJobs int+ IsTimescaledb bool+}+// Result is populated even on the error path (see ErrRestoreFailed).type Result struct {PgRestoreExitCode intdiff --git a/agent/verification/internal/features/restore/restorer.go b/agent/verification/internal/features/restore/restorer.goindex 0c66686f..e311d966 100644--- a/agent/verification/internal/features/restore/restorer.go+++ b/agent/verification/internal/features/restore/restorer.go@@ -7,8 +7,6 @@ import ("log/slog""strconv""time"-- "databasus-verification-agent/internal/features/dbconn")type Restorer struct {@@ -42,20 +40,30 @@ func (r *Restorer) StageBackupViaExec(func (r *Restorer) RunPgRestore(ctx context.Context,exec ExecRunner,- archivePath string,- conn dbconn.Conn,- parallelJobs int,+ spec PgRestoreSpec,) (Result, error) {started := time.Now().UTC()+ conn := spec.Conn+cmd := []string{"pg_restore", "-Fc", "--no-password","--no-owner", "--no-acl","-h", conn.Host, "-p", strconv.Itoa(conn.Port),"-U", conn.User, "-d", conn.Database,- "-j", strconv.Itoa(parallelJobs),- archivePath,+ "-j", strconv.Itoa(spec.ParallelJobs),+ }++ // The target is a throwaway freshly-initdb'd database, so every DROP is a no-op except the one+ // that matters: an archive dumped with -n public carries CREATE SCHEMA public, which would+ // otherwise collide with the schema initdb already made (issue #726). TimescaleDB is excluded+ // because --clean would DROP EXTENSION timescaledb, taking the catalog pre_restore needs.+ if !spec.IsTimescaledb {+ cmd = append(cmd, "--clean", "--if-exists")}++ cmd = append(cmd, spec.ArchivePath)+env := []string{"PGPASSWORD=" + conn.Password}execResult, err := exec.Exec(ctx, cmd, nil, env)diff --git a/agent/verification/internal/features/restore/restorer_test.go b/agent/verification/internal/features/restore/restorer_test.goindex 9b8893b3..025b3e0e 100644--- a/agent/verification/internal/features/restore/restorer_test.go+++ b/agent/verification/internal/features/restore/restorer_test.go@@ -46,6 +46,14 @@ func testConn() dbconn.Conn {}}+func testSpec(parallelJobs int) PgRestoreSpec {+ return PgRestoreSpec{+ ArchivePath: "/restore/x.dump",+ Conn: testConn(),+ ParallelJobs: parallelJobs,+ }+}+func Test_StageBackupViaExec_WhenDdSucceeds_StreamsBodyToDest(t *testing.T) {exec := &fakeExecRunner{result: ExecResult{ExitCode: 0}}r := NewRestorer(testutil.DiscardLogger())@@ -84,7 +92,7 @@ func Test_RunPgRestore_WhenPgRestoreSucceeds_ReturnsResultWithoutError(t *testinexec := &fakeExecRunner{result: ExecResult{ExitCode: 0}}r := NewRestorer(testutil.DiscardLogger())- result, err := r.RunPgRestore(t.Context(), exec, "/restore/x.dump", testConn(), 4)+ result, err := r.RunPgRestore(t.Context(), exec, testSpec(4))require.NoError(t, err)assert.Equal(t, 0, result.PgRestoreExitCode)@@ -103,11 +111,39 @@ func Test_RunPgRestore_WhenPgRestoreSucceeds_ReturnsResultWithoutError(t *testinassert.Equal(t, []string{"PGPASSWORD=deadbeef"}, exec.recorded[0].env)}+func Test_RunPgRestore_WhenNotTimescaledb_PassesCleanAndIfExists(t *testing.T) {+ exec := &fakeExecRunner{result: ExecResult{ExitCode: 0}}+ r := NewRestorer(testutil.DiscardLogger())++ _, err := r.RunPgRestore(t.Context(), exec, testSpec(1))++ require.NoError(t, err)+ require.Len(t, exec.recorded, 1)+ assert.Contains(t, exec.recorded[0].cmd, "--clean")+ assert.Contains(t, exec.recorded[0].cmd, "--if-exists")+}++func Test_RunPgRestore_WhenTimescaledb_OmitsCleanAndIfExists(t *testing.T) {+ exec := &fakeExecRunner{result: ExecResult{ExitCode: 0}}+ r := NewRestorer(testutil.DiscardLogger())++ spec := testSpec(1)+ spec.IsTimescaledb = true++ _, err := r.RunPgRestore(t.Context(), exec, spec)++ require.NoError(t, err)+ require.Len(t, exec.recorded, 1)+ assert.NotContains(t, exec.recorded[0].cmd, "--clean",+ "--clean would DROP EXTENSION timescaledb before pre_restore needs its catalog")+ assert.NotContains(t, exec.recorded[0].cmd, "--if-exists")+}+func Test_RunPgRestore_WhenPgRestoreExitsNonZero_ReturnsErrRestoreFailedWithPopulatedResult(t *testing.T) {exec := &fakeExecRunner{result: ExecResult{ExitCode: 1, Stderr: "could not execute query"}}r := NewRestorer(testutil.DiscardLogger())- result, err := r.RunPgRestore(t.Context(), exec, "/restore/x.dump", testConn(), 2)+ result, err := r.RunPgRestore(t.Context(), exec, testSpec(2))require.Error(t, err)assert.ErrorIs(t, err, ErrRestoreFailed)@@ -119,7 +155,7 @@ func Test_RunPgRestore_WhenExecInfraFails_ReturnsNonRestoreError(t *testing.T) {exec := &fakeExecRunner{err: errors.New("exec create failed")}r := NewRestorer(testutil.DiscardLogger())- _, err := r.RunPgRestore(t.Context(), exec, "/restore/x.dump", testConn(), 1)+ _, err := r.RunPgRestore(t.Context(), exec, testSpec(1))require.Error(t, err)assert.NotErrorIs(t, err, ErrRestoreFailed,@@ -131,7 +167,7 @@ func Test_RunPgRestore_WhenStderrHuge_TailIsTruncatedSuffix(t *testing.T) {exec := &fakeExecRunner{result: ExecResult{ExitCode: 0, Stderr: huge}}r := NewRestorer(testutil.DiscardLogger())- result, err := r.RunPgRestore(t.Context(), exec, "/restore/x.dump", testConn(), 1)+ result, err := r.RunPgRestore(t.Context(), exec, testSpec(1))require.NoError(t, err)assert.Len(t, result.StderrTail, 8192)diff --git a/agent/verification/internal/features/restore/missingextensions.go b/agent/verification/internal/features/restore/toleratederrors.gosimilarity index 67%rename from agent/verification/internal/features/restore/missingextensions.gorename to agent/verification/internal/features/restore/toleratederrors.goindex 07cbbbee..9886b305 100644--- a/agent/verification/internal/features/restore/missingextensions.go+++ b/agent/verification/internal/features/restore/toleratederrors.go@@ -11,14 +11,9 @@ 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 {+// The count guard matters because StderrTail is capped at 8192 bytes: a truncated tail could hide an+// error we would never tolerate, so when N can't be fully accounted for we refuse to tolerate.+func IsToleratedErrorsOnly(stderrTail string) bool {ignoredCount, hasMarker := parseIgnoredErrorCount(stderrTail)if !hasMarker || ignoredCount < 1 {return false@@ -30,7 +25,7 @@ func IsMissingExtensionOnly(stderrTail string) bool {}for _, line := range itemErrors {- if !isExtensionErrorLine(line) {+ if !isToleratedErrorLine(line) {return false}}@@ -46,7 +41,7 @@ func ExtractUnavailableExtensions(stderrTail string) []string {var names []stringfor _, line := range queryErrorLines(stderrTail) {- if !isExtensionErrorLine(line) {+ if !isMissingExtensionLine(line) {continue}@@ -97,10 +92,20 @@ func queryErrorLines(stderrTail string) []string {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 {+func isToleratedErrorLine(line string) bool {+ return isMissingExtensionLine(line) || isPreexistingPublicSchemaLine(line)+}++// The archive was dumped with -n public, which makes pg_dump emit the schema definition too, and+// every freshly initdb'd target already owns public (issue #726). Deliberately narrow: a blanket+// "already exists" rule would hide a genuinely half-restored archive.+func isPreexistingPublicSchemaLine(line string) bool {+ return strings.Contains(strings.ToLower(line), `schema "public" already exists`)+}++// The "extension" guard keeps unrelated cascades (`type "..." does not exist`) out, leaving the+// failed CREATE EXTENSION and its cascading COMMENT ON EXTENSION.+func isMissingExtensionLine(line string) bool {lowered := strings.ToLower(line)if !strings.Contains(lowered, "extension") {return falsediff --git a/agent/verification/internal/features/restore/missingextensions_test.go b/agent/verification/internal/features/restore/toleratederrors_test.gosimilarity index 59%rename from agent/verification/internal/features/restore/missingextensions_test.gorename to agent/verification/internal/features/restore/toleratederrors_test.goindex 932cd28d..1da4b96e 100644--- a/agent/verification/internal/features/restore/missingextensions_test.go+++ b/agent/verification/internal/features/restore/toleratederrors_test.go@@ -48,45 +48,77 @@ 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))+// An archive dumped with -n public carries the schema definition, and the restore target already+// owns public (issue #726).+const preexistingPublicSchemaStderr = `pg_restore: error: could not execute query: ERROR: schema "public" already exists+Command was: CREATE SCHEMA public;+++pg_restore: warning: errors ignored on restore: 1+`++func Test_IsToleratedErrorsOnly_WhenAllIgnoredErrorsAreMissingExtensions_ReturnsTrue(t *testing.T) {+ assert.True(t, IsToleratedErrorsOnly(missingAuxExtensionsStderr))}-func Test_IsMissingExtensionOnly_WhenCascadeDataErrorsPresent_ReturnsFalse(t *testing.T) {- assert.False(t, IsMissingExtensionOnly(postgisCascadeStderr))+func Test_IsToleratedErrorsOnly_WhenCascadeDataErrorsPresent_ReturnsFalse(t *testing.T) {+ assert.False(t, IsToleratedErrorsOnly(postgisCascadeStderr))}-func Test_IsMissingExtensionOnly_WhenNoIgnoredErrorsMarker_ReturnsFalse(t *testing.T) {+func Test_IsToleratedErrorsOnly_WhenNoIgnoredErrorsMarker_ReturnsFalse(t *testing.T) {fatal := `pg_restore: error: could not execute query: ERROR: extension "set_user" is not availableCommand was: CREATE EXTENSION IF NOT EXISTS set_user WITH SCHEMA public;pg_restore: error: aborting because of errors`- assert.False(t, IsMissingExtensionOnly(fatal))+ assert.False(t, IsToleratedErrorsOnly(fatal))}-func Test_IsMissingExtensionOnly_WhenVisibleErrorCountBelowMarker_ReturnsFalse(t *testing.T) {+func Test_IsToleratedErrorsOnly_WhenVisibleErrorCountBelowMarker_ReturnsFalse(t *testing.T) {truncated := `pg_restore: error: could not execute query: ERROR: extension "set_user" is not availableCommand was: CREATE EXTENSION IF NOT EXISTS set_user WITH SCHEMA public;pg_restore: error: could not execute query: ERROR: extension "set_user" does not existCommand was: COMMENT ON EXTENSION set_user IS 'x';pg_restore: warning: errors ignored on restore: 5`- assert.False(t, IsMissingExtensionOnly(truncated),+ assert.False(t, IsToleratedErrorsOnly(truncated),"a truncated tail that cannot account for all N errors must not be tolerated")}-func Test_IsMissingExtensionOnly_WhenNonExtensionErrorMixedIn_ReturnsFalse(t *testing.T) {+func Test_IsToleratedErrorsOnly_WhenNonExtensionErrorMixedIn_ReturnsFalse(t *testing.T) {mixed := `pg_restore: error: could not execute query: ERROR: extension "set_user" is not availableCommand 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))+ assert.False(t, IsToleratedErrorsOnly(mixed))+}++func Test_IsToleratedErrorsOnly_WhenEmpty_ReturnsFalse(t *testing.T) {+ assert.False(t, IsToleratedErrorsOnly(""))+}++func Test_IsToleratedErrorsOnly_WhenOnlyPreexistingPublicSchema_ReturnsTrue(t *testing.T) {+ assert.True(t, IsToleratedErrorsOnly(preexistingPublicSchemaStderr))}-func Test_IsMissingExtensionOnly_WhenEmpty_ReturnsFalse(t *testing.T) {- assert.False(t, IsMissingExtensionOnly(""))+func Test_IsToleratedErrorsOnly_WhenMissingExtensionsAndPreexistingPublicSchema_ReturnsTrue(t *testing.T) {+ combined := `pg_restore: error: could not execute query: ERROR: schema "public" already exists+Command was: CREATE SCHEMA public;+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: warning: errors ignored on restore: 2`++ assert.True(t, IsToleratedErrorsOnly(combined))+}++func Test_IsToleratedErrorsOnly_WhenRelationAlreadyExists_ReturnsFalse(t *testing.T) {+ relationClash := `pg_restore: error: could not execute query: ERROR: relation "public.t_a" already exists+Command was: CREATE TABLE public.t_a (id integer NOT NULL);+pg_restore: warning: errors ignored on restore: 1`++ assert.False(t, IsToleratedErrorsOnly(relationClash),+ "tolerating a pre-existing public schema must not become a blanket already-exists rule")}func Test_ExtractUnavailableExtensions_ReturnsSortedDedupedNames(t *testing.T) {diff --git a/agent/verification/internal/features/runner/concurrent_restores_integration_test.go b/agent/verification/internal/features/runner/concurrent_restores_integration_test.goindex e9552b6f..f3d0106b 100644--- a/agent/verification/internal/features/runner/concurrent_restores_integration_test.go+++ b/agent/verification/internal/features/runner/concurrent_restores_integration_test.go@@ -184,7 +184,7 @@ func (r *barrierRestorer) StageBackupViaExec(}func (r *barrierRestorer) RunPgRestore(- _ context.Context, _ restore.ExecRunner, _ string, _ dbconn.Conn, _ int,+ _ context.Context, _ restore.ExecRunner, _ restore.PgRestoreSpec,) (restore.Result, error) {r.barrier.Done()r.barrier.Wait()diff --git a/agent/verification/internal/features/runner/fakes_test.go b/agent/verification/internal/features/runner/fakes_test.goindex 36f6e2e9..7a6e19be 100644--- a/agent/verification/internal/features/runner/fakes_test.go+++ b/agent/verification/internal/features/runner/fakes_test.go@@ -143,7 +143,8 @@ type fakeRestorer struct {// calls records the restore-related call order ("roles", "pre", "restore", "post") for a single job.calls []string// runParallelJobs records the -j value RunPgRestore was invoked with.- runParallelJobs int+ runParallelJobs int+ runIsTimescaledb bool}func (r *fakeRestorer) StageBackupViaExec(@@ -157,10 +158,11 @@ func (r *fakeRestorer) StageBackupViaExec(}func (r *fakeRestorer) RunPgRestore(- ctx context.Context, _ restore.ExecRunner, _ string, _ dbconn.Conn, parallelJobs int,+ ctx context.Context, _ restore.ExecRunner, spec restore.PgRestoreSpec,) (restore.Result, error) {r.calls = append(r.calls, "restore")- r.runParallelJobs = parallelJobs+ r.runParallelJobs = spec.ParallelJobs+ r.runIsTimescaledb = spec.IsTimescaledbif r.runBlocks {r.runEntered.Store(true)diff --git a/agent/verification/internal/features/runner/interfaces.go b/agent/verification/internal/features/runner/interfaces.goindex 5766ef54..a6fea534 100644--- a/agent/verification/internal/features/runner/interfaces.go+++ b/agent/verification/internal/features/runner/interfaces.go@@ -35,9 +35,7 @@ type Restorer interface {RunPgRestore(ctx context.Context,exec restore.ExecRunner,- archivePath string,- conn dbconn.Conn,- parallelJobs int,+ spec restore.PgRestoreSpec,) (restore.Result, error)EnsureArchiveOwnerRoles(ctx context.Context,diff --git a/agent/verification/internal/features/runner/runner.go b/agent/verification/internal/features/runner/runner.goindex 907fc732..b18f6d5a 100644--- a/agent/verification/internal/features/runner/runner.go+++ b/agent/verification/internal/features/runner/runner.go@@ -296,8 +296,12 @@ func (r *Runner) executeJob(ctx context.Context, job *api.JobAssignment) {}}- restoreResult, err := r.restorer.RunPgRestore(- jobCtx, jobContainer, archivePath, jobContainer.GetInContainerConn(), parallelJobs)+ restoreResult, err := r.restorer.RunPgRestore(jobCtx, jobContainer, restore.PgRestoreSpec{+ ArchivePath: archivePath,+ Conn: jobContainer.GetInContainerConn(),+ ParallelJobs: parallelJobs,+ IsTimescaledb: job.TimescaledbVersion != "",+ })if err != nil {if reportIfDiskLimitHit() {return@@ -325,7 +329,7 @@ func (r *Runner) executeJob(ctx context.Context, job *api.JobAssignment) {return}- if !restore.IsMissingExtensionOnly(restoreResult.StderrTail) {+ if !restore.IsToleratedErrorsOnly(restoreResult.StderrTail) {runLogger.Error("pg_restore failed","exit_code", restoreResult.PgRestoreExitCode,"stderr_tail", restoreResult.StderrTail)@@ -336,12 +340,12 @@ func (r *Runner) executeJob(ctx context.Context, job *api.JobAssignment) {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.+ // The only items pg_restore skipped are ones that say nothing about the archive's integrity:+ // CREATE/COMMENT EXTENSION for extensions this environment lacks, and a public schema the+ // target already owned — 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",+ "pg_restore completed with only tolerated errors; treating backup as restorable","exit_code", restoreResult.PgRestoreExitCode,"skipped_extensions",strings.Join(restore.ExtractUnavailableExtensions(restoreResult.StderrTail), ","),diff --git a/agent/verification/internal/features/runner/runner_test.go b/agent/verification/internal/features/runner/runner_test.goindex 83bd0da0..ba282fb4 100644--- a/agent/verification/internal/features/runner/runner_test.go+++ b/agent/verification/internal/features/runner/runner_test.go@@ -252,6 +252,27 @@ func Test_ExecuteJob_WhenRestoreFailsWithOnlyMissingExtensions_ReportsCompleted(assert.Equal(t, int64(9_000_000), *report.DBSizeBytesAfterRestore)}+func Test_ExecuteJob_WhenRestoreFailsWithOnlyPreexistingPublicSchema_ReportsCompleted(t *testing.T) {+ apiClient := &fakeAPI{downloadBody: []byte("ARCHIVE")}+ stderr := "pg_restore: error: could not execute query: ERROR: schema \"public\" already exists\n" ++ "Command was: CREATE SCHEMA public;\n" ++ "pg_restore: warning: errors ignored on restore: 1\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,+ "an archive dumped with -n public collides with the target's own public schema; the data restored")+}+func Test_ExecuteJob_WhenRestoreExecInfraFails_ReportsFailedWithoutExitCode(t *testing.T) {apiClient := &fakeAPI{downloadBody: []byte("ARCHIVE")}restorer := &fakeRestorer{runErr: errors.New("exec create failed")}@@ -345,6 +366,8 @@ func Test_ExecuteJob_WhenTimescaleJobSucceeds_RunsPreRestoreThenRestoreThenPostR"timescaledb restore must enter restoring mode, restore, then leave it")assert.Equal(t, 1, restorer.runParallelJobs,"timescaledb restore must be single-threaded to keep _timescaledb_catalog FK order")+ assert.True(t, restorer.runIsTimescaledb,+ "the restorer decides on --clean from this flag")}func Test_ExecuteJob_WhenNonTimescaleJob_DoesNotRunTimescaleHooks(t *testing.T) {@@ -360,6 +383,8 @@ func Test_ExecuteJob_WhenNonTimescaleJob_DoesNotRunTimescaleHooks(t *testing.T)"a non-timescaledb restore must not run the timescaledb hooks")assert.Equal(t, 2, restorer.runParallelJobs,"a non-timescaledb restore keeps parallel jobs (CPUPerJob)")+ assert.False(t, restorer.runIsTimescaledb,+ "the restorer decides on --clean from this flag")}func Test_ExecuteJob_WhenOwnerRoleCreationFails_ReportsFailedWithoutRestoring(t *testing.T) {diff --git a/backend/internal/features/restores/usecases/postgresql/preexistingpublicschema.go b/backend/internal/features/restores/usecases/postgresql/preexistingpublicschema.gonew file mode 100644index 00000000..245a70af--- /dev/null+++ b/backend/internal/features/restores/usecases/postgresql/preexistingpublicschema.go@@ -0,0 +1,64 @@+package usecases_postgresql++import (+ "strconv"+ "strings"+)++const ignoredErrorsMarker = "errors ignored on restore:"++// A backup taken with include-schemas selects public explicitly, so pg_dump emits CREATE SCHEMA+// public and every restore target already owns that schema (issue #726). pg_restore runs without+// --exit-on-error, so it reports "errors ignored on restore: N" and exits non-zero even though the+// data restored. Tolerating that is only safe when every ignored error is accounted for and is this+// one — a --clean restore never reaches here, since the DROP removes the collision first.+func IsPreexistingPublicSchemaOnly(stderr string) bool {+ ignoredCount, hasMarker := parseIgnoredErrorCount(stderr)+ if !hasMarker || ignoredCount < 1 {+ return false+ }++ itemErrors := queryErrorLines(stderr)+ if len(itemErrors) != ignoredCount {+ return false+ }++ for _, line := range itemErrors {+ if !strings.Contains(strings.ToLower(line), `schema "public" already exists`) {+ return false+ }+ }++ return true+}++func parseIgnoredErrorCount(stderr string) (int, bool) {+ markerIndex := strings.LastIndex(strings.ToLower(stderr), ignoredErrorsMarker)+ if markerIndex < 0 {+ return 0, false+ }++ fields := strings.Fields(stderr[markerIndex+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(stderr string) []string {+ var errorLines []string++ for line := range strings.SplitSeq(stderr, "\n") {+ if strings.Contains(strings.ToLower(line), "could not execute query: error:") {+ errorLines = append(errorLines, line)+ }+ }++ return errorLines+}diff --git a/backend/internal/features/restores/usecases/postgresql/preexistingpublicschema_test.go b/backend/internal/features/restores/usecases/postgresql/preexistingpublicschema_test.gonew file mode 100644index 00000000..fbaf7c77--- /dev/null+++ b/backend/internal/features/restores/usecases/postgresql/preexistingpublicschema_test.go@@ -0,0 +1,58 @@+package usecases_postgresql++import (+ "testing"++ "github.com/stretchr/testify/assert"+)++const publicSchemaClashStderr = `pg_restore: error: could not execute query: ERROR: schema "public" already exists+Command was: CREATE SCHEMA public;+++pg_restore: warning: errors ignored on restore: 1+`++func Test_IsPreexistingPublicSchemaOnly_WhenOnlyPublicSchemaError_ReturnsTrue(t *testing.T) {+ assert.True(t, IsPreexistingPublicSchemaOnly(publicSchemaClashStderr))+}++func Test_IsPreexistingPublicSchemaOnly_WhenMissingExtensionAlsoIgnored_ReturnsFalse(t *testing.T) {+ mixed := `pg_restore: error: could not execute query: ERROR: schema "public" already exists+Command was: CREATE SCHEMA public;+pg_restore: error: could not execute query: ERROR: extension "postgis" is not available+Command was: CREATE EXTENSION IF NOT EXISTS postgis WITH SCHEMA public;+pg_restore: warning: errors ignored on restore: 2`++ assert.False(t, IsPreexistingPublicSchemaOnly(mixed),+ "a user-facing restore that silently dropped an extension is still a failed restore")+}++func Test_IsPreexistingPublicSchemaOnly_WhenVisibleErrorCountBelowMarker_ReturnsFalse(t *testing.T) {+ truncated := `pg_restore: error: could not execute query: ERROR: schema "public" already exists+Command was: CREATE SCHEMA public;+pg_restore: warning: errors ignored on restore: 4`++ assert.False(t, IsPreexistingPublicSchemaOnly(truncated),+ "stderr that cannot account for all N errors must not be tolerated")+}++func Test_IsPreexistingPublicSchemaOnly_WhenNoIgnoredErrorsMarker_ReturnsFalse(t *testing.T) {+ aborted := `pg_restore: error: could not execute query: ERROR: schema "public" already exists+Command was: CREATE SCHEMA public;+pg_restore: error: aborting because of errors`++ assert.False(t, IsPreexistingPublicSchemaOnly(aborted))+}++func Test_IsPreexistingPublicSchemaOnly_WhenEmpty_ReturnsFalse(t *testing.T) {+ assert.False(t, IsPreexistingPublicSchemaOnly(""))+}++func Test_IsPreexistingPublicSchemaOnly_WhenRelationAlreadyExists_ReturnsFalse(t *testing.T) {+ relationClash := `pg_restore: error: could not execute query: ERROR: relation "public.t_a" already exists+Command was: CREATE TABLE public.t_a (id integer NOT NULL);+pg_restore: warning: errors ignored on restore: 1`++ assert.False(t, IsPreexistingPublicSchemaOnly(relationClash))+}diff --git a/backend/internal/features/restores/usecases/postgresql/restore_backup_uc.go b/backend/internal/features/restores/usecases/postgresql/restore_backup_uc.goindex b985e3ed..e6db5f46 100644--- a/backend/internal/features/restores/usecases/postgresql/restore_backup_uc.go+++ b/backend/internal/features/restores/usecases/postgresql/restore_backup_uc.go@@ -372,7 +372,15 @@ func (uc *RestorePostgresqlBackupUsecase) restoreViaStdin(return fmt.Errorf("restore cancelled due to shutdown")}- return uc.handlePgRestoreError(originalDB, waitErr, stderrOutput, pgBin, args, pg)+ return uc.resolvePgRestoreOutcome(pgRestoreFailure{+ database: originalDB,+ waitErr: waitErr,+ stderrOutput: stderrOutput,+ pgBin: pgBin,+ args: args,+ pgConfig: pg,+ logger: logger,+ })}return nil@@ -453,15 +461,17 @@ func (uc *RestorePostgresqlBackupUsecase) restoreFromStorage(pgConfig *pgtypes.PostgresqlLogicalDatabase,options restores_core.RestoreOptions,) error {- uc.logger.Info(- "Restoring PostgreSQL backup from storage via temporary file",- "pgBin",+ logger := uc.logger.With("backup_id", backup.ID)++ logger.Info(+ "restoring backup from storage via temporary file",+ "pg_bin",pgBin,"args",args,- "isExcludeExtensions",+ "is_exclude_extensions",options.IsExcludeExtensions,- "isSkipUserMappings",+ "is_skip_user_mappings",options.IsSkipUserMappings,)@@ -530,7 +540,14 @@ func (uc *RestorePostgresqlBackupUsecase) restoreFromStorage(// Add the temporary backup file as the last argument to pg_restoreargs = append(args, tempBackupFile)- return uc.executePgRestore(ctx, database, pgBin, args, credentials, pgConfig)+ return uc.executePgRestore(ctx, pgRestoreCommand{+ database: database,+ pgBin: pgBin,+ args: args,+ credentials: credentials,+ pgConfig: pgConfig,+ logger: logger,+ })}func (uc *RestorePostgresqlBackupUsecase) downloadBackupToTempFile(@@ -640,20 +657,26 @@ func (uc *RestorePostgresqlBackupUsecase) downloadBackupToTempFile(return tempBackupFile, cleanupFunc, nil}-// executePgRestore executes the pg_restore command with proper environment setup+type pgRestoreCommand struct {+ database *databases.Database+ pgBin string+ args []string+ credentials *postgresql_shared.CredentialTempFiles+ pgConfig *pgtypes.PostgresqlLogicalDatabase+ logger *slog.Logger+}+func (uc *RestorePostgresqlBackupUsecase) executePgRestore(ctx context.Context,- database *databases.Database,- pgBin string,- args []string,- credentials *postgresql_shared.CredentialTempFiles,- pgConfig *pgtypes.PostgresqlLogicalDatabase,+ command pgRestoreCommand,) error {- cmd := exec.CommandContext(ctx, pgBin, args...)- uc.logger.Info("Executing PostgreSQL restore command", "command", cmd.String())+ pgBin := command.pgBin++ cmd := exec.CommandContext(ctx, pgBin, command.args...)+ command.logger.Info("executing pg_restore command", "command", cmd.String())// Setup environment variables- uc.setupPgRestoreEnvironment(cmd, credentials, pgConfig)+ uc.setupPgRestoreEnvironment(cmd, command.credentials, command.pgConfig)// Verify executable exists and is accessibleif _, err := exec.LookPath(pgBin); err != nil {@@ -714,7 +737,15 @@ func (uc *RestorePostgresqlBackupUsecase) executePgRestore(return fmt.Errorf("restore cancelled due to shutdown")}- return uc.handlePgRestoreError(database, waitErr, stderrOutput, pgBin, args, pgConfig)+ return uc.resolvePgRestoreOutcome(pgRestoreFailure{+ database: command.database,+ waitErr: waitErr,+ stderrOutput: stderrOutput,+ pgBin: command.pgBin,+ args: command.args,+ pgConfig: command.pgConfig,+ logger: command.logger,+ })}return nil@@ -756,22 +787,34 @@ func (uc *RestorePostgresqlBackupUsecase) setupPgRestoreEnvironment(uc.logger.Info("Using SSL mode", "sslMode", sslMode)}-// handlePgRestoreError processes and formats pg_restore errors-func (uc *RestorePostgresqlBackupUsecase) handlePgRestoreError(- database *databases.Database,- waitErr error,- stderrOutput []byte,- pgBin string,- args []string,- pgConfig *pgtypes.PostgresqlLogicalDatabase,-) error {- // Enhanced error handling for PostgreSQL connection and restore issues- stderrStr := string(stderrOutput)+type pgRestoreFailure struct {+ database *databases.Database+ waitErr error+ stderrOutput []byte+ pgBin string+ args []string+ pgConfig *pgtypes.PostgresqlLogicalDatabase+ logger *slog.Logger+}++func (uc *RestorePostgresqlBackupUsecase) resolvePgRestoreOutcome(failure pgRestoreFailure) error {+ pgBin := failure.pgBin+ waitErr := failure.waitErr+ stderr := string(failure.stderrOutput)++ if IsPreexistingPublicSchemaOnly(stderr) {+ failure.logger.Warn(+ "pg_restore ignored a pre-existing public schema; treating the restore as successful",+ )++ return nil+ }+errorMsg := fmt.Sprintf("%s failed: %v – stderr: %s",filepath.Base(pgBin),waitErr,- stderrStr,+ stderr,)// Check for specific PostgreSQL error patterns@@ -780,7 +823,7 @@ func (uc *RestorePostgresqlBackupUsecase) handlePgRestoreError(exitCode := exitErr.ExitCode()switch {- case exitCode == 1 && strings.TrimSpace(stderrStr) == "":+ case exitCode == 1 && strings.TrimSpace(stderr) == "":errorMsg = fmt.Sprintf("%s failed with exit status 1 but provided no error details. "+"This often indicates: "+@@ -793,63 +836,65 @@ func (uc *RestorePostgresqlBackupUsecase) handlePgRestoreError("Command executed: %s %s",filepath.Base(pgBin),pgBin,- strings.Join(args, " "),+ strings.Join(failure.args, " "),)case exitCode == -1073741819: // 0xC0000005 in decimalerrorMsg = fmt.Sprintf("%s crashed with access violation (0xC0000005). This may indicate incompatible PostgreSQL version, corrupted installation, or connection issues. stderr: %s",filepath.Base(pgBin),- stderrStr,+ stderr,)case exitCode == 1 || exitCode == 2:// Check for common connection and authentication issuesswitch {- case containsIgnoreCase(stderrStr, "pg_hba.conf"):+ case containsIgnoreCase(stderr, "pg_hba.conf"):errorMsg = fmt.Sprintf("PostgreSQL connection rejected by server configuration (pg_hba.conf). stderr: %s",- stderrStr,+ stderr,)- case containsIgnoreCase(stderrStr, "no password supplied") || containsIgnoreCase(stderrStr, "fe_sendauth"):+ case containsIgnoreCase(stderr, "no password supplied") || containsIgnoreCase(stderr, "fe_sendauth"):errorMsg = fmt.Sprintf("PostgreSQL authentication failed - no password supplied. stderr: %s",- stderrStr,+ stderr,)- case containsIgnoreCase(stderrStr, "ssl") && containsIgnoreCase(stderrStr, "connection"):+ case containsIgnoreCase(stderr, "ssl") && containsIgnoreCase(stderr, "connection"):errorMsg = fmt.Sprintf("PostgreSQL SSL connection failed. stderr: %s",- stderrStr,+ stderr,)- case containsIgnoreCase(stderrStr, "connection") && containsIgnoreCase(stderrStr, "refused"):+ case containsIgnoreCase(stderr, "connection") && containsIgnoreCase(stderr, "refused"):errorMsg = fmt.Sprintf("PostgreSQL connection refused. Check if the server is running and accessible. stderr: %s",- stderrStr,+ stderr,)- case containsIgnoreCase(stderrStr, "authentication") || containsIgnoreCase(stderrStr, "password"):+ case containsIgnoreCase(stderr, "authentication") || containsIgnoreCase(stderr, "password"):errorMsg = fmt.Sprintf("PostgreSQL authentication failed. Check username and password. stderr: %s",- stderrStr,+ stderr,)- case containsIgnoreCase(stderrStr, "timeout"):+ case containsIgnoreCase(stderr, "timeout"):errorMsg = fmt.Sprintf("PostgreSQL connection timeout. stderr: %s",- stderrStr,+ stderr,)- case containsIgnoreCase(stderrStr, "database") && containsIgnoreCase(stderrStr, "does not exist"):+ case containsIgnoreCase(stderr, "database") && containsIgnoreCase(stderr, "does not exist"):+ sourceDatabase := failure.database.PostgresqlLogical+backupDbName := "unknown"- if database.PostgresqlLogical != nil && database.PostgresqlLogical.Database != nil {- backupDbName = *database.PostgresqlLogical.Database+ if sourceDatabase != nil && sourceDatabase.Database != nil {+ backupDbName = *sourceDatabase.Database}targetDbName := "unknown"- if pgConfig.Database != nil {- targetDbName = *pgConfig.Database+ if failure.pgConfig.Database != nil {+ targetDbName = *failure.pgConfig.Database}errorMsg = fmt.Sprintf("Target database does not exist (backup db %s, not found %s). Create the database before restoring. stderr: %s",backupDbName,targetDbName,- stderrStr,+ stderr,)}}diff --git a/backend/internal/features/tests/logical/postgresql/timescaledb_test.go b/backend/internal/features/tests/logical/postgresql/timescaledb_test.goindex 7bc747f3..2fef4884 100644--- a/backend/internal/features/tests/logical/postgresql/timescaledb_test.go+++ b/backend/internal/features/tests/logical/postgresql/timescaledb_test.go@@ -42,6 +42,105 @@ func Test_PostgresqlBackupRestore_TimescaleDB(t *testing.T) {}}+// A TimescaleDB restore is the one path that omits --clean --if-exists, so an archive dumped with+// -n public (which carries CREATE SCHEMA public) collides with the schema the target already owns.+// pg_restore ignores that item and exits non-zero; the restore must still succeed (issue #726).+func Test_PostgresqlBackupRestore_TimescaleDBWithIncludePublicSchema_RestoreSucceeds(t *testing.T) {+ endpoint := containers.StartTimescaleDB(t, timescaleImage)++ container, err := connectToPostgresEndpoint(t, endpoint)+ require.NoError(t, err)+ defer func() {+ if container.DB != nil {+ container.DB.Close()+ }+ }()++ tableName := fmt.Sprintf("readings_%s", uuid.New().String()[:8])+ _, err = container.DB.Exec(fmt.Sprintf(`+CREATE EXTENSION IF NOT EXISTS timescaledb;++CREATE TABLE public.%s (id INTEGER PRIMARY KEY, label TEXT NOT NULL);++INSERT INTO public.%s (id, label) VALUES (1, 'alpha'), (2, 'beta'), (3, 'gamma');+`, tableName, tableName))+ require.NoError(t, err)++ defer func() {+ _, _ = container.DB.Exec(fmt.Sprintf("DROP TABLE IF EXISTS public.%s;", tableName))+ }()++ router := logicaltesting.CreateTestRouter()+ user := users_testing.CreateTestUser(users_enums.UserRoleMember)+ workspace := workspaces_testing.CreateTestWorkspace("Test Workspace", user, router)+ storage := storages.CreateTestStorage(workspace.ID)++ database := createDatabaseWithSchemasViaAPI(+ t, router, "Timescale Public Schema Database", workspace.ID,+ container.Host, container.Port,+ container.Username, container.Password, container.Database,+ []string{"public"},+ user.Token,+ )++ logicaltesting.EnableBackupsViaAPI(+ t, router, database.ID, storage.ID,+ backups_core_enums.BackupEncryptionNone, user.Token,+ )++ logicaltesting.CreateBackupViaAPI(t, router, database.ID, user.Token)++ backup := logicaltesting.WaitForBackupCompletion(t, router, database.ID, user.Token, 5*time.Minute)+ require.Equal(t, backups_core_logical.BackupStatusCompleted, backup.Status)+ require.NotEmpty(t, backup.TimescaledbVersion,+ "the restore only skips --clean when the backup is timescaledb-flavoured")++ newDBName := fmt.Sprintf("restored_ts_public_%s", uuid.New().String()[:8])+ _, err = container.DB.Exec(fmt.Sprintf("CREATE DATABASE %s;", newDBName))+ require.NoError(t, err)++ defer func() {+ _, _ = container.DB.Exec(fmt.Sprintf("DROP DATABASE IF EXISTS %s;", newDBName))+ }()++ newDSN := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",+ container.Host, container.Port, container.Username, container.Password, newDBName)+ restoredDB, err := sqlx.Connect("postgres", newDSN)+ require.NoError(t, err)+ defer restoredDB.Close()++ createRestoreWithCpuCountViaAPI(+ t, router, backup.ID,+ container.Host, container.Port,+ container.Username, container.Password, newDBName,+ 1,+ user.Token,+ )++ restore := waitForRestoreCompletion(t, router, backup.ID, user.Token, 5*time.Minute)+ assert.Equal(t, restores_core.RestoreStatusCompleted, restore.Status,+ "a pre-existing public schema is the only ignored error, so the restore is successful")++ var restoredRowCount int+ require.NoError(t, restoredDB.Get(&restoredRowCount,+ fmt.Sprintf("SELECT count(*) FROM public.%s", tableName)))+ assert.Equal(t, 3, restoredRowCount)++ err = os.Remove(filepath.Join(config.GetEnv().DataFolder, backup.ID.String()))+ if err != nil {+ t.Logf("Warning: Failed to delete backup file: %v", err)+ }++ test_utils.MakeDeleteRequest(+ t, router,+ "/api/v1/databases/"+database.ID.String(),+ "Bearer "+user.Token,+ http.StatusNoContent,+ )+ storages.RemoveTestStorage(storage.ID)+ workspaces_testing.RemoveTestWorkspace(workspace, router)+}+func seedHypertableQuery(tableName string) string {return fmt.Sprintf(`CREATE EXTENSION IF NOT EXISTS timescaledb;