PostgreSQL backup tool with Point-In-Time-Recovery and restore verification
TypeScript backupbackupsdatabasedatabase-backupdevopsdockergolangkubernetesmariadbmongodbmysqlpgpostgrespostgresqls3self-hostedsystem-administrationtoolsweb-ui
FEATURE (verifications): Add backups verification
Rostislav Duginf4ad457c9efe
diff --git a/.github/workflows/ci-release.yml b/.github/workflows/ci-release.ymlindex 68bf916a..7fbd3808 100644--- a/.github/workflows/ci-release.yml+++ b/.github/workflows/ci-release.yml@@ -251,6 +251,84 @@ jobs:docker compose -f docker-compose.backup-restore.yml down -v --rmi local || truerm -rf artifacts || true+ lint-verification-agent:+ if: github.ref != 'refs/heads/develop'+ runs-on: ubuntu-latest+ steps:+ - name: Check out code+ uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1++ - name: Set up Go+ uses: actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff # v5.6.0+ with:+ go-version: "1.26.3"+ cache-dependency-path: agent/verification/go.sum++ - name: Download Go modules+ run: |+ cd agent/verification+ go mod download++ - name: Install golangci-lint+ run: |+ go install github.com/golangci/golangci-lint/v2/cmd/[email protected]+ echo "$(go env GOPATH)/bin" >> $GITHUB_PATH++ - name: Run golangci-lint+ run: |+ cd agent/verification+ golangci-lint run++ - name: Verify go mod tidy+ run: |+ cd agent/verification+ go mod tidy+ git diff --exit-code go.mod go.sum || (echo "go mod tidy made changes, please run 'go mod tidy' and commit the changes" && exit 1)++ test-verification-agent:+ if: github.ref != 'refs/heads/develop'+ runs-on: ubuntu-latest+ needs: [lint-verification-agent]+ steps:+ - name: Check out code+ uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1++ - name: Set up Go+ uses: actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff # v5.6.0+ with:+ go-version: "1.26.3"+ cache-dependency-path: agent/verification/go.sum++ - name: Download Go modules+ run: |+ cd agent/verification+ go mod download++ - name: Run Go tests+ run: |+ cd agent/verification+ go test -race -count=1 -failfast ./internal/...++ e2e-verification-agent:+ if: github.ref != 'refs/heads/develop'+ runs-on: ubuntu-latest+ needs: [lint-verification-agent]+ steps:+ - name: Check out code+ uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1++ - name: Run e2e tests+ run: |+ cd agent/verification+ make e2e++ - name: Cleanup+ if: always()+ run: |+ cd agent/verification/e2e+ docker compose down -v --rmi local || true+ rm -rf artifacts || true+# Self-hosted: performant high-frequency CPU is used to start many containers and run tests fast. Tests# step is bottle-neck, because we need a lot of containers and cannot parallelize tests due to shared resourcestest-backend:@@ -530,6 +608,30 @@ jobs:rm -f "$out"done+ for arch in amd64 arm64; do+ echo "Checking verification agent download for $arch..."+ out=$(mktemp)+ http=$(curl -sS -o "$out" -w '%{http_code}' "http://localhost:4005/api/v1/system/verification-agent?arch=$arch")+ if [ "$http" != "200" ]; then+ echo "verification agent ($arch) download failed: HTTP $http"+ head -c 200 "$out" || true+ docker logs databasus-dev-smoke+ rm -f "$out"+ exit 1+ fi+ magic=$(head -c 4 "$out" | od -An -t x1 | tr -d ' ')+ if [ "$magic" != "7f454c46" ]; then+ echo "verification agent ($arch) is not an ELF binary (first 4 bytes: $magic)"+ head -c 200 "$out" || true+ docker logs databasus-dev-smoke+ rm -f "$out"+ exit 1+ fi+ size=$(stat -c%s "$out")+ echo "verification agent ($arch) OK (${size} bytes)"+ rm -f "$out"+ done+- name: Install Trivyrun: |sudo apt-get update@@ -594,7 +696,7 @@ jobs:build-image:if: github.ref != 'refs/heads/develop'runs-on: ubuntu-latest- needs: [lint-backend, lint-frontend, lint-agent, dockerfile-scan]+ needs: [lint-backend, lint-frontend, lint-agent, lint-verification-agent, dockerfile-scan]steps:- name: Clean workspacerun: |@@ -681,6 +783,30 @@ jobs:rm -f "$out"done+ for arch in amd64 arm64; do+ echo "Checking verification agent download for $arch..."+ out=$(mktemp)+ http=$(curl -sS -o "$out" -w '%{http_code}' "http://localhost:4005/api/v1/system/verification-agent?arch=$arch")+ if [ "$http" != "200" ]; then+ echo "verification agent ($arch) download failed: HTTP $http"+ head -c 200 "$out" || true+ docker logs databasus-smoke+ rm -f "$out"+ exit 1+ fi+ magic=$(head -c 4 "$out" | od -An -t x1 | tr -d ' ')+ if [ "$magic" != "7f454c46" ]; then+ echo "verification agent ($arch) is not an ELF binary (first 4 bytes: $magic)"+ head -c 200 "$out" || true+ docker logs databasus-smoke+ rm -f "$out"+ exit 1+ fi+ size=$(stat -c%s "$out")+ echo "verification agent ($arch) OK (${size} bytes)"+ rm -f "$out"+ done+- name: Install Trivyrun: |sudo apt-get update@@ -708,7 +834,7 @@ jobs:runs-on: self-hostedcontainer:image: node:20- needs: [test-backend, test-frontend, test-agent, e2e-agent, e2e-agent-backup-restore]+ needs: [test-backend, test-frontend, test-agent, e2e-agent, e2e-agent-backup-restore, test-verification-agent, e2e-verification-agent]if: ${{ github.ref == 'refs/heads/main' && !contains(github.event.head_commit.message, '[skip-release]') }}outputs:should_release: ${{ steps.version_bump.outputs.should_release }}diff --git a/CLAUDE.md b/CLAUDE.mdindex fa1327d1..6b2f2597 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -7,6 +7,7 @@ Per-folder rules live next to the code they govern:- [`backend/CLAUDE.md`](backend/CLAUDE.md) — Go + Gin + GORM + PostgreSQL backend (controllers, migrations, CRUD, DI, testing, logging)- [`agent/backup/CLAUDE.md`](agent/backup/CLAUDE.md) — Go agent CLI (no HTTP server, no schema; shares Go conventions with the backend)+- [`agent/verification/CLAUDE.md`](agent/verification/CLAUDE.md) — Go verification agent CLI (self-update + capacity heartbeat; restore logic deferred)- [`frontend/CLAUDE.md`](frontend/CLAUDE.md) — React 19 + TypeScript + Vite + Ant Design + TailwindThis root file holds the engineering philosophy that applies everywhere.@@ -45,10 +46,64 @@ Reread the diff with fresh eyes and **list** (don't silently apply) refactor sug### Naming-Name variables and functions for **intent**, not mechanism. Naming is the biggest readability lever — avoid generic names like `data`, `handle`, `process`.+Name variables and functions for **intent**, not mechanism. Naming is the biggest readability lever — avoid generic placeholders (`data`, `handle`, `process`, `tmp`, `helper`, `manager`), type-suffix noise (`nameStr`, `agentList`, `tokenObj`), and mechanism-flavored names (`tickNow`, `hbResp`, `dataObj`).Booleans take an `is` / `can` / `has` / `should` prefix (`isAllowed`, `canAccess`, `hasItems`, `shouldRetry`) — never bare nouns/verbs like `allowed` or `touches`.+State that holds "the entity currently being X-ed" must include the entity: `createdAgent`, not `created`; `listedAgents`, not `listed`; `deletingAgentId`, not `deletingId`. Pair related state explicitly: `revealedToken` + `revealedTokenAgentName`, not `tokenAgentName`. Loop variables get the domain word — `for _, agent := range listedAgents` (Go) — single letters only inside trivial one-line lambdas (`.map((a) => a.id)`).++Test-mechanism names (`got`, `want`, `expected`) are not acceptable — use the domain noun: `persistedAgent`, `firstRotation`, `secondRotation`. Match domain language across the wire — if the API says `agent`, don't rename to `worker` or `node` in client code.++Idiomatic short names stay where the convention is well-established: Go receivers (`s *AgentService`, `r *AgentRepository`, `ctx *gin.Context`) and JS/TS error catches (`} catch (e) {`). When no good name exists, the abstraction is wrong — extract or rename it, don't reach for `helper` / `tmp` / `manager`.++Examples:++```go+// bad+var hbResp HeartbeatResponse+var got *Agent+for _, a := range listed { ... }++// good+var heartbeatResponse HeartbeatResponse+var persistedAgent *Agent+for _, agent := range listedAgents { ... }+```++```ts+// bad+const [tickNow, setTickNow] = useState(Date.now());+const [deletingId, setDeletingId] = useState<string | null>(null);+const [tokenAgentName, setTokenAgentName] = useState('');++// good+const [currentTimeMs, setCurrentTimeMs] = useState(Date.now());+const [deletingAgentId, setDeletingAgentId] = useState<string | null>(null);+const [revealedTokenAgentName, setRevealedTokenAgentName] = useState('');+```++### Functions, methods and types++The intent rule applies to callables and types too — this is where it's violated most:++- **A name that needs a "what" comment is a naming bug.** Doc comments are for *why*, ordering, and hidden constraints — never to restate behavior. If you wrote `// Foo does X` above `func Foo`, rename `Foo` until that comment is redundant, then delete it. Keep only the sentence a name *cannot* carry (e.g. "must be called before the container exists").+- **Predicate methods read as a question**, same as boolean vars: `IsAborted(id)`, not `AbortedContains(id)`; `HasCapacity()`, not `CapacityCheck()`.+- **The name states everything the unit does.** A function that records *and* cancels is `recordAndCancelAborts` — or it's two functions. A name that hides a second effect is a lie.+- **Getters take a `Get` prefix and name the entity.** `GetRunningVerificationIDs()`, not `Active()`, `RunningVerificationIDs()`, or `DiskUsageBytes()`. This is a deliberate house style: prefer the explicit `Get` *even though vanilla Go idiom omits it* — it keeps accessors visually distinct from actions and matches the backend (`GetAuditLogService`, `GetGlobalAuditLogs`). Constructors stay `New...`; a getter that returns a bool is still a predicate, so it stays `Is/Has...`, not `Get...`.+- **Long positional parameter lists become a struct.** ~4+ params, or two same-typed params adjacent → a named parameter/DTO struct (the input counterpart to the result type, e.g. `spawnPlan` → `SpawnSpec`). Kills call-site ordering bugs and the comment explaining argument order.+- **Type names: avoid generic *and* avoid package stutter.** Not `Manager` / `Provisioner` / `Handler` (generic), not `container.ContainerManager` (stutters — `revive` fails CI). If the only honest name stutters, put the noun on the *variable*, not the type: keep the type `container.Manager`, name the variable `containerManager`. If no precise type name exists, the abstraction is wrong — split it.++```go+// bad — comment restates the name; name hides the second effect; predicate isn't a question+// applyAborts records the abort set and cancels each registered job.+func (h *Heartbeater) applyAborts(ids []uuid.UUID) { ... }+func (h *Heartbeater) AbortedContains(id uuid.UUID) bool { ... }++// good — the names carry it; no comment needed+func (h *Heartbeater) recordAndCancelAborts(ids []uuid.UUID) { ... }+func (h *Heartbeater) IsAborted(id uuid.UUID) bool { ... }+```+### Linting and formattingAfter each change run linting and formatting depending on folder you are working it.diff --git a/Dockerfile b/Dockerfileindex ee124594..629043de 100644--- a/Dockerfile+++ b/Dockerfile@@ -103,6 +103,27 @@ RUN CGO_ENABLED=0 GOOS=linux GOARCH=arm64 \-o /agent-binaries/databasus-agent-linux-arm64 ./cmd/main.go+# ========= BUILD VERIFICATION AGENT =========+FROM --platform=$BUILDPLATFORM golang:1.26.3 AS verification-agent-build++ARG APP_VERSION=dev++WORKDIR /agent++COPY agent/verification/go.mod agent/verification/go.sum ./+RUN go mod download++COPY agent/verification/ ./++RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 \+ go build -ldflags "-X main.Version=${APP_VERSION}" \+ -o /verification-agent-binaries/databasus-verification-agent-linux-amd64 ./cmd++RUN CGO_ENABLED=0 GOOS=linux GOARCH=arm64 \+ go build -ldflags "-X main.Version=${APP_VERSION}" \+ -o /verification-agent-binaries/databasus-verification-agent-linux-arm64 ./cmd++# ========= RUNTIME =========FROM debian:bookworm-slim@@ -125,7 +146,8 @@ RUN set -eux; \apt-get install -y --no-install-recommends \wget ca-certificates gnupg lsb-release sudo gosu curl unzip xz-utils \libncurses5 libncurses6 rclone \- libmariadb3; \+ libmariadb3 \+ libgnutls30; \wget -qO- https://www.postgresql.org/media/keys/ACCC4CF8.asc | apt-key add -; \echo "deb http://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" \> /etc/apt/sources.list.d/pgdg.list; \@@ -183,6 +205,7 @@ COPY frontend/cloud-root-content.html /app/cloud-root-content.html# Copy agent binaries (both architectures) — served by the backend# at GET /api/v1/system/agent?arch=amd64|arm64COPY --from=agent-build /agent-binaries ./agent-binaries+COPY --from=verification-agent-build /verification-agent-binaries/* ./agent-binaries/# Bake .env.example as /.env so the binary has defaults when no env file is# mounted. The backend looks for .env at the parent of cwd (= /app), i.e. /.diff --git a/README.md b/README.mdindex 74a67503..4d09918d 100644--- a/README.md+++ b/README.md@@ -50,6 +50,15 @@- **Precise timing**: run backups at specific times (e.g., 4 AM during low traffic)- **Smart compression**: 4-8x space savings with balanced compression (~20% overhead)+### 🧪 **Restore verification** <a href="https://databasus.com/restore-verification">(docs)</a>++Databasus performs a real restore to confirm backups are usable, not just intact on disk or checksum check.++- **Triggers**: after each backup or on a flexible schedule (hourly, daily, weekly, monthly or cron)+- **Real restore**: spins up a database container, runs the restore and checks the restored size against the backup+- **Report**: lists every table with its row count+- **Optional notifications**: send the report or failure-only alerts through any configured notifier+### 🗑️ **Retention policies**- **Time period**: Keep backups for a fixed duration (e.g., 7 days, 3 months, 1 year)@@ -63,7 +72,7 @@- **Cloud storage**: S3, Cloudflare R2, Google Drive, NAS, Dropbox, SFTP, Rclone and more- **Secure**: All data stays under your control-### 📱 **Smart notifications** <a href="https://databasus.com/notifiers">(view supported)</a>+### 📱 **Notifications** <a href="https://databasus.com/notifiers">(view supported)</a>- **Multiple channels**: Email, Telegram, Slack, Discord, webhooks- **Real-time updates**: Success and failure notifications@@ -312,8 +321,12 @@ The engineering safeguards behind these rules (CI, static analysis, dependency sYes. Every feature available in Databasus Cloud is equally available in the self-hosted version with no restrictions, no feature gates and no usage limits. The entire codebase is Apache 2.0 licensed and always will be.-Databasus is not "open core". We do not withhold features behind a paid tier and then call the limited remainder "open source" as projects like GitLab or Sentry do. We believe open source means the complete product is open, not just a marketing label on a stripped-down edition.+Databasus is not "open core". We do not withhold features behind a paid tier and then call the limited remainder "open source," as projects like GitLab or Sentry do. We believe open source means the complete product is open, not just a marketing label on a stripped-down edition.Databasus Cloud runs the exact same code as the self-hosted version. The only difference is that we take care of infrastructure, availability, backups, reservations, monitoring and updates for you — so you don't have to. If you are using cloud, you can always move your databases from cloud to self-hosted if you wish.-Revenue from Databasus Cloud funds full-time development of the project. Many open-source projects depend on corporate backing, sponsorships or volunteer maintainers, which can create long-term sustainability challenges. Recent discussions around [Tailwind](https://github.com/tailwindlabs/tailwindcss.com/pull/2388#issuecomment-3717222957) and the archival of [pgBackRest](https://github.com/pgbackrest/pgbackrest#notice-of-obsolescence) show that even popular or critical open-source projects need a durable funding model. Databasus Cloud is our way to make the project financially sustainable while keeping the full product open source, self-hostable and independent from any single corporate sponsor.+Moreover, we have a DBA-as-a-service offering, [Databasus Labs](https://databasus.com/labs), to fund Databasus development and help companies with their database backup needs.++Any long-running OSS project needs to be funded. Revenue from Cloud and Databasus Labs funds full-time development of the project. Most large open-source projects rely on corporate backing or sponsorship to survive (as well as TailwindCSS and pgBackRest, for example).++To address this, Databasus sustains itself so it can grow and improve independently, without being tied to any enterprise or sponsor. Our vision is to keep Databasus fully open-source forever, with a promise to never close it off through licensing or withheld code. So any DevOps or DBA company can provide services on top of Databasus as well.diff --git a/agent/backup/.env.example b/agent/backup/.env.examplenew file mode 100644index 00000000..1a680c13--- /dev/null+++ b/agent/backup/.env.example@@ -0,0 +1,2 @@+AGENT_DB_ID=+AGENT_TOKEN=\ No newline at end of filediff --git a/agent/backup/CLAUDE.md b/agent/backup/CLAUDE.mdindex 0e6ffa01..41a4517d 100644--- a/agent/backup/CLAUDE.md+++ b/agent/backup/CLAUDE.md@@ -10,6 +10,7 @@ For project-wide engineering philosophy, naming, and lint/format commands, see t- [Spacing between logical statements](#spacing-between-logical-statements)- [Comments](#comments)+- [File organization](#file-organization)- [Background services](#background-services)- [Testing](#testing)- [Time handling](#time-handling)@@ -81,6 +82,27 @@ func CreateValidLogItems(count int, uniqueID string) []LogItemRequestDTO {---+## File organization++One responsibility per file. Don't dump a whole package into one file — split+by role so a reader can find a type by its filename. Conventional names within+a feature package:++- `doc.go` — package doc comment, once the package spans more than one file+- `<feature>.go` — the core type and its methods (the orchestrator/executor)+- `dto.go` — request/response and cross-package data + interface seams+- `errors.go` — sentinel errors (`var Err... = errors.New(...)`)+- `enums.go` — typed-constant groups (`type Status string` + its values)+- `constants.go` — package-level constants that aren't an enum+- background loops, reapers, and pools get their own file (`reaper.go`, `pool.go`)++Only create a file when there is real content for it — an empty `enums.go` or+`constants.go` is noise, not structure. Test files mirror the source split:+`restorer.go` → `restorer_test.go`, `diskexhaustion.go` →+`diskexhaustion_test.go`.++---+## Background servicesThe agent ships at least one long-running goroutine (e.g. `BackgroundUpgrader`). Calling `Run()` twice on the same instance is always a bug — duplicate goroutines leak resources and corrupt state. **Always panic; never just log a warning.**diff --git a/agent/verification/.dockerignore b/agent/verification/.dockerignorenew file mode 100644index 00000000..09d05b6b--- /dev/null+++ b/agent/verification/.dockerignore@@ -0,0 +1,24 @@+# Local dev state — regenerated at runtime, never belongs in a build context+databasus-verification.log+databasus-verification.log.old+databasus-verification.daemon.log+databasus-verification.lock+databasus-verification.json++# Local build artifacts (host binaries)+*.exe+databasus-verification-agent++# E2E working directories+e2e/artifacts/++# VCS and editor+.git/+.gitignore+.idea/+.vscode/++# Docs / env+*.md+.env+.env.examplediff --git a/agent/verification/.env.example b/agent/verification/.env.examplenew file mode 100644index 00000000..63f07af9--- /dev/null+++ b/agent/verification/.env.example@@ -0,0 +1,3 @@+DATABASUS_URL=+AGENT_ID=+AGENT_TOKEN=diff --git a/agent/verification/.gitignore b/agent/verification/.gitignorenew file mode 100644index 00000000..358b2722--- /dev/null+++ b/agent/verification/.gitignore@@ -0,0 +1,19 @@+# Runtime state — regenerated at runtime, never committed+databasus-verification.json+databasus-verification.log+databasus-verification.log.old+databasus-verification.daemon.log+databasus-verification.lock+.env+.test-tmp/++# Local build artifacts (host binaries)+*.exe+databasus-verification-agent++# E2E working directories+e2e/artifacts/++# Editor / VCS+.idea/+.vscode/diff --git a/agent/verification/.golangci.yml b/agent/verification/.golangci.ymlnew file mode 100644index 00000000..68890796--- /dev/null+++ b/agent/verification/.golangci.yml@@ -0,0 +1,41 @@+version: "2"++run:+ timeout: 5m+ tests: false+ concurrency: 4++linters:+ default: standard+ enable:+ - funcorder+ - bodyclose+ - errorlint+ - gocritic+ - unconvert+ - misspell+ - errname+ - noctx+ - modernize++ settings:+ errcheck:+ check-type-assertions: true++formatters:+ enable:+ - gofumpt+ - golines+ - gci++ settings:+ golines:+ max-len: 120+ gofumpt:+ module-path: databasus-verification-agent+ extra-rules: true+ gci:+ sections:+ - standard+ - default+ - localmodulediff --git a/agent/verification/CLAUDE.md b/agent/verification/CLAUDE.mdnew file mode 100644index 00000000..677f022f--- /dev/null+++ b/agent/verification/CLAUDE.md@@ -0,0 +1,289 @@+# Verification agent guidelines (Go CLI)++Coding standards for the Databasus verification agent — a Go CLI worker that runs on a cloud-managed Linux VM, reports its capacity to the backend over HTTP, and (once the restore phase lands) claims and verifies backups. It has no Gin HTTP server and owns no database schema. The long-running goroutine in this phase is the **capacity heartbeat loop**; the claim/report runner arrives with the restore phase. There is no Windows daemon — the agent runs in the foreground under systemd or as a container.++This file is intentionally a near-copy of [`agent/backup/CLAUDE.md`](../backup/CLAUDE.md) — the Go conventions are shared and **both must stay in sync as conventions evolve**. For project-wide engineering philosophy, naming, and lint/format commands, see the root `CLAUDE.md`. For the backend (Gin/GORM/Swagger) ruleset, see `backend/CLAUDE.md`.++---++## Table of Contents++- [Spacing between logical statements](#spacing-between-logical-statements)+- [Comments](#comments)+- [File organization](#file-organization)+- [Background services](#background-services)+- [Testing](#testing)+- [Time handling](#time-handling)+- [Logging](#logging)+- [Modern Go](#modern-go)++---++## Spacing between logical statements++Add blank lines between logical blocks so the flow is visible at a glance:++- before the final `return`+- after variable declarations, before they're used+- between error handling and subsequent logic+- between distinct logical operations++Bad:++```go+func encodeMessages(messages []Message) (string, error) {+ if len(messages) > 0 {+ messagesBytes, err := json.Marshal(messages)+ if err != nil {+ return "", err+ }+ return string(messagesBytes), nil+ }+ return "", nil+}+```++Good:++```go+func encodeMessages(messages []Message) (string, error) {+ if len(messages) > 0 {+ messagesBytes, err := json.Marshal(messages)+ if err != nil {+ return "", err+ }++ return string(messagesBytes), nil+ }++ return "", nil+}+```++---++## Comments++- **No obvious comments** — don't restate what the code already shows.+- **Explain *why*, not *what*** — code shows what happens; comments explain business rules, hidden constraints, or non-obvious optimizations.+- **Prefer refactoring over commenting** — better names or smaller functions usually beat a comment.+- **Complex algorithms deserve comments** — formulas, business rules, non-obvious optimizations.+- **No "Summary" / "Conclusion" sections in `.md` files** unless explicitly requested.++Bad (each comment restates the function name):++```go+// Send heartbeat+sendHeartbeat(request)++// CreateValidLogItems creates valid log items for testing+func CreateValidLogItems(count int, uniqueID string) []LogItemRequestDTO {+```++---++## File organization++One responsibility per file. Don't dump a whole package into one file — split+by role so a reader can find a type by its filename. Conventional names within+a feature package:++- `doc.go` — package doc comment, once the package spans more than one file+- `<feature>.go` — the core type and its methods (the orchestrator/executor)+- `dto.go` — request/response and cross-package data + interface seams+- `errors.go` — sentinel errors (`var Err... = errors.New(...)`)+- `enums.go` — typed-constant groups (`type Status string` + its values)+- `constants.go` — package-level constants that aren't an enum+- background loops, reapers, and pools get their own file (`reaper.go`, `pool.go`)++Only create a file when there is real content for it — an empty `enums.go` or+`constants.go` is noise, not structure. Test files mirror the source split:+`restorer.go` → `restorer_test.go`, `diskexhaustion.go` →+`diskexhaustion_test.go`.++---++## Background services++The agent ships at least one long-running goroutine (the capacity `Heartbeater`; also `BackgroundUpgrader`). Calling `Run()` twice on the same instance is always a bug — duplicate goroutines leak resources and corrupt state. **Always panic; never just log a warning.**++```go+type Heartbeater struct {+ // ...+ hasRun atomic.Bool+}++func (h *Heartbeater) Run(ctx context.Context) {+ if h.hasRun.Swap(true) {+ panic(fmt.Sprintf("%T.Run() called multiple times", h))+ }++ ticker := time.NewTicker(heartbeatInterval)+ defer ticker.Stop()++ for {+ select {+ case <-ctx.Done():+ return+ case <-ticker.C:+ h.beat(ctx, logger)+ }+ }+}+```++`atomic.Bool.Swap(true)` does the check-and-set atomically — no `sync.Once` needed.++---++## Testing++**Always run tests after writing them and verify they pass.**++### Naming++- `Test_WhatWeDo_WhatWeExpect`+- `Test_WhatWeDo_WhichConditions_WhatWeExpect`++Examples: `Test_DeriveCapacity_WhenConcurrentJobsExceedCPU_ReturnsError`, `Test_ValidateTransport_WhenHttpAndNotTTYWithoutFlag_FailsFast`, `Test_Heartbeat_WhenCalled_SendsFlatEnvelopeWithBearerAndAgentPath`, `Test_BackgroundUpgrader_WhenRunCalledTwice_Panics`.++### Where tests live++- **Unit / package tests**: alongside the code, named `*_test.go` (e.g. `internal/features/heartbeat/heartbeat_test.go`).+- **End-to-end tests**: under `agent/verification/e2e/`. Run via `make e2e` / `make e2e-clean`.++The agent has no HTTP API of its own, so there are no controller tests — test exported functions of the packages, the CLI commands, and the HTTP-client/IO logic directly.++### Refactor tests as you touch them++When editing existing tests, look for repetitive setup that should become a helper, oversized tests that should be split, and similar patterns across files that should be consolidated. Helpers live in a `testing.go` file inside the package.++### Clean up test data++If a test creates files, processes, or external state, clean it up via `t.Cleanup(...)` or `defer`. Skip cleanup only when the test uses an isolated tempdir the OS reclaims, or when it explicitly validates a failure path where cleanup isn't possible.++---++## Time handling++Always use `time.Now().UTC()` instead of `time.Now()` to keep timezones consistent across the application.++---++## Logging++We use `log/slog`. Three rules.++### 1. Scope IDs early via `logger.With(...)`++Attach `agent_id`, `verification_id`, `upgrade_target`, etc. as soon as you know them so every downstream line carries them automatically. For background services, also scope `job_id` (fresh UUID per execution) and `job_name` (stable snake_case const) in `Run()`.++```go+const jobName = "verification_heartbeat"++func (h *Heartbeater) Run(ctx context.Context) {+ logger := h.log.With("job_id", uuid.New(), "job_name", jobName)++ logger.Info("heartbeat loop started")+ // every subsequent log carries job_id + job_name+}+```++### 2. Values in message, IDs and errors as kv pairs++Sizes, counts, and status transitions go into the message via `fmt.Sprintf`. IDs and errors stay as structured kv pairs so they're searchable in log aggregation tools.++```go+// good+logger.Info(fmt.Sprintf("heartbeat ok: last_seen_at=%s", seenAt))+logger.Info("agent registered", "agent_id", agentID)+logger.Error("heartbeat failed", "error", err)++// bad — ID buried in the message string, error formatted instead of attached+logger.Info(fmt.Sprintf("agent registered %s", agentID))+logger.Error(fmt.Sprintf("heartbeat failed: %v", err))+```++### 3. Style and level++- All keys `snake_case` (`agent_id`, `verification_id`) — never camelCase.+- Messages start lowercase, no trailing period.+- **Debug**: routine ops, function entry, query result counts.+- **Info**: significant state changes, completed actions (`"agent started"`, `"heartbeat loop stopped"`).+- **Warn**: degraded but recoverable (`"heartbeat failed, will retry next tick"`, `"upgrade skipped: same version"`).+- **Error**: failures that need attention (`"auto-update failed"`, `"failed to re-exec after upgrade"`).++### What never goes into logs++- **Passwords, tokens, API keys, full `Authorization` headers** — centralize redaction; don't redact ad-hoc at call sites (config logging masks the token via `maskSensitive`).+- **Full request / response bodies** — log only the fields you actually need.++---++## Modern Go++Prefer modern stdlib idioms over manual equivalents.++### `slices` package — avoid manual loops++```go+slices.Contains(items, x)+slices.Index(items, x) // returns index or -1+slices.IndexFunc(items, func(item T) bool { return item.ID == id })+slices.SortFunc(items, func(a, b T) int { return cmp.Compare(a.X, b.X) })+slices.Sort(items)+slices.Max(items) / slices.Min(items)+slices.Reverse(items) // in-place+slices.Compact(items) // remove consecutive duplicates+slices.Clone(s)+slices.Clip(s)+```++### Quick wins++- `any` instead of `interface{}`.+- `for i := range len(items)` instead of `for i := 0; i < len(items); i++`.+- `sync.OnceFunc(fn)` / `sync.OnceValue(fn)` instead of `sync.Once` + wrapper.+- `t.Context()` in tests instead of `context.WithCancel(context.Background())` + `defer cancel()` — auto-cancels at test end.+- `wg.Go(fn)` instead of `wg.Add(1)` + `go func() { defer wg.Done(); fn() }()`.+- `slog.DiscardHandler` for a no-op logger in tests.++### `context` helpers++```go+stop := context.AfterFunc(ctx, cleanup) // run cleanup on cancellation+ctx, cancel := context.WithTimeoutCause(parent, d, ErrTimeout) // timeout with cause+ctx, cancel := context.WithDeadlineCause(parent, deadline, ErrDeadline) // deadline with cause+```++### `omitzero` instead of `omitempty` for non-nullable types++`omitempty` is broken for `time.Duration`, `time.Time`, structs, slices, and maps — it doesn't omit a zero value. Use `omitzero`:++```go+// good+type Config struct {+ Timeout time.Duration `json:"timeout,omitzero"`+ CreatedAt time.Time `json:"createdAt,omitzero"`+}++// bad+type Config struct {+ Timeout time.Duration `json:"timeout,omitempty"` // broken for Duration!+ CreatedAt time.Time `json:"createdAt,omitempty"`+}+```++### `new(val)` for pointer literals (Go 1.26+)++`new()` accepts expressions, eliminating the temp-variable pattern:++```go+// good+cfg := Config{Timeout: new(30), Debug: new(true)}++// bad+timeout := 30+debug := true+cfg := Config{Timeout: &timeout, Debug: &debug}+```diff --git a/agent/verification/Makefile b/agent/verification/Makefilenew file mode 100644index 00000000..c1af8ccc--- /dev/null+++ b/agent/verification/Makefile@@ -0,0 +1,50 @@+.PHONY: run build test lint e2e e2e-clean++-include .env+export++ifeq ($(shell uname),)+CLEAN_ARTIFACTS := if exist e2e\artifacts rmdir /s /q e2e\artifacts+DOWN_QUIET := cd e2e && docker compose down -v --remove-orphans 2>NUL+DOWN_CLEAN_QUIET := cd e2e && docker compose down -v --rmi local 2>NUL+else+CLEAN_ARTIFACTS := rm -rf e2e/artifacts+DOWN_QUIET := cd e2e && docker compose down -v --remove-orphans 2>/dev/null+DOWN_CLEAN_QUIET := cd e2e && docker compose down -v --rmi local 2>/dev/null+endif++run:+ go run ./cmd run \+ --databasus-host $(DATABASUS_URL) \+ --agent-id $(AGENT_ID) \+ --token $(AGENT_TOKEN) \+ --max-cpu 4 \+ --max-ram-mb 4096 \+ --max-disk-gb 50 \+ --max-concurrent-jobs 2 \+ --allow-insecure-http \+ --skip-update++build:+ CGO_ENABLED=0 go build -ldflags "-X main.Version=$(VERSION)" -o databasus-verification-agent ./cmd++test:+ go test -race -count=1 -failfast ./internal/...++lint:+ golangci-lint fmt ./cmd/... ./internal/... ./e2e/... && golangci-lint run ./cmd/... ./internal/... ./e2e/...++e2e:+ -$(DOWN_QUIET)+ -$(CLEAN_ARTIFACTS)+ cd e2e && docker compose build --no-cache e2e-mock-server+ cd e2e && docker compose build+ cd e2e && docker compose run --rm e2e-agent-builder+ cd e2e && docker compose run --rm e2e-fixture-gen+ cd e2e && docker compose up -d e2e-mock-server+ cd e2e && docker compose run --rm e2e-agent-runner+ cd e2e && docker compose down -v++e2e-clean:+ -$(DOWN_CLEAN_QUIET)+ -$(CLEAN_ARTIFACTS)diff --git a/agent/verification/cmd/main.go b/agent/verification/cmd/main.gonew file mode 100644index 00000000..2a0c7bed--- /dev/null+++ b/agent/verification/cmd/main.go@@ -0,0 +1,209 @@+package main++import (+ "errors"+ "flag"+ "fmt"+ "log/slog"+ "os"+ "path/filepath"+ "strings"++ "databasus-verification-agent/internal/config"+ "databasus-verification-agent/internal/features/api"+ "databasus-verification-agent/internal/features/start"+ "databasus-verification-agent/internal/features/upgrade"+ "databasus-verification-agent/internal/logger"+)++var Version = "dev"++func main() {+ if len(os.Args) < 2 {+ printUsage()+ os.Exit(1)+ }++ switch os.Args[1] {+ case "start":+ runStart(os.Args[2:])+ case "run":+ runAgent(os.Args[2:])+ case "_run":+ runDaemon(os.Args[2:])+ case "stop":+ runStop()+ case "status":+ runStatus()+ case "version":+ fmt.Println(Version)+ default:+ fmt.Fprintf(os.Stderr, "unknown command: %s\n", os.Args[1])+ printUsage()+ os.Exit(1)+ }+}++func runStart(args []string) {+ fs := flag.NewFlagSet("start", flag.ExitOnError)++ isSkipUpdate := fs.Bool("skip-update", false, "Skip auto-update check")++ cfg := &config.Config{}+ cfg.LoadFromJSONAndArgs(fs, args)++ if err := cfg.SaveToJSON(); err != nil {+ fmt.Fprintf(os.Stderr, "Failed to save config: %v\n", err)+ }++ log := logger.GetLogger()++ isDev := checkIsDevelopment()+ runUpdateCheck(cfg.DatabasusHost, *isSkipUpdate, isDev, log)++ if err := start.Start(cfg, Version, isDev, log); err != nil {+ if errors.Is(err, upgrade.ErrUpgradeRestart) {+ reexecAfterUpgrade(log)+ }++ fmt.Fprintf(os.Stderr, "Error: %v\n", err)+ os.Exit(1)+ }+}++func runAgent(args []string) {+ fs := flag.NewFlagSet("run", flag.ExitOnError)++ isSkipUpdate := fs.Bool("skip-update", false, "Skip auto-update check")++ cfg := &config.Config{}+ cfg.LoadFromJSONAndArgs(fs, args)++ if err := cfg.SaveToJSON(); err != nil {+ fmt.Fprintf(os.Stderr, "Failed to save config: %v\n", err)+ }++ log := logger.GetLogger()++ isDev := checkIsDevelopment()+ runUpdateCheck(cfg.DatabasusHost, *isSkipUpdate, isDev, log)++ if err := start.RunDaemon(cfg, Version, isDev, log); err != nil {+ if errors.Is(err, upgrade.ErrUpgradeRestart) {+ reexecAfterUpgrade(log)+ }++ fmt.Fprintf(os.Stderr, "Error: %v\n", err)+ os.Exit(1)+ }+}++func runDaemon(args []string) {+ fs := flag.NewFlagSet("_run", flag.ExitOnError)++ if err := fs.Parse(args); err != nil {+ os.Exit(1)+ }++ log := logger.GetLogger()++ cfg := &config.Config{}+ cfg.LoadFromJSON()++ if err := start.RunDaemon(cfg, Version, checkIsDevelopment(), log); err != nil {+ if errors.Is(err, upgrade.ErrUpgradeRestart) {+ reexecAfterUpgrade(log)+ }++ log.Error("Agent exited with error", "error", err)+ os.Exit(1)+ }+}++func runStop() {+ log := logger.GetLogger()++ if err := start.Stop(log); err != nil {+ fmt.Fprintf(os.Stderr, "Error: %v\n", err)+ os.Exit(1)+ }+}++func runStatus() {+ log := logger.GetLogger()++ if err := start.Status(log); err != nil {+ fmt.Fprintf(os.Stderr, "Error: %v\n", err)+ os.Exit(1)+ }+}++func printUsage() {+ fmt.Fprintln(os.Stderr, "Usage: databasus-verification-agent <command> [flags]")+ fmt.Fprintln(os.Stderr, "")+ fmt.Fprintln(os.Stderr, "Commands:")+ fmt.Fprintln(os.Stderr, " start Start the verification agent in the background (daemon)")+ fmt.Fprintln(os.Stderr, " run Run the verification agent in the foreground (systemd / container)")+ fmt.Fprintln(os.Stderr, " stop Stop a running agent")+ fmt.Fprintln(os.Stderr, " status Show agent status")+ fmt.Fprintln(os.Stderr, " version Print agent version")+}++func runUpdateCheck(host string, isSkipUpdate, isDev bool, log *slog.Logger) {+ if isSkipUpdate {+ return+ }++ if host == "" {+ return+ }++ apiClient := api.NewClient(host, "", "", log)++ isUpgraded, err := upgrade.CheckAndUpdate(apiClient, Version, isDev, log)+ if err != nil {+ log.Error("Auto-update failed", "error", err)+ os.Exit(1)+ }++ if isUpgraded {+ reexecAfterUpgrade(log)+ }+}++func checkIsDevelopment() bool {+ dir, err := os.Getwd()+ if err != nil {+ return false+ }++ for range 3 {+ if data, err := os.ReadFile(filepath.Join(dir, ".env")); err == nil {+ return parseEnvMode(data)+ }++ if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil {+ return false+ }++ dir = filepath.Dir(dir)+ }++ return false+}++func parseEnvMode(data []byte) bool {+ for line := range strings.SplitSeq(string(data), "\n") {+ line = strings.TrimSpace(line)+ if line == "" || strings.HasPrefix(line, "#") {+ continue+ }++ parts := strings.SplitN(line, "=", 2)+ if len(parts) == 2 && strings.TrimSpace(parts[0]) == "ENV_MODE" {+ return strings.TrimSpace(parts[1]) == "development"+ }+ }++ return false+}diff --git a/agent/verification/cmd/reexec_unix.go b/agent/verification/cmd/reexec_unix.gonew file mode 100644index 00000000..5cae34e5--- /dev/null+++ b/agent/verification/cmd/reexec_unix.go@@ -0,0 +1,24 @@+//go:build !windows++package main++import (+ "log/slog"+ "os"+ "syscall"+)++func reexecAfterUpgrade(log *slog.Logger) {+ selfPath, err := os.Executable()+ if err != nil {+ log.Error("Failed to resolve executable for re-exec", "error", err)+ os.Exit(1)+ }++ log.Info("Re-executing after upgrade...")++ if err := syscall.Exec(selfPath, os.Args, os.Environ()); err != nil {+ log.Error("Failed to re-exec after upgrade", "error", err)+ os.Exit(1)+ }+}diff --git a/agent/verification/cmd/reexec_windows.go b/agent/verification/cmd/reexec_windows.gonew file mode 100644index 00000000..699de527--- /dev/null+++ b/agent/verification/cmd/reexec_windows.go@@ -0,0 +1,13 @@+//go:build windows++package main++import (+ "log/slog"+ "os"+)++func reexecAfterUpgrade(log *slog.Logger) {+ log.Error("self-update re-exec is not supported on Windows; run the verification agent on Linux")+ os.Exit(1)+}diff --git a/agent/verification/e2e/.env.example b/agent/verification/e2e/.env.examplenew file mode 100644index 00000000..872b2a68--- /dev/null+++ b/agent/verification/e2e/.env.example@@ -0,0 +1,4 @@+# Host port the e2e mock-server publishes. The agent-runner reaches it via+# 127.0.0.1:<port> (network_mode: host). Defaults to 4050 in docker-compose.yml;+# override here only if 4050 is already taken on the host.+E2E_MOCK_SERVER_PORT=4050diff --git a/agent/verification/e2e/Dockerfile.agent-builder b/agent/verification/e2e/Dockerfile.agent-buildernew file mode 100644index 00000000..d636c746--- /dev/null+++ b/agent/verification/e2e/Dockerfile.agent-builder@@ -0,0 +1,14 @@+# Builds verification agent binaries with different versions so the upgrade+# behaviour (v1 -> v2) can be tested. Built from ./cmd (not ./cmd/main.go)+# because the package has platform-split files.+FROM golang:1.26.3-alpine AS build+WORKDIR /src+COPY go.mod go.sum ./+RUN go mod download+COPY . .+RUN CGO_ENABLED=0 go build -ldflags "-X main.Version=v1.0.0" -o /out/agent-v1 ./cmd+RUN CGO_ENABLED=0 go build -ldflags "-X main.Version=v2.0.0" -o /out/agent-v2 ./cmd++FROM alpine:3.21+COPY --from=build /out/ /out/+CMD ["cp", "-v", "/out/agent-v1", "/out/agent-v2", "/artifacts/"]diff --git a/agent/verification/e2e/Dockerfile.agent-runner b/agent/verification/e2e/Dockerfile.agent-runnernew file mode 100644index 00000000..9a473253--- /dev/null+++ b/agent/verification/e2e/Dockerfile.agent-runner@@ -0,0 +1,13 @@+# Runs the verification agent against the mock server. The agent spawns+# ephemeral Postgres containers on the host daemon (docker socket mounted by+# compose); docker-cli here is for the e2e scripts themselves (leak_check+# inspects containers/networks/volumes by label after each terminal outcome).+FROM debian:bookworm-slim++RUN apt-get update && \+ apt-get install -y --no-install-recommends \+ ca-certificates curl docker.io jq && \+ rm -rf /var/lib/apt/lists/*++WORKDIR /tmp+ENTRYPOINT []diff --git a/agent/verification/e2e/Dockerfile.fixture-gen b/agent/verification/e2e/Dockerfile.fixture-gennew file mode 100644index 00000000..98adb9ac--- /dev/null+++ b/agent/verification/e2e/Dockerfile.fixture-gen@@ -0,0 +1,16 @@+# Generates one pg_dump fixture per supported major (good-pg12.dump ..+# good-pg18.dump) plus a single broken.dump sentinel. The entrypoint shells+# out to docker against the host daemon (mounted /var/run/docker.sock) and+# spawns a sibling postgres:N container per iteration so each dump is produced+# by the matching server. No in-container postgres binaries needed.+FROM debian:bookworm-slim++RUN apt-get update && \+ apt-get install -y --no-install-recommends ca-certificates docker.io && \+ rm -rf /var/lib/apt/lists/*++COPY fixture-gen/entrypoint.sh /usr/local/bin/fixture-gen+RUN chmod +x /usr/local/bin/fixture-gen++ENTRYPOINT []+CMD ["/usr/local/bin/fixture-gen"]diff --git a/agent/verification/e2e/Dockerfile.mock-server b/agent/verification/e2e/Dockerfile.mock-servernew file mode 100644index 00000000..1bd16f13--- /dev/null+++ b/agent/verification/e2e/Dockerfile.mock-server@@ -0,0 +1,10 @@+# Mock Databasus API server for version checks, verification-agent binary+# downloads and heartbeat capture. Serves static responses and files.+FROM golang:1.26.3-alpine AS build+WORKDIR /app+COPY mock-server/main.go .+RUN CGO_ENABLED=0 go build -o mock-server main.go++FROM alpine:3.21+COPY --from=build /app/mock-server /usr/local/bin/mock-server+ENTRYPOINT ["mock-server"]diff --git a/agent/verification/e2e/docker-compose.yml b/agent/verification/e2e/docker-compose.ymlnew file mode 100644index 00000000..fe9c1e83--- /dev/null+++ b/agent/verification/e2e/docker-compose.yml@@ -0,0 +1,65 @@+services:+ e2e-agent-builder:+ build:+ context: ..+ dockerfile: e2e/Dockerfile.agent-builder+ volumes:+ - ./artifacts:/artifacts+ container_name: e2e-verification-agent-builder++ e2e-fixture-gen:+ build:+ context: .+ dockerfile: Dockerfile.fixture-gen+ volumes:+ - ./artifacts:/artifacts+ # The entrypoint spawns one sibling postgres:N container per supported+ # major (12..18) and pipes pg_dump out via docker exec, so it talks to+ # the host daemon the same way e2e-agent-runner does.+ - /var/run/docker.sock:/var/run/docker.sock+ container_name: e2e-verification-fixture-gen++ e2e-mock-server:+ build:+ context: .+ dockerfile: Dockerfile.mock-server+ volumes:+ - ./artifacts:/artifacts:ro+ container_name: e2e-verification-mock-server+ # Published to host so e2e-agent-runner (network_mode: host) can reach it+ # via 127.0.0.1:<port> — same path the spawned Postgres ports use. Host+ # port defaults to 4050; override via E2E_MOCK_SERVER_PORT in+ # agent/verification/e2e/.env if 4050 is already taken.+ ports:+ - "${E2E_MOCK_SERVER_PORT:-4050}:4050"+ healthcheck:+ test: ["CMD", "wget", "-q", "--spider", "http://127.0.0.1:4050/health"]+ interval: 2s+ timeout: 5s+ retries: 10++ e2e-agent-runner:+ build:+ context: .+ dockerfile: Dockerfile.agent-runner+ volumes:+ - ./artifacts:/opt/agent/artifacts:ro+ - ./scripts:/opt/agent/scripts:ro+ # The agent's Docker SDK client spawns the ephemeral Postgres containers+ # on the host daemon; pg_restore runs inside those containers (no host+ # client, no assets bundle).+ - /var/run/docker.sock:/var/run/docker.sock+ # Mirrors production: the agent runs directly on the VM, so 127.0.0.1 IS+ # the host. Spawned Postgres containers publish 5432 to a random host port+ # bound to the host's 127.0.0.1 (dockerengine.go binds {HostIP:"127.0.0.1",+ # HostPort:"0"}); the agent-process verifier reaches them on that loopback.+ # A bridge-network runner cannot see those ports — its 127.0.0.1 is its+ # own. Linux-only; document accordingly.+ network_mode: host+ environment:+ - E2E_MOCK_SERVER_PORT=${E2E_MOCK_SERVER_PORT:-4050}+ depends_on:+ e2e-mock-server:+ condition: service_healthy+ container_name: e2e-verification-agent-runner+ command: ["bash", "/opt/agent/scripts/run-all.sh"]diff --git a/agent/verification/e2e/fixture-gen/entrypoint.sh b/agent/verification/e2e/fixture-gen/entrypoint.shnew file mode 100644index 00000000..fbfb1aa9--- /dev/null+++ b/agent/verification/e2e/fixture-gen/entrypoint.sh@@ -0,0 +1,65 @@+#!/bin/bash+# Produces /artifacts/good-pgN.dump for each supported Postgres major and a+# single /artifacts/broken.dump sentinel. For each major: spawn a sibling+# postgres:N container against the host daemon, wait for pg_isready, seed the+# t_a + t_b schema, pg_dump -Fc to the artifacts dir, and remove the+# container. Producer and consumer (pg_restore in the agent's spawned target)+# share the major so the custom-format archive header matches.+set -euo pipefail++VERSIONS=(12 13 14 15 16 17 18)+ARTIFACTS=/artifacts+BROKEN="$ARTIFACTS/broken.dump"++mkdir -p "$ARTIFACTS"++CID=""+cleanup() {+ if [ -n "${CID:-}" ]; then+ docker rm -f "$CID" >/dev/null 2>&1 || true+ fi+}+trap cleanup EXIT++for V in "${VERSIONS[@]}"; do+ CID="$(docker run -d -e POSTGRES_PASSWORD=test "postgres:$V")"++ READY=0+ for _ in $(seq 1 30); do+ if docker exec "$CID" pg_isready -U postgres -h 127.0.0.1 >/dev/null 2>&1; then+ READY=1+ break+ fi+ sleep 1+ done++ if [ "$READY" -ne 1 ]; then+ echo "FAIL: postgres:$V never became ready within 30s"+ docker logs "$CID" 2>&1 | tail -30+ exit 1+ fi++ docker exec -i "$CID" psql -U postgres -d postgres -v ON_ERROR_STOP=1 <<'SQL'+CREATE TABLE public.t_a (id int PRIMARY KEY, name text);+CREATE TABLE public.t_b (+ id int PRIMARY KEY,+ a_id int NOT NULL REFERENCES public.t_a(id),+ value text+);+INSERT INTO public.t_a (id, name) VALUES (1, 'alpha'), (2, 'beta'), (3, 'gamma');+INSERT INTO public.t_b (id, a_id, value) VALUES+ (1, 1, 'x'), (2, 1, 'y'), (3, 2, 'z'), (4, 3, 'w'), (5, 3, 'v');+SQL++ OUT="$ARTIFACTS/good-pg${V}.dump"+ docker exec "$CID" pg_dump -Fc -U postgres postgres > "$OUT"++ docker rm -f "$CID" >/dev/null+ CID=""++ echo "fixture: good-pg${V}.dump=$(stat -c%s "$OUT")B"+done++printf 'not-a-valid-pg-dump-custom-format-archive\n' > "$BROKEN"+chmod 644 "$ARTIFACTS"/good-pg*.dump "$BROKEN"+echo "fixture: broken.dump=$(stat -c%s "$BROKEN")B"diff --git a/agent/verification/e2e/mock-server/main.go b/agent/verification/e2e/mock-server/main.gonew file mode 100644index 00000000..4a5a95a1--- /dev/null+++ b/agent/verification/e2e/mock-server/main.go@@ -0,0 +1,366 @@+// Mock Databasus API server for the verification agent e2e: serves version+// checks, the verification-agent binary download, the capacity heartbeat, and+// the job protocol (claim / backup-stream / report) with fault-injection+// controls. Stdlib only — built standalone via `go build main.go`.+package main++import (+ "encoding/json"+ "log"+ "net/http"+ "os"+ "sync"+ "time"+)++type server struct {+ mu sync.RWMutex+ version string+ binaryPath string+ heartbeats int+ lastBody map[string]any++ // job protocol state+ claimJob map[string]any+ backupFixturePath string+ reports []map[string]any+ abortIDs []string+ streamFailRemain int+ tearStreamOnce bool+ reportGone bool+}++func main() {+ s := &server{version: "v1.0.0", binaryPath: "/artifacts/agent-v1"}++ mux := http.NewServeMux()+ mux.HandleFunc("GET /api/v1/system/version", s.handleVersion)+ mux.HandleFunc("GET /api/v1/system/verification-agent", s.handleDownload)+ mux.HandleFunc("POST /api/v1/agent/verification/{agentId}/heartbeat", s.handleHeartbeat)++ mux.HandleFunc("POST /api/v1/agent/verifications/{agentId}/claim", s.handleClaim)+ mux.HandleFunc("GET /api/v1/agent/verifications/{agentId}/{id}/backup-stream", s.handleBackupStream)+ mux.HandleFunc("POST /api/v1/agent/verifications/{agentId}/{id}/report", s.handleReport)++ mux.HandleFunc("POST /mock/set-version", s.handleSetVersion)+ mux.HandleFunc("POST /mock/set-binary-path", s.handleSetBinaryPath)+ mux.HandleFunc("GET /mock/heartbeats", s.handleHeartbeatStatus)+ mux.HandleFunc("POST /mock/set-claim", s.handleSetClaim)+ mux.HandleFunc("POST /mock/set-backup-fixture", s.handleSetBackupFixture)+ mux.HandleFunc("POST /mock/set-abort", s.handleSetAbort)+ mux.HandleFunc("POST /mock/set-stream-fail", s.handleSetStreamFail)+ mux.HandleFunc("POST /mock/set-report-gone", s.handleSetReportGone)+ mux.HandleFunc("GET /mock/reports", s.handleGetReports)+ mux.HandleFunc("POST /mock/reset", s.handleReset)+ mux.HandleFunc("GET /health", s.handleHealth)++ addr := ":4050"+ log.Printf("mock server starting on %s", addr)++ if err := http.ListenAndServe(addr, mux); err != nil {+ log.Fatalf("server failed: %v", err)+ }+}++func (s *server) handleVersion(w http.ResponseWriter, _ *http.Request) {+ s.mu.RLock()+ version := s.version+ s.mu.RUnlock()++ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(map[string]string{"version": version})+}++func (s *server) handleDownload(w http.ResponseWriter, r *http.Request) {+ s.mu.RLock()+ path := s.binaryPath+ s.mu.RUnlock()++ log.Printf("GET verification-agent (arch=%s) -> %s", r.URL.Query().Get("arch"), path)+ http.ServeFile(w, r, path)+}++func (s *server) handleHeartbeat(w http.ResponseWriter, r *http.Request) {+ var body map[string]any+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {+ http.Error(w, err.Error(), http.StatusBadRequest)+ return+ }++ s.mu.Lock()+ s.heartbeats+++ s.lastBody = body+ count := s.heartbeats+ abortIDs := append([]string{}, s.abortIDs...)+ s.mu.Unlock()++ log.Printf("POST heartbeat (agent=%s) -> count=%d", r.PathValue("agentId"), count)++ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(map[string]any{+ "lastSeenAt": time.Now().UTC().Format(time.RFC3339),+ "abortVerificationIds": abortIDs,+ })+}++func (s *server) handleClaim(w http.ResponseWriter, r *http.Request) {+ s.mu.Lock()+ job := s.claimJob+ s.claimJob = nil // one-shot: a single verification per test run+ s.mu.Unlock()++ if job == nil {+ w.WriteHeader(http.StatusNoContent)+ return+ }++ log.Printf("POST claim (agent=%s) -> assigning %v", r.PathValue("agentId"), job["verificationId"])+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(job)+}++func (s *server) handleBackupStream(w http.ResponseWriter, r *http.Request) {+ s.mu.Lock()+ failRemain := s.streamFailRemain+ if failRemain > 0 {+ s.streamFailRemain--+ }+ tear := s.tearStreamOnce+ s.tearStreamOnce = false+ fixture := s.backupFixturePath+ s.mu.Unlock()++ if failRemain > 0 {+ log.Printf("GET backup-stream -> injected 503 (remaining=%d)", failRemain-1)+ w.WriteHeader(http.StatusServiceUnavailable)+ return+ }++ if tear {+ log.Printf("GET backup-stream -> tearing connection mid-body")+ w.Header().Set("Content-Type", "application/octet-stream")+ _, _ = w.Write([]byte("PARTIAL"))++ if flusher, ok := w.(http.Flusher); ok {+ flusher.Flush()+ }++ if hj, ok := w.(http.Hijacker); ok {+ conn, _, err := hj.Hijack()+ if err == nil {+ _ = conn.Close()+ }+ }++ return+ }++ log.Printf("GET backup-stream (id=%s) -> %s", r.PathValue("id"), fixture)+ w.Header().Set("Content-Type", "application/octet-stream")+ http.ServeFile(w, r, fixture)+}++func (s *server) handleReport(w http.ResponseWriter, r *http.Request) {+ var body map[string]any+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {+ http.Error(w, err.Error(), http.StatusBadRequest)+ return+ }++ body["verificationId"] = r.PathValue("id")++ s.mu.Lock()+ gone := s.reportGone+ if !gone {+ s.reports = append(s.reports, body)+ }+ s.mu.Unlock()++ if gone {+ log.Printf("POST report (id=%s) -> 410 gone", r.PathValue("id"))+ w.WriteHeader(http.StatusGone)+ _, _ = w.Write([]byte(`{"reason":"gone"}`))+ return+ }++ log.Printf("POST report (id=%s) -> status=%v exit=%v", r.PathValue("id"), body["status"], body["pgRestoreExitCode"])+ w.WriteHeader(http.StatusNoContent)+}++func (s *server) handleSetVersion(w http.ResponseWriter, r *http.Request) {+ var body struct {+ Version string `json:"version"`+ }++ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {+ http.Error(w, err.Error(), http.StatusBadRequest)+ return+ }++ s.mu.Lock()+ s.version = body.Version+ s.mu.Unlock()++ log.Printf("POST /mock/set-version -> %s", body.Version)+ w.WriteHeader(http.StatusOK)+}++func (s *server) handleSetBinaryPath(w http.ResponseWriter, r *http.Request) {+ var body struct {+ BinaryPath string `json:"binaryPath"`+ }++ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {+ http.Error(w, err.Error(), http.StatusBadRequest)+ return+ }++ s.mu.Lock()+ s.binaryPath = body.BinaryPath+ s.mu.Unlock()++ log.Printf("POST /mock/set-binary-path -> %s", body.BinaryPath)+ w.WriteHeader(http.StatusOK)+}++func (s *server) handleSetClaim(w http.ResponseWriter, r *http.Request) {+ var job map[string]any+ if err := json.NewDecoder(r.Body).Decode(&job); err != nil {+ http.Error(w, err.Error(), http.StatusBadRequest)+ return+ }++ s.mu.Lock()+ s.claimJob = job+ s.mu.Unlock()++ log.Printf("POST /mock/set-claim -> %v", job["verificationId"])+ w.WriteHeader(http.StatusOK)+}++func (s *server) handleSetBackupFixture(w http.ResponseWriter, r *http.Request) {+ var body struct {+ Path string `json:"path"`+ }++ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {+ http.Error(w, err.Error(), http.StatusBadRequest)+ return+ }++ if _, err := os.Stat(body.Path); err != nil {+ http.Error(w, "fixture not found: "+err.Error(), http.StatusBadRequest)+ return+ }++ s.mu.Lock()+ s.backupFixturePath = body.Path+ s.mu.Unlock()++ log.Printf("POST /mock/set-backup-fixture -> %s", body.Path)+ w.WriteHeader(http.StatusOK)+}++func (s *server) handleSetAbort(w http.ResponseWriter, r *http.Request) {+ var body struct {+ IDs []string `json:"ids"`+ }++ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {+ http.Error(w, err.Error(), http.StatusBadRequest)+ return+ }++ s.mu.Lock()+ s.abortIDs = body.IDs+ s.mu.Unlock()++ log.Printf("POST /mock/set-abort -> %v", body.IDs)+ w.WriteHeader(http.StatusOK)+}++func (s *server) handleSetStreamFail(w http.ResponseWriter, r *http.Request) {+ var body struct {+ Count int `json:"count"`+ TearStreamOnce bool `json:"tearStreamOnce"`+ }++ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {+ http.Error(w, err.Error(), http.StatusBadRequest)+ return+ }++ s.mu.Lock()+ s.streamFailRemain = body.Count+ s.tearStreamOnce = body.TearStreamOnce+ s.mu.Unlock()++ log.Printf("POST /mock/set-stream-fail -> count=%d tear=%v", body.Count, body.TearStreamOnce)+ w.WriteHeader(http.StatusOK)+}++func (s *server) handleSetReportGone(w http.ResponseWriter, r *http.Request) {+ var body struct {+ Gone bool `json:"gone"`+ }++ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {+ http.Error(w, err.Error(), http.StatusBadRequest)+ return+ }++ s.mu.Lock()+ s.reportGone = body.Gone+ s.mu.Unlock()++ log.Printf("POST /mock/set-report-gone -> %v", body.Gone)+ w.WriteHeader(http.StatusOK)+}++func (s *server) handleGetReports(w http.ResponseWriter, _ *http.Request) {+ s.mu.RLock()+ defer s.mu.RUnlock()++ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(map[string]any{+ "count": len(s.reports),+ "reports": s.reports,+ })+}++func (s *server) handleHeartbeatStatus(w http.ResponseWriter, _ *http.Request) {+ s.mu.RLock()+ defer s.mu.RUnlock()++ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(map[string]any{+ "count": s.heartbeats,+ "last": s.lastBody,+ })+}++// handleReset wipes per-test state (reports, claim, abort/stream/report-gone+// flags, fixture path). Version + binary path are left alone — pin them via+// /mock/set-version + /mock/set-binary-path. Each restore-style e2e test+// should call this at the top to avoid seeing prior-test artifacts.+func (s *server) handleReset(w http.ResponseWriter, _ *http.Request) {+ s.mu.Lock()+ s.reports = nil+ s.claimJob = nil+ s.backupFixturePath = ""+ s.abortIDs = nil+ s.streamFailRemain = 0+ s.tearStreamOnce = false+ s.reportGone = false+ s.heartbeats = 0+ s.lastBody = nil+ s.mu.Unlock()++ log.Printf("POST /mock/reset -> state wiped")+ w.WriteHeader(http.StatusOK)+}++func (s *server) handleHealth(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte("ok"))+}diff --git a/agent/verification/e2e/scripts/lib.sh b/agent/verification/e2e/scripts/lib.shnew file mode 100644index 00000000..566f061e--- /dev/null+++ b/agent/verification/e2e/scripts/lib.sh@@ -0,0 +1,137 @@+#!/bin/bash+# Shared helpers for verification-agent e2e scripts (sourced by each+# scripts/test-*.sh). The runner uses network_mode: host so 127.0.0.1:4050+# reaches the published mock-server port AND the random host ports the+# spawned Postgres containers bind 5432 to — same setup as production+# (agent on the VM, sibling containers).++MOCK="http://127.0.0.1:${E2E_MOCK_SERVER_PORT:-4050}"+ARTIFACTS="/opt/agent/artifacts"++hb_count() {+ curl -sf "$MOCK/mock/heartbeats" | sed -n 's/.*"count":\([0-9]*\).*/\1/p'+}++reports_json() {+ curl -sf "$MOCK/mock/reports"+}++# reset_mock_version pins the mock to v1.0.0 / agent-v1 so the agent's+# background upgrader finds no newer version and the process stays up for the+# whole test.+reset_mock_version() {+ curl -sf -X POST "$MOCK/mock/set-version" \+ -H 'Content-Type: application/json' -d '{"version":"v1.0.0"}'+ curl -sf -X POST "$MOCK/mock/set-binary-path" \+ -H 'Content-Type: application/json' -d '{"binaryPath":"/artifacts/agent-v1"}'+}++# reset_mock_state wipes per-test state (reports, claim, fixture, abort/stream+# flags, heartbeat counter). The mock is shared across all e2e scripts in one+# run; without this, a later script sees an earlier script's report and bails.+reset_mock_state() {+ curl -sf -X POST "$MOCK/mock/reset" >/dev/null+}++# leak_check is non-zero if any container/network labeled with the given agent+# ID survives. The anonymous PGDATA volume carries no label and is removed+# alongside the container by RemoveOptions{RemoveVolumes:true}, so a leaked+# container is the canonical signal of a leaked PGDATA.+leak_check() {+ local agent_id="$1"+ local label="databasus.verification.agent_id=${agent_id}"+ local rc=0++ local containers+ containers="$(docker ps -a --filter "label=${label}" --format '{{.ID}} {{.Names}}')"+ if [ -n "$containers" ]; then+ echo "FAIL: leaked containers labeled ${label}:"+ echo "$containers"+ rc=1+ fi++ local networks+ networks="$(docker network ls --filter "label=${label}" --format '{{.ID}} {{.Name}}')"+ if [ -n "$networks" ]; then+ echo "FAIL: leaked networks labeled ${label}:"+ echo "$networks"+ rc=1+ fi++ return $rc+}++# start_agent <agent_id> [extra_flag...] — runs `databasus-verification-agent run`+# with the standard launch block in the current dir, redirects stdout+stderr to+# ./agent.out, and sets AGENT_PID. Extra flags forwarded to the binary.+start_agent() {+ local agent_id="$1"+ shift+ ./databasus-verification-agent run \+ --databasus-host "$MOCK" \+ --agent-id "$agent_id" \+ --token test-token \+ --max-cpu 4 \+ --max-ram-mb 2048 \+ --max-disk-gb 20 \+ --max-concurrent-jobs 2 \+ --allow-insecure-http \+ --skip-update \+ "$@" > agent.out 2>&1 &+ AGENT_PID=$!+}++stop_agent() {+ kill "$AGENT_PID" 2>/dev/null || true+ wait "$AGENT_PID" 2>/dev/null || true+}++dump_diagnostics() {+ echo "---- agent.out (last 30) ----"+ tail -30 agent.out 2>/dev/null || echo "(no agent.out)"+ echo "---- databasus-verification.log (last 60) ----"+ tail -60 databasus-verification.log 2>/dev/null || echo "(no log file)"+}++# wait_for_report <pattern> <deadline_seconds> [fatal_pattern] — polls+# /mock/reports every 2s until grep -q "$pattern" matches. If fatal_pattern is+# set and matches first, exits 1 with diagnostics. On timeout, exits 1 with+# diagnostics. On success, REPORTS holds the body for follow-up asserts.+wait_for_report() {+ local want="$1"+ local seconds="$2"+ local fatal="${3:-}"+ local deadline=$((SECONDS + seconds))+ REPORTS=""+ while [ $SECONDS -lt $deadline ]; do+ REPORTS="$(reports_json)"+ if echo "$REPORTS" | grep -q "$want"; then+ return 0+ fi+ if [ -n "$fatal" ] && echo "$REPORTS" | grep -q "$fatal"; then+ echo "FAIL: saw fatal pattern $fatal before expected $want"+ echo "reports: $REPORTS"+ dump_diagnostics+ exit 1+ fi+ sleep 2+ done+ echo "FAIL: no report matching $want within ${seconds}s"+ echo "reports: $REPORTS"+ dump_diagnostics+ exit 1+}++# assert_report <verification_id> <jq_expr> — selects the report whose+# verificationId matches and asserts jq_expr is truthy. On failure prints the+# matching report pretty-printed.+assert_report() {+ local vid="$1"+ local expr="$2"+ if ! reports_json | jq -e --arg vid "$vid" \+ "(.reports[] | select(.verificationId == \$vid)) | $expr" >/dev/null; then+ echo "FAIL: report assertion failed for $vid: $expr"+ reports_json | jq --arg vid "$vid" '.reports[] | select(.verificationId == $vid)'+ exit 1+ fi+}diff --git a/agent/verification/e2e/scripts/run-all.sh b/agent/verification/e2e/scripts/run-all.shnew file mode 100644index 00000000..d7825c0b--- /dev/null+++ b/agent/verification/e2e/scripts/run-all.sh@@ -0,0 +1,50 @@+#!/bin/bash+set -uo pipefail++SCRIPT_DIR="$(dirname "$0")"++TESTS=(+ "test-heartbeat-and-upgrade.sh"+ "test-start-stop-status.sh"+ "test-startup-purge.sh"+ "test-restore-broken.sh"+ "test-restore-disk-budget.sh"+)++PG_VERSIONS=(12 13 14 15 16 17 18)++echo "========================================"+echo " Verification agent e2e"+echo "========================================"++PASSED=0+FAILED=0++for test in "${TESTS[@]}"; do+ echo ""+ echo "---- $test ----"+ if bash "$SCRIPT_DIR/$test"; then+ PASSED=$((PASSED + 1))+ else+ FAILED=$((FAILED + 1))+ fi+done++for V in "${PG_VERSIONS[@]}"; do+ echo ""+ echo "---- test-restore-success.sh $V ----"+ if bash "$SCRIPT_DIR/test-restore-success.sh" "$V"; then+ PASSED=$((PASSED + 1))+ else+ FAILED=$((FAILED + 1))+ fi+done++echo ""+echo "========================================"+echo " Results: $PASSED passed, $FAILED failed"+echo "========================================"++if [ "$FAILED" -ne 0 ]; then+ exit 1+fidiff --git a/agent/verification/e2e/scripts/test-heartbeat-and-upgrade.sh b/agent/verification/e2e/scripts/test-heartbeat-and-upgrade.shnew file mode 100644index 00000000..e8e79f71--- /dev/null+++ b/agent/verification/e2e/scripts/test-heartbeat-and-upgrade.sh@@ -0,0 +1,122 @@+#!/bin/bash+set -euo pipefail++source "$(dirname "$0")/lib.sh"++WORK="/tmp/agent-work"+AGENT_ID="11111111-1111-1111-1111-111111111111"++rm -rf "$WORK"+mkdir -p "$WORK"+cd "$WORK"++reset_mock_version++cp "$ARTIFACTS/agent-v1" ./databasus-verification-agent+chmod +x ./databasus-verification-agent++INITIAL="$(./databasus-verification-agent version)"+if [ "$INITIAL" != "v1.0.0" ]; then+ echo "FAIL: expected initial version v1.0.0, got $INITIAL"+ exit 1+fi+echo "Initial version: $INITIAL"++./databasus-verification-agent run \+ --databasus-host "$MOCK" \+ --agent-id "$AGENT_ID" \+ --token test-token \+ --max-cpu 4 \+ --max-ram-mb 2048 \+ --max-disk-gb 20 \+ --max-concurrent-jobs 2 \+ --allow-insecure-http > agent.out 2>&1 &+AGENT_PID=$!++# 1) Capacity heartbeat is received (Run sends one immediately).+COUNT=0+for _ in $(seq 1 20); do+ COUNT="$(hb_count || echo 0)"+ [ "${COUNT:-0}" -ge 1 ] && break+ sleep 1+done+if [ "${COUNT:-0}" -lt 1 ]; then+ echo "FAIL: no heartbeat received"+ cat agent.out+ exit 1+fi+echo "Heartbeat received (count=$COUNT)"++# 2) Heartbeat wire shape: flat maxRamGb (2048 MB -> 2 GB), empty job list.+BODY="$(curl -sf "$MOCK/mock/heartbeats")"+if ! echo "$BODY" | grep -q '"maxRamGb":2'; then+ echo "FAIL: heartbeat missing maxRamGb:2"+ echo "$BODY"+ exit 1+fi+if ! echo "$BODY" | grep -q '"currentVerificationIds":\[\]'; then+ echo "FAIL: heartbeat currentVerificationIds not []"+ echo "$BODY"+ exit 1+fi+echo "Heartbeat wire shape OK"++# 3) Bump version -> background self-update downloads v2 and re-execs.+curl -sf -X POST "$MOCK/mock/set-binary-path" \+ -H 'Content-Type: application/json' -d '{"binaryPath":"/artifacts/agent-v2"}'+curl -sf -X POST "$MOCK/mock/set-version" \+ -H 'Content-Type: application/json' -d '{"version":"v2.0.0"}'+echo "Mock bumped to v2.0.0, waiting for background upgrade..."++DEADLINE=$((SECONDS + 90))+while [ $SECONDS -lt $DEADLINE ]; do+ [ "$(./databasus-verification-agent version)" = "v2.0.0" ] && break+ sleep 3+done++FINAL="$(./databasus-verification-agent version)"+if [ "$FINAL" != "v2.0.0" ]; then+ echo "FAIL: expected v2.0.0 after background upgrade, got $FINAL"+ cat agent.out+ exit 1+fi+echo "Binary upgraded to $FINAL"++if ! grep -q "Agent binary updated" agent.out; then+ echo "FAIL: upgrade log line missing"+ cat agent.out+ exit 1+fi+if ! grep -q "Re-executing after upgrade" agent.out; then+ echo "FAIL: re-exec log line missing"+ cat agent.out+ exit 1+fi++# 4) Same PID is alive after re-exec (syscall.Exec preserves the PID).+if ! kill -0 "$AGENT_PID" 2>/dev/null; then+ echo "FAIL: agent process died during self-update"+ cat agent.out+ exit 1+fi++# 5) Heartbeats resume after re-exec.+BEFORE="$(hb_count || echo 0)"+RESUMED=0+for _ in $(seq 1 45); do+ AFTER="$(hb_count || echo 0)"+ if [ "${AFTER:-0}" -gt "${BEFORE:-0}" ]; then+ RESUMED=1+ break+ fi+ sleep 1+done+if [ "$RESUMED" -ne 1 ]; then+ echo "FAIL: heartbeats did not resume after re-exec ($BEFORE -> ${AFTER:-0})"+ cat agent.out+ exit 1+fi+echo "Heartbeats resumed after re-exec ($BEFORE -> $AFTER)"++kill "$AGENT_PID" 2>/dev/null || true+echo "Verification agent e2e passed"diff --git a/agent/verification/e2e/scripts/test-restore-broken.sh b/agent/verification/e2e/scripts/test-restore-broken.shnew file mode 100644index 00000000..1985c412--- /dev/null+++ b/agent/verification/e2e/scripts/test-restore-broken.sh@@ -0,0 +1,51 @@+#!/bin/bash+# Restore e2e (broken dump): mock serves a file that is NOT a valid -Fc+# archive; pg_restore -Fc inside the spawned Postgres container must reject+# it and exit non-zero, and the agent must POST FAILED with a real+# pgRestoreExitCode. Independent of the verifier-conn fix — the failure+# happens at restore, never reaches the verifier.+set -euo pipefail++source "$(dirname "$0")/lib.sh"++WORK="/tmp/agent-work-restore-broken"+AGENT_ID="33333333-3333-3333-3333-333333333333"+VERIFICATION_ID="33333333-aaaa-aaaa-aaaa-333333333333"+BACKUP_ID="33333333-bbbb-bbbb-bbbb-333333333333"++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/broken.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\",\"postgresql\":{\"version\":\"16\"}}}"++# Spawn + image pull (first run) + restore + report. Generous budget on cold cache.+wait_for_report '"status":"FAILED"' 240++assert_report "$VERIFICATION_ID" '.pgRestoreExitCode >= 1'++echo "Broken-dump report OK: FAILED with non-zero pgRestoreExitCode"++stop_agent++if ! leak_check "$AGENT_ID"; then+ echo "---- agent.out ----"+ cat agent.out+ exit 1+fi++echo "Verification agent restore-broken e2e passed"diff --git a/agent/verification/e2e/scripts/test-restore-disk-budget.sh b/agent/verification/e2e/scripts/test-restore-disk-budget.shnew file mode 100644index 00000000..3b1b144a--- /dev/null+++ b/agent/verification/e2e/scripts/test-restore-disk-budget.sh@@ -0,0 +1,48 @@+#!/bin/bash+# Disk-budget enforcement (real Docker): tiny maxContainerDiskMb (1 MB) against+# the standard postgres:16 init footprint (~50 MB) makes the disk watcher trip+# on its first poll. The agent must POST FAILED with failureKind:+# DISK_LIMIT_EXCEEDED and the container/anonymous PGDATA volume must be torn+# down. The watcher polls every 3 s so the verdict lands within ~10 s of spawn.+set -euo pipefail++source "$(dirname "$0")/lib.sh"++WORK="/tmp/agent-work-disk-budget"+AGENT_ID="55555555-5555-5555-5555-555555555555"+VERIFICATION_ID="55555555-aaaa-aaaa-aaaa-555555555555"+BACKUP_ID="55555555-bbbb-bbbb-bbbb-555555555555"++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-pg16.dump"}'++curl -sf -X POST "$MOCK/mock/set-claim" \+ -H 'Content-Type: application/json' \+ -d "{\"verificationId\":\"$VERIFICATION_ID\",\"backupId\":\"$BACKUP_ID\",\"backupSizeMb\":1,\"maxContainerDiskMb\":1,\"database\":{\"type\":\"POSTGRES\",\"postgresql\":{\"version\":\"16\"}}}"++wait_for_report '"failureKind":"DISK_LIMIT_EXCEEDED"' 180 '"status":"COMPLETED"'++assert_report "$VERIFICATION_ID" '.status == "FAILED"'++echo "Disk-budget verdict OK: FAILED with failureKind:DISK_LIMIT_EXCEEDED"++stop_agent++if ! leak_check "$AGENT_ID"; then+ exit 1+fi++echo "Verification agent restore-disk-budget e2e passed"diff --git a/agent/verification/e2e/scripts/test-restore-success.sh b/agent/verification/e2e/scripts/test-restore-success.shnew file mode 100644index 00000000..debe179b--- /dev/null+++ b/agent/verification/e2e/scripts/test-restore-success.sh@@ -0,0 +1,58 @@+#!/bin/bash+# Restore e2e (correct dump) for one Postgres major: mock serves the matching+# -Fc archive of a tiny seeded schema; the agent must run pg_restore inside+# the spawned postgres:N container, then the verifier (out-of-container pgx+# via the container's published host port) must collect tier stats, and the+# agent must POST COMPLETED with non-null dbSizeBytesAfterRestore /+# tableCount / pgRestoreExitCode==0 / non-empty tableStats. The PG major is+# the first positional arg (default 16); run-all.sh loops it over 12..18.+set -euo pipefail++source "$(dirname "$0")/lib.sh"++PG_VERSION="${1:-16}"++WORK="/tmp/agent-work-restore-success-pg${PG_VERSION}"+AGENT_ID="44444444-4444-4444-4444-444444444444"+VERIFICATION_ID="44444444-aaaa-aaaa-aaaa-4444444444${PG_VERSION}"+BACKUP_ID="44444444-bbbb-bbbb-bbbb-4444444444${PG_VERSION}"++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}.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\",\"postgresql\":{\"version\":\"${PG_VERSION}\"}}}"++wait_for_report '"status":"COMPLETED"' 240 '"status":"FAILED"'++assert_report "$VERIFICATION_ID" '.pgRestoreExitCode == 0'+assert_report "$VERIFICATION_ID" '.dbSizeBytesAfterRestore > 0'+assert_report "$VERIFICATION_ID" '.tableCount == 2'+assert_report "$VERIFICATION_ID" '.schemaCount == 1'+assert_report "$VERIFICATION_ID" '(.tableStats | map(.name) | sort) == ["t_a","t_b"]'++echo "Success report OK (pg${PG_VERSION}): COMPLETED with tableCount=2 schemaCount=1 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-success e2e (pg${PG_VERSION}) passed"diff --git a/agent/verification/e2e/scripts/test-start-stop-status.sh b/agent/verification/e2e/scripts/test-start-stop-status.shnew file mode 100644index 00000000..6112ae1c--- /dev/null+++ b/agent/verification/e2e/scripts/test-start-stop-status.sh@@ -0,0 +1,131 @@+#!/bin/bash+set -euo pipefail++source "$(dirname "$0")/lib.sh"++WORK="/tmp/agent-work-startstop"+AGENT_ID="22222222-2222-2222-2222-222222222222"++dump_daemon_log() {+ echo "---- databasus-verification.daemon.log ----"+ cat databasus-verification.daemon.log 2>/dev/null || echo "(no daemon log)"+}++rm -rf "$WORK"+mkdir -p "$WORK"+cd "$WORK"++reset_mock_version++cp "$ARTIFACTS/agent-v1" ./databasus-verification-agent+chmod +x ./databasus-verification-agent++LAUNCH_FLAGS=(+ --databasus-host "$MOCK"+ --agent-id "$AGENT_ID"+ --token test-token+ --max-cpu 4+ --max-ram-mb 2048+ --max-disk-gb 20+ --max-concurrent-jobs 2+ --allow-insecure-http+ --skip-update+)++# 1) status before start -> not running.+STATUS_OUT="$(./databasus-verification-agent status)"+echo "status (before): $STATUS_OUT"+if ! echo "$STATUS_OUT" | grep -q "Agent is not running"; then+ echo "FAIL: expected 'Agent is not running' before start"+ exit 1+fi++# 2) start detaches, returns promptly, prints the daemon PID.+START_OUT="$(./databasus-verification-agent start "${LAUNCH_FLAGS[@]}")"+echo "start: $START_OUT"+if ! echo "$START_OUT" | grep -q "Agent started in background (PID "; then+ echo "FAIL: start did not report a background PID"+ dump_daemon_log+ exit 1+fi++# 3) start created the single-instance lock file.+if [ ! -f databasus-verification.lock ]; then+ echo "FAIL: databasus-verification.lock not created"+ dump_daemon_log+ exit 1+fi++# 4) the detached daemon heartbeats.+RESUMED=0+for _ in $(seq 1 20); do+ COUNT="$(hb_count || echo 0)"+ if [ "${COUNT:-0}" -ge 1 ]; then+ RESUMED=1+ break+ fi+ sleep 1+done+if [ "$RESUMED" -ne 1 ]; then+ echo "FAIL: detached daemon did not heartbeat after start"+ dump_daemon_log+ exit 1+fi+echo "Daemon heartbeating"++# 5) status -> running with a live PID.+STATUS_OUT="$(./databasus-verification-agent status)"+echo "status (running): $STATUS_OUT"+if ! echo "$STATUS_OUT" | grep -q "Agent is running (PID "; then+ echo "FAIL: status did not report running"+ dump_daemon_log+ exit 1+fi+PID="$(echo "$STATUS_OUT" | sed -n 's/.*PID \([0-9]*\).*/\1/p')"+if ! kill -0 "$PID" 2>/dev/null; then+ echo "FAIL: reported PID $PID is not alive"+ exit 1+fi++# 6) a second agent in the same directory is rejected by the lock. `run` is the+# foreground command, so the lock error surfaces directly on its stderr.+set +e+SECOND_OUT="$(./databasus-verification-agent run "${LAUNCH_FLAGS[@]}" 2>&1)"+SECOND_RC=$?+set -e+echo "second run: $SECOND_OUT"+if [ "$SECOND_RC" -eq 0 ]; then+ echo "FAIL: a second agent started while one was already running"+ exit 1+fi+if ! echo "$SECOND_OUT" | grep -q "another instance is already running"; then+ echo "FAIL: second agent did not fail with the single-instance error"+ exit 1+fi+echo "Second instance rejected"++# 7) stop terminates the daemon within the stop timeout.+./databasus-verification-agent stop+GONE=0+for _ in $(seq 1 35); do+ if ! kill -0 "$PID" 2>/dev/null; then+ GONE=1+ break+ fi+ sleep 1+done+if [ "$GONE" -ne 1 ]; then+ echo "FAIL: agent (PID $PID) still alive after stop"+ exit 1+fi+echo "Agent stopped"++# 8) status after stop -> not running again.+STATUS_OUT="$(./databasus-verification-agent status)"+echo "status (after): $STATUS_OUT"+if ! echo "$STATUS_OUT" | grep -q "Agent is not running"; then+ echo "FAIL: expected 'Agent is not running' after stop"+ exit 1+fi++echo "Verification agent start/stop/status e2e passed"diff --git a/agent/verification/e2e/scripts/test-startup-purge.sh b/agent/verification/e2e/scripts/test-startup-purge.shnew file mode 100644index 00000000..055c0832--- /dev/null+++ b/agent/verification/e2e/scripts/test-startup-purge.sh@@ -0,0 +1,61 @@+#!/bin/bash+# Startup purge: at boot the agent removes every container labeled with its+# agent_id — the single-agent invariant means no other process owns containers+# with the same agent_id, so blanket removal is safe. Pre-seed a stray, start+# the agent, assert it's gone.+set -euo pipefail++source "$(dirname "$0")/lib.sh"++WORK="/tmp/agent-work-purge"+AGENT_ID="66666666-6666-6666-6666-666666666666"+STRAY_NAME="databasus-verif-purge-stray"+STRAY_LABEL="databasus.verification.agent_id=${AGENT_ID}"++rm -rf "$WORK"+mkdir -p "$WORK"+cd "$WORK"++reset_mock_state+reset_mock_version++docker rm -f "$STRAY_NAME" >/dev/null 2>&1 || true+docker run -d --name "$STRAY_NAME" --label "$STRAY_LABEL" alpine sleep 600 >/dev/null++if ! docker ps -a --filter "label=$STRAY_LABEL" --format '{{.Names}}' | grep -q "$STRAY_NAME"; then+ echo "FAIL: pre-seed stray container not present"+ exit 1+fi+echo "Pre-seeded stray container $STRAY_NAME with label $STRAY_LABEL"++cp "$ARTIFACTS/agent-v1" ./databasus-verification-agent+chmod +x ./databasus-verification-agent++start_agent "$AGENT_ID"++GONE=0+for _ in $(seq 1 30); do+ if [ -z "$(docker ps -a --filter "label=$STRAY_LABEL" --format '{{.Names}}')" ]; then+ GONE=1+ break+ fi+ sleep 1+done++if [ "$GONE" -ne 1 ]; then+ echo "FAIL: stray container still present after agent start; PurgeContainers did not run"+ docker ps -a --filter "label=$STRAY_LABEL"+ echo "---- agent.out (last 30) ----"+ tail -30 agent.out+ stop_agent+ exit 1+fi+echo "Stray container purged by agent startup"++stop_agent++if ! leak_check "$AGENT_ID"; then+ exit 1+fi++echo "Verification agent startup-purge e2e passed"diff --git a/agent/verification/go.mod b/agent/verification/go.modnew file mode 100644index 00000000..e13820f1--- /dev/null+++ b/agent/verification/go.mod@@ -0,0 +1,48 @@+module databasus-verification-agent++go 1.26.3++require (+ github.com/docker/docker v28.3.3+incompatible+ github.com/docker/go-connections v0.5.0+ github.com/go-resty/resty/v2 v2.17.2+ github.com/google/uuid v1.6.0+ github.com/jackc/pgx/v5 v5.9.2+ github.com/stretchr/testify v1.11.1+)++require (+ github.com/Microsoft/go-winio v0.6.2 // indirect+ github.com/cespare/xxhash/v2 v2.3.0 // indirect+ github.com/containerd/errdefs v1.0.0 // indirect+ github.com/containerd/errdefs/pkg v0.3.0 // indirect+ github.com/containerd/log v0.1.0 // indirect+ github.com/davecgh/go-spew v1.1.1 // indirect+ github.com/distribution/reference v0.6.0 // indirect+ github.com/docker/go-units v0.5.0 // indirect+ github.com/felixge/httpsnoop v1.0.4 // indirect+ github.com/go-logr/logr v1.4.3 // indirect+ github.com/go-logr/stdr v1.2.2 // indirect+ github.com/gogo/protobuf v1.3.2 // indirect+ github.com/jackc/pgpassfile v1.0.0 // indirect+ github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect+ github.com/moby/docker-image-spec v1.3.1 // indirect+ github.com/moby/sys/atomicwriter v0.1.0 // indirect+ github.com/moby/term v0.5.2 // indirect+ github.com/morikuni/aec v1.1.0 // indirect+ github.com/opencontainers/go-digest v1.0.0 // indirect+ github.com/opencontainers/image-spec v1.1.1 // indirect+ github.com/pkg/errors v0.9.1 // indirect+ github.com/pmezard/go-difflib v1.0.0 // indirect+ go.opentelemetry.io/auto/sdk v1.2.1 // indirect+ go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.68.0 // indirect+ go.opentelemetry.io/otel v1.43.0 // indirect+ go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.43.0 // indirect+ go.opentelemetry.io/otel/metric v1.43.0 // indirect+ go.opentelemetry.io/otel/trace v1.43.0 // indirect+ golang.org/x/net v0.52.0 // indirect+ golang.org/x/sys v0.42.0 // indirect+ golang.org/x/text v0.35.0 // indirect+ gopkg.in/yaml.v3 v3.0.1 // indirect+ gotest.tools/v3 v3.5.2 // indirect+)diff --git a/agent/verification/go.sum b/agent/verification/go.sumnew file mode 100644index 00000000..7bee80bd--- /dev/null+++ b/agent/verification/go.sum@@ -0,0 +1,156 @@+github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c h1:udKWzYgxTojEKWjV8V+WSxDXJ4NFATAsZjh8iIbsQIg=+github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E=+github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=+github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=+github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=+github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=+github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=+github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=+github.com/containerd/errdefs v1.0.0 h1:tg5yIfIlQIrxYtu9ajqY42W3lpS19XqdxRQeEwYG8PI=+github.com/containerd/errdefs v1.0.0/go.mod h1:+YBYIdtsnF4Iw6nWZhJcqGSg/dwvV7tyJ/kCkyJ2k+M=+github.com/containerd/errdefs/pkg v0.3.0 h1:9IKJ06FvyNlexW690DXuQNx2KA2cUJXx151Xdx3ZPPE=+github.com/containerd/errdefs/pkg v0.3.0/go.mod h1:NJw6s9HwNuRhnjJhM7pylWwMyAkmCQvQ4GpJHEqRLVk=+github.com/containerd/log v0.1.0 h1:TCJt7ioM2cr/tfR8GPbGf9/VRAX8D2B4PjzCpfX540I=+github.com/containerd/log v0.1.0/go.mod h1:VRRf09a7mHDIRezVKTRCrOq78v577GXq3bSa3EhrzVo=+github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=+github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=+github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=+github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk=+github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E=+github.com/docker/docker v28.3.3+incompatible h1:Dypm25kh4rmk49v1eiVbsAtpAsYURjYkaKubwuBdxEI=+github.com/docker/docker v28.3.3+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk=+github.com/docker/go-connections v0.5.0 h1:USnMq7hx7gwdVZq1L49hLXaFtUdTADjXGp+uj1Br63c=+github.com/docker/go-connections v0.5.0/go.mod h1:ov60Kzw0kKElRwhNs9UlUHAE/F9Fe6GLaXnqyDdmEXc=+github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4=+github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk=+github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=+github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=+github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=+github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=+github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=+github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=+github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=+github.com/go-resty/resty/v2 v2.17.2 h1:FQW5oHYcIlkCNrMD2lloGScxcHJ0gkjshV3qcQAyHQk=+github.com/go-resty/resty/v2 v2.17.2/go.mod h1:kCKZ3wWmwJaNc7S29BRtUhJwy7iqmn+2mLtQrOyQlVA=+github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=+github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=+github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=+github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=+github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=+github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=+github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 h1:HWRh5R2+9EifMyIHV7ZV+MIZqgz+PMpZ14Jynv3O2Zs=+github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0/go.mod h1:JfhWUomR1baixubs02l85lZYYOm7LV6om4ceouMv45c=+github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=+github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=+github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=+github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=+github.com/jackc/pgx/v5 v5.9.2 h1:3ZhOzMWnR4yJ+RW1XImIPsD1aNSz4T4fyP7zlQb56hw=+github.com/jackc/pgx/v5 v5.9.2/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=+github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=+github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=+github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=+github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=+github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=+github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=+github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=+github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=+github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0=+github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo=+github.com/moby/sys/atomicwriter v0.1.0 h1:kw5D/EqkBwsBFi0ss9v1VG3wIkVhzGvLklJ+w3A14Sw=+github.com/moby/sys/atomicwriter v0.1.0/go.mod h1:Ul8oqv2ZMNHOceF643P6FKPXeCmYtlQMvpizfsSoaWs=+github.com/moby/sys/sequential v0.6.0 h1:qrx7XFUd/5DxtqcoH1h438hF5TmOvzC/lspjy7zgvCU=+github.com/moby/sys/sequential v0.6.0/go.mod h1:uyv8EUTrca5PnDsdMGXhZe6CCe8U/UiTWd+lL+7b/Ko=+github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ=+github.com/moby/term v0.5.2/go.mod h1:d3djjFCrjnB+fl8NJux+EJzu0msscUP+f8it8hPkFLc=+github.com/morikuni/aec v1.1.0 h1:vBBl0pUnvi/Je71dsRrhMBtreIqNMYErSAbEeb8jrXQ=+github.com/morikuni/aec v1.1.0/go.mod h1:xDRgiq/iw5l+zkao76YTKzKttOp2cwPEne25HDkJnBw=+github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=+github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=+github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040=+github.com/opencontainers/image-spec v1.1.1/go.mod h1:qpqAh3Dmcf36wStyyWU+kCeDgrGnAve2nCC8+7h8Q0M=+github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=+github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=+github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=+github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=+github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=+github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=+github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=+github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=+github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=+github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=+github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=+github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=+github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=+github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=+github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=+go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=+go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=+go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.68.0 h1:CqXxU8VOmDefoh0+ztfGaymYbhdB/tT3zs79QaZTNGY=+go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.68.0/go.mod h1:BuhAPThV8PBHBvg8ZzZ/Ok3idOdhWIodywz2xEcRbJo=+go.opentelemetry.io/otel v1.43.0 h1:mYIM03dnh5zfN7HautFE4ieIig9amkNANT+xcVxAj9I=+go.opentelemetry.io/otel v1.43.0/go.mod h1:JuG+u74mvjvcm8vj8pI5XiHy1zDeoCS2LB1spIq7Ay0=+go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.43.0 h1:88Y4s2C8oTui1LGM6bTWkw0ICGcOLCAI5l6zsD1j20k=+go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.43.0/go.mod h1:Vl1/iaggsuRlrHf/hfPJPvVag77kKyvrLeD10kpMl+A=+go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.43.0 h1:3iZJKlCZufyRzPzlQhUIWVmfltrXuGyfjREgGP3UUjc=+go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.43.0/go.mod h1:/G+nUPfhq2e+qiXMGxMwumDrP5jtzU+mWN7/sjT2rak=+go.opentelemetry.io/otel/metric v1.43.0 h1:d7638QeInOnuwOONPp4JAOGfbCEpYb+K6DVWvdxGzgM=+go.opentelemetry.io/otel/metric v1.43.0/go.mod h1:RDnPtIxvqlgO8GRW18W6Z/4P462ldprJtfxHxyKd2PY=+go.opentelemetry.io/otel/sdk v1.43.0 h1:pi5mE86i5rTeLXqoF/hhiBtUNcrAGHLKQdhg4h4V9Dg=+go.opentelemetry.io/otel/sdk v1.43.0/go.mod h1:P+IkVU3iWukmiit/Yf9AWvpyRDlUeBaRg6Y+C58QHzg=+go.opentelemetry.io/otel/sdk/metric v1.43.0 h1:S88dyqXjJkuBNLeMcVPRFXpRw2fuwdvfCGLEo89fDkw=+go.opentelemetry.io/otel/sdk/metric v1.43.0/go.mod h1:C/RJtwSEJ5hzTiUz5pXF1kILHStzb9zFlIEe85bhj6A=+go.opentelemetry.io/otel/trace v1.43.0 h1:BkNrHpup+4k4w+ZZ86CZoHHEkohws8AY+WTX09nk+3A=+go.opentelemetry.io/otel/trace v1.43.0/go.mod h1:/QJhyVBUUswCphDVxq+8mld+AvhXZLhe+8WVFxiFff0=+go.opentelemetry.io/proto/otlp v1.10.0 h1:IQRWgT5srOCYfiWnpqUYz9CVmbO8bFmKcwYxpuCSL2g=+go.opentelemetry.io/proto/otlp v1.10.0/go.mod h1:/CV4QoCR/S9yaPj8utp3lvQPoqMtxXdzn7ozvvozVqk=+golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=+golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=+golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=+golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=+golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=+golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=+golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=+golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=+golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=+golang.org/x/net v0.52.0 h1:He/TN1l0e4mmR3QqHMT2Xab3Aj3L9qjbhRm78/6jrW0=+golang.org/x/net v0.52.0/go.mod h1:R1MAz7uMZxVMualyPXb+VaqGSa3LIaUqk0eEt3w36Sw=+golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=+golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=+golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=+golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=+golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=+golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=+golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=+golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=+golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=+golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=+golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=+golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=+golang.org/x/text v0.35.0 h1:JOVx6vVDFokkpaq1AEptVzLTpDe9KGpj5tR4/X+ybL8=+golang.org/x/text v0.35.0/go.mod h1:khi/HExzZJ2pGnjenulevKNX1W67CUy0AsXcNubPGCA=+golang.org/x/time v0.12.0 h1:ScB/8o8olJvc+CQPWrK3fPZNfh7qgwCrY0zJmoEQLSE=+golang.org/x/time v0.12.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg=+golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=+golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=+golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=+golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=+golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=+golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=+golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=+golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=+google.golang.org/genproto/googleapis/api v0.0.0-20260401024825-9d38bb4040a9 h1:VPWxll4HlMw1Vs/qXtN7BvhZqsS9cdAittCNvVENElA=+google.golang.org/genproto/googleapis/api v0.0.0-20260401024825-9d38bb4040a9/go.mod h1:7QBABkRtR8z+TEnmXTqIqwJLlzrZKVfAUm7tY3yGv0M=+google.golang.org/genproto/googleapis/rpc v0.0.0-20260401024825-9d38bb4040a9 h1:m8qni9SQFH0tJc1X0vmnpw/0t+AImlSvp30sEupozUg=+google.golang.org/genproto/googleapis/rpc v0.0.0-20260401024825-9d38bb4040a9/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=+google.golang.org/grpc v1.80.0 h1:Xr6m2WmWZLETvUNvIUmeD5OAagMw3FiKmMlTdViWsHM=+google.golang.org/grpc v1.80.0/go.mod h1:ho/dLnxwi3EDJA4Zghp7k2Ec1+c2jqup0bFkw07bwF4=+google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=+google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=+gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=+gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=+gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=+gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=+gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=+gotest.tools/v3 v3.5.2 h1:7koQfIKdy+I8UTetycgUqXWSDwpgv193Ka+qRsmBY8Q=+gotest.tools/v3 v3.5.2/go.mod h1:LtdLGcnqToBH83WByAAi/wiwSFCArdFIUV/xxN4pcjA=diff --git a/agent/verification/internal/config/config.go b/agent/verification/internal/config/config.gonew file mode 100644index 00000000..f3b59b38--- /dev/null+++ b/agent/verification/internal/config/config.go@@ -0,0 +1,350 @@+package config++import (+ "bufio"+ "encoding/json"+ "flag"+ "fmt"+ "net/url"+ "os"+ "strings"++ "databasus-verification-agent/internal/logger"+)++var log = logger.GetLogger()++const configFileName = "databasus-verification.json"++const minRAMMbPerJob = 512++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"`++ flags parsedFlags+}++type Capacity struct {+ MaxCPU int+ MaxRAMMb int+ MaxDiskGb int+ MaxConcurrentJobs int++ CPUPerJob int+ RAMMbPerJob int+}++// LoadFromJSONAndArgs reads databasus-verification.json into the struct+// and overrides JSON values with any explicitly provided CLI flags.+func (c *Config) LoadFromJSONAndArgs(fs *flag.FlagSet, args []string) {+ c.loadFromJSON()+ c.initSources()++ c.flags.databasusHost = fs.String(+ "databasus-host",+ "",+ "Databasus server URL (e.g. https://your-server:4005)",+ )+ c.flags.agentID = fs.String("agent-id", "", "Verification agent ID")+ c.flags.token = fs.String("token", "", "Verification agent token")+ c.flags.maxCPU = fs.Int("max-cpu", 0, "Total CPU cores available to the agent")+ c.flags.maxRAMMb = fs.Int("max-ram-mb", 0, "Total RAM in MB available to the agent")+ c.flags.maxDiskGb = fs.Int("max-disk-gb", 0, "Total scratch disk in GB available to the agent")+ c.flags.maxConcurrentJobs = fs.Int("max-concurrent-jobs", 0, "Number of verifications to run in parallel")+ c.flags.allowInsecureHTTP = fs.Bool(+ "allow-insecure-http",+ false,+ "Permit a plain http:// databasus-host (token and backup data sent unencrypted)",+ )++ if err := fs.Parse(args); err != nil {+ os.Exit(1)+ }++ c.applyFlags()+ log.Info("========= Loading config ============")+ c.logConfigSources()+ log.Info("========= Config has been loaded ====")+}++// SaveToJSON writes the current struct to databasus-verification.json.+func (c *Config) SaveToJSON() error {+ data, err := json.MarshalIndent(c, "", " ")+ if err != nil {+ return err+ }++ return os.WriteFile(configFileName, data, 0o644)+}++// LoadFromJSON reads databasus-verification.json without applying CLI flags.+// The detached _run daemon uses this: the parent `start` already validated and+// persisted the config, so the child trusts the file as-is.+func (c *Config) LoadFromJSON() {+ c.loadFromJSON()+}++func (c *Config) Validate() (Capacity, error) {+ if c.DatabasusHost == "" {+ return Capacity{}, fmt.Errorf("databasus-host is required")+ }++ if c.AgentID == "" {+ return Capacity{}, fmt.Errorf("agent-id is required")+ }++ if c.Token == "" {+ return Capacity{}, fmt.Errorf("token is required")+ }++ return c.DeriveCapacity()+}++func (c *Config) DeriveCapacity() (Capacity, error) {+ if c.MaxConcurrentJobs < 1 {+ return Capacity{}, fmt.Errorf(+ "max-concurrent-jobs must be >= 1 (got %d)", c.MaxConcurrentJobs)+ }++ if c.MaxCPU < 1 {+ return Capacity{}, fmt.Errorf("max-cpu must be >= 1 (got %d)", c.MaxCPU)+ }++ if c.MaxDiskGb < 1 {+ return Capacity{}, fmt.Errorf("max-disk-gb must be >= 1 (got %d)", c.MaxDiskGb)+ }++ if c.MaxRAMMb < minRAMMbPerJob {+ return Capacity{}, fmt.Errorf(+ "max-ram-mb must be >= %d (got %d)", minRAMMbPerJob, c.MaxRAMMb)+ }++ cpuPerJob := c.MaxCPU / c.MaxConcurrentJobs+ ramMbPerJob := c.MaxRAMMb / c.MaxConcurrentJobs++ if cpuPerJob < 1 {+ return Capacity{}, fmt.Errorf(+ "max-cpu (%d) split across max-concurrent-jobs (%d) yields < 1 CPU per job; "++ "lower max-concurrent-jobs or raise max-cpu",+ c.MaxCPU, c.MaxConcurrentJobs)+ }++ if ramMbPerJob < minRAMMbPerJob {+ return Capacity{}, fmt.Errorf(+ "max-ram-mb (%d) split across max-concurrent-jobs (%d) yields %d MB per job, "++ "below the %d MB floor; lower max-concurrent-jobs or raise max-ram-mb",+ c.MaxRAMMb, c.MaxConcurrentJobs, ramMbPerJob, minRAMMbPerJob)+ }++ return Capacity{+ MaxCPU: c.MaxCPU,+ MaxRAMMb: c.MaxRAMMb,+ MaxDiskGb: c.MaxDiskGb,+ MaxConcurrentJobs: c.MaxConcurrentJobs,+ CPUPerJob: cpuPerJob,+ RAMMbPerJob: ramMbPerJob,+ }, nil+}++// ValidateTransport enforces the http/https gate before any goroutine starts.+// The per-agent token and the decrypted backup stream both cross this link, so+// plain HTTP is allowed only with explicit operator consent.+func (c *Config) ValidateTransport(isStdinTTY bool, in *bufio.Reader) error {+ parsed, err := url.Parse(c.DatabasusHost)+ if err != nil {+ return fmt.Errorf("databasus-host is not a valid URL: %w", err)+ }++ switch parsed.Scheme {+ case "https":+ return nil++ case "http":+ return c.consentToInsecureHTTP(isStdinTTY, in)++ default:+ return fmt.Errorf(+ "databasus-host must start with https:// or http:// (got scheme %q)", parsed.Scheme)+ }+}++func (c *Config) loadFromJSON() {+ data, err := os.ReadFile(configFileName)+ if err != nil {+ if os.IsNotExist(err) {+ log.Info("No databasus-verification.json found, will create on save")+ return+ }++ log.Warn("Failed to read databasus-verification.json", "error", err)++ return+ }++ if err := json.Unmarshal(data, c); err != nil {+ log.Warn("Failed to parse databasus-verification.json", "error", err)++ return+ }++ log.Info("Configuration loaded from " + configFileName)+}++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",+ }++ if c.DatabasusHost != "" {+ c.flags.sources["databasus-host"] = configFileName+ }++ if c.AgentID != "" {+ c.flags.sources["agent-id"] = configFileName+ }++ if c.Token != "" {+ c.flags.sources["token"] = configFileName+ }++ if c.MaxCPU != 0 {+ c.flags.sources["max-cpu"] = configFileName+ }++ if c.MaxRAMMb != 0 {+ c.flags.sources["max-ram-mb"] = configFileName+ }++ if c.MaxDiskGb != 0 {+ c.flags.sources["max-disk-gb"] = configFileName+ }++ if c.MaxConcurrentJobs != 0 {+ c.flags.sources["max-concurrent-jobs"] = configFileName+ }++ if c.AllowInsecureHTTP {+ c.flags.sources["allow-insecure-http"] = configFileName+ }+}++func (c *Config) applyFlags() {+ if c.flags.databasusHost != nil && *c.flags.databasusHost != "" {+ c.DatabasusHost = *c.flags.databasusHost+ c.flags.sources["databasus-host"] = "command line args"+ }++ if c.flags.agentID != nil && *c.flags.agentID != "" {+ c.AgentID = *c.flags.agentID+ c.flags.sources["agent-id"] = "command line args"+ }++ if c.flags.token != nil && *c.flags.token != "" {+ c.Token = *c.flags.token+ c.flags.sources["token"] = "command line args"+ }++ if c.flags.maxCPU != nil && *c.flags.maxCPU != 0 {+ c.MaxCPU = *c.flags.maxCPU+ c.flags.sources["max-cpu"] = "command line args"+ }++ if c.flags.maxRAMMb != nil && *c.flags.maxRAMMb != 0 {+ c.MaxRAMMb = *c.flags.maxRAMMb+ c.flags.sources["max-ram-mb"] = "command line args"+ }++ if c.flags.maxDiskGb != nil && *c.flags.maxDiskGb != 0 {+ c.MaxDiskGb = *c.flags.maxDiskGb+ c.flags.sources["max-disk-gb"] = "command line args"+ }++ if c.flags.maxConcurrentJobs != nil && *c.flags.maxConcurrentJobs != 0 {+ c.MaxConcurrentJobs = *c.flags.maxConcurrentJobs+ c.flags.sources["max-concurrent-jobs"] = "command line args"+ }++ // --allow-insecure-http is a presence flag: passing it (or a persisted+ // true) latches on; it is never turned back off from the CLI so a+ // restart under systemd does not re-prompt.+ if c.flags.allowInsecureHTTP != nil && *c.flags.allowInsecureHTTP {+ c.AllowInsecureHTTP = true+ c.flags.sources["allow-insecure-http"] = "command line args"+ }+}++func (c *Config) logConfigSources() {+ log.Info("databasus-host", "value", c.DatabasusHost, "source", c.flags.sources["databasus-host"])+ log.Info("agent-id", "value", c.AgentID, "source", c.flags.sources["agent-id"])+ log.Info("token", "value", maskSensitive(c.Token), "source", c.flags.sources["token"])+ log.Info("max-cpu", "value", c.MaxCPU, "source", c.flags.sources["max-cpu"])+ log.Info("max-ram-mb", "value", c.MaxRAMMb, "source", c.flags.sources["max-ram-mb"])+ log.Info("max-disk-gb", "value", c.MaxDiskGb, "source", c.flags.sources["max-disk-gb"])+ log.Info(+ "max-concurrent-jobs",+ "value",+ c.MaxConcurrentJobs,+ "source",+ c.flags.sources["max-concurrent-jobs"],+ )+ log.Info(+ "allow-insecure-http",+ "value",+ fmt.Sprintf("%v", c.AllowInsecureHTTP),+ "source",+ c.flags.sources["allow-insecure-http"],+ )+}++func (c *Config) consentToInsecureHTTP(isStdinTTY bool, in *bufio.Reader) error {+ if c.AllowInsecureHTTP {+ log.Warn("databasus-host is plain HTTP; transport is unencrypted")++ return nil+ }++ if !isStdinTTY {+ return fmt.Errorf(+ "refusing to use plain HTTP over a non-interactive connection: " ++ "switch --databasus-host to https:// or pass --allow-insecure-http " ++ "to accept unencrypted transport")+ }++ fmt.Fprint(os.Stderr,+ "WARNING: connecting to the primary over plain HTTP, not HTTPS. "++ "The agent token and decrypted backup data are sent unencrypted. "++ "Continue? [y/N] ")++ answer, _ := in.ReadString('\n')+ answer = strings.ToLower(strings.TrimSpace(answer))++ if answer != "y" && answer != "yes" {+ return fmt.Errorf("aborted: plain HTTP transport declined by operator")+ }++ return nil+}++func maskSensitive(value string) string {+ if value == "" {+ return "(not set)"+ }++ visibleLen := max(len(value)/4, 1)++ return value[:visibleLen] + "***"+}diff --git a/agent/verification/internal/config/config_test.go b/agent/verification/internal/config/config_test.gonew file mode 100644index 00000000..39509280--- /dev/null+++ b/agent/verification/internal/config/config_test.go@@ -0,0 +1,175 @@+package config++import (+ "bufio"+ "strings"+ "testing"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++func emptyReader() *bufio.Reader {+ return bufio.NewReader(strings.NewReader(""))+}++func Test_Validate_WhenConfigComplete_ReturnsCapacity(t *testing.T) {+ cfg := &Config{+ DatabasusHost: "https://primary.example:4005",+ AgentID: "agent-1",+ Token: "secret",+ MaxCPU: 8,+ MaxRAMMb: 4096,+ MaxDiskGb: 100,+ MaxConcurrentJobs: 4,+ }++ capacity, err := cfg.Validate()++ require.NoError(t, err)+ assert.Equal(t, 2, capacity.CPUPerJob)+ assert.Equal(t, 1024, capacity.RAMMbPerJob)+}++func Test_Validate_WhenRequiredStringMissing_ReturnsError(t *testing.T) {+ for name, cfg := range map[string]*Config{+ "no databasus-host": {AgentID: "a", Token: "t", MaxCPU: 4, MaxRAMMb: 2048, MaxDiskGb: 10, MaxConcurrentJobs: 1},+ "no agent-id": {DatabasusHost: "https://x:4005", Token: "t", MaxCPU: 4, MaxRAMMb: 2048, MaxDiskGb: 10, MaxConcurrentJobs: 1},+ "no token": {DatabasusHost: "https://x:4005", AgentID: "a", MaxCPU: 4, MaxRAMMb: 2048, MaxDiskGb: 10, MaxConcurrentJobs: 1},+ } {+ t.Run(name, func(t *testing.T) {+ _, err := cfg.Validate()+ require.Error(t, err)+ })+ }+}++func Test_Validate_WhenStringsSetButCapacityInvalid_ReturnsCapacityError(t *testing.T) {+ cfg := &Config{+ DatabasusHost: "https://primary.example:4005",+ AgentID: "agent-1",+ Token: "secret",+ MaxCPU: 2,+ MaxRAMMb: 4096,+ MaxDiskGb: 100,+ MaxConcurrentJobs: 4,+ }++ _, err := cfg.Validate()++ require.Error(t, err)+ assert.Contains(t, err.Error(), "CPU per job")+}++func Test_DeriveCapacity_WhenConfigValid_DerivesPerJobSplit(t *testing.T) {+ cfg := &Config{MaxCPU: 8, MaxRAMMb: 4096, MaxDiskGb: 100, MaxConcurrentJobs: 4}++ capacity, err := cfg.DeriveCapacity()++ require.NoError(t, err)+ assert.Equal(t, 2, capacity.CPUPerJob)+ assert.Equal(t, 1024, capacity.RAMMbPerJob)+ assert.Equal(t, 8, capacity.MaxCPU)+ assert.Equal(t, 4096, capacity.MaxRAMMb)+ assert.Equal(t, 100, capacity.MaxDiskGb)+ assert.Equal(t, 4, capacity.MaxConcurrentJobs)+}++func Test_DeriveCapacity_WhenConcurrentJobsExceedCPU_ReturnsError(t *testing.T) {+ cfg := &Config{MaxCPU: 2, MaxRAMMb: 4096, MaxDiskGb: 100, MaxConcurrentJobs: 4}++ _, err := cfg.DeriveCapacity()++ require.Error(t, err)+ assert.Contains(t, err.Error(), "CPU per job")+}++func Test_DeriveCapacity_WhenRAMBelowFloor_ReturnsError(t *testing.T) {+ cfg := &Config{MaxCPU: 4, MaxRAMMb: 256, MaxDiskGb: 100, MaxConcurrentJobs: 1}++ _, err := cfg.DeriveCapacity()++ require.Error(t, err)+ assert.Contains(t, err.Error(), "max-ram-mb")+}++func Test_DeriveCapacity_WhenRAMPerJobBelowFloor_ReturnsError(t *testing.T) {+ cfg := &Config{MaxCPU: 8, MaxRAMMb: 1024, MaxDiskGb: 100, MaxConcurrentJobs: 8}++ _, err := cfg.DeriveCapacity()++ require.Error(t, err)+ assert.Contains(t, err.Error(), "per job")+}++func Test_DeriveCapacity_WhenZeroFields_ReturnsError(t *testing.T) {+ for name, cfg := range map[string]*Config{+ "no concurrent jobs": {MaxCPU: 4, MaxRAMMb: 2048, MaxDiskGb: 10, MaxConcurrentJobs: 0},+ "no cpu": {MaxCPU: 0, MaxRAMMb: 2048, MaxDiskGb: 10, MaxConcurrentJobs: 1},+ "no disk": {MaxCPU: 4, MaxRAMMb: 2048, MaxDiskGb: 0, MaxConcurrentJobs: 1},+ } {+ t.Run(name, func(t *testing.T) {+ _, err := cfg.DeriveCapacity()+ require.Error(t, err)+ })+ }+}++func Test_ValidateTransport_WhenHTTPS_PassesWithoutPrompt(t *testing.T) {+ cfg := &Config{DatabasusHost: "https://primary.example:4005"}++ err := cfg.ValidateTransport(false, emptyReader())++ require.NoError(t, err)+}++func Test_ValidateTransport_WhenHTTPNonTTYWithoutFlag_FailsNamingBothFixes(t *testing.T) {+ cfg := &Config{DatabasusHost: "http://primary.example:4005"}++ err := cfg.ValidateTransport(false, emptyReader())++ require.Error(t, err)+ assert.Contains(t, err.Error(), "https://")+ assert.Contains(t, err.Error(), "--allow-insecure-http")+}++func Test_ValidateTransport_WhenHTTPWithAllowFlag_PassesWithWarn(t *testing.T) {+ cfg := &Config{DatabasusHost: "http://primary.example:4005", AllowInsecureHTTP: true}++ err := cfg.ValidateTransport(false, emptyReader())++ require.NoError(t, err)+}++func Test_ValidateTransport_WhenHTTPTTYAndOperatorConsents_Passes(t *testing.T) {+ cfg := &Config{DatabasusHost: "http://primary.example:4005"}++ err := cfg.ValidateTransport(true, bufio.NewReader(strings.NewReader("y\n")))++ require.NoError(t, err)+}++func Test_ValidateTransport_WhenHTTPTTYAndOperatorDeclines_ReturnsError(t *testing.T) {+ cfg := &Config{DatabasusHost: "http://primary.example:4005"}++ err := cfg.ValidateTransport(true, bufio.NewReader(strings.NewReader("n\n")))++ require.Error(t, err)+}++func Test_ValidateTransport_WhenSchemeUnsupported_ReturnsError(t *testing.T) {+ cfg := &Config{DatabasusHost: "ftp://primary.example:4005"}++ err := cfg.ValidateTransport(true, emptyReader())++ require.Error(t, err)+ assert.Contains(t, err.Error(), "https://")+}++func Test_MaskSensitive_WhenEmpty_ReturnsNotSet(t *testing.T) {+ assert.Equal(t, "(not set)", maskSensitive(""))+}++func Test_MaskSensitive_WhenValue_RevealsQuarterThenMasks(t *testing.T) {+ assert.Equal(t, "ab***", maskSensitive("abcdefgh"))+}diff --git a/agent/verification/internal/config/dto.go b/agent/verification/internal/config/dto.gonew file mode 100644index 00000000..dab50b28--- /dev/null+++ b/agent/verification/internal/config/dto.go@@ -0,0 +1,14 @@+package config++type parsedFlags struct {+ databasusHost *string+ agentID *string+ token *string+ maxCPU *int+ maxRAMMb *int+ maxDiskGb *int+ maxConcurrentJobs *int+ allowInsecureHTTP *bool++ sources map[string]string+}diff --git a/agent/verification/internal/features/api/api.go b/agent/verification/internal/features/api/api.gonew file mode 100644index 00000000..fe889efb--- /dev/null+++ b/agent/verification/internal/features/api/api.go@@ -0,0 +1,298 @@+package api++import (+ "context"+ "encoding/json"+ "fmt"+ "io"+ "log/slog"+ "net/http"+ "net/url"+ "os"+ "time"++ "github.com/go-resty/resty/v2"+ "github.com/google/uuid"+)++// reportRetryDelay returns the exponential backoff for report attempt n+// (1-based): 1s,2s,4s,8s,16s,32s, capped at maxBackoff. The exponent is+// clamped before the shift so a large attempt count cannot overflow.+func reportRetryDelay(attempt int) time.Duration {+ return expBackoff(attempt - 1)+}++func expBackoff(shift int) time.Duration {+ const maxShift = 5 // 2^5 s = 32s = maxBackoff++ if shift < 0 {+ shift = 0+ }++ if shift >= maxShift {+ return maxBackoff+ }++ d := time.Duration(1<<shift) * time.Second+ if d > maxBackoff {+ return maxBackoff+ }++ return d+}++type Client struct {+ json *resty.Client+ noRetry *resty.Client+ streamHTTP *http.Client+ host string+ token string+ agentID string+ log *slog.Logger+}++func NewClient(host, token, agentID string, log *slog.Logger) *Client {+ setAuth := func(_ *resty.Client, req *resty.Request) error {+ if h := bearerHeader(token); h != "" {+ req.SetHeader("Authorization", h)+ }++ return nil+ }++ jsonClient := resty.New().+ SetTimeout(apiCallTimeout).+ SetRetryCount(maxRetryAttempts - 1).+ SetRetryWaitTime(retryBaseDelay).+ SetRetryMaxWaitTime(4 * retryBaseDelay).+ AddRetryCondition(func(resp *resty.Response, err error) bool {+ return err != nil || resp.StatusCode() >= 500+ }).+ OnBeforeRequest(setAuth)++ // Claim and report own their retry policy explicitly (claim: loop retries+ // forever; report: bounded retry-with-deadline). A retrying client here+ // would make "exactly N retries / give up at the budget" untestable.+ noRetryClient := resty.New().+ SetTimeout(apiCallTimeout).+ OnBeforeRequest(setAuth)++ return &Client{+ json: jsonClient,+ noRetry: noRetryClient,+ streamHTTP: &http.Client{},+ host: host,+ token: token,+ agentID: agentID,+ log: log,+ }+}++func (c *Client) FetchServerVersion(ctx context.Context) (string, error) {+ var ver versionResponse++ httpResp, err := c.json.R().+ SetContext(ctx).+ SetResult(&ver).+ Get(c.buildURL(versionPath))+ if err != nil {+ return "", err+ }++ if err := c.checkResponse(httpResp, "fetch server version"); err != nil {+ return "", err+ }++ return ver.Version, nil+}++func (c *Client) DownloadVerificationAgentBinary(ctx context.Context, arch, destPath string) error {+ requestURL := c.buildURL(verificationAgentBinaryPath) + "?" + url.Values{"arch": {arch}}.Encode()++ req, err := http.NewRequestWithContext(ctx, http.MethodGet, requestURL, nil)+ if err != nil {+ return fmt.Errorf("create agent download request: %w", err)+ }++ c.setStreamHeaders(req)++ resp, err := c.streamHTTP.Do(req)+ if err != nil {+ return err+ }+ defer func() { _ = resp.Body.Close() }()++ if resp.StatusCode != http.StatusOK {+ return fmt.Errorf("server returned %d for verification agent download", resp.StatusCode)+ }++ file, err := os.Create(destPath)+ if err != nil {+ return err+ }+ defer func() { _ = file.Close() }()++ _, err = io.Copy(file, resp.Body)++ return err+}++func (c *Client) Heartbeat(+ ctx context.Context,+ request HeartbeatRequest,+) (*HeartbeatResponse, error) {+ var response HeartbeatResponse++ httpResp, err := c.json.R().+ SetContext(ctx).+ SetBody(request).+ SetResult(&response).+ Post(c.buildURL(fmt.Sprintf(heartbeatPathFmt, c.agentID)))+ if err != nil {+ return nil, err+ }++ if err := c.checkResponse(httpResp, "heartbeat"); err != nil {+ return nil, err+ }++ return &response, nil+}++// ClaimVerification performs a single claim attempt. 200 returns the assignment;+// 204 returns (nil, nil) meaning nothing fits; any other status is an error.+// The runner loop owns retry/backoff — this never loops.+func (c *Client) ClaimVerification(+ ctx context.Context,+ capacity AgentCapacity,+) (*JobAssignment, error) {+ resp, err := c.noRetry.R().+ SetContext(ctx).+ SetBody(ClaimRequest{Capacity: capacity}).+ Post(c.buildURL(fmt.Sprintf(claimPathFmt, c.agentID)))+ if err != nil {+ return nil, err+ }++ if resp.StatusCode() == http.StatusNoContent {+ return nil, nil+ }++ if resp.StatusCode() != http.StatusOK {+ return nil, &ResponseError{Op: "claim", StatusCode: resp.StatusCode(), Body: resp.String()}+ }++ var assignment JobAssignment+ if err := json.Unmarshal(resp.Body(), &assignment); err != nil {+ return nil, fmt.Errorf("decode job assignment: %w", err)+ }++ return &assignment, nil+}++// DownloadBackup opens the plaintext backup stream. On 200 it returns the+// response body for the caller to stream into the container. A non-2xx status+// is returned as *ResponseError so the caller can tell 410 (drop, no report)+// from other 4xx (agent-setup failure) from 5xx (retryable). A transport error+// is returned as-is (retryable).+func (c *Client) DownloadBackup(+ ctx context.Context,+ verificationID uuid.UUID,+) (io.ReadCloser, error) {+ requestURL := c.buildURL(fmt.Sprintf(backupStreamPathFmt, c.agentID, verificationID))++ req, err := http.NewRequestWithContext(ctx, http.MethodGet, requestURL, nil)+ if err != nil {+ return nil, fmt.Errorf("create backup stream request: %w", err)+ }++ c.setStreamHeaders(req)++ resp, err := c.streamHTTP.Do(req)+ if err != nil {+ return nil, err+ }++ if resp.StatusCode != http.StatusOK {+ body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))+ _ = resp.Body.Close()++ return nil, &ResponseError{+ Op: "backup stream",+ StatusCode: resp.StatusCode,+ Body: string(body),+ }+ }++ return resp.Body, nil+}++// Report submits the terminal result with bounded retry-with-deadline. Transport+// errors and 5xx are retried with exponential backoff under reportRetryBudget; a+// 410 returns ErrReportGone immediately (zero retries); any other 4xx is a+// non-retryable error; budget exhaustion returns ErrReportBudgetExhausted so the+// run is reclaimed by the backend on the agent's next heartbeat.+func (c *Client) Report(+ ctx context.Context,+ verificationID uuid.UUID,+ req ReportRequest,+) error {+ ctx, cancel := context.WithTimeoutCause(ctx, reportRetryBudget, ErrReportBudgetExhausted)+ defer cancel()++ requestURL := c.buildURL(fmt.Sprintf(reportPathFmt, c.agentID, verificationID))++ for attempt := 1; ; attempt++ {+ resp, err := c.noRetry.R().+ SetContext(ctx).+ SetBody(req).+ Post(requestURL)++ if err == nil {+ switch {+ case resp.StatusCode() == http.StatusNoContent:+ return nil+ case resp.StatusCode() == http.StatusGone:+ return ErrReportGone+ case resp.StatusCode() < 500:+ return &ResponseError{+ Op: "report",+ StatusCode: resp.StatusCode(),+ Body: resp.String(),+ }+ }+ }++ select {+ case <-ctx.Done():+ return context.Cause(ctx)+ case <-timeAfterFn(reportRetryDelay(attempt)):+ }+ }+}++func (c *Client) buildURL(path string) string {+ return c.host + path+}++func (c *Client) checkResponse(resp *resty.Response, method string) error {+ if resp.StatusCode() >= 400 {+ return fmt.Errorf("%s: server returned status %d: %s", method, resp.StatusCode(), resp.String())+ }++ return nil+}++func (c *Client) setStreamHeaders(req *http.Request) {+ if h := bearerHeader(c.token); h != "" {+ req.Header.Set("Authorization", h)+ }+}++func bearerHeader(token string) string {+ if token == "" {+ return ""+ }++ return "Bearer " + token+}diff --git a/agent/verification/internal/features/api/api_test.go b/agent/verification/internal/features/api/api_test.gonew file mode 100644index 00000000..af8cbd5c--- /dev/null+++ b/agent/verification/internal/features/api/api_test.go@@ -0,0 +1,368 @@+package api++import (+ "encoding/json"+ "errors"+ "io"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "sync/atomic"+ "testing"+ "time"++ "github.com/google/uuid"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ "databasus-verification-agent/internal/testutil"+)++func instantAfter(t *testing.T) {+ t.Helper()++ original := timeAfterFn+ timeAfterFn = func(time.Duration) <-chan time.Time {+ ch := make(chan time.Time, 1)+ ch <- time.Now()++ return ch+ }++ t.Cleanup(func() { timeAfterFn = original })+}++func Test_ClaimVerification_WhenServer200_SendsNestedMaxRamMbAndDeserializes(t *testing.T) {+ var capturedPath, capturedAuth string+ var capturedBody map[string]any++ verificationID := uuid.New()+ backupID := uuid.New()++ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ capturedPath = r.URL.Path+ capturedAuth = r.Header.Get("Authorization")+ require.NoError(t, json.NewDecoder(r.Body).Decode(&capturedBody))++ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(map[string]any{+ "verificationId": verificationID.String(),+ "backupId": backupID.String(),+ "backupSizeMb": 120.5,+ "maxContainerDiskMb": 800.25,+ "database": map[string]any{+ "type": "POSTGRES",+ "postgresql": map[string]any{"version": "16"},+ },+ })+ }))+ t.Cleanup(server.Close)++ client := NewClient(server.URL, "tok123", "agent-9", testutil.DiscardLogger())++ assignment, err := client.ClaimVerification(t.Context(), AgentCapacity{+ MaxCPU: 8, MaxRAMMb: 4096, MaxDiskGb: 100, MaxConcurrentJobs: 4,+ })++ require.NoError(t, err)+ require.NotNil(t, assignment)++ assert.Equal(t, "/api/v1/agent/verifications/agent-9/claim", capturedPath)+ assert.Equal(t, "Bearer tok123", capturedAuth)++ capacity, ok := capturedBody["capacity"].(map[string]any)+ require.True(t, ok, "claim body must nest capacity under \"capacity\"")+ assert.Equal(t, float64(4096), capacity["maxRamMb"])+ _, hasRamGb := capacity["maxRamGb"]+ assert.False(t, hasRamGb, "claim envelope must use maxRamMb, never maxRamGb")++ assert.Equal(t, verificationID, assignment.VerificationID)+ assert.Equal(t, backupID, assignment.BackupID)+ assert.InDelta(t, 120.5, assignment.BackupSizeMb, 0.001)+ assert.InDelta(t, 800.25, assignment.MaxContainerDiskMb, 0.001)+ assert.Equal(t, "POSTGRES", assignment.Database.Type)+ require.NotNil(t, assignment.Database.Postgresql)+ assert.Equal(t, "16", assignment.Database.Postgresql.Version)+}++func Test_ClaimVerification_WhenServer204_ReturnsNilNoError(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusNoContent)+ }))+ t.Cleanup(server.Close)++ client := NewClient(server.URL, "t", "a", testutil.DiscardLogger())++ assignment, err := client.ClaimVerification(t.Context(), AgentCapacity{})++ require.NoError(t, err)+ assert.Nil(t, assignment)+}++func Test_ClaimVerification_WhenServer500_ReturnsRetryableResponseError(t *testing.T) {+ var calls atomic.Int32++ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ calls.Add(1)+ w.WriteHeader(http.StatusInternalServerError)+ }))+ t.Cleanup(server.Close)++ client := NewClient(server.URL, "t", "a", testutil.DiscardLogger())++ _, err := client.ClaimVerification(t.Context(), AgentCapacity{})++ require.Error(t, err)+ assert.Equal(t, int32(1), calls.Load(), "claim must not retry internally — the loop owns retry")++ var respErr *ResponseError+ require.True(t, errors.As(err, &respErr))+ assert.True(t, respErr.Retryable())+}++func Test_DownloadBackup_WhenServer200_ReturnsBody(t *testing.T) {+ payload := []byte("PGDMP fake custom-format archive")++ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ assert.Equal(t,+ "/api/v1/agent/verifications/agent-x/"++ "22222222-2222-2222-2222-222222222222/backup-stream",+ r.URL.Path)+ _, _ = w.Write(payload)+ }))+ t.Cleanup(server.Close)++ client := NewClient(server.URL, "", "agent-x", testutil.DiscardLogger())++ body, err := client.DownloadBackup(+ t.Context(), uuid.MustParse("22222222-2222-2222-2222-222222222222"))+ require.NoError(t, err)+ t.Cleanup(func() { _ = body.Close() })++ read, err := io.ReadAll(body)+ require.NoError(t, err)+ assert.Equal(t, payload, read)+}++func Test_DownloadBackup_WhenServer410_ReturnsGoneResponseError(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusGone)+ _, _ = w.Write([]byte(`{"reason":"gone"}`))+ }))+ t.Cleanup(server.Close)++ client := NewClient(server.URL, "", "a", testutil.DiscardLogger())++ _, err := client.DownloadBackup(t.Context(), uuid.New())++ require.Error(t, err)+ var respErr *ResponseError+ require.True(t, errors.As(err, &respErr))+ assert.True(t, respErr.IsGone())+ assert.False(t, respErr.Retryable())+}++func Test_Report_WhenServer204_Succeeds(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ assert.Equal(t, "/api/v1/agent/verifications/a/33333333-3333-3333-3333-333333333333/report",+ r.URL.Path)+ w.WriteHeader(http.StatusNoContent)+ }))+ t.Cleanup(server.Close)++ client := NewClient(server.URL, "", "a", testutil.DiscardLogger())++ err := client.Report(t.Context(),+ uuid.MustParse("33333333-3333-3333-3333-333333333333"),+ ReportRequest{Status: VerificationStatusCompleted})++ require.NoError(t, err)+}++func Test_Report_WhenServer410_ReturnsErrReportGoneWithoutRetry(t *testing.T) {+ var calls atomic.Int32++ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ calls.Add(1)+ w.WriteHeader(http.StatusGone)+ }))+ t.Cleanup(server.Close)++ client := NewClient(server.URL, "", "a", testutil.DiscardLogger())++ err := client.Report(t.Context(), uuid.New(), ReportRequest{Status: VerificationStatusFailed})++ require.ErrorIs(t, err, ErrReportGone)+ assert.Equal(t, int32(1), calls.Load(), "410 must not be retried")+}++func Test_Report_When5xxThenRecovers_RetriesThenSucceeds(t *testing.T) {+ instantAfter(t)++ var calls atomic.Int32++ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ if calls.Add(1) < 3 {+ w.WriteHeader(http.StatusServiceUnavailable)+ return+ }++ w.WriteHeader(http.StatusNoContent)+ }))+ t.Cleanup(server.Close)++ client := NewClient(server.URL, "", "a", testutil.DiscardLogger())++ err := client.Report(t.Context(), uuid.New(), ReportRequest{Status: VerificationStatusCompleted})++ require.NoError(t, err)+ assert.Equal(t, int32(3), calls.Load())+}++func Test_Report_When5xxAndBudgetExhausted_ReturnsBudgetError(t *testing.T) {+ originalBudget := reportRetryBudget+ reportRetryBudget = 25 * time.Millisecond+ t.Cleanup(func() { reportRetryBudget = originalBudget })++ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusBadGateway)+ }))+ t.Cleanup(server.Close)++ client := NewClient(server.URL, "", "a", testutil.DiscardLogger())++ err := client.Report(t.Context(), uuid.New(), ReportRequest{Status: VerificationStatusFailed})++ require.ErrorIs(t, err, ErrReportBudgetExhausted)+}++func Test_Constants_SatisfyInvariants(t *testing.T) {+ // reportRetryBudget must stay a short, bounded window: once it is exhausted+ // the backend reclaims the run on the agent's next heartbeat, so retrying+ // for minutes would be pointless. 5m is a generous sanity ceiling.+ assert.Less(t, reportRetryBudget, 5*time.Minute)++ assert.Equal(t, maxBackoff, reportRetryDelay(99), "report backoff must cap at maxBackoff")+ assert.Equal(t, 1*time.Second, reportRetryDelay(1))+ assert.Equal(t, 2*time.Second, reportRetryDelay(2))+}++func Test_Heartbeat_WhenCalled_SendsFlatEnvelopeWithBearerAndAgentPath(t *testing.T) {+ var capturedPath, capturedMethod, capturedAuth string+ var capturedBody map[string]any++ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ capturedPath = r.URL.Path+ capturedMethod = r.Method+ capturedAuth = r.Header.Get("Authorization")++ require.NoError(t, json.NewDecoder(r.Body).Decode(&capturedBody))++ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(map[string]any{+ "lastSeenAt": time.Now().UTC().Format(time.RFC3339),+ "abortVerificationIds": []string{},+ })+ }))+ t.Cleanup(server.Close)++ client := NewClient(server.URL, "tok123", "11111111-1111-1111-1111-111111111111", testutil.DiscardLogger())++ response, err := client.Heartbeat(t.Context(), HeartbeatRequest{+ MaxCPU: 8,+ MaxRAMGb: 4,+ MaxDiskGb: 100,+ MaxConcurrentJobs: 4,+ CurrentVerificationIDs: []uuid.UUID{},+ })++ require.NoError(t, err)+ require.NotNil(t, response)++ assert.Equal(t, http.MethodPost, capturedMethod)+ assert.Equal(t,+ "/api/v1/agent/verification/11111111-1111-1111-1111-111111111111/heartbeat",+ capturedPath)+ assert.Equal(t, "Bearer tok123", capturedAuth)++ assert.Equal(t, float64(8), capturedBody["maxCpu"])+ assert.Equal(t, float64(4), capturedBody["maxRamGb"])+ assert.Equal(t, float64(100), capturedBody["maxDiskGb"])+ assert.Equal(t, float64(4), capturedBody["maxConcurrentJobs"])++ _, hasRamMb := capturedBody["maxRamMb"]+ assert.False(t, hasRamMb, "heartbeat envelope must use maxRamGb, never maxRamMb")++ require.Contains(t, capturedBody, "currentVerificationIds")+ assert.Equal(t, []any{}, capturedBody["currentVerificationIds"],+ "currentVerificationIds must serialize as [] not null")+}++func Test_Heartbeat_WhenServerReturns4xx_ReturnsErrorWithoutRetry(t *testing.T) {+ var calls int++ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ calls+++ w.WriteHeader(http.StatusUnauthorized)+ _, _ = w.Write([]byte(`{"error":"invalid agent credentials"}`))+ }))+ t.Cleanup(server.Close)++ client := NewClient(server.URL, "bad", "agent-1", testutil.DiscardLogger())++ _, err := client.Heartbeat(t.Context(), HeartbeatRequest{CurrentVerificationIDs: []uuid.UUID{}})++ require.Error(t, err)+ assert.Equal(t, 1, calls, "4xx must not be retried")+}++func Test_FetchServerVersion_WhenServerResponds_ReturnsVersion(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ assert.Equal(t, "/api/v1/system/version", r.URL.Path)+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(map[string]string{"version": "v3.27.0"})+ }))+ t.Cleanup(server.Close)++ client := NewClient(server.URL, "", "", testutil.DiscardLogger())++ version, err := client.FetchServerVersion(t.Context())++ require.NoError(t, err)+ assert.Equal(t, "v3.27.0", version)+}++func Test_DownloadVerificationAgentBinary_WhenServerServesFile_WritesItToDisk(t *testing.T) {+ payload := []byte("\x7fELF fake verification agent")++ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ assert.Equal(t, "/api/v1/system/verification-agent", r.URL.Path)+ assert.Equal(t, "arm64", r.URL.Query().Get("arch"))+ _, _ = w.Write(payload)+ }))+ t.Cleanup(server.Close)++ client := NewClient(server.URL, "", "", testutil.DiscardLogger())+ destPath := filepath.Join(t.TempDir(), "agent")++ err := client.DownloadVerificationAgentBinary(t.Context(), "arm64", destPath)+ require.NoError(t, err)++ written, err := os.ReadFile(destPath)+ require.NoError(t, err)+ assert.Equal(t, payload, written)+}++func Test_DownloadVerificationAgentBinary_WhenServer404_ReturnsError(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusNotFound)+ }))+ t.Cleanup(server.Close)++ client := NewClient(server.URL, "", "", testutil.DiscardLogger())++ err := client.DownloadVerificationAgentBinary(t.Context(), "amd64", filepath.Join(t.TempDir(), "a"))++ require.Error(t, err)+}diff --git a/agent/verification/internal/features/api/constants.go b/agent/verification/internal/features/api/constants.gonew file mode 100644index 00000000..3798d721--- /dev/null+++ b/agent/verification/internal/features/api/constants.go@@ -0,0 +1,28 @@+package api++import "time"++const (+ versionPath = "/api/v1/system/version"+ verificationAgentBinaryPath = "/api/v1/system/verification-agent"+ heartbeatPathFmt = "/api/v1/agent/verification/%s/heartbeat"++ claimPathFmt = "/api/v1/agent/verifications/%s/claim"+ backupStreamPathFmt = "/api/v1/agent/verifications/%s/%s/backup-stream"+ reportPathFmt = "/api/v1/agent/verifications/%s/%s/report"++ apiCallTimeout = 30 * time.Second+ maxRetryAttempts = 3+ retryBaseDelay = 1 * time.Second++ maxBackoff = 32 * time.Second+)++// timeAfterFn is time.After in production; tests swap it to avoid real sleeps in+// the report retry loop. reportRetryBudget is the report retry deadline (60s in+// production); tests shrink it to exercise budget exhaustion without a 60s+// wall-clock wait.+var (+ timeAfterFn = time.After+ reportRetryBudget = 60 * time.Second+)diff --git a/agent/verification/internal/features/api/dto.go b/agent/verification/internal/features/api/dto.gonew file mode 100644index 00000000..2fd85c17--- /dev/null+++ b/agent/verification/internal/features/api/dto.go@@ -0,0 +1,87 @@+package api++import (+ "fmt"+ "net/http"+ "time"++ "github.com/google/uuid"+)++type HeartbeatRequest struct {+ MaxCPU int `json:"maxCpu"`+ MaxRAMGb int `json:"maxRamGb"`+ MaxDiskGb int `json:"maxDiskGb"`+ MaxConcurrentJobs int `json:"maxConcurrentJobs"`+ CurrentVerificationIDs []uuid.UUID `json:"currentVerificationIds"`+}++type HeartbeatResponse struct {+ LastSeenAt time.Time `json:"lastSeenAt"`+ AbortVerificationIDs []uuid.UUID `json:"abortVerificationIds"`+}++type versionResponse struct {+ Version string `json:"version"`+}++type AgentCapacity struct {+ MaxCPU int `json:"maxCpu"`+ MaxRAMMb int `json:"maxRamMb"`+ MaxDiskGb int `json:"maxDiskGb"`+ MaxConcurrentJobs int `json:"maxConcurrentJobs"`+}++type ClaimRequest struct {+ Capacity AgentCapacity `json:"capacity"`+}++type AssignedPostgresql struct {+ Version string `json:"version"`+}++type AssignedDatabase struct {+ Type string `json:"type"`+ Postgresql *AssignedPostgresql `json:"postgresql"`+}++type JobAssignment struct {+ VerificationID uuid.UUID `json:"verificationId"`+ BackupID uuid.UUID `json:"backupId"`+ BackupSizeMb float64 `json:"backupSizeMb"`+ MaxContainerDiskMb float64 `json:"maxContainerDiskMb"`+ Database AssignedDatabase `json:"database"`+}++type ReportTableStat struct {+ SchemaName string `json:"schemaName"`+ Name string `json:"name"`+ RowCount int64 `json:"rowCount"`+}++type ReportRequest struct {+ Status VerificationStatus `json:"status"`+ PgRestoreExitCode *int `json:"pgRestoreExitCode"`+ FailureKind *FailureType `json:"failureKind"`+ RestoreDurationMs *int64 `json:"restoreDurationMs"`+ VerifyDurationMs *int64 `json:"verifyDurationMs"`+ DBSizeBytesAfterRestore *int64 `json:"dbSizeBytesAfterRestore"`+ TableCount *int `json:"tableCount"`+ SchemaCount *int `json:"schemaCount"`+ TableStats []ReportTableStat `json:"tableStats"`+ FailMessage *string `json:"failMessage"`+}++type ResponseError struct {+ Op string+ StatusCode int+ Body string+}++func (e *ResponseError) Error() string {+ return fmt.Sprintf("%s: server returned status %d: %s", e.Op, e.StatusCode, e.Body)+}++func (e *ResponseError) Retryable() bool { return e.StatusCode >= 500 }++func (e *ResponseError) IsGone() bool { return e.StatusCode == http.StatusGone }diff --git a/agent/verification/internal/features/api/enums.go b/agent/verification/internal/features/api/enums.gonew file mode 100644index 00000000..fe31ed64--- /dev/null+++ b/agent/verification/internal/features/api/enums.go@@ -0,0 +1,15 @@+package api++type VerificationStatus string++const (+ VerificationStatusCompleted VerificationStatus = "COMPLETED"+ VerificationStatusFailed VerificationStatus = "FAILED"+)++type FailureType string++// FailureKindDiskLimitExceeded tells the backend the restore exceeded its+// server-computed per-job disk budget — a terminal verdict, distinct from the+// retryable nil-exit-code path.+const FailureKindDiskLimitExceeded FailureType = "DISK_LIMIT_EXCEEDED"diff --git a/agent/verification/internal/features/api/errors.go b/agent/verification/internal/features/api/errors.gonew file mode 100644index 00000000..9c3f4b85--- /dev/null+++ b/agent/verification/internal/features/api/errors.go@@ -0,0 +1,12 @@+package api++import "errors"++// ErrReportGone signals the report route returned 410 — the row is no longer+// this agent's. The caller logs at info and drops; it is never retried.+var ErrReportGone = errors.New("verification no longer owned by this agent")++// ErrReportBudgetExhausted is the cause attached when report retries exceed+// reportRetryBudget; the run is then reclaimed by the backend on the agent's+// next heartbeat.+var ErrReportBudgetExhausted = errors.New("report retry budget exhausted")diff --git a/agent/verification/internal/features/api/idle_timeout_reader.go b/agent/verification/internal/features/api/idle_timeout_reader.gonew file mode 100644index 00000000..5f4c9143--- /dev/null+++ b/agent/verification/internal/features/api/idle_timeout_reader.go@@ -0,0 +1,60 @@+package api++import (+ "context"+ "fmt"+ "io"+ "time"+)++// IdleTimeoutReader wraps an io.Reader and cancels the associated context+// if no bytes are successfully read within the specified timeout duration.+// This detects stalled uploads where the network or source stops transmitting data.+//+// When the idle timeout fires, the reader is also closed (if it implements io.Closer)+// to unblock any goroutine blocked on the underlying Read.+type IdleTimeoutReader struct {+ reader io.Reader+ timeout time.Duration+ cancel context.CancelCauseFunc+ timer *time.Timer+}++// NewIdleTimeoutReader creates a reader that cancels the context via cancel+// if Read does not return any bytes for the given timeout duration.+func NewIdleTimeoutReader(reader io.Reader, timeout time.Duration, cancel context.CancelCauseFunc) *IdleTimeoutReader {+ r := &IdleTimeoutReader{+ reader: reader,+ timeout: timeout,+ cancel: cancel,+ }++ r.timer = time.AfterFunc(timeout, func() {+ cancel(fmt.Errorf("upload idle timeout: no bytes transmitted for %v", timeout))++ if closer, ok := reader.(io.Closer); ok {+ _ = closer.Close()+ }+ })++ return r+}++func (r *IdleTimeoutReader) Read(p []byte) (int, error) {+ n, err := r.reader.Read(p)++ if n > 0 {+ r.timer.Reset(r.timeout)+ }++ if err != nil && err != io.EOF {+ r.Stop()+ }++ return n, err+}++// Stop cancels the idle timer. Must be called when the reader is no longer needed.+func (r *IdleTimeoutReader) Stop() {+ r.timer.Stop()+}diff --git a/agent/verification/internal/features/api/idle_timeout_reader_test.go b/agent/verification/internal/features/api/idle_timeout_reader_test.gonew file mode 100644index 00000000..17d52ffc--- /dev/null+++ b/agent/verification/internal/features/api/idle_timeout_reader_test.go@@ -0,0 +1,112 @@+package api++import (+ "context"+ "fmt"+ "io"+ "testing"+ "time"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++func Test_ReadThroughIdleTimeoutReader_WhenBytesFlowContinuously_DoesNotCancelContext(t *testing.T) {+ ctx, cancel := context.WithCancelCause(t.Context())+ defer cancel(nil)++ pr, pw := io.Pipe()++ idleReader := NewIdleTimeoutReader(pr, 200*time.Millisecond, cancel)+ defer idleReader.Stop()++ go func() {+ for range 5 {+ _, _ = pw.Write([]byte("data"))+ time.Sleep(50 * time.Millisecond)+ }++ _ = pw.Close()+ }()++ data, err := io.ReadAll(idleReader)++ require.NoError(t, err)+ assert.Equal(t, "datadatadatadatadata", string(data))+ assert.NoError(t, ctx.Err(), "context should not be cancelled when bytes flow continuously")+}++func Test_ReadThroughIdleTimeoutReader_WhenNoBytesTransmitted_CancelsContext(t *testing.T) {+ ctx, cancel := context.WithCancelCause(t.Context())+ defer cancel(nil)++ pr, _ := io.Pipe()++ idleReader := NewIdleTimeoutReader(pr, 100*time.Millisecond, cancel)+ defer idleReader.Stop()++ time.Sleep(200 * time.Millisecond)++ assert.Error(t, ctx.Err(), "context should be cancelled when no bytes are transmitted")+ assert.Contains(t, context.Cause(ctx).Error(), "upload idle timeout")+}++func Test_ReadThroughIdleTimeoutReader_WhenBytesStopMidStream_CancelsContext(t *testing.T) {+ ctx, cancel := context.WithCancelCause(t.Context())+ defer cancel(nil)++ pr, pw := io.Pipe()++ idleReader := NewIdleTimeoutReader(pr, 100*time.Millisecond, cancel)+ defer idleReader.Stop()++ go func() {+ _, _ = pw.Write([]byte("initial"))+ // Stop writing — simulate stalled source+ }()++ buf := make([]byte, 1024)+ n, _ := idleReader.Read(buf)+ assert.Equal(t, "initial", string(buf[:n]))++ time.Sleep(200 * time.Millisecond)++ assert.Error(t, ctx.Err(), "context should be cancelled when bytes stop mid-stream")+ assert.Contains(t, context.Cause(ctx).Error(), "upload idle timeout")+}++func Test_StopIdleTimeoutReader_WhenCalledBeforeTimeout_DoesNotCancelContext(t *testing.T) {+ ctx, cancel := context.WithCancelCause(t.Context())+ defer cancel(nil)++ pr, _ := io.Pipe()++ idleReader := NewIdleTimeoutReader(pr, 100*time.Millisecond, cancel)+ idleReader.Stop()++ time.Sleep(200 * time.Millisecond)++ assert.NoError(t, ctx.Err(), "context should not be cancelled when reader is stopped before timeout")+}++func Test_ReadThroughIdleTimeoutReader_WhenReaderReturnsError_PropagatesError(t *testing.T) {+ ctx, cancel := context.WithCancelCause(t.Context())+ defer cancel(nil)++ pr, pw := io.Pipe()++ idleReader := NewIdleTimeoutReader(pr, 5*time.Second, cancel)+ defer idleReader.Stop()++ expectedErr := fmt.Errorf("test read error")+ _ = pw.CloseWithError(expectedErr)++ buf := make([]byte, 1024)+ _, err := idleReader.Read(buf)++ assert.ErrorIs(t, err, expectedErr)++ // Timer should be stopped after error — context should not be cancelled+ time.Sleep(100 * time.Millisecond)+ assert.NoError(t, ctx.Err(), "context should not be cancelled after reader error stops the timer")+}diff --git a/agent/verification/internal/features/container/container.go b/agent/verification/internal/features/container/container.gonew file mode 100644index 00000000..bcdf85c3--- /dev/null+++ b/agent/verification/internal/features/container/container.go@@ -0,0 +1,108 @@+package container++import (+ "context"+ "fmt"+ "io"+ "log/slog"+ "strconv"+ "strings"+ "time"++ "databasus-verification-agent/internal/features/dbconn"+ "databasus-verification-agent/internal/features/restore"+)++const (+ containerTerminateTimeout = 30 * time.Second++ restoreUser = "postgres"+ restoreDB = "postgres"+)++// PostgresContainer exposes two distinct Postgres conns. pg_restore runs+// INSIDE the container and reaches the DB on the container's own loopback+// (GetInContainerConn). The agent-process verifier runs OUTSIDE the container+// and reaches the DB via the random 127.0.0.1 host port the container's 5432+// was published to (GetVerifierConn) — populated by Manager.Spawn after the+// container starts.+type PostgresContainer struct {+ engine *dockerEngine+ id string+ networkID string+ hostPort int+ password string+ log *slog.Logger+}++func (c *PostgresContainer) Exec(+ ctx context.Context, cmd []string, stdin io.Reader, env []string,+) (restore.ExecResult, error) {+ return c.engine.Exec(ctx, c.id, cmd, stdin, env)+}++func (c *PostgresContainer) GetInContainerConn() dbconn.Conn {+ return dbconn.Conn{+ Host: "127.0.0.1", Port: pgInternalPort,+ User: restoreUser, Password: c.password, Database: restoreDB,+ }+}++func (c *PostgresContainer) GetVerifierConn() dbconn.Conn {+ return dbconn.Conn{+ Host: "127.0.0.1", Port: c.hostPort,+ User: restoreUser, Password: c.password, Database: restoreDB,+ }+}++// GetDiskUsageBytes sums the byte footprint of the dirs the restore writes+// into: PGDATA (an anonymous volume declared by the postgres image, NOT in+// SizeRw) plus /tmp (where the agent stages the dump). Daemon-reported SizeRw+// alone misses PGDATA entirely; an in-container `du -sb` does not.+func (c *PostgresContainer) GetDiskUsageBytes(ctx context.Context) (int64, error) {+ res, err := c.engine.Exec(ctx, c.id,+ []string{"du", "-sb", "/var/lib/postgresql/data", "/tmp"}, nil, nil)+ if err != nil {+ return 0, fmt.Errorf("exec du: %w", err)+ }++ if res.ExitCode != 0 {+ return 0, fmt.Errorf("du exited %d: %s", res.ExitCode, strings.TrimSpace(res.Stderr))+ }++ var total int64+ for line := range strings.SplitSeq(strings.TrimRight(res.Stdout, "\n"), "\n") {+ fields := strings.Fields(line)+ if len(fields) == 0 {+ continue+ }++ n, parseErr := strconv.ParseInt(fields[0], 10, 64)+ if parseErr != nil {+ return 0, fmt.Errorf("parse du line %q: %w", line, parseErr)+ }++ total += n+ }++ return total, nil+}++// Terminate removes the container and its network. The caller's context is+// intentionally ignored: teardown runs during job shutdown when that context is+// usually already cancelled, so the removal deadline is rooted in a fresh+// background context. The parameter is kept to satisfy runner.JobContainer.+func (c *PostgresContainer) Terminate(context.Context) error {+ ctx, cancel := context.WithTimeout(context.Background(), containerTerminateTimeout)+ defer cancel()++ rmErr := c.engine.RemoveContainer(ctx, c.id)++ if c.networkID != "" {+ if netErr := c.engine.RemoveNetwork(ctx, c.networkID); netErr != nil && rmErr == nil {+ rmErr = netErr+ }+ }++ return rmErr+}diff --git a/agent/verification/internal/features/container/dockerengine.go b/agent/verification/internal/features/container/dockerengine.gonew file mode 100644index 00000000..4626d41a--- /dev/null+++ b/agent/verification/internal/features/container/dockerengine.go@@ -0,0 +1,316 @@+// Package container owns the ephemeral Postgres container lifecycle. Every+// Docker-SDK call is confined to this file; the Manager builds a hardened+// SpawnSpec (unit-tested) that this file translates 1:1 to Docker.+package container++import (+ "bytes"+ "context"+ "fmt"+ "io"+ "strconv"+ "strings"++ "github.com/docker/docker/api/types/container"+ "github.com/docker/docker/api/types/filters"+ "github.com/docker/docker/api/types/image"+ "github.com/docker/docker/api/types/network"+ "github.com/docker/docker/client"+ "github.com/docker/docker/pkg/stdcopy"+ "github.com/docker/go-connections/nat"++ "databasus-verification-agent/internal/features/restore"+)++const (+ // LabelVerificationID / LabelAgentID tag every container and network so the+ // startup purge can find and remove this agent's leftovers by agent ID+ LabelVerificationID = "databasus.verification.verification_id"+ LabelAgentID = "databasus.verification.agent_id"++ containerPidsLimit = 512++ // pgInternalPort is the in-container Postgres port; it is published to an+ // ephemeral 127.0.0.1 host port for the verifier.+ pgInternalPort = 5432+)++type dockerEngine struct {+ cli *client.Client+}++func NewDockerEngine() (*dockerEngine, error) {+ cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())+ if err != nil {+ return nil, fmt.Errorf("create docker client: %w", err)+ }++ return &dockerEngine{cli: cli}, nil+}++func (e *dockerEngine) Ping(ctx context.Context) error {+ _, err := e.cli.Ping(ctx)+ return err+}++func (e *dockerEngine) UserNSRemapEnabled(ctx context.Context) (bool, error) {+ info, err := e.cli.Info(ctx)+ if err != nil {+ return false, err+ }++ for _, opt := range info.SecurityOptions {+ if strings.Contains(opt, "name=userns") {+ return true, nil+ }+ }++ return false, nil+}++func (e *dockerEngine) EnsureImage(ctx context.Context, ref string) error {+ if _, err := e.cli.ImageInspect(ctx, ref); err == nil {+ return nil+ }++ reader, err := e.cli.ImagePull(ctx, ref, image.PullOptions{})+ if err != nil {+ return fmt.Errorf("image pull: %w", err)+ }+ defer func() { _ = reader.Close() }()++ if _, err := io.Copy(io.Discard, reader); err != nil {+ return fmt.Errorf("drain image pull: %w", err)+ }++ return nil+}++func (e *dockerEngine) CreateNetwork(+ ctx context.Context, name string, labels map[string]string,+) (string, error) {+ // Each job gets its own user-defined bridge — that isolates jobs from each+ // other. We deliberately do NOT set Internal:true: Docker silently disables+ // port publishing on internal networks, and the agent-process verifier can+ // only reach the restored DB via the published host port (verifier package+ // doc). Outbound from PG to the host network is therefore not blocked at+ // the docker layer; rely on the host firewall + the other hardening+ // controls (cap-drop, no-new-privs, pids/memory, ephemeral, userns).+ resp, err := e.cli.NetworkCreate(ctx, name, network.CreateOptions{+ Driver: "bridge",+ Labels: labels,+ })+ if err != nil {+ return "", err+ }++ return resp.ID, nil+}++func (e *dockerEngine) RemoveNetwork(ctx context.Context, networkID string) error {+ return e.cli.NetworkRemove(ctx, networkID)+}++func (e *dockerEngine) CreateContainer(ctx context.Context, spec SpawnSpec) (string, error) {+ port := nat.Port(strconv.Itoa(pgInternalPort) + "/tcp")++ securityOpt := []string{}+ if spec.NoNewPrivileges {+ securityOpt = append(securityOpt, "no-new-privileges")+ }++ capDrop := []string{}+ if spec.CapDropAll {+ capDrop = append(capDrop, "ALL")+ }++ var pidsLimit *int64+ if spec.PidsLimit > 0 {+ limit := spec.PidsLimit+ pidsLimit = &limit+ }++ hostConfig := &container.HostConfig{+ SecurityOpt: securityOpt,+ CapDrop: capDrop,+ CapAdd: spec.CapAdd,+ ReadonlyRootfs: spec.ReadonlyRootfs,+ NetworkMode: container.NetworkMode(spec.NetworkID),+ PortBindings: nat.PortMap{+ port: []nat.PortBinding{{HostIP: "127.0.0.1", HostPort: "0"}},+ },+ Resources: container.Resources{+ NanoCPUs: spec.NanoCPUs,+ Memory: spec.MemoryBytes,+ PidsLimit: pidsLimit,+ },+ }++ resp, err := e.cli.ContainerCreate(ctx,+ &container.Config{+ Image: spec.Image,+ Env: spec.Env,+ Labels: spec.Labels,+ ExposedPorts: nat.PortSet{port: struct{}{}},+ },+ hostConfig, nil, nil, spec.Name)+ if err != nil {+ return "", err+ }++ return resp.ID, nil+}++func (e *dockerEngine) StartContainer(ctx context.Context, containerID string) error {+ return e.cli.ContainerStart(ctx, containerID, container.StartOptions{})+}++func (e *dockerEngine) HostPort(+ ctx context.Context, containerID, containerPort string,+) (int, error) {+ insp, err := e.cli.ContainerInspect(ctx, containerID)+ if err != nil {+ return 0, err+ }++ bindings, ok := insp.NetworkSettings.Ports[nat.Port(containerPort)]+ if !ok || len(bindings) == 0 {+ return 0, fmt.Errorf("container port %s is not published", containerPort)+ }++ return strconv.Atoi(bindings[0].HostPort)+}++func (e *dockerEngine) InspectSecurity(+ ctx context.Context, containerID string,+) (SecurityState, error) {+ insp, err := e.cli.ContainerInspect(ctx, containerID)+ if err != nil {+ return SecurityState{}, err+ }++ state := SecurityState{+ ReadonlyRootfs: insp.HostConfig.ReadonlyRootfs,+ // Only flag mounts the AGENT requested. insp.Mounts (runtime) includes+ // image-declared anonymous volumes (postgres:16 declares VOLUME+ // /var/lib/postgresql/data for PGDATA) that we explicitly want; only+ // host bind mounts from our spec are a hardening regression.+ HasHostBinds: len(insp.HostConfig.Binds) > 0 || len(insp.HostConfig.Mounts) > 0,+ }++ for _, opt := range insp.HostConfig.SecurityOpt {+ if strings.Contains(opt, "no-new-privileges") {+ state.NoNewPrivileges = true+ }+ }++ for _, cap := range insp.HostConfig.CapDrop {+ if cap == "ALL" {+ state.CapDropAll = true+ }+ }++ return state, nil+}++func (e *dockerEngine) Exec(+ ctx context.Context,+ containerID string,+ cmd []string,+ stdin io.Reader,+ env []string,+) (restore.ExecResult, error) {+ created, err := e.cli.ContainerExecCreate(ctx, containerID, container.ExecOptions{+ Cmd: cmd,+ Env: env,+ AttachStdin: stdin != nil,+ AttachStdout: true,+ AttachStderr: true,+ })+ if err != nil {+ return restore.ExecResult{}, fmt.Errorf("exec create: %w", err)+ }++ attached, err := e.cli.ContainerExecAttach(ctx, created.ID, container.ExecAttachOptions{})+ if err != nil {+ return restore.ExecResult{}, fmt.Errorf("exec attach: %w", err)+ }+ defer attached.Close()++ // The hijacked conn's Read/Write are not ctx-aware: a container that wedges+ // while consuming stdin (or producing output) would otherwise hang Exec+ // indefinitely, defeating jobCtx/heartbeat-abort. Closing it on cancellation+ // unblocks the in-flight copy; the deferred Close above is then a harmless+ // second close.+ stopOnCancel := context.AfterFunc(ctx, func() { attached.Close() })+ defer stopOnCancel()++ if stdin != nil {+ copyErr := make(chan error, 1)+ go func() {+ _, cErr := io.Copy(attached.Conn, stdin)+ _ = attached.CloseWrite()+ copyErr <- cErr+ }()++ if cErr := <-copyErr; cErr != nil {+ return restore.ExecResult{}, fmt.Errorf("exec stdin copy: %w", cErr)+ }+ }++ var stdout, stderr bytes.Buffer+ if _, err := stdcopy.StdCopy(&stdout, &stderr, attached.Reader); err != nil {+ return restore.ExecResult{}, fmt.Errorf("exec stream copy: %w", err)+ }++ inspect, err := e.cli.ContainerExecInspect(ctx, created.ID)+ if err != nil {+ return restore.ExecResult{}, fmt.Errorf("exec inspect: %w", err)+ }++ return restore.ExecResult{+ ExitCode: inspect.ExitCode,+ Stdout: stdout.String(),+ Stderr: stderr.String(),+ }, nil+}++func (e *dockerEngine) RemoveContainer(ctx context.Context, containerID string) error {+ return e.cli.ContainerRemove(ctx, containerID, container.RemoveOptions{+ Force: true,+ RemoveVolumes: true,+ })+}++func (e *dockerEngine) ListManaged(+ ctx context.Context, agentID string,+) ([]ManagedContainer, error) {+ summaries, err := e.cli.ContainerList(ctx, container.ListOptions{+ All: true,+ Filters: filters.NewArgs(+ filters.Arg("label", LabelAgentID+"="+agentID)),+ })+ if err != nil {+ return nil, err+ }++ managed := make([]ManagedContainer, 0, len(summaries))+ for _, s := range summaries {+ mc := ManagedContainer{+ ID: s.ID,+ VerificationID: s.Labels[LabelVerificationID],+ CreatedUnix: s.Created,+ }++ for _, endpoint := range s.NetworkSettings.Networks {+ if endpoint.NetworkID != "" {+ mc.NetworkID = endpoint.NetworkID+ break+ }+ }++ managed = append(managed, mc)+ }++ return managed, nil+}diff --git a/agent/verification/internal/features/container/fake_engine_test.go b/agent/verification/internal/features/container/fake_engine_test.gonew file mode 100644index 00000000..abddc92d--- /dev/null+++ b/agent/verification/internal/features/container/fake_engine_test.go@@ -0,0 +1,31 @@+package container++import "context"++type fakePurgeEngine struct {+ managed []ManagedContainer+ removedContainer []string+ removedNetwork []string+ listErr error+ removeContainerErr error+}++func (f *fakePurgeEngine) ListManaged(context.Context, string) ([]ManagedContainer, error) {+ return f.managed, f.listErr+}++func (f *fakePurgeEngine) RemoveContainer(_ context.Context, id string) error {+ if f.removeContainerErr != nil {+ return f.removeContainerErr+ }++ f.removedContainer = append(f.removedContainer, id)++ return nil+}++func (f *fakePurgeEngine) RemoveNetwork(_ context.Context, id string) error {+ f.removedNetwork = append(f.removedNetwork, id)++ return nil+}diff --git a/agent/verification/internal/features/container/managedcontainer.go b/agent/verification/internal/features/container/managedcontainer.gonew file mode 100644index 00000000..83a2a6a3--- /dev/null+++ b/agent/verification/internal/features/container/managedcontainer.go@@ -0,0 +1,8 @@+package container++type ManagedContainer struct {+ ID string+ NetworkID string+ VerificationID string+ CreatedUnix int64+}diff --git a/agent/verification/internal/features/container/manager.go b/agent/verification/internal/features/container/manager.gonew file mode 100644index 00000000..3546e22a--- /dev/null+++ b/agent/verification/internal/features/container/manager.go@@ -0,0 +1,238 @@+package container++import (+ "context"+ "crypto/rand"+ "encoding/hex"+ "fmt"+ "log/slog"+ "strconv"+ "time"++ "github.com/jackc/pgx/v5"++ "databasus-verification-agent/internal/features/dbconn"+)++const (+ containerReadyTimeout = 60 * time.Second+ readyPollInterval = 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"+)++// minimalCaps are the only capabilities added back after CapDrop ALL — exactly+// what the official entrypoint needs for initdb + the gosu privilege drop, not+// a blanket keep.+var minimalCaps = []string{"CHOWN", "DAC_OVERRIDE", "FOWNER", "SETGID", "SETUID"}++type Manager struct {+ engine *dockerEngine+ agentID string+ log *slog.Logger+}++func NewManager(+ engine *dockerEngine,+ agentID string,+ log *slog.Logger,+) *Manager {+ return &Manager{+ engine: engine,+ agentID: agentID,+ log: log,+ }+}++func (m *Manager) StartupSelfCheck(ctx context.Context) error {+ if err := m.engine.Ping(ctx); err != nil {+ return fmt.Errorf("docker daemon unreachable: %w", err)+ }++ m.log.Info("docker daemon is reachable")++ remapOn, err := m.engine.UserNSRemapEnabled(ctx)+ if err != nil {+ m.log.Warn("could not determine user-namespace remap state", "error", err)+ } else if !remapOn {+ m.log.Warn(+ "docker user-namespace remapping is OFF — the strongest control " ++ "against a container escape is absent; enable userns-remap on the " ++ "verification host")+ }++ return nil+}++// PurgeContainers removes every container+network this agent owns so each+// process starts from a clean slate. Call once at startup, after+// StartupSelfCheck (Docker must be reachable) and before any job is claimed.+// See purgeAgentContainers for why blanket removal is safe under one agent.+func (m *Manager) PurgeContainers(ctx context.Context) {+ purgeAgentContainers(ctx, m.engine, m.agentID, m.log)+}++// 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 := imageForMajor(req.PgMajor)++ if err := m.engine.EnsureImage(jobCtx, image); err != nil {+ return nil, fmt.Errorf("ensure image: %w", err)+ }++ password, err := randomPassword()+ if err != nil {+ return nil, fmt.Errorf("generate password: %w", err)+ }++ // LabelAgentID is load-bearing for the startup purge: ListManaged filters+ // solely on it, so a container spawned without this label can never be+ // purged and leaks until the host is cleaned by hand.+ labels := map[string]string{+ LabelAgentID: m.agentID,+ LabelVerificationID: req.VerificationID.String(),+ }++ networkID, err := m.engine.CreateNetwork(+ jobCtx, "databasus-verif-"+req.VerificationID.String(), labels)+ if err != nil {+ return nil, fmt.Errorf("create isolated network: %w", err)+ }++ spec := m.buildSpec(spawnPlan{+ verificationID: req.VerificationID,+ image: image,+ password: password,+ cpuPerJob: req.CPUPerJob,+ ramMbPerJob: req.RAMMbPerJob,+ networkID: networkID,+ labels: labels,+ })++ containerID, err := m.engine.CreateContainer(jobCtx, spec)+ if err != nil {+ _ = m.engine.RemoveNetwork(jobCtx, networkID)+ return nil, fmt.Errorf("create container: %w", err)+ }++ c := &PostgresContainer{engine: m.engine, id: containerID, networkID: networkID, password: password, log: m.log}++ if err := m.engine.StartContainer(jobCtx, containerID); err != nil {+ _ = c.Terminate(jobCtx)+ return nil, fmt.Errorf("start container: %w", err)+ }++ hostPort, err := m.engine.HostPort(jobCtx, containerID, strconv.Itoa(pgInternalPort)+"/tcp")+ if err != nil {+ _ = c.Terminate(jobCtx)+ return nil, fmt.Errorf("resolve published port: %w", err)+ }++ c.hostPort = hostPort++ if err := waitForReady(jobCtx, c.GetVerifierConn()); err != nil {+ _ = c.Terminate(jobCtx)+ return nil, fmt.Errorf("container never became ready: %w", err)+ }++ if err := m.assertSecurity(jobCtx, containerID); err != nil {+ _ = c.Terminate(jobCtx)+ return nil, err+ }++ return c, nil+}++func (m *Manager) buildSpec(plan spawnPlan) SpawnSpec {+ return SpawnSpec{+ Name: "databasus-verif-" + plan.verificationID.String(),+ Image: plan.image,+ Env: []string{"POSTGRES_PASSWORD=" + plan.password},+ Labels: plan.labels,+ NanoCPUs: int64(plan.cpuPerJob) * 1_000_000_000,+ MemoryBytes: int64(plan.ramMbPerJob) * 1024 * 1024,+ PidsLimit: containerPidsLimit,+ NetworkID: plan.networkID,++ NoNewPrivileges: true,+ CapDropAll: true,+ CapAdd: minimalCaps,+ // rootfs is writable because the official image needs a writable PGDATA;+ // the per-job disk budget is enforced by the agent's disk watcher, not a+ // Docker cap. The dominant controls (cap-drop, no-new-privs, pids,+ // memory, userns, ephemeral lifecycle) remain in force. The job network+ // is a per-job user-defined bridge (job isolation) but NOT --internal:+ // see CreateNetwork in dockerengine.go for why.+ ReadonlyRootfs: false,+ }+}++func (m *Manager) assertSecurity(ctx context.Context, containerID string) error {+ state, err := m.engine.InspectSecurity(ctx, containerID)+ if err != nil {+ return fmt.Errorf("inspect security state: %w", err)+ }++ switch {+ case !state.NoNewPrivileges:+ return fmt.Errorf("hardening regression: no-new-privileges not applied")+ case !state.CapDropAll:+ return fmt.Errorf("hardening regression: CapDrop ALL not applied")+ case state.HasHostBinds:+ return fmt.Errorf("hardening regression: container has host bind mounts")+ }++ return nil+}++func waitForReady(ctx context.Context, conn dbconn.Conn) error {+ readyCtx, cancel := context.WithTimeout(ctx, containerReadyTimeout)+ defer cancel()++ ticker := time.NewTicker(readyPollInterval)+ defer ticker.Stop()++ for {+ if pingOnce(readyCtx, conn) {+ return nil+ }++ select {+ case <-readyCtx.Done():+ return readyCtx.Err()+ case <-ticker.C:+ }+ }+}++func pingOnce(ctx context.Context, conn dbconn.Conn) bool {+ pingCtx, cancel := context.WithTimeout(ctx, readyPollInterval)+ defer cancel()++ pgConn, err := pgx.Connect(pingCtx, conn.DSN())+ if err != nil {+ return false+ }+ defer func() { _ = pgConn.Close(pingCtx) }()++ return pgConn.Ping(pingCtx) == nil+}++// imageForMajor returns the Docker image tag the agent spawns for a given+// Postgres major. Extracted so the major-to-image contract is unit-testable+// without standing up a Docker engine.+func imageForMajor(pgMajor string) string {+ return engineImageRepo + ":" + pgMajor+}++func randomPassword() (string, error) {+ buf := make([]byte, 24)+ if _, err := rand.Read(buf); err != nil {+ return "", err+ }++ return hex.EncodeToString(buf), nil+}diff --git a/agent/verification/internal/features/container/postgres_test.go b/agent/verification/internal/features/container/postgres_test.gonew file mode 100644index 00000000..429d0016--- /dev/null+++ b/agent/verification/internal/features/container/postgres_test.go@@ -0,0 +1,80 @@+package container++import (+ "testing"++ "github.com/google/uuid"+ "github.com/stretchr/testify/assert"++ "databasus-verification-agent/internal/testutil"+)++func Test_BuildSpec_AppliesHardeningControls(t *testing.T) {+ // nil engine: buildSpec is pure and never calls the engine.+ containerManager := NewManager(nil, "agent-1", testutil.DiscardLogger())++ labels := map[string]string{LabelAgentID: "agent-1"}+ spec := containerManager.buildSpec(spawnPlan{+ verificationID: uuid.New(),+ image: "postgres@sha256:x",+ password: "pw",+ cpuPerJob: 2,+ ramMbPerJob: 1024,+ networkID: "net-id",+ labels: labels,+ })++ assert.True(t, spec.NoNewPrivileges)+ assert.True(t, spec.CapDropAll)+ assert.Equal(t, minimalCaps, spec.CapAdd)+ assert.EqualValues(t, containerPidsLimit, spec.PidsLimit)+ assert.Equal(t, "net-id", spec.NetworkID)+ assert.Equal(t, int64(2)*1_000_000_000, spec.NanoCPUs)+ assert.Equal(t, int64(1024)*1024*1024, spec.MemoryBytes)+ assert.Equal(t, []string{"POSTGRES_PASSWORD=pw"}, spec.Env)+}++func Test_GetInContainerConn_UsesInternalPort(t *testing.T) {+ c := &PostgresContainer{password: "pw"}++ conn := c.GetInContainerConn()++ assert.Equal(t, "127.0.0.1", conn.Host)+ assert.Equal(t, pgInternalPort, conn.Port)+ assert.Equal(t, restoreUser, conn.User)+ assert.Equal(t, restoreDB, conn.Database)+ assert.Equal(t, "pw", conn.Password)+}++func Test_GetVerifierConn_WhenSpawned_UsesResolvedHostPort(t *testing.T) {+ c := &PostgresContainer{password: "pw", hostPort: 54321}++ conn := c.GetVerifierConn()++ assert.Equal(t, "127.0.0.1", conn.Host)+ assert.Equal(t, 54321, conn.Port)+ assert.Equal(t, restoreUser, conn.User)+ assert.Equal(t, restoreDB, conn.Database)+ assert.Equal(t, "pw", conn.Password)+}++func Test_ImageForMajor_ReturnsPostgresOfficialTagPerMajor(t *testing.T) {+ cases := []struct {+ major string+ expected string+ }{+ {"12", "postgres:12"},+ {"13", "postgres:13"},+ {"14", "postgres:14"},+ {"15", "postgres:15"},+ {"16", "postgres:16"},+ {"17", "postgres:17"},+ {"18", "postgres:18"},+ }++ for _, tc := range cases {+ t.Run(tc.major, func(t *testing.T) {+ assert.Equal(t, tc.expected, imageForMajor(tc.major))+ })+ }+}diff --git a/agent/verification/internal/features/container/purge.go b/agent/verification/internal/features/container/purge.gonew file mode 100644index 00000000..009a2966--- /dev/null+++ b/agent/verification/internal/features/container/purge.go@@ -0,0 +1,58 @@+package container++import (+ "context"+ "fmt"+ "log/slog"+)++// purgeEngine is the Docker seam for the startup purge — the same three methods+// the unit tests fake, rather than the whole Docker surface.+type purgeEngine interface {+ ListManaged(ctx context.Context, agentID string) ([]ManagedContainer, error)+ RemoveContainer(ctx context.Context, containerID string) error+ RemoveNetwork(ctx context.Context, networkID string) error+}++// purgeAgentContainers runs once at startup, with no age grace and no+// active-set check, so each agent process begins from a clean slate+// ("always fresh").+//+// Best-effort by design: a per-item failure is logged and skipped, and a+// failed listing is logged and ignored, never blocking startup. Container and+// network names are per-UUID (databasus-verif-<uuid>), so a leftover never+// collides with a fresh run; degraded (a few stale containers until the next+// restart) beats refusing to start on a transient Docker hiccup.+func purgeAgentContainers(ctx context.Context, engine purgeEngine, agentID string, log *slog.Logger) {+ managed, err := engine.ListManaged(ctx, agentID)+ if err != nil {+ log.Warn("startup purge could not list managed containers", "error", err)++ return+ }++ if len(managed) == 0 {+ return+ }++ removed := 0+ for _, mc := range managed {+ if err := engine.RemoveContainer(ctx, mc.ID); err != nil {+ log.Warn("startup purge failed to remove container",+ "verification_id", mc.VerificationID, "error", err)++ continue+ }++ if mc.NetworkID != "" {+ if err := engine.RemoveNetwork(ctx, mc.NetworkID); err != nil {+ log.Warn("startup purge failed to remove network",+ "verification_id", mc.VerificationID, "error", err)+ }+ }++ removed+++ }++ log.Info(fmt.Sprintf("startup purge removed %d stale container(s)", removed))+}diff --git a/agent/verification/internal/features/container/purge_test.go b/agent/verification/internal/features/container/purge_test.gonew file mode 100644index 00000000..7f394c1d--- /dev/null+++ b/agent/verification/internal/features/container/purge_test.go@@ -0,0 +1,74 @@+package container++import (+ "errors"+ "testing"++ "github.com/google/uuid"+ "github.com/stretchr/testify/assert"++ "databasus-verification-agent/internal/testutil"+)++func Test_PurgeAgentContainers_RemovesEveryContainerAndNetwork(t *testing.T) {+ engine := &fakePurgeEngine{+ managed: []ManagedContainer{+ {ID: "c1", NetworkID: "n1", VerificationID: uuid.New().String()},+ {ID: "c2", NetworkID: "n2", VerificationID: uuid.New().String()},+ },+ }++ purgeAgentContainers(t.Context(), engine, "agent-1", testutil.DiscardLogger())++ assert.ElementsMatch(t, []string{"c1", "c2"}, engine.removedContainer)+ assert.ElementsMatch(t, []string{"n1", "n2"}, engine.removedNetwork)+}++func Test_PurgeAgentContainers_WhenNetworkIDEmpty_RemovesContainerOnly(t *testing.T) {+ engine := &fakePurgeEngine{+ managed: []ManagedContainer{{ID: "c1", VerificationID: uuid.New().String()}},+ }++ purgeAgentContainers(t.Context(), engine, "agent-1", testutil.DiscardLogger())++ assert.Equal(t, []string{"c1"}, engine.removedContainer)+ assert.Empty(t, engine.removedNetwork)+}++func Test_PurgeAgentContainers_WhenListFails_RemovesNothing(t *testing.T) {+ engine := &fakePurgeEngine{+ managed: []ManagedContainer{{ID: "c1", NetworkID: "n1"}},+ listErr: errors.New("docker unreachable"),+ }++ purgeAgentContainers(t.Context(), engine, "agent-1", testutil.DiscardLogger())++ assert.Empty(t, engine.removedContainer)+ assert.Empty(t, engine.removedNetwork)+}++func Test_PurgeAgentContainers_WhenListEmpty_DoesNothing(t *testing.T) {+ engine := &fakePurgeEngine{}++ purgeAgentContainers(t.Context(), engine, "agent-1", testutil.DiscardLogger())++ assert.Empty(t, engine.removedContainer)+ assert.Empty(t, engine.removedNetwork)+}++func Test_PurgeAgentContainers_WhenContainerRemovalFails_SkipsNetworkAndContinues(t *testing.T) {+ engine := &fakePurgeEngine{+ managed: []ManagedContainer{+ {ID: "c1", NetworkID: "n1", VerificationID: uuid.New().String()},+ {ID: "c2", NetworkID: "n2", VerificationID: uuid.New().String()},+ },+ removeContainerErr: errors.New("container in use"),+ }++ assert.NotPanics(t, func() {+ purgeAgentContainers(t.Context(), engine, "agent-1", testutil.DiscardLogger())+ })++ assert.Empty(t, engine.removedContainer)+ assert.Empty(t, engine.removedNetwork)+}diff --git a/agent/verification/internal/features/container/securitystate.go b/agent/verification/internal/features/container/securitystate.gonew file mode 100644index 00000000..e56bba02--- /dev/null+++ b/agent/verification/internal/features/container/securitystate.go@@ -0,0 +1,10 @@+package container++// SecurityState is read back from the live container so each job re-asserts its+// own hardening landed (a daemon glitch fails that job, never the process).+type SecurityState struct {+ NoNewPrivileges bool+ CapDropAll bool+ ReadonlyRootfs bool+ HasHostBinds bool+}diff --git a/agent/verification/internal/features/container/spawnspec.go b/agent/verification/internal/features/container/spawnspec.gonew file mode 100644index 00000000..84209503--- /dev/null+++ b/agent/verification/internal/features/container/spawnspec.go@@ -0,0 +1,42 @@+package container++import "github.com/google/uuid"++type SpawnRequest struct {+ PgMajor string+ CPUPerJob int+ RAMMbPerJob int+ VerificationID uuid.UUID+}++type spawnPlan struct {+ verificationID uuid.UUID+ image string+ password string+ cpuPerJob int+ ramMbPerJob int+ networkID string+ labels map[string]string+}++// SpawnSpec is the security-hardened container request. Every clause is a+// load-bearing control: the container is the only boundary around a restore+// that runs attacker-controlled code as the DB superuser. Constructed by the+// Manager (unit-testable) and translated 1:1 to Docker by dockerEngine.+type SpawnSpec struct {+ Name string+ Image string+ Env []string+ Labels map[string]string+ NanoCPUs int64+ MemoryBytes int64+ PidsLimit int64+ NetworkID string++ // The hardening invariants, explicit so a unit test asserts them and the+ // engine translation cannot silently drop one.+ NoNewPrivileges bool+ CapDropAll bool+ CapAdd []string+ ReadonlyRootfs bool+}diff --git a/agent/verification/internal/features/dbconn/dbconn.go b/agent/verification/internal/features/dbconn/dbconn.gonew file mode 100644index 00000000..6640772e--- /dev/null+++ b/agent/verification/internal/features/dbconn/dbconn.go@@ -0,0 +1,18 @@+package dbconn++import "fmt"++type Conn struct {+ Host string+ Port int+ User string+ Password string+ Database string+}++func (c Conn) DSN() string {+ return fmt.Sprintf(+ "host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",+ c.Host, c.Port, c.User, c.Password, c.Database,+ )+}diff --git a/agent/verification/internal/features/heartbeat/heartbeat.go b/agent/verification/internal/features/heartbeat/heartbeat.gonew file mode 100644index 00000000..e26ceee6--- /dev/null+++ b/agent/verification/internal/features/heartbeat/heartbeat.go@@ -0,0 +1,150 @@+package heartbeat++import (+ "context"+ "fmt"+ "log/slog"+ "sync"+ "sync/atomic"+ "time"++ "github.com/google/uuid"++ "databasus-verification-agent/internal/config"+ "databasus-verification-agent/internal/features/api"+)++const (+ jobName = "verification_heartbeat"+ heartbeatInterval = 30 * time.Second+)++// Heartbeater periodically reports the agent's capacity and the set of+// in-flight verification IDs (the backend reclaims any RUNNING job absent from+// that set), and acts on the abort list in the response. It is the single+// source of truth for which verifications are active and records the last+// abort set so the runner can re-check it immediately before any FAILED report+// (the abort/report-race mitigation).+type Heartbeater struct {+ api *api.Client+ capacity config.Capacity+ hasRun atomic.Bool++ mu sync.Mutex+ registry map[uuid.UUID]context.CancelFunc+ lastAbort map[uuid.UUID]struct{}++ log *slog.Logger+}++func NewHeartbeater(apiClient *api.Client, capacity config.Capacity, log *slog.Logger) *Heartbeater {+ return &Heartbeater{+ api: apiClient,+ capacity: capacity,+ registry: make(map[uuid.UUID]context.CancelFunc),+ lastAbort: make(map[uuid.UUID]struct{}),+ log: log,+ }+}++func (h *Heartbeater) Run(ctx context.Context) {+ if h.hasRun.Swap(true) {+ panic(fmt.Sprintf("%T.Run() called multiple times", h))+ }++ logger := h.log.With("job_id", uuid.New(), "job_name", jobName)+ logger.Info("heartbeat loop started")++ ticker := time.NewTicker(heartbeatInterval)+ defer ticker.Stop()++ if ctx.Err() == nil {+ h.sendHeartbeat(ctx, logger)+ }++ for {+ select {+ case <-ctx.Done():+ logger.Info("heartbeat loop stopped")++ return+ case <-ticker.C:+ h.sendHeartbeat(ctx, logger)+ }+ }+}++// TrackVerification must be called before the container/network exists so the+// ID rides the heartbeat envelope and is reachable by an abort the instant it+// has any artifact.+func (h *Heartbeater) TrackVerification(id uuid.UUID, cancel context.CancelFunc) {+ h.mu.Lock()+ defer h.mu.Unlock()++ h.registry[id] = cancel+}++func (h *Heartbeater) UntrackVerification(id uuid.UUID) {+ h.mu.Lock()+ defer h.mu.Unlock()++ delete(h.registry, id)+}++func (h *Heartbeater) GetRunningVerificationIDs() []uuid.UUID {+ h.mu.Lock()+ defer h.mu.Unlock()++ ids := make([]uuid.UUID, 0, len(h.registry))+ for id := range h.registry {+ ids = append(ids, id)+ }++ return ids+}++func (h *Heartbeater) IsAborted(id uuid.UUID) bool {+ h.mu.Lock()+ defer h.mu.Unlock()++ _, aborted := h.lastAbort[id]++ return aborted+}++func (h *Heartbeater) sendHeartbeat(ctx context.Context, logger *slog.Logger) {+ request := api.HeartbeatRequest{+ MaxCPU: h.capacity.MaxCPU,+ MaxRAMGb: h.capacity.MaxRAMMb / 1024,+ MaxDiskGb: h.capacity.MaxDiskGb,+ MaxConcurrentJobs: h.capacity.MaxConcurrentJobs,+ CurrentVerificationIDs: h.GetRunningVerificationIDs(),+ }++ response, err := h.api.Heartbeat(ctx, request)+ if err != nil {+ logger.Warn("heartbeat failed, will retry next tick", "error", err)++ return+ }++ h.abortVerifications(response.AbortVerificationIDs, logger)++ logger.Debug(fmt.Sprintf(+ "heartbeat ok: last_seen_at=%s", response.LastSeenAt.UTC().Format(time.RFC3339)))+}++func (h *Heartbeater) abortVerifications(abortIDs []uuid.UUID, logger *slog.Logger) {+ h.mu.Lock()+ defer h.mu.Unlock()++ h.lastAbort = make(map[uuid.UUID]struct{}, len(abortIDs))+ for _, id := range abortIDs {+ h.lastAbort[id] = struct{}{}++ if cancel, registered := h.registry[id]; registered {+ logger.Info(fmt.Sprintf("aborting verification %s on server request", id))+ cancel()+ }+ }+}diff --git a/agent/verification/internal/features/heartbeat/heartbeat_test.go b/agent/verification/internal/features/heartbeat/heartbeat_test.gonew file mode 100644index 00000000..fa2484dd--- /dev/null+++ b/agent/verification/internal/features/heartbeat/heartbeat_test.go@@ -0,0 +1,144 @@+package heartbeat++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "testing"+ "time"++ "github.com/google/uuid"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ "databasus-verification-agent/internal/config"+ "databasus-verification-agent/internal/features/api"+ "databasus-verification-agent/internal/testutil"+)++func Test_Beat_WhenNoJobsRegistered_ReportsCapacityWithRamConvertedToGbAndNoVerificationIDs(t *testing.T) {+ var body map[string]any++ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ require.NoError(t, json.NewDecoder(r.Body).Decode(&body))+ _ = json.NewEncoder(w).Encode(map[string]any{+ "lastSeenAt": time.Now().UTC().Format(time.RFC3339),+ "abortVerificationIds": []string{},+ })+ }))+ t.Cleanup(server.Close)++ client := api.NewClient(server.URL, "tok", "agent-1", testutil.DiscardLogger())+ capacity := config.Capacity{+ MaxCPU: 8,+ MaxRAMMb: 4096,+ MaxDiskGb: 100,+ MaxConcurrentJobs: 4,+ }++ NewHeartbeater(client, capacity, testutil.DiscardLogger()).sendHeartbeat(t.Context(), testutil.DiscardLogger())++ assert.Equal(t, float64(8), body["maxCpu"])+ assert.Equal(t, float64(4), body["maxRamGb"], "4096 MB must be reported as 4 GB")+ assert.Equal(t, float64(100), body["maxDiskGb"])+ assert.Equal(t, float64(4), body["maxConcurrentJobs"])+ assert.Equal(t, []any{}, body["currentVerificationIds"])+}++func Test_Beat_WhenJobRegistered_ReportsItsIDAsCurrentVerificationID(t *testing.T) {+ var body map[string]any++ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ require.NoError(t, json.NewDecoder(r.Body).Decode(&body))+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(map[string]any{+ "lastSeenAt": time.Now().UTC().Format(time.RFC3339),+ "abortVerificationIds": []string{},+ })+ }))+ t.Cleanup(server.Close)++ client := api.NewClient(server.URL, "tok", "agent-1", testutil.DiscardLogger())+ hb := NewHeartbeater(client, config.Capacity{}, testutil.DiscardLogger())++ jobID := uuid.New()+ hb.TrackVerification(jobID, func() {})++ hb.sendHeartbeat(t.Context(), testutil.DiscardLogger())++ ids, ok := body["currentVerificationIds"].([]any)+ require.True(t, ok)+ require.Len(t, ids, 1)+ assert.Equal(t, jobID.String(), ids[0])+}++func Test_Beat_WhenResponseListsAbortID_CancelsMatchingJobAndRecordsAbort(t *testing.T) {+ abortID := uuid.New()++ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(map[string]any{+ "lastSeenAt": time.Now().UTC().Format(time.RFC3339),+ "abortVerificationIds": []string{abortID.String()},+ })+ }))+ t.Cleanup(server.Close)++ client := api.NewClient(server.URL, "tok", "agent-1", testutil.DiscardLogger())+ hb := NewHeartbeater(client, config.Capacity{}, testutil.DiscardLogger())++ canceled := make(chan struct{})+ hb.TrackVerification(abortID, func() { close(canceled) })++ hb.sendHeartbeat(t.Context(), testutil.DiscardLogger())++ select {+ case <-canceled:+ case <-time.After(2 * time.Second):+ t.Fatal("registered job's context was not cancelled on server abort")+ }++ assert.True(t, hb.IsAborted(abortID),+ "the abort set must be recorded for the runner's pre-FAILED re-check")+}++func Test_Heartbeater_Run_WhenCalledTwice_Panics(t *testing.T) {+ client := api.NewClient("http://127.0.0.1:0", "tok", "agent-1", testutil.DiscardLogger())+ heartbeater := NewHeartbeater(client, config.Capacity{}, testutil.DiscardLogger())++ ctx, cancel := context.WithCancel(t.Context())+ cancel()+ heartbeater.Run(ctx)++ assert.Panics(t, func() { heartbeater.Run(ctx) })+}++func Test_Heartbeater_Run_WhenContextCanceled_StopsPromptly(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ _ = json.NewEncoder(w).Encode(map[string]any{+ "lastSeenAt": time.Now().UTC().Format(time.RFC3339),+ "abortVerificationIds": []string{},+ })+ }))+ t.Cleanup(server.Close)++ client := api.NewClient(server.URL, "tok", "agent-1", testutil.DiscardLogger())+ heartbeater := NewHeartbeater(client, config.Capacity{MaxConcurrentJobs: 1}, testutil.DiscardLogger())++ ctx, cancel := context.WithCancel(t.Context())+ stopped := make(chan struct{})++ go func() {+ heartbeater.Run(ctx)+ close(stopped)+ }()++ cancel()++ select {+ case <-stopped:+ case <-time.After(5 * time.Second):+ t.Fatal("Run did not return after context cancellation")+ }+}diff --git a/agent/verification/internal/features/restore/diskexhaustion.go b/agent/verification/internal/features/restore/diskexhaustion.gonew file mode 100644index 00000000..cd61ef08--- /dev/null+++ b/agent/verification/internal/features/restore/diskexhaustion.go@@ -0,0 +1,23 @@+package restore++import "strings"++// The runner uses this to reclassify a non-zero pg_restore exit away from+// BackupRejected: exceeding an estimate-derived bound is agent infra, not+// proof the backup is corrupt.+func IsDiskExhausted(stderrTail string) bool {+ lowered := strings.ToLower(stderrTail)++ for _, sig := range []string{+ "no space left on device",+ "could not extend",+ "disk full",+ "wrote only",+ } {+ if strings.Contains(lowered, sig) {+ return true+ }+ }++ return false+}diff --git a/agent/verification/internal/features/restore/diskexhaustion_test.go b/agent/verification/internal/features/restore/diskexhaustion_test.gonew file mode 100644index 00000000..b66ade11--- /dev/null+++ b/agent/verification/internal/features/restore/diskexhaustion_test.go@@ -0,0 +1,14 @@+package restore++import (+ "testing"++ "github.com/stretchr/testify/assert"+)++func Test_IsDiskExhausted_DetectsENOSPCSignatures(t *testing.T) {+ assert.True(t, IsDiskExhausted("pg_restore: error: could not write to output file: No space left on device"))+ assert.True(t, IsDiskExhausted("ERROR: could not extend file"))+ assert.False(t, IsDiskExhausted("pg_restore: error: relation already exists"))+ assert.False(t, IsDiskExhausted(""))+}diff --git a/agent/verification/internal/features/restore/doc.go b/agent/verification/internal/features/restore/doc.gonew file mode 100644index 00000000..192a755c--- /dev/null+++ b/agent/verification/internal/features/restore/doc.go@@ -0,0 +1,4 @@+// Package restore drives pg_restore inside the job's ephemeral container. It+// never imports the Docker SDK: it works through the ExecRunner interface so+// the runner's exit-code contract is unit-testable with a fake.+package restorediff --git a/agent/verification/internal/features/restore/dto.go b/agent/verification/internal/features/restore/dto.gonew file mode 100644index 00000000..fe13add1--- /dev/null+++ b/agent/verification/internal/features/restore/dto.go@@ -0,0 +1,16 @@+package restore++// A non-zero ExitCode is not a Go error here — only failing to create, start,+// or attach the exec is.+type ExecResult struct {+ ExitCode int+ Stdout string+ Stderr string+}++// Result is populated even on the error path (see ErrRestoreFailed).+type Result struct {+ PgRestoreExitCode int+ DurationMs int64+ StderrTail string+}diff --git a/agent/verification/internal/features/restore/errors.go b/agent/verification/internal/features/restore/errors.gonew file mode 100644index 00000000..d57eb487--- /dev/null+++ b/agent/verification/internal/features/restore/errors.go@@ -0,0 +1,9 @@+package restore++import "errors"++// ErrRestoreFailed is the contract boundary the runner keys on: a non-zero+// pg_restore exit is terminal "backup rejected" (modulo the disk-ceiling+// probe), whereas any other RunPgRestore error is an exec-infrastructure+// failure with no usable exit code — a retryable agent-setup failure.+var ErrRestoreFailed = errors.New("pg_restore exited non-zero")diff --git a/agent/verification/internal/features/restore/interfaces.go b/agent/verification/internal/features/restore/interfaces.gonew file mode 100644index 00000000..7ad600d6--- /dev/null+++ b/agent/verification/internal/features/restore/interfaces.go@@ -0,0 +1,10 @@+package restore++import (+ "context"+ "io"+)++type ExecRunner interface {+ Exec(ctx context.Context, cmd []string, stdin io.Reader, env []string) (ExecResult, error)+}diff --git a/agent/verification/internal/features/restore/restorer.go b/agent/verification/internal/features/restore/restorer.gonew file mode 100644index 00000000..0c66686f--- /dev/null+++ b/agent/verification/internal/features/restore/restorer.go@@ -0,0 +1,86 @@+package restore++import (+ "context"+ "fmt"+ "io"+ "log/slog"+ "strconv"+ "time"++ "databasus-verification-agent/internal/features/dbconn"+)++type Restorer struct {+ log *slog.Logger+}++func NewRestorer(log *slog.Logger) *Restorer {+ return &Restorer{log: log}+}++// No host bind mount: the decrypted dump never touches the agent host.+func (r *Restorer) StageBackupViaExec(+ ctx context.Context,+ exec ExecRunner,+ body io.Reader,+ destPath string,+) error {+ result, err := exec.Exec(ctx, []string{"dd", "of=" + destPath, "bs=4M"}, body, nil)+ if err != nil {+ return fmt.Errorf("stage exec: %w", err)+ }++ if result.ExitCode != 0 {+ return fmt.Errorf(+ "stage dd exited %d: %s", result.ExitCode, tailString(result.Stderr, 2048))+ }++ return nil+}++func (r *Restorer) RunPgRestore(+ ctx context.Context,+ exec ExecRunner,+ archivePath string,+ conn dbconn.Conn,+ parallelJobs int,+) (Result, error) {+ started := time.Now().UTC()++ 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,+ }+ env := []string{"PGPASSWORD=" + conn.Password}++ execResult, err := exec.Exec(ctx, cmd, nil, env)++ result := Result{+ PgRestoreExitCode: execResult.ExitCode,+ DurationMs: time.Since(started).Milliseconds(),+ StderrTail: tailString(execResult.Stderr, 8192),+ }++ if err != nil {+ return result, fmt.Errorf("pg_restore exec: %w", err)+ }++ if execResult.ExitCode != 0 {+ return result, fmt.Errorf("%w (code %d)", ErrRestoreFailed, execResult.ExitCode)+ }++ return result, nil+}++func tailString(s string, maxBytes int) string {+ if len(s) <= maxBytes {+ return s+ }++ return s[len(s)-maxBytes:]+}diff --git a/agent/verification/internal/features/restore/restorer_test.go b/agent/verification/internal/features/restore/restorer_test.gonew file mode 100644index 00000000..9b8893b3--- /dev/null+++ b/agent/verification/internal/features/restore/restorer_test.go@@ -0,0 +1,139 @@+package restore++import (+ "context"+ "errors"+ "io"+ "strings"+ "testing"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ "databasus-verification-agent/internal/features/dbconn"+ "databasus-verification-agent/internal/testutil"+)++type recordedExec struct {+ cmd []string+ env []string+ stdin []byte+}++type fakeExecRunner struct {+ recorded []recordedExec+ result ExecResult+ err error+}++func (f *fakeExecRunner) Exec(+ _ context.Context, cmd []string, stdin io.Reader, env []string,+) (ExecResult, error) {+ rec := recordedExec{cmd: cmd, env: env}+ if stdin != nil {+ rec.stdin, _ = io.ReadAll(stdin)+ }++ f.recorded = append(f.recorded, rec)++ return f.result, f.err+}++func testConn() dbconn.Conn {+ return dbconn.Conn{+ Host: "127.0.0.1", Port: 5432,+ User: "postgres", Password: "deadbeef", Database: "verifydb",+ }+}++func Test_StageBackupViaExec_WhenDdSucceeds_StreamsBodyToDest(t *testing.T) {+ exec := &fakeExecRunner{result: ExecResult{ExitCode: 0}}+ r := NewRestorer(testutil.DiscardLogger())++ err := r.StageBackupViaExec(+ t.Context(), exec, strings.NewReader("ARCHIVE BYTES"), "/restore/x.dump")++ require.NoError(t, err)+ require.Len(t, exec.recorded, 1)+ assert.Equal(t, []string{"dd", "of=/restore/x.dump", "bs=4M"}, exec.recorded[0].cmd)+ assert.Equal(t, "ARCHIVE BYTES", string(exec.recorded[0].stdin))+}++func Test_StageBackupViaExec_WhenDdExitsNonZero_ReturnsError(t *testing.T) {+ exec := &fakeExecRunner{result: ExecResult{ExitCode: 1, Stderr: "No space left on device"}}+ r := NewRestorer(testutil.DiscardLogger())++ err := r.StageBackupViaExec(t.Context(), exec, strings.NewReader("x"), "/restore/x.dump")++ require.Error(t, err)+ assert.Contains(t, err.Error(), "stage dd exited 1")+ assert.Contains(t, err.Error(), "No space left")+}++func Test_StageBackupViaExec_WhenExecInfraFails_ReturnsError(t *testing.T) {+ exec := &fakeExecRunner{err: errors.New("docker daemon unreachable")}+ r := NewRestorer(testutil.DiscardLogger())++ err := r.StageBackupViaExec(t.Context(), exec, strings.NewReader("x"), "/restore/x.dump")++ require.Error(t, err)+ assert.Contains(t, err.Error(), "stage exec")+}++func Test_RunPgRestore_WhenPgRestoreSucceeds_ReturnsResultWithoutError(t *testing.T) {+ exec := &fakeExecRunner{result: ExecResult{ExitCode: 0}}+ r := NewRestorer(testutil.DiscardLogger())++ result, err := r.RunPgRestore(t.Context(), exec, "/restore/x.dump", testConn(), 4)++ require.NoError(t, err)+ assert.Equal(t, 0, result.PgRestoreExitCode)++ require.Len(t, exec.recorded, 1)+ cmd := exec.recorded[0].cmd+ assert.Equal(t, "pg_restore", cmd[0])+ assert.Contains(t, cmd, "-Fc")+ assert.Contains(t, cmd, "--no-password")+ assert.Contains(t, cmd, "--no-owner")+ assert.Contains(t, cmd, "--no-acl")+ assert.Contains(t, cmd, "-j")+ assert.Contains(t, cmd, "4")+ assert.Contains(t, cmd, "verifydb")+ assert.Equal(t, "/restore/x.dump", cmd[len(cmd)-1])+ assert.Equal(t, []string{"PGPASSWORD=deadbeef"}, exec.recorded[0].env)+}++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)++ require.Error(t, err)+ assert.ErrorIs(t, err, ErrRestoreFailed)+ assert.Equal(t, 1, result.PgRestoreExitCode)+ assert.Contains(t, result.StderrTail, "could not execute query")+}++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)++ require.Error(t, err)+ assert.NotErrorIs(t, err, ErrRestoreFailed,+ "an exec-infrastructure failure must not look like a non-zero pg_restore exit")+}++func Test_RunPgRestore_WhenStderrHuge_TailIsTruncatedSuffix(t *testing.T) {+ huge := strings.Repeat("A", 9000) + "TAIL-MARKER"+ exec := &fakeExecRunner{result: ExecResult{ExitCode: 0, Stderr: huge}}+ r := NewRestorer(testutil.DiscardLogger())++ result, err := r.RunPgRestore(t.Context(), exec, "/restore/x.dump", testConn(), 1)++ require.NoError(t, err)+ assert.Len(t, result.StderrTail, 8192)+ assert.True(t, strings.HasSuffix(result.StderrTail, "TAIL-MARKER"))+}diff --git a/agent/verification/internal/features/runner/abort_midrestore_integration_test.go b/agent/verification/internal/features/runner/abort_midrestore_integration_test.gonew file mode 100644index 00000000..295c1bec--- /dev/null+++ b/agent/verification/internal/features/runner/abort_midrestore_integration_test.go@@ -0,0 +1,131 @@+package runner++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "slices"+ "sync/atomic"+ "testing"+ "time"++ "github.com/google/uuid"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ "databasus-verification-agent/internal/features/api"+ "databasus-verification-agent/internal/features/heartbeat"+ "databasus-verification-agent/internal/testutil"+)++type abortMidRestoreBackend struct {+ abortID uuid.UUID+ reportHits atomic.Int32+}++func newAbortMidRestoreBackend(abortID uuid.UUID) (*abortMidRestoreBackend, *httptest.Server) {+ backend := &abortMidRestoreBackend{abortID: abortID}++ mux := http.NewServeMux()++ mux.HandleFunc(+ "GET /api/v1/agent/verifications/{agentId}/{id}/backup-stream",+ func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte("ARCHIVE"))+ },+ )++ mux.HandleFunc(+ "POST /api/v1/agent/verifications/{agentId}/{id}/report",+ func(w http.ResponseWriter, _ *http.Request) {+ backend.reportHits.Add(1)++ w.WriteHeader(http.StatusOK)+ },+ )++ mux.HandleFunc(+ "POST /api/v1/agent/verification/{agentId}/heartbeat",+ func(w http.ResponseWriter, req *http.Request) {+ var body struct {+ CurrentVerificationIDs []uuid.UUID `json:"currentVerificationIds"`+ }+ _ = json.NewDecoder(req.Body).Decode(&body)++ abortIDs := []uuid.UUID{}+ if slices.Contains(body.CurrentVerificationIDs, backend.abortID) {+ abortIDs = []uuid.UUID{backend.abortID}+ }++ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(map[string]any{+ "lastSeenAt": time.Now().UTC(),+ "abortVerificationIds": abortIDs,+ })+ },+ )++ return backend, httptest.NewServer(mux)+}++func Test_ExecuteJob_WhenServerAbortsMidRestore_HardStopsRestoreCleansContainerAndDoesNotReport(+ t *testing.T,+) {+ job := postgresJob()++ backend, server := newAbortMidRestoreBackend(job.VerificationID)+ t.Cleanup(server.Close)++ client := api.NewClient(server.URL, "", uuid.NewString(), testutil.DiscardLogger())+ heartbeater := heartbeat.NewHeartbeater(client, testCapacity(), testutil.DiscardLogger())++ jobContainer := fakeContainerWith(testConn())+ restorer := &fakeRestorer{runBlocks: true}++ runnerUnderTest := NewRunner(+ client, testCapacity(), NewPool(2),+ &fakeSpawner{container: jobContainer},+ restorer,+ &fakeStats{},+ heartbeater,+ testutil.DiscardLogger(),+ )++ execDone := make(chan struct{})+ go func() {+ runnerUnderTest.executeJob(t.Context(), job)+ close(execDone)+ }()++ require.Eventually(t, func() bool { return restorer.runEntered.Load() },+ 2*time.Second, 5*time.Millisecond,+ "executeJob must reach pg_restore before the server delivers the abort")++ beatCtx, beatCancel := context.WithCancel(t.Context())+ beatDone := make(chan struct{})+ go func() {+ heartbeater.Run(beatCtx)+ close(beatDone)+ }()++ select {+ case <-execDone:+ case <-time.After(5 * time.Second):+ t.Fatal("executeJob did not return after the server abort; restore was not hard-stopped")+ }++ beatCancel()+ <-beatDone++ assert.True(t, restorer.runCtxCancelled.Load(),+ "pg_restore must be hard-stopped by jobCtx cancellation, not run to completion")+ assert.True(t, jobContainer.terminated,+ "the container and its anonymous PGDATA volume must be torn down on a server abort, "++ "even though the same cancellation triggered the teardown")+ assert.Equal(t, int32(0), backend.reportHits.Load(),+ "a server-aborted verification must be dropped silently with no FAILED report")+ assert.True(t, heartbeater.IsAborted(job.VerificationID),+ "the abort set must be recorded for the runner's pre-FAILED re-check")+}diff --git a/agent/verification/internal/features/runner/concurrent_restores_integration_test.go b/agent/verification/internal/features/runner/concurrent_restores_integration_test.gonew file mode 100644index 00000000..6853fcc1--- /dev/null+++ b/agent/verification/internal/features/runner/concurrent_restores_integration_test.go@@ -0,0 +1,272 @@+package runner++import (+ "context"+ "encoding/json"+ "io"+ "net/http"+ "net/http/httptest"+ "sync"+ "sync/atomic"+ "testing"+ "time"++ "github.com/google/uuid"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ "databasus-verification-agent/internal/features/api"+ "databasus-verification-agent/internal/features/dbconn"+ "databasus-verification-agent/internal/features/heartbeat"+ "databasus-verification-agent/internal/features/restore"+ "databasus-verification-agent/internal/features/verifier"+ "databasus-verification-agent/internal/testutil"+)++type concurrentRestoreBackend struct {+ claims []*api.JobAssignment+ claimIdx atomic.Int32++ mu sync.Mutex+ reports map[uuid.UUID]api.VerificationStatus+}++func newConcurrentRestoreBackend(claims []*api.JobAssignment) (*concurrentRestoreBackend, *httptest.Server) {+ backend := &concurrentRestoreBackend{+ claims: claims,+ reports: make(map[uuid.UUID]api.VerificationStatus),+ }++ mux := http.NewServeMux()++ mux.HandleFunc(+ "POST /api/v1/agent/verifications/{agentId}/claim",+ func(w http.ResponseWriter, _ *http.Request) {+ i := int(backend.claimIdx.Add(1)) - 1+ if i >= len(backend.claims) {+ w.WriteHeader(http.StatusNoContent)+ return+ }++ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(backend.claims[i])+ },+ )++ mux.HandleFunc(+ "GET /api/v1/agent/verifications/{agentId}/{id}/backup-stream",+ func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte("ARCHIVE"))+ },+ )++ mux.HandleFunc(+ "POST /api/v1/agent/verifications/{agentId}/{id}/report",+ func(w http.ResponseWriter, req *http.Request) {+ verificationID, err := uuid.Parse(req.PathValue("id"))+ if err != nil {+ http.Error(w, err.Error(), http.StatusBadRequest)+ return+ }++ var body struct {+ Status api.VerificationStatus `json:"status"`+ }+ _ = json.NewDecoder(req.Body).Decode(&body)++ backend.mu.Lock()+ backend.reports[verificationID] = body.Status+ backend.mu.Unlock()++ w.WriteHeader(http.StatusNoContent)+ },+ )++ mux.HandleFunc(+ "POST /api/v1/agent/verification/{agentId}/heartbeat",+ func(w http.ResponseWriter, _ *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(map[string]any{+ "lastSeenAt": time.Now().UTC(),+ "abortVerificationIds": []uuid.UUID{},+ })+ },+ )++ return backend, httptest.NewServer(mux)+}++func (b *concurrentRestoreBackend) reportsSnapshot() map[uuid.UUID]api.VerificationStatus {+ b.mu.Lock()+ defer b.mu.Unlock()++ out := make(map[uuid.UUID]api.VerificationStatus, len(b.reports))+ for id, status := range b.reports {+ out[id] = status+ }++ return out+}++type recordingContainer struct {+ id int+ inContainerConn dbconn.Conn+ verifierConn dbconn.Conn+ terminated atomic.Bool+}++func (c *recordingContainer) Exec(+ _ context.Context, _ []string, stdin io.Reader, _ []string,+) (restore.ExecResult, error) {+ if stdin != nil {+ _, _ = io.Copy(io.Discard, stdin)+ }++ return restore.ExecResult{}, nil+}++func (c *recordingContainer) GetInContainerConn() dbconn.Conn { return c.inContainerConn }+func (c *recordingContainer) GetVerifierConn() dbconn.Conn { return c.verifierConn }++func (c *recordingContainer) GetDiskUsageBytes(context.Context) (int64, error) {+ return 0, nil+}++func (c *recordingContainer) Terminate(context.Context) error {+ c.terminated.Store(true)+ return nil+}++type recordingSpawner struct {+ nextID atomic.Int32++ mu sync.Mutex+ containers []*recordingContainer+}++func (s *recordingSpawner) Spawn(_ context.Context, _ SpawnRequest) (JobContainer, error) {+ c := &recordingContainer{+ id: int(s.nextID.Add(1)),+ inContainerConn: testConn(),+ verifierConn: testConn(),+ }++ s.mu.Lock()+ s.containers = append(s.containers, c)+ s.mu.Unlock()++ return c, nil+}++func (s *recordingSpawner) snapshot() []*recordingContainer {+ s.mu.Lock()+ defer s.mu.Unlock()++ out := make([]*recordingContainer, len(s.containers))+ copy(out, s.containers)++ return out+}++type barrierRestorer struct {+ barrier *sync.WaitGroup+}++func (r *barrierRestorer) StageBackupViaExec(+ _ context.Context, _ restore.ExecRunner, body io.Reader, _ string,+) error {+ if body != nil {+ _, _ = io.Copy(io.Discard, body)+ }++ return nil+}++func (r *barrierRestorer) RunPgRestore(+ _ context.Context, _ restore.ExecRunner, _ string, _ dbconn.Conn, _ int,+) (restore.Result, error) {+ r.barrier.Done()+ r.barrier.Wait()++ return restore.Result{PgRestoreExitCode: 0, DurationMs: 1}, nil+}++func makeConcurrentAssignment(id uuid.UUID) *api.JobAssignment {+ return &api.JobAssignment{+ VerificationID: id,+ BackupID: uuid.New(),+ BackupSizeMb: 1,+ MaxContainerDiskMb: 0,+ Database: api.AssignedDatabase{+ Type: "POSTGRES",+ Postgresql: &api.AssignedPostgresql{Version: "16"},+ },+ }+}++func Test_Run_WhenTwoVerificationsClaimed_EachGetsIsolatedContainerAndBothComplete(+ t *testing.T,+) {+ id1, id2 := uuid.New(), uuid.New()+ claims := []*api.JobAssignment{+ makeConcurrentAssignment(id1),+ makeConcurrentAssignment(id2),+ }++ backend, server := newConcurrentRestoreBackend(claims)+ t.Cleanup(server.Close)++ client := api.NewClient(server.URL, "", uuid.NewString(), testutil.DiscardLogger())+ heartbeater := heartbeat.NewHeartbeater(client, testCapacity(), testutil.DiscardLogger())++ spawner := &recordingSpawner{}+ barrier := &sync.WaitGroup{}+ barrier.Add(2)++ runnerUnderTest := NewRunner(+ client, testCapacity(), NewPool(2),+ spawner,+ &barrierRestorer{barrier: barrier},+ &fakeStats{stats: verifier.Stats{DBSizeBytes: 1, SchemaCount: 1, TableCount: 1}},+ heartbeater,+ testutil.DiscardLogger(),+ )+ runnerUnderTest.connAlive = func(context.Context, dbconn.Conn) bool { return true }++ runCtx, runCancel := context.WithCancel(t.Context())+ runDone := make(chan struct{})+ go func() {+ runnerUnderTest.Run(runCtx)+ close(runDone)+ }()++ require.Eventually(t, func() bool {+ snapshot := backend.reportsSnapshot()+ return snapshot[id1] == api.VerificationStatusCompleted &&+ snapshot[id2] == api.VerificationStatusCompleted+ }, 10*time.Second, 20*time.Millisecond,+ "both verifications must complete via the real claim loop + NewPool(2) fan-out; "++ "the barrier in pg_restore would deadlock unless both jobs were truly in flight at once")++ runCancel()+ select {+ case <-runDone:+ case <-time.After(5 * time.Second):+ t.Fatal("Run did not return after context cancellation")+ }++ spawned := spawner.snapshot()+ require.Len(t, spawned, 2,+ "each claimed verification must spawn its own container — proves isolation, not reuse")+ assert.NotEqual(t, spawned[0].id, spawned[1].id,+ "the two spawned containers must be distinct instances")+ for _, c := range spawned {+ assert.True(t, c.terminated.Load(),+ "every spawned container must be torn down (deferred Terminate in executeJob)")+ }++ reports := backend.reportsSnapshot()+ assert.Equal(t, api.VerificationStatusCompleted, reports[id1])+ assert.Equal(t, api.VerificationStatusCompleted, reports[id2])+}diff --git a/agent/verification/internal/features/runner/diskwatch.go b/agent/verification/internal/features/runner/diskwatch.gonew file mode 100644index 00000000..0fd5f120--- /dev/null+++ b/agent/verification/internal/features/runner/diskwatch.go@@ -0,0 +1,60 @@+package runner++import (+ "context"+ "fmt"+ "log/slog"+ "time"+)++var diskWatchInterval = 3 * time.Second++// diskWatcher polls the job's written bytes and fires onLimitExceeded once when+// the footprint reaches the server-computed ceiling. It never trips on a probe+// error (a transient daemon hiccup must not fail a healthy restore). The caller+// owns the reaction: onLimitExceeded records the trip and cancels the job.+type diskWatcher struct {+ probe diskUsageProber+ ceilingBytes int64+ interval time.Duration+ onLimitExceeded func()+ log *slog.Logger+}++func newDiskWatcher(+ probe diskUsageProber, ceilingBytes int64, onLimitExceeded func(), log *slog.Logger,+) *diskWatcher {+ return &diskWatcher{+ probe: probe,+ ceilingBytes: ceilingBytes,+ interval: diskWatchInterval,+ onLimitExceeded: onLimitExceeded,+ log: log,+ }+}++func (w *diskWatcher) run(ctx context.Context) {+ ticker := time.NewTicker(w.interval)+ defer ticker.Stop()++ for {+ used, err := w.probe.GetDiskUsageBytes(ctx)+ switch {+ case err != nil:+ w.log.Debug("disk watch probe failed, will retry next tick", "error", err)+ case used >= w.ceilingBytes:+ w.log.Warn(fmt.Sprintf(+ "job disk usage %d bytes reached ceiling %d bytes; aborting restore",+ used, w.ceilingBytes))+ w.onLimitExceeded()++ return+ }++ select {+ case <-ctx.Done():+ return+ case <-ticker.C:+ }+ }+}diff --git a/agent/verification/internal/features/runner/diskwatch_test.go b/agent/verification/internal/features/runner/diskwatch_test.gonew file mode 100644index 00000000..d7f700bb--- /dev/null+++ b/agent/verification/internal/features/runner/diskwatch_test.go@@ -0,0 +1,139 @@+package runner++import (+ "context"+ "errors"+ "sync"+ "sync/atomic"+ "testing"+ "time"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ "databasus-verification-agent/internal/testutil"+)++type fakeDiskProbe struct {+ mu sync.Mutex+ values []int64+ errs []error+ calls int+}++func (p *fakeDiskProbe) GetDiskUsageBytes(context.Context) (int64, error) {+ p.mu.Lock()+ defer p.mu.Unlock()++ i := p.calls+ if i >= len(p.values) {+ i = len(p.values) - 1+ }++ p.calls++++ var err error+ if p.calls-1 < len(p.errs) {+ err = p.errs[p.calls-1]+ }++ return p.values[i], err+}++func newTestDiskWatcher(probe diskUsageProber, ceilingBytes int64, onLimitExceeded func()) *diskWatcher {+ w := newDiskWatcher(probe, ceilingBytes, onLimitExceeded, testutil.DiscardLogger())+ w.interval = time.Millisecond++ return w+}++func Test_DiskWatcher_WhenUsageReachesCeiling_FiresOnce(t *testing.T) {+ var fired atomic.Int32+ done := make(chan struct{})++ w := newTestDiskWatcher(+ &fakeDiskProbe{values: []int64{100}}, 100,+ func() { fired.Add(1); close(done) },+ )++ go w.run(t.Context())++ select {+ case <-done:+ case <-time.After(2 * time.Second):+ t.Fatal("watcher never fired despite usage at ceiling")+ }++ time.Sleep(20 * time.Millisecond)+ assert.Equal(t, int32(1), fired.Load(), "onLimitExceeded must fire exactly once")+}++func Test_DiskWatcher_WhenUsageBelowCeiling_NeverFires(t *testing.T) {+ var fired atomic.Int32+ ctx, cancel := context.WithCancel(t.Context())++ w := newTestDiskWatcher(+ &fakeDiskProbe{values: []int64{50}}, 100,+ func() { fired.Add(1) },+ )++ stopped := make(chan struct{})+ go func() { w.run(ctx); close(stopped) }()++ time.Sleep(30 * time.Millisecond)+ cancel()++ select {+ case <-stopped:+ case <-time.After(2 * time.Second):+ t.Fatal("watcher did not stop on context cancel")+ }++ assert.Equal(t, int32(0), fired.Load(), "must not fire while under the ceiling")+}++func Test_DiskWatcher_WhenProbeErrorsThenRecovers_DoesNotTripOnError(t *testing.T) {+ var fired atomic.Int32+ done := make(chan struct{})++ probe := &fakeDiskProbe{+ values: []int64{0, 0, 200},+ errs: []error{errors.New("daemon busy"), errors.New("daemon busy"), nil},+ }++ w := newTestDiskWatcher(probe, 100, func() { fired.Add(1); close(done) })++ go w.run(t.Context())++ select {+ case <-done:+ case <-time.After(2 * time.Second):+ t.Fatal("watcher never fired after probe recovered above ceiling")+ }++ assert.Equal(t, int32(1), fired.Load(),+ "a probe error must not trip the watcher nor stop the loop")+}++func Test_DiskWatcher_WhenContextCancelled_StopsWithoutFiring(t *testing.T) {+ var fired atomic.Int32+ ctx, cancel := context.WithCancel(t.Context())++ w := newTestDiskWatcher(+ &fakeDiskProbe{values: []int64{10}}, 100,+ func() { fired.Add(1) },+ )++ stopped := make(chan struct{})+ go func() { w.run(ctx); close(stopped) }()++ cancel()++ select {+ case <-stopped:+ case <-time.After(2 * time.Second):+ t.Fatal("watcher did not return after context cancel")+ }++ require.Equal(t, int32(0), fired.Load())+}diff --git a/agent/verification/internal/features/runner/fakes_test.go b/agent/verification/internal/features/runner/fakes_test.gonew file mode 100644index 00000000..562cf25a--- /dev/null+++ b/agent/verification/internal/features/runner/fakes_test.go@@ -0,0 +1,203 @@+package runner++import (+ "bytes"+ "context"+ "io"+ "sync"+ "sync/atomic"++ "github.com/google/uuid"++ "databasus-verification-agent/internal/features/api"+ "databasus-verification-agent/internal/features/dbconn"+ "databasus-verification-agent/internal/features/restore"+ "databasus-verification-agent/internal/features/verifier"+)++type fakeAPI struct {+ mu sync.Mutex++ claims []*api.JobAssignment+ claimErrs []error+ claimIdx int++ downloadBody []byte+ downloadErr error++ reportErr error+ reportedReqs []api.ReportRequest+ reportedIDs []uuid.UUID+ reportCalled int+}++func (f *fakeAPI) ClaimVerification(+ _ context.Context, _ api.AgentCapacity,+) (*api.JobAssignment, error) {+ f.mu.Lock()+ defer f.mu.Unlock()++ i := f.claimIdx+ f.claimIdx++++ if i < len(f.claimErrs) && f.claimErrs[i] != nil {+ return nil, f.claimErrs[i]+ }++ if i < len(f.claims) {+ return f.claims[i], nil+ }++ return nil, nil+}++func (f *fakeAPI) DownloadBackup(+ _ context.Context, _ uuid.UUID,+) (io.ReadCloser, error) {+ if f.downloadErr != nil {+ return nil, f.downloadErr+ }++ return io.NopCloser(bytes.NewReader(f.downloadBody)), nil+}++func (f *fakeAPI) Report(+ _ context.Context, verificationID uuid.UUID, req api.ReportRequest,+) error {+ f.mu.Lock()+ defer f.mu.Unlock()++ f.reportCalled+++ f.reportedReqs = append(f.reportedReqs, req)+ f.reportedIDs = append(f.reportedIDs, verificationID)++ return f.reportErr+}++func (f *fakeAPI) lastReport() (api.ReportRequest, bool) {+ f.mu.Lock()+ defer f.mu.Unlock()++ if len(f.reportedReqs) == 0 {+ return api.ReportRequest{}, false+ }++ return f.reportedReqs[len(f.reportedReqs)-1], true+}++type fakeContainer struct {+ inContainerConn dbconn.Conn+ verifierConn dbconn.Conn+ terminated bool+ diskUsageBytes int64+ diskUsageErr error+}++func (c *fakeContainer) Exec(+ _ context.Context, _ []string, stdin io.Reader, _ []string,+) (restore.ExecResult, error) {+ if stdin != nil {+ _, _ = io.Copy(io.Discard, stdin)+ }++ return restore.ExecResult{}, nil+}++func (c *fakeContainer) GetInContainerConn() dbconn.Conn { return c.inContainerConn }+func (c *fakeContainer) GetVerifierConn() dbconn.Conn { return c.verifierConn }++func (c *fakeContainer) GetDiskUsageBytes(context.Context) (int64, error) {+ return c.diskUsageBytes, c.diskUsageErr+}++func (c *fakeContainer) Terminate(context.Context) error {+ c.terminated = true+ return nil+}++type fakeSpawner struct {+ container JobContainer+ err error+}++func (s *fakeSpawner) Spawn(_ context.Context, _ SpawnRequest) (JobContainer, error) {+ if s.err != nil {+ return nil, s.err+ }++ return s.container, nil+}++type fakeRestorer struct {+ stageErr error+ runResult restore.Result+ runErr error+ runBlocks bool++ runEntered atomic.Bool+ runCtxCancelled atomic.Bool+}++func (r *fakeRestorer) StageBackupViaExec(+ _ context.Context, _ restore.ExecRunner, body io.Reader, _ string,+) error {+ if body != nil {+ _, _ = io.Copy(io.Discard, body)+ }++ return r.stageErr+}++func (r *fakeRestorer) RunPgRestore(+ ctx context.Context, _ restore.ExecRunner, _ string, _ dbconn.Conn, _ int,+) (restore.Result, error) {+ if r.runBlocks {+ r.runEntered.Store(true)+ <-ctx.Done()+ r.runCtxCancelled.Store(true)++ return restore.Result{}, ctx.Err()+ }++ return r.runResult, r.runErr+}++type fakeStats struct {+ stats verifier.Stats+ err error+}++func (s *fakeStats) CollectStats(context.Context, dbconn.Conn) (verifier.Stats, error) {+ return s.stats, s.err+}++type fakeRegistrar struct {+ mu sync.Mutex+ registered map[uuid.UUID]struct{}+ aborted bool+}++func newFakeRegistrar() *fakeRegistrar {+ return &fakeRegistrar{registered: make(map[uuid.UUID]struct{})}+}++func (r *fakeRegistrar) TrackVerification(id uuid.UUID, _ context.CancelFunc) {+ r.mu.Lock()+ defer r.mu.Unlock()++ r.registered[id] = struct{}{}+}++func (r *fakeRegistrar) UntrackVerification(id uuid.UUID) {+ r.mu.Lock()+ defer r.mu.Unlock()++ delete(r.registered, id)+}++func (r *fakeRegistrar) IsAborted(uuid.UUID) bool {+ r.mu.Lock()+ defer r.mu.Unlock()++ return r.aborted+}diff --git a/agent/verification/internal/features/runner/interfaces.go b/agent/verification/internal/features/runner/interfaces.gonew file mode 100644index 00000000..17cf7fee--- /dev/null+++ b/agent/verification/internal/features/runner/interfaces.go@@ -0,0 +1,59 @@+package runner++import (+ "context"+ "io"++ "github.com/google/uuid"++ "databasus-verification-agent/internal/features/api"+ "databasus-verification-agent/internal/features/dbconn"+ "databasus-verification-agent/internal/features/restore"+ "databasus-verification-agent/internal/features/verifier"+)++type JobContainer interface {+ Exec(ctx context.Context, cmd []string, stdin io.Reader, env []string) (restore.ExecResult, error)+ GetInContainerConn() dbconn.Conn+ GetVerifierConn() dbconn.Conn+ GetDiskUsageBytes(ctx context.Context) (int64, error)+ Terminate(ctx context.Context) error+}++type Spawner interface {+ Spawn(ctx context.Context, req SpawnRequest) (JobContainer, error)+}++type APIClient interface {+ ClaimVerification(ctx context.Context, capacity api.AgentCapacity) (*api.JobAssignment, error)+ DownloadBackup(ctx context.Context, verificationID uuid.UUID) (io.ReadCloser, error)+ Report(ctx context.Context, verificationID uuid.UUID, req api.ReportRequest) error+}++type Restorer interface {+ StageBackupViaExec(ctx context.Context, exec restore.ExecRunner, body io.Reader, destPath string) error+ RunPgRestore(+ ctx context.Context,+ exec restore.ExecRunner,+ archivePath string,+ conn dbconn.Conn,+ parallelJobs int,+ ) (restore.Result, error)+}++type StatsCollector interface {+ CollectStats(ctx context.Context, conn dbconn.Conn) (verifier.Stats, error)+}++// Registrar is the heartbeat registry seam: register before any container+// exists so the ID rides every heartbeat, and re-check the recorded abort set+// before any FAILED POST.+type Registrar interface {+ TrackVerification(id uuid.UUID, cancel context.CancelFunc)+ UntrackVerification(id uuid.UUID)+ IsAborted(id uuid.UUID) bool+}++type diskUsageProber interface {+ GetDiskUsageBytes(ctx context.Context) (int64, error)+}diff --git a/agent/verification/internal/features/runner/pool.go b/agent/verification/internal/features/runner/pool.gonew file mode 100644index 00000000..8dfedd45--- /dev/null+++ b/agent/verification/internal/features/runner/pool.go@@ -0,0 +1,45 @@+package runner++import "sync"++// Pool is a plain bounded-concurrency semaphore. There is deliberately no+// disk math here — the server is the sole disk-admission authority; the pool+// only caps how many verifications run at once.+type Pool struct {+ slots chan struct{}+ wg sync.WaitGroup+}++func NewPool(maxConcurrentJobs int) *Pool {+ return &Pool{slots: make(chan struct{}, maxConcurrentJobs)}+}++func (p *Pool) Saturated() bool {+ return len(p.slots) == cap(p.slots)+}++// Go acquires a slot and runs fn in a goroutine, releasing the slot when fn+// returns. The runner loop is the only producer and only calls Go after+// Saturated() == false, so the send never blocks in practice.+//+// There is deliberately no recover() here. Container freshness has no periodic+// reaper — it relies on the invariant that any lost container is followed by a+// process restart (then the startup purge cleans up). A panicking job must+// therefore crash the process. Adding recovery would let a long-lived process+// leak a container with no safety net; restore a sweep before doing so.+func (p *Pool) Go(fn func()) {+ p.slots <- struct{}{}++ p.wg.Go(func() {+ defer func() { <-p.slots }()++ fn()+ })+}++// Wait blocks until every in-flight job has returned. The runner calls it on+// shutdown so deferred container teardown runs before the process exits or+// re-execs on self-update.+func (p *Pool) Wait() {+ p.wg.Wait()+}diff --git a/agent/verification/internal/features/runner/pool_test.go b/agent/verification/internal/features/runner/pool_test.gonew file mode 100644index 00000000..f84aa221--- /dev/null+++ b/agent/verification/internal/features/runner/pool_test.go@@ -0,0 +1,59 @@+package runner++import (+ "sync"+ "sync/atomic"+ "testing"++ "github.com/stretchr/testify/assert"+)++func Test_Pool_Saturated_ReflectsSlotOccupancyAsJobsStartAndFinish(t *testing.T) {+ pool := NewPool(2)+ assert.False(t, pool.Saturated())++ release := make(chan struct{})+ var started sync.WaitGroup+ started.Add(2)++ for range 2 {+ pool.Go(func() {+ started.Done()+ <-release+ })+ }++ started.Wait()+ assert.True(t, pool.Saturated(), "pool must report saturated at MaxConcurrentJobs")++ close(release)+ pool.Wait()+ assert.False(t, pool.Saturated(), "slots must be released when jobs finish")+}++func Test_Pool_WhenFloodedWithJobs_NeverExceedsCapAndWaitDrainsAll(t *testing.T) {+ const capLimit = 4+ pool := NewPool(capLimit)++ var concurrent, maxConcurrent atomic.Int32++ for range 100 {+ pool.Go(func() {+ cur := concurrent.Add(1)+ for {+ observed := maxConcurrent.Load()+ if cur <= observed || maxConcurrent.CompareAndSwap(observed, cur) {+ break+ }+ }++ concurrent.Add(-1)+ })+ }++ pool.Wait()++ assert.LessOrEqual(t, int(maxConcurrent.Load()), capLimit,+ "concurrency must never exceed the slot count")+ assert.Equal(t, int32(0), concurrent.Load(), "Wait must drain every job")+}diff --git a/agent/verification/internal/features/runner/report_giveup_integration_test.go b/agent/verification/internal/features/runner/report_giveup_integration_test.gonew file mode 100644index 00000000..5c4aca7c--- /dev/null+++ b/agent/verification/internal/features/runner/report_giveup_integration_test.go@@ -0,0 +1,155 @@+package runner++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "sync"+ "sync/atomic"+ "testing"+ "time"++ "github.com/google/uuid"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ "databasus-verification-agent/internal/features/api"+ "databasus-verification-agent/internal/features/dbconn"+ "databasus-verification-agent/internal/features/heartbeat"+ "databasus-verification-agent/internal/features/restore"+ "databasus-verification-agent/internal/features/verifier"+ "databasus-verification-agent/internal/testutil"+)++type giveupMockBackend struct {+ mu sync.Mutex+ heartbeatCount int+ lastHeartbeatIDs []uuid.UUID++ reportHits atomic.Int32+ secondReport chan struct{}+ signalSecondOnce sync.Once+}++func newGiveupMockBackend() (*giveupMockBackend, *httptest.Server) {+ backend := &giveupMockBackend{secondReport: make(chan struct{})}++ mux := http.NewServeMux()++ mux.HandleFunc(+ "GET /api/v1/agent/verifications/{agentId}/{id}/backup-stream",+ func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte("ARCHIVE"))+ },+ )++ mux.HandleFunc(+ "POST /api/v1/agent/verifications/{agentId}/{id}/report",+ func(w http.ResponseWriter, _ *http.Request) {+ if backend.reportHits.Add(1) == 2 {+ backend.signalSecondOnce.Do(func() { close(backend.secondReport) })+ }++ w.WriteHeader(http.StatusServiceUnavailable)+ },+ )++ mux.HandleFunc(+ "POST /api/v1/agent/verification/{agentId}/heartbeat",+ func(w http.ResponseWriter, req *http.Request) {+ var body struct {+ CurrentVerificationIDs []uuid.UUID `json:"currentVerificationIds"`+ }+ _ = json.NewDecoder(req.Body).Decode(&body)++ backend.mu.Lock()+ backend.heartbeatCount+++ backend.lastHeartbeatIDs = body.CurrentVerificationIDs+ backend.mu.Unlock()++ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(map[string]any{+ "lastSeenAt": time.Now().UTC(),+ "abortVerificationIds": []uuid.UUID{},+ })+ },+ )++ return backend, httptest.NewServer(mux)+}++func (b *giveupMockBackend) heartbeatsSeen() int {+ b.mu.Lock()+ defer b.mu.Unlock()++ return b.heartbeatCount+}++func (b *giveupMockBackend) lastHeartbeatVerificationIDs() []uuid.UUID {+ b.mu.Lock()+ defer b.mu.Unlock()++ return b.lastHeartbeatIDs+}++func Test_ExecuteJob_WhenReportGivenUp_UnregistersAndHeartbeatOmitsJob(t *testing.T) {+ backend, server := newGiveupMockBackend()+ t.Cleanup(server.Close)++ client := api.NewClient(server.URL, "", uuid.NewString(), testutil.DiscardLogger())+ heartbeater := heartbeat.NewHeartbeater(client, testCapacity(), testutil.DiscardLogger())++ runnerUnderTest := NewRunner(+ client, testCapacity(), NewPool(2),+ okSpawner(),+ &fakeRestorer{runResult: restore.Result{PgRestoreExitCode: 0}},+ &fakeStats{stats: verifier.Stats{+ DBSizeBytes: 9_000_000,+ SchemaCount: 2,+ TableCount: 3,+ TableStats: []verifier.TableStat{{SchemaName: "public", Name: "t1", RowCount: 10}},+ }},+ heartbeater,+ testutil.DiscardLogger(),+ )+ runnerUnderTest.connAlive = func(context.Context, dbconn.Conn) bool { return true }++ job := postgresJob()++ ctx, cancel := context.WithCancel(t.Context())+ defer cancel()++ go func() {+ select {+ case <-backend.secondReport:+ cancel()+ case <-ctx.Done():+ }+ }()++ runnerUnderTest.executeJob(ctx, job)++ assert.GreaterOrEqual(t, backend.reportHits.Load(), int32(2),+ "the real report retry loop must have actually retried against the unresponsive server")+ assert.NotContains(t, heartbeater.GetRunningVerificationIDs(), job.VerificationID,+ "report give-up must untrack the job from the real heartbeat registry")++ beatCtx, beatCancel := context.WithCancel(t.Context())+ beatDone := make(chan struct{})+ go func() {+ heartbeater.Run(beatCtx)+ close(beatDone)+ }()++ require.Eventually(t, func() bool { return backend.heartbeatsSeen() > 0 },+ 2*time.Second, 10*time.Millisecond,+ "the real Heartbeater must send at least one heartbeat")++ beatCancel()+ <-beatDone++ assert.NotContains(t, backend.lastHeartbeatVerificationIDs(), job.VerificationID,+ "after give-up the real heartbeat wire must no longer carry the dropped job")+}diff --git a/agent/verification/internal/features/runner/runner.go b/agent/verification/internal/features/runner/runner.gonew file mode 100644index 00000000..acabcc61--- /dev/null+++ b/agent/verification/internal/features/runner/runner.go@@ -0,0 +1,533 @@+package runner++import (+ "context"+ "errors"+ "fmt"+ "log/slog"+ "slices"+ "sync/atomic"+ "time"++ "github.com/google/uuid"++ "databasus-verification-agent/internal/config"+ "databasus-verification-agent/internal/features/api"+ "databasus-verification-agent/internal/features/dbconn"+ "databasus-verification-agent/internal/features/restore"+ "databasus-verification-agent/internal/features/verifier"+)++const (+ jobName = "verification_runner"++ claimErrorBackoff = 5 * time.Second+ idleClaimBackoff = 15 * time.Second+ maxBackupDownloadAttempts = 5+ streamIdleTimeout = 60 * time.Second+ maxBackupDownloadBackoff = 32 * time.Second++ // archive layout inside the per-job container's writable volume.+ inContainerArchiveDir = "/tmp"++ maxParallelRestoreJobs = 8+)++var supportedMajors = []string{"12", "13", "14", "15", "16", "17", "18"}++// errAbortNoReport signals the job was aborted (jobCtx cancelled, or the+// stream returned 410) — executeJob returns without POSTing a report.+var errAbortNoReport = errors.New("verification aborted; no report")++// backupDownloadBackoffFn is the download retry delay; tests swap it to avoid real sleeps.+var backupDownloadBackoffFn = backupDownloadBackoff++type SpawnRequest struct {+ PgMajor string+ CPUPerJob int+ RAMMbPerJob int+ VerificationID uuid.UUID+}++type Runner struct {+ api APIClient+ capacity config.Capacity+ pool *Pool+ spawner Spawner+ restorer Restorer+ verifier StatsCollector+ heartbeat Registrar+ connAlive func(ctx context.Context, conn dbconn.Conn) bool+ hasRun atomic.Bool+ log *slog.Logger+}++func NewRunner(+ apiClient APIClient,+ capacity config.Capacity,+ pool *Pool,+ spawner Spawner,+ restorer Restorer,+ statsCollector StatsCollector,+ heartbeat Registrar,+ log *slog.Logger,+) *Runner {+ return &Runner{+ api: apiClient,+ capacity: capacity,+ pool: pool,+ spawner: spawner,+ restorer: restorer,+ verifier: statsCollector,+ heartbeat: heartbeat,+ connAlive: verifier.ProbeConnAlive,+ log: log,+ }+}++func (r *Runner) Run(ctx context.Context) {+ if r.hasRun.Swap(true) {+ panic(fmt.Sprintf("%T.Run() called multiple times", r))+ }++ logger := r.log.With("job_id", uuid.New(), "job_name", jobName)+ logger.Info("runner loop started")++ for ctx.Err() == nil {+ // Gate claiming on local capacity so we never hold a server-claimed+ // job we cannot start immediately.+ if r.pool.Saturated() {+ if !sleepOrDone(ctx, 1*time.Second) {+ break+ }++ continue+ }++ capacity := api.AgentCapacity{+ MaxCPU: r.capacity.MaxCPU,+ MaxRAMMb: r.capacity.MaxRAMMb,+ MaxDiskGb: r.capacity.MaxDiskGb,+ MaxConcurrentJobs: r.capacity.MaxConcurrentJobs,+ }++ assignment, err := r.api.ClaimVerification(ctx, capacity)+ if err != nil {+ logger.Warn("claim failed", "error", err)++ if !sleepOrDone(ctx, claimErrorBackoff) {+ break+ }++ continue+ }++ if assignment == nil {+ if !sleepOrDone(ctx, idleClaimBackoff) {+ break+ }++ continue+ }++ r.pool.Go(func() { r.executeJob(ctx, assignment) })+ }++ logger.Info("runner loop draining in-flight jobs")+ r.pool.Wait()+ logger.Info("runner loop stopped")+}++func (r *Runner) executeJob(ctx context.Context, job *api.JobAssignment) {+ runLogger := r.log.With(+ "job_id", uuid.New(),+ "job_name", jobName,+ "verification_id", job.VerificationID,+ )++ jobCtx, cancel := context.WithCancel(ctx)+ defer cancel()++ // Register FIRST so the ID is in the heartbeat envelope before any+ // container exists: the backend must never see an artifact-bearing job+ // that is absent from this agent's reported in-flight set.+ r.heartbeat.TrackVerification(job.VerificationID, cancel)+ defer r.heartbeat.UntrackVerification(job.VerificationID)++ pgMajor, err := pgMajorFromDatabase(job.Database)+ if err != nil {+ r.reportFailure(ctx, job.VerificationID, nil, fmt.Sprintf("resolve pg major: %v", err), runLogger)++ return+ }++ jobContainer, err := r.spawner.Spawn(jobCtx, SpawnRequest{+ PgMajor: pgMajor,+ CPUPerJob: r.capacity.CPUPerJob,+ RAMMbPerJob: r.capacity.RAMMbPerJob,+ VerificationID: job.VerificationID,+ })+ if err != nil {+ if jobCtx.Err() != nil {+ return+ }++ r.reportFailure(ctx, job.VerificationID, nil, fmt.Sprintf("spawn container: %v", err), runLogger)++ return+ }++ defer func() {+ if termErr := jobContainer.Terminate(ctx); termErr != nil {+ runLogger.Error("failed to terminate container", "error", termErr)+ }+ }()++ // Server-authoritative per-job disk budget (downloaded archive + restored+ // DB + safe gap). The agent enforces it by watching the container's written+ // bytes and aborting the instant the budget is reached — uniform on every+ // storage driver, unlike a Docker --storage-opt cap.+ diskBudgetMb := int64(job.MaxContainerDiskMb)+ diskBudgetFailMessage := fmt.Sprintf("restore exceeded the per-job disk budget of %d MB", diskBudgetMb)++ var isDiskLimitHit atomic.Bool++ // A zero/absent budget (older backend) means no enforceable ceiling — skip+ // the watcher rather than trip instantly on used >= 0.+ if diskBudgetMb > 0 {+ watchCtx, watchStop := context.WithCancel(jobCtx)+ defer watchStop()++ go newDiskWatcher(+ jobContainer, diskBudgetMb*1024*1024,+ func() { isDiskLimitHit.Store(true); cancel() },+ runLogger,+ ).run(watchCtx)+ } else {+ runLogger.Warn("no per-job disk budget from server; disk watcher disabled for this job")+ }++ archivePath := fmt.Sprintf("%s/%s.dump", inContainerArchiveDir, job.VerificationID)++ if err := r.downloadBackupIntoContainer(+ jobCtx,+ jobContainer,+ job.VerificationID,+ archivePath,+ runLogger,+ ); err != nil {+ if isDiskLimitHit.Load() {+ r.reportDiskLimitExceeded(ctx, job.VerificationID, diskBudgetFailMessage, runLogger)++ return+ }++ if errors.Is(err, errAbortNoReport) {+ return+ }++ r.reportFailure(ctx, job.VerificationID, nil, fmt.Sprintf("download backup: %v", err), runLogger)++ return+ }++ parallelJobs := min(maxParallelRestoreJobs, r.capacity.CPUPerJob)++ restoreResult, err := r.restorer.RunPgRestore(+ jobCtx, jobContainer, archivePath, jobContainer.GetInContainerConn(), parallelJobs)+ if err != nil {+ if isDiskLimitHit.Load() {+ r.reportDiskLimitExceeded(ctx, job.VerificationID, diskBudgetFailMessage, runLogger)++ return+ }++ if jobCtx.Err() != nil {+ 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)++ return+ }++ runLogger.Error("pg_restore failed",+ "exit_code", restoreResult.PgRestoreExitCode,+ "stderr_tail", restoreResult.StderrTail)++ r.reportFailure(ctx, job.VerificationID, &restoreResult,+ fmt.Sprintf("pg_restore failed: %v", err), runLogger)++ return+ }++ // Exec-infrastructure failure (no usable exit code).+ r.reportFailure(ctx, job.VerificationID, nil,+ fmt.Sprintf("pg_restore exec: %v", err), runLogger)++ return+ }++ verifierConn := jobContainer.GetVerifierConn()++ stats, err := r.verifier.CollectStats(jobCtx, verifierConn)+ if err != nil {+ if isDiskLimitHit.Load() {+ r.reportDiskLimitExceeded(ctx, job.VerificationID, diskBudgetFailMessage, runLogger)++ return+ }++ if jobCtx.Err() != nil {+ return+ }++ if !r.connAlive(jobCtx, verifierConn) {+ r.reportFailure(ctx, job.VerificationID, nil,+ fmt.Sprintf("verify (conn dead): %v", err), runLogger)++ return+ }++ r.reportFailure(ctx, job.VerificationID, &restoreResult,+ fmt.Sprintf("verify: %v", err), runLogger)++ return+ }++ if isDiskLimitHit.Load() {+ r.reportDiskLimitExceeded(ctx, job.VerificationID, diskBudgetFailMessage, runLogger)++ return+ }++ r.reportSuccess(ctx, job.VerificationID, restoreResult, stats, runLogger)+}++func (r *Runner) downloadBackupIntoContainer(+ jobCtx context.Context,+ jobContainer JobContainer,+ verificationID uuid.UUID,+ archivePath string,+ logger *slog.Logger,+) error {+ var lastErr error++ for attempt := 1; attempt <= maxBackupDownloadAttempts; attempt++ {+ if jobCtx.Err() != nil {+ return errAbortNoReport+ }++ err := r.downloadBackupIntoContainerOnce(jobCtx, jobContainer, verificationID, archivePath)+ if err == nil {+ return nil+ }++ var respErr *api.ResponseError+ if errors.As(err, &respErr) {+ if respErr.IsGone() {+ logger.Info("backup stream gone (410); dropping without report")++ return errAbortNoReport+ }++ if !respErr.Retryable() {+ return fmt.Errorf("backup stream non-retryable: %w", err)+ }+ }++ lastErr = err+ logger.Warn("backup stream attempt failed",+ "attempt", attempt, "max_attempts", maxBackupDownloadAttempts, "error", err)++ if !sleepOrDone(jobCtx, backupDownloadBackoffFn(attempt)) {+ return errAbortNoReport+ }+ }++ return fmt.Errorf("backup stream failed after %d attempts: %w", maxBackupDownloadAttempts, lastErr)+}++func (r *Runner) downloadBackupIntoContainerOnce(+ jobCtx context.Context,+ jobContainer JobContainer,+ verificationID uuid.UUID,+ archivePath string,+) error {+ body, err := r.api.DownloadBackup(jobCtx, verificationID)+ if err != nil {+ return err+ }+ defer func() { _ = body.Close() }()++ dlCtx, dlCancel := context.WithCancelCause(jobCtx)+ defer dlCancel(nil)++ idleReader := api.NewIdleTimeoutReader(body, streamIdleTimeout, dlCancel)+ defer idleReader.Stop()++ return r.restorer.StageBackupViaExec(dlCtx, jobContainer, idleReader, archivePath)+}++func (r *Runner) reportSuccess(+ ctx context.Context,+ verificationID uuid.UUID,+ restoreResult restore.Result,+ stats verifier.Stats,+ logger *slog.Logger,+) {+ tableStats := make([]api.ReportTableStat, 0, len(stats.TableStats))+ for _, ts := range stats.TableStats {+ tableStats = append(tableStats, api.ReportTableStat{+ SchemaName: ts.SchemaName,+ Name: ts.Name,+ RowCount: ts.RowCount,+ })+ }++ req := api.ReportRequest{+ Status: api.VerificationStatusCompleted,+ PgRestoreExitCode: &restoreResult.PgRestoreExitCode,+ RestoreDurationMs: &restoreResult.DurationMs,+ DBSizeBytesAfterRestore: &stats.DBSizeBytes,+ TableCount: &stats.TableCount,+ SchemaCount: &stats.SchemaCount,+ TableStats: tableStats,+ }++ r.sendReport(ctx, verificationID, req, logger)+}++func (r *Runner) reportFailure(+ ctx context.Context,+ verificationID uuid.UUID,+ restoreResult *restore.Result,+ failMessage string,+ logger *slog.Logger,+) {+ if r.shouldSkipFailedReport(ctx, verificationID, logger) {+ return+ }++ message := failMessage+ req := api.ReportRequest{+ Status: api.VerificationStatusFailed,+ FailMessage: &message,+ }++ if restoreResult != nil {+ req.PgRestoreExitCode = &restoreResult.PgRestoreExitCode+ req.RestoreDurationMs = &restoreResult.DurationMs+ }++ r.sendReport(ctx, verificationID, req, logger)+}++// reportDiskLimitExceeded posts the terminal disk-budget verdict. FailureKind+// makes the backend classify it DISK_LIMIT_EXCEEDED (terminal) instead of the+// retryable nil-exit-code path: the budget is server-computed, so retrying the+// same job against the same budget would fail identically.+func (r *Runner) reportDiskLimitExceeded(+ ctx context.Context,+ verificationID uuid.UUID,+ failMessage string,+ logger *slog.Logger,+) {+ if r.shouldSkipFailedReport(ctx, verificationID, logger) {+ return+ }++ message := failMessage+ kind := api.FailureKindDiskLimitExceeded+ r.sendReport(ctx, verificationID, api.ReportRequest{+ Status: api.VerificationStatusFailed,+ FailMessage: &message,+ FailureKind: &kind,+ }, logger)+}++// shouldSkipFailedReport is the abort/report-race guard (the only agent-side+// lever with a frozen FAILED path): never POST FAILED for an aborted/cancelled+// ID — a spurious FAILED would flip CANCELED→FAILED or resurrect a cancelled+// row.+func (r *Runner) shouldSkipFailedReport(+ ctx context.Context, verificationID uuid.UUID, logger *slog.Logger,+) bool {+ if ctx.Err() != nil || r.heartbeat.IsAborted(verificationID) {+ logger.Info("skipping FAILED report: verification aborted/cancelled")++ return true+ }++ return false+}++func (r *Runner) sendReport(+ ctx context.Context,+ verificationID uuid.UUID,+ req api.ReportRequest,+ logger *slog.Logger,+) {+ err := r.api.Report(ctx, verificationID, req)+ if err == nil {+ logger.Info(fmt.Sprintf("report accepted: status=%s", req.Status))++ return+ }++ switch {+ case errors.Is(err, api.ErrReportGone):+ logger.Info("report dropped: verification no longer owned by this agent (410)")+ case errors.Is(err, api.ErrReportBudgetExhausted):+ logger.Warn("report abandoned: retry budget exhausted; backend will reclaim on next heartbeat")+ default:+ logger.Warn("report failed", "error", err)+ }+}++func pgMajorFromDatabase(db api.AssignedDatabase) (string, error) {+ if db.Type != "POSTGRES" {+ return "", fmt.Errorf("unsupported database type %q (v1 is Postgres only)", db.Type)+ }++ if db.Postgresql == nil || db.Postgresql.Version == "" {+ return "", errors.New("assignment missing postgresql version")+ }++ if !slices.Contains(supportedMajors, db.Postgresql.Version) {+ return "", fmt.Errorf("unsupported postgres major %q", db.Postgresql.Version)+ }++ return db.Postgresql.Version, nil+}++func backupDownloadBackoff(attempt int) time.Duration {+ if attempt < 1 {+ attempt = 1+ }++ d := time.Duration(1<<attempt) * time.Second+ if d > maxBackupDownloadBackoff {+ return maxBackupDownloadBackoff+ }++ return d+}++func sleepOrDone(ctx context.Context, d time.Duration) bool {+ timer := time.NewTimer(d)+ defer timer.Stop()++ select {+ case <-ctx.Done():+ return false+ case <-timer.C:+ return true+ }+}diff --git a/agent/verification/internal/features/runner/runner_test.go b/agent/verification/internal/features/runner/runner_test.gonew file mode 100644index 00000000..973ff4fd--- /dev/null+++ b/agent/verification/internal/features/runner/runner_test.go@@ -0,0 +1,314 @@+package runner++import (+ "context"+ "errors"+ "fmt"+ "testing"+ "time"++ "github.com/google/uuid"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ "databasus-verification-agent/internal/config"+ "databasus-verification-agent/internal/features/api"+ "databasus-verification-agent/internal/features/dbconn"+ "databasus-verification-agent/internal/features/restore"+ "databasus-verification-agent/internal/features/verifier"+ "databasus-verification-agent/internal/testutil"+)++func testCapacity() config.Capacity {+ return config.Capacity{+ MaxCPU: 4, MaxRAMMb: 4096, MaxDiskGb: 50, MaxConcurrentJobs: 2,+ CPUPerJob: 2, RAMMbPerJob: 2048,+ }+}++func postgresJob() *api.JobAssignment {+ return &api.JobAssignment{+ VerificationID: uuid.New(),+ BackupID: uuid.New(),+ BackupSizeMb: 50,+ MaxContainerDiskMb: 200,+ Database: api.AssignedDatabase{+ Type: "POSTGRES",+ Postgresql: &api.AssignedPostgresql{Version: "16"},+ },+ }+}++func newTestRunner(+ apiClient APIClient, spawner Spawner, restorer Restorer,+ stats StatsCollector, reg Registrar,+) *Runner {+ return NewRunner(+ apiClient, testCapacity(), NewPool(2),+ spawner, restorer, stats, reg, testutil.DiscardLogger(),+ )+}++func testConn() dbconn.Conn {+ return dbconn.Conn{+ Host: "127.0.0.1", Port: 5432,+ User: "postgres", Password: "pw", Database: "postgres",+ }+}++func fakeContainerWith(conn dbconn.Conn) *fakeContainer {+ return &fakeContainer{inContainerConn: conn, verifierConn: conn}+}++func okSpawner() *fakeSpawner {+ return &fakeSpawner{container: fakeContainerWith(testConn())}+}++func Test_ExecuteJob_WhenPgMajorUnsupported_ReportsFailedWithoutExitCode(t *testing.T) {+ apiClient := &fakeAPI{}+ r := newTestRunner(apiClient, okSpawner(), &fakeRestorer{}, &fakeStats{}, newFakeRegistrar())++ job := postgresJob()+ job.Database.Type = "MYSQL"++ r.executeJob(t.Context(), job)++ report, ok := apiClient.lastReport()+ require.True(t, ok)+ assert.Equal(t, api.VerificationStatusFailed, report.Status)+ assert.Nil(t, report.PgRestoreExitCode)+}++func Test_ExecuteJob_WhenSpawnFails_ReportsFailedWithoutExitCode(t *testing.T) {+ apiClient := &fakeAPI{}+ spawner := &fakeSpawner{err: errors.New("image pull failed")}+ r := newTestRunner(apiClient, spawner, &fakeRestorer{}, &fakeStats{}, newFakeRegistrar())++ r.executeJob(t.Context(), postgresJob())++ report, ok := apiClient.lastReport()+ require.True(t, ok)+ assert.Equal(t, api.VerificationStatusFailed, report.Status)+ assert.Nil(t, report.PgRestoreExitCode)+}++func Test_ExecuteJob_WhenStreamReturns410_DoesNotReport(t *testing.T) {+ apiClient := &fakeAPI{downloadErr: &api.ResponseError{Op: "backup stream", StatusCode: 410}}+ r := newTestRunner(apiClient, okSpawner(), &fakeRestorer{}, &fakeStats{}, newFakeRegistrar())++ r.executeJob(t.Context(), postgresJob())++ assert.Equal(t, 0, apiClient.reportCalled, "a 410 on the stream is an abort — no report")+}++func Test_ExecuteJob_WhenStreamExhaustsRetries_ReportsFailedWithoutExitCode(t *testing.T) {+ original := backupDownloadBackoffFn+ backupDownloadBackoffFn = func(int) time.Duration { return 0 }+ t.Cleanup(func() { backupDownloadBackoffFn = original })++ apiClient := &fakeAPI{downloadErr: errors.New("connection refused")}+ r := newTestRunner(apiClient, okSpawner(), &fakeRestorer{}, &fakeStats{}, newFakeRegistrar())++ r.executeJob(t.Context(), postgresJob())++ report, ok := apiClient.lastReport()+ require.True(t, ok)+ assert.Equal(t, api.VerificationStatusFailed, report.Status)+ assert.Nil(t, report.PgRestoreExitCode)+}++func Test_ExecuteJob_WhenRestoreFailsAndDiskExhausted_ReportsFailedWithoutExitCode(t *testing.T) {+ apiClient := &fakeAPI{downloadBody: []byte("ARCHIVE")}+ restorer := &fakeRestorer{+ runErr: fmt.Errorf("restore: %w", restore.ErrRestoreFailed),+ runResult: restore.Result{PgRestoreExitCode: 1, StderrTail: "could not write: No space left on device"},+ }+ r := newTestRunner(apiClient, okSpawner(), restorer, &fakeStats{}, newFakeRegistrar())++ r.executeJob(t.Context(), postgresJob())++ report, ok := apiClient.lastReport()+ require.True(t, ok)+ assert.Equal(t, api.VerificationStatusFailed, report.Status)+ assert.Nil(t, report.PgRestoreExitCode,+ "hitting the estimate-derived disk ceiling is agent infra, not BackupRejected")+}++func Test_ExecuteJob_WhenDiskWatcherTrips_ReportsTerminalDiskLimitExceeded(t *testing.T) {+ originalInterval := diskWatchInterval+ diskWatchInterval = time.Millisecond+ t.Cleanup(func() { diskWatchInterval = originalInterval })++ originalBackoff := backupDownloadBackoffFn+ backupDownloadBackoffFn = func(int) time.Duration { return 0 }+ t.Cleanup(func() { backupDownloadBackoffFn = originalBackoff })++ apiClient := &fakeAPI{downloadBody: []byte("ARCHIVE")}+ jobContainer := fakeContainerWith(testConn())+ jobContainer.diskUsageBytes = 1 << 40+ restorer := &fakeRestorer{runBlocks: true}++ r := newTestRunner(+ apiClient, &fakeSpawner{container: jobContainer}, restorer, &fakeStats{}, newFakeRegistrar())++ r.executeJob(t.Context(), postgresJob())++ report, ok := apiClient.lastReport()+ require.True(t, ok)+ assert.Equal(t, api.VerificationStatusFailed, report.Status)+ require.NotNil(t, report.FailureKind)+ assert.Equal(t, api.FailureKindDiskLimitExceeded, *report.FailureKind)+ assert.Nil(t, report.PgRestoreExitCode, "a disk-limit verdict carries no pg_restore exit code")+ assert.True(t, jobContainer.terminated, "the container must be torn down on disk-limit abort")+}++func Test_ExecuteJob_WhenServerSendsNoDiskBudget_DoesNotFalselyTrip(t *testing.T) {+ apiClient := &fakeAPI{downloadBody: []byte("ARCHIVE")}+ jobContainer := fakeContainerWith(testConn())+ jobContainer.diskUsageBytes = 1 << 40++ job := postgresJob()+ job.MaxContainerDiskMb = 0++ r := newTestRunner(+ apiClient, &fakeSpawner{container: jobContainer}, &fakeRestorer{}, &fakeStats{}, newFakeRegistrar())++ r.executeJob(t.Context(), job)++ report, ok := apiClient.lastReport()+ require.True(t, ok)+ assert.Equal(t, api.VerificationStatusCompleted, report.Status,+ "a zero budget disables the watcher; the job must not be falsely failed")+ assert.Nil(t, report.FailureKind)+}++func Test_ExecuteJob_WhenRestoreFailsNormally_ReportsFailedWithExitCode(t *testing.T) {+ apiClient := &fakeAPI{downloadBody: []byte("ARCHIVE")}+ restorer := &fakeRestorer{+ runErr: fmt.Errorf("restore: %w", restore.ErrRestoreFailed),+ runResult: restore.Result{PgRestoreExitCode: 1, DurationMs: 42, StderrTail: "syntax error in dump"},+ }+ r := newTestRunner(apiClient, okSpawner(), restorer, &fakeStats{}, newFakeRegistrar())++ r.executeJob(t.Context(), postgresJob())++ report, ok := apiClient.lastReport()+ require.True(t, ok)+ assert.Equal(t, api.VerificationStatusFailed, report.Status)+ require.NotNil(t, report.PgRestoreExitCode)+ assert.Equal(t, 1, *report.PgRestoreExitCode)+}++func Test_ExecuteJob_WhenRestoreExecInfraFails_ReportsFailedWithoutExitCode(t *testing.T) {+ apiClient := &fakeAPI{downloadBody: []byte("ARCHIVE")}+ restorer := &fakeRestorer{runErr: errors.New("exec create failed")}+ r := newTestRunner(apiClient, okSpawner(), restorer, &fakeStats{}, newFakeRegistrar())++ r.executeJob(t.Context(), postgresJob())++ report, ok := apiClient.lastReport()+ require.True(t, ok)+ assert.Equal(t, api.VerificationStatusFailed, report.Status)+ assert.Nil(t, report.PgRestoreExitCode)+}++func Test_ExecuteJob_WhenVerifyFailsAndConnDead_ReportsFailedWithoutExitCode(t *testing.T) {+ apiClient := &fakeAPI{downloadBody: []byte("ARCHIVE")}+ restorer := &fakeRestorer{runResult: restore.Result{PgRestoreExitCode: 0}}+ stats := &fakeStats{err: errors.New("tier 1 failed")}+ r := newTestRunner(apiClient, okSpawner(), restorer, stats, newFakeRegistrar())+ r.connAlive = func(context.Context, dbconn.Conn) bool { return false }++ r.executeJob(t.Context(), postgresJob())++ report, ok := apiClient.lastReport()+ require.True(t, ok)+ assert.Equal(t, api.VerificationStatusFailed, report.Status)+ assert.Nil(t, report.PgRestoreExitCode, "a dead connection is agent infra (retryable)")+}++func Test_ExecuteJob_WhenVerifyFailsAndConnAlive_ReportsFailedWithExitCodeZero(t *testing.T) {+ apiClient := &fakeAPI{downloadBody: []byte("ARCHIVE")}+ restorer := &fakeRestorer{runResult: restore.Result{PgRestoreExitCode: 0}}+ stats := &fakeStats{err: errors.New("tier 1 impossible result")}+ 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.VerificationStatusFailed, report.Status)+ require.NotNil(t, report.PgRestoreExitCode)+ assert.Equal(t, 0, *report.PgRestoreExitCode,+ "a live conn with a broken tier-1 result is BackupRejected with exit 0")+}++func Test_ExecuteJob_WhenAllSucceeds_ReportsCompletedWithStats(t *testing.T) {+ apiClient := &fakeAPI{downloadBody: []byte("ARCHIVE")}+ restorer := &fakeRestorer{runResult: restore.Result{PgRestoreExitCode: 0, DurationMs: 1234}}+ stats := &fakeStats{stats: verifier.Stats{+ DBSizeBytes: 9_000_000,+ SchemaCount: 2,+ TableCount: 3,+ TableStats: []verifier.TableStat{{SchemaName: "public", Name: "t1", RowCount: 10}},+ }}+ 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)+ require.NotNil(t, report.DBSizeBytesAfterRestore)+ assert.Equal(t, int64(9_000_000), *report.DBSizeBytesAfterRestore)+ require.NotNil(t, report.TableCount)+ assert.Equal(t, 3, *report.TableCount)+ require.Len(t, report.TableStats, 1)+ assert.Equal(t, "public", report.TableStats[0].SchemaName)+}++func Test_ExecuteJob_WhenAbortedBeforeFailedReport_DoesNotReport(t *testing.T) {+ apiClient := &fakeAPI{}+ spawner := &fakeSpawner{err: errors.New("spawn failed")}+ reg := newFakeRegistrar()+ reg.aborted = true+ r := newTestRunner(apiClient, spawner, &fakeRestorer{}, &fakeStats{}, reg)++ r.executeJob(t.Context(), postgresJob())++ assert.Equal(t, 0, apiClient.reportCalled,+ "an aborted/cancelled verification must not get a spurious FAILED report")+}++func Test_Run_WhenContextCancelled_DrainsAndStops(t *testing.T) {+ apiClient := &fakeAPI{}+ r := newTestRunner(apiClient, okSpawner(), &fakeRestorer{}, &fakeStats{}, newFakeRegistrar())++ ctx, cancel := context.WithCancel(t.Context())++ done := make(chan struct{})+ go func() {+ r.Run(ctx)+ close(done)+ }()++ cancel()++ select {+ case <-done:+ case <-time.After(5 * time.Second):+ t.Fatal("Run did not return after context cancellation")+ }+}++func Test_Run_WhenCalledTwice_Panics(t *testing.T) {+ r := newTestRunner(&fakeAPI{}, okSpawner(), &fakeRestorer{}, &fakeStats{}, newFakeRegistrar())++ ctx, cancel := context.WithCancel(t.Context())+ cancel()+ r.Run(ctx)++ assert.Panics(t, func() { r.Run(ctx) })+}diff --git a/agent/verification/internal/features/start/daemon.go b/agent/verification/internal/features/start/daemon.gonew file mode 100644index 00000000..3d132940--- /dev/null+++ b/agent/verification/internal/features/start/daemon.go@@ -0,0 +1,121 @@+//go:build !windows++package start++import (+ "context"+ "errors"+ "fmt"+ "log/slog"+ "os"+ "os/exec"+ "syscall"+ "time"+)++const (+ logFileName = "databasus-verification.daemon.log"+ stopTimeout = 30 * time.Second+ stopPollInterval = 500 * time.Millisecond+ daemonStartupDelay = 500 * time.Millisecond+)++func Stop(log *slog.Logger) error {+ pid, err := ReadLockFilePID()+ if err != nil {+ if errors.Is(err, os.ErrNotExist) {+ return errors.New("agent is not running (no lock file found)")+ }++ return fmt.Errorf("failed to read lock file: %w", err)+ }++ if !isProcessAlive(pid) {+ _ = os.Remove(lockFileName)+ return fmt.Errorf("agent is not running (stale lock file removed, PID %d)", pid)+ }++ log.Info("Sending SIGTERM to agent", "pid", pid)++ if err := syscall.Kill(pid, syscall.SIGTERM); err != nil {+ return fmt.Errorf("failed to send SIGTERM to PID %d: %w", pid, err)+ }++ deadline := time.Now().Add(stopTimeout)+ for time.Now().Before(deadline) {+ if !isProcessAlive(pid) {+ log.Info("Agent stopped", "pid", pid)+ return nil+ }++ time.Sleep(stopPollInterval)+ }++ return fmt.Errorf("agent (PID %d) did not stop within %s — process may be stuck", pid, stopTimeout)+}++func Status(log *slog.Logger) error {+ pid, err := ReadLockFilePID()+ if err != nil {+ if errors.Is(err, os.ErrNotExist) {+ fmt.Println("Agent is not running")+ return nil+ }++ return fmt.Errorf("failed to read lock file: %w", err)+ }++ if isProcessAlive(pid) {+ fmt.Printf("Agent is running (PID %d)\n", pid)+ } else {+ fmt.Println("Agent is not running (stale lock file)")+ _ = os.Remove(lockFileName)+ }++ return nil+}++func spawnDaemon(log *slog.Logger) (int, error) {+ execPath, err := os.Executable()+ if err != nil {+ return 0, fmt.Errorf("failed to resolve executable path: %w", err)+ }++ args := []string{"_run"}++ logFile, err := os.OpenFile(logFileName, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)+ if err != nil {+ return 0, fmt.Errorf("failed to open log file %s: %w", logFileName, err)+ }++ cwd, err := os.Getwd()+ if err != nil {+ _ = logFile.Close()+ return 0, fmt.Errorf("failed to get working directory: %w", err)+ }++ cmd := exec.CommandContext(context.Background(), execPath, args...)+ cmd.Dir = cwd+ cmd.Stderr = logFile+ cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}++ if err := cmd.Start(); err != nil {+ _ = logFile.Close()+ return 0, fmt.Errorf("failed to start daemon process: %w", err)+ }++ pid := cmd.Process.Pid++ // Detach — we don't wait for the child+ _ = logFile.Close()++ time.Sleep(daemonStartupDelay)++ if !isProcessAlive(pid) {+ return 0, fmt.Errorf("daemon process (PID %d) exited immediately — check %s for details", pid, logFileName)+ }++ log.Info("Daemon spawned", "pid", pid, "log", logFileName)++ return pid, nil+}diff --git a/agent/verification/internal/features/start/daemon_windows.go b/agent/verification/internal/features/start/daemon_windows.gonew file mode 100644index 00000000..8743554b--- /dev/null+++ b/agent/verification/internal/features/start/daemon_windows.go@@ -0,0 +1,20 @@+//go:build windows++package start++import (+ "errors"+ "log/slog"+)++func Stop(log *slog.Logger) error {+ return errors.New("stop is not supported on Windows — use Ctrl+C in the terminal where the agent is running")+}++func Status(log *slog.Logger) error {+ return errors.New("status is not supported on Windows — check the terminal where the agent is running")+}++func spawnDaemon(_ *slog.Logger) (int, error) {+ return 0, errors.New("daemon mode is not supported on Windows")+}diff --git a/agent/verification/internal/features/start/doc.go b/agent/verification/internal/features/start/doc.gonew file mode 100644index 00000000..ddf7755c--- /dev/null+++ b/agent/verification/internal/features/start/doc.go@@ -0,0 +1,6 @@+// Package start runs the verification agent as a single-instance background+// daemon: it spawns a detached process, holds an exclusive lock so a second+// agent cannot run from the same working directory, and supervises the+// capacity heartbeat and verification runner until a signal or a self-upgrade+// restart.+package startdiff --git a/agent/verification/internal/features/start/lock.go b/agent/verification/internal/features/start/lock.gonew file mode 100644index 00000000..7f37bcdf--- /dev/null+++ b/agent/verification/internal/features/start/lock.go@@ -0,0 +1,132 @@+//go:build !windows++package start++import (+ "errors"+ "fmt"+ "io"+ "log/slog"+ "os"+ "strconv"+ "strings"+ "syscall"+)++const lockFileName = "databasus-verification.lock"++func AcquireLock(log *slog.Logger) (*os.File, error) {+ f, err := os.OpenFile(lockFileName, os.O_CREATE|os.O_RDWR, 0o644)+ if err != nil {+ return nil, fmt.Errorf("failed to open lock file: %w", err)+ }++ err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)+ if err == nil {+ if err := writePID(f); err != nil {+ _ = f.Close()+ return nil, err+ }++ log.Info("Process lock acquired", "pid", os.Getpid(), "lockFile", lockFileName)++ return f, nil+ }++ if !errors.Is(err, syscall.EWOULDBLOCK) {+ _ = f.Close()+ return nil, fmt.Errorf("failed to acquire lock: %w", err)+ }++ pid, pidErr := readLockPID(f)+ _ = f.Close()++ if pidErr != nil {+ return nil, fmt.Errorf("another instance is already running")+ }++ return nil, fmt.Errorf("another instance is already running (PID %d)", pid)+}++func ReleaseLock(f *os.File) {+ _ = syscall.Flock(int(f.Fd()), syscall.LOCK_UN)++ lockedStat, lockedErr := f.Stat()+ _ = f.Close()++ if lockedErr != nil {+ _ = os.Remove(lockFileName)+ return+ }++ diskStat, diskErr := os.Stat(lockFileName)+ if diskErr != nil {+ return+ }++ if os.SameFile(lockedStat, diskStat) {+ _ = os.Remove(lockFileName)+ }+}++func ReadLockFilePID() (int, error) {+ f, err := os.Open(lockFileName)+ if err != nil {+ return 0, err+ }+ defer func() { _ = f.Close() }()++ return readLockPID(f)+}++func writePID(f *os.File) error {+ if err := f.Truncate(0); err != nil {+ return fmt.Errorf("failed to truncate lock file: %w", err)+ }++ if _, err := f.Seek(0, io.SeekStart); err != nil {+ return fmt.Errorf("failed to seek lock file: %w", err)+ }++ if _, err := fmt.Fprintf(f, "%d\n", os.Getpid()); err != nil {+ return fmt.Errorf("failed to write PID to lock file: %w", err)+ }++ return f.Sync()+}++func readLockPID(f *os.File) (int, error) {+ if _, err := f.Seek(0, io.SeekStart); err != nil {+ return 0, err+ }++ data, err := io.ReadAll(f)+ if err != nil {+ return 0, err+ }++ s := strings.TrimSpace(string(data))+ if s == "" {+ return 0, errors.New("lock file is empty")+ }++ pid, err := strconv.Atoi(s)+ if err != nil {+ return 0, fmt.Errorf("invalid PID in lock file: %w", err)+ }++ return pid, nil+}++func isProcessAlive(pid int) bool {+ err := syscall.Kill(pid, 0)+ if err == nil {+ return true+ }++ if errors.Is(err, syscall.EPERM) {+ return true+ }++ return false+}diff --git a/agent/verification/internal/features/start/lock_test.go b/agent/verification/internal/features/start/lock_test.gonew file mode 100644index 00000000..97f0e3fd--- /dev/null+++ b/agent/verification/internal/features/start/lock_test.go@@ -0,0 +1,148 @@+//go:build !windows++package start++import (+ "fmt"+ "os"+ "strconv"+ "strings"+ "testing"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ "databasus-verification-agent/internal/logger"+)++func Test_AcquireLock_LockFileCreatedWithPID(t *testing.T) {+ setupTempDir(t)+ log := logger.GetLogger()++ lockFile, err := AcquireLock(log)+ require.NoError(t, err)+ defer ReleaseLock(lockFile)++ data, err := os.ReadFile(lockFileName)+ require.NoError(t, err)++ pid, err := strconv.Atoi(strings.TrimSpace(string(data)))+ require.NoError(t, err)+ assert.Equal(t, os.Getpid(), pid)+}++func Test_AcquireLock_SecondAcquireFails_WhenFirstHeld(t *testing.T) {+ setupTempDir(t)+ log := logger.GetLogger()++ first, err := AcquireLock(log)+ require.NoError(t, err)+ defer ReleaseLock(first)++ second, err := AcquireLock(log)+ assert.Nil(t, second)+ require.Error(t, err)+ assert.Contains(t, err.Error(), "another instance is already running")+ assert.Contains(t, err.Error(), fmt.Sprintf("PID %d", os.Getpid()))+}++func Test_AcquireLock_StaleLockReacquired_WhenProcessDead(t *testing.T) {+ setupTempDir(t)+ log := logger.GetLogger()++ err := os.WriteFile(lockFileName, []byte("999999999\n"), 0o644)+ require.NoError(t, err)++ lockFile, err := AcquireLock(log)+ require.NoError(t, err)+ defer ReleaseLock(lockFile)++ data, err := os.ReadFile(lockFileName)+ require.NoError(t, err)++ pid, err := strconv.Atoi(strings.TrimSpace(string(data)))+ require.NoError(t, err)+ assert.Equal(t, os.Getpid(), pid)+}++func Test_ReleaseLock_LockFileRemoved(t *testing.T) {+ setupTempDir(t)+ log := logger.GetLogger()++ lockFile, err := AcquireLock(log)+ require.NoError(t, err)++ ReleaseLock(lockFile)++ _, err = os.Stat(lockFileName)+ assert.True(t, os.IsNotExist(err))+}++func Test_AcquireLock_ReacquiredAfterRelease(t *testing.T) {+ setupTempDir(t)+ log := logger.GetLogger()++ first, err := AcquireLock(log)+ require.NoError(t, err)+ ReleaseLock(first)++ second, err := AcquireLock(log)+ require.NoError(t, err)+ defer ReleaseLock(second)++ data, err := os.ReadFile(lockFileName)+ require.NoError(t, err)++ pid, err := strconv.Atoi(strings.TrimSpace(string(data)))+ require.NoError(t, err)+ assert.Equal(t, os.Getpid(), pid)+}++func Test_isProcessAlive_ReturnsTrueForSelf(t *testing.T) {+ assert.True(t, isProcessAlive(os.Getpid()))+}++func Test_isProcessAlive_ReturnsFalseForNonExistentPID(t *testing.T) {+ assert.False(t, isProcessAlive(999999999))+}++func Test_readLockPID_ParsesValidPID(t *testing.T) {+ setupTempDir(t)++ f, err := os.CreateTemp("", "lock-test-*")+ require.NoError(t, err)+ defer os.Remove(f.Name())++ _, err = f.WriteString("12345\n")+ require.NoError(t, err)++ pid, err := readLockPID(f)+ require.NoError(t, err)+ assert.Equal(t, 12345, pid)+}++func Test_readLockPID_ReturnsErrorForEmptyFile(t *testing.T) {+ setupTempDir(t)++ f, err := os.CreateTemp("", "lock-test-*")+ require.NoError(t, err)+ defer os.Remove(f.Name())++ _, err = readLockPID(f)+ require.Error(t, err)+ assert.Contains(t, err.Error(), "lock file is empty")+}++func setupTempDir(t *testing.T) string {+ t.Helper()++ origDir, err := os.Getwd()+ require.NoError(t, err)++ dir := t.TempDir()+ require.NoError(t, os.Chdir(dir))++ t.Cleanup(func() { _ = os.Chdir(origDir) })++ return dir+}diff --git a/agent/verification/internal/features/start/lock_watcher.go b/agent/verification/internal/features/start/lock_watcher.gonew file mode 100644index 00000000..27e8ca46--- /dev/null+++ b/agent/verification/internal/features/start/lock_watcher.go@@ -0,0 +1,90 @@+//go:build !windows++package start++import (+ "context"+ "log/slog"+ "os"+ "syscall"+ "time"+)++const lockWatchInterval = 5 * time.Second++type LockWatcher struct {+ originalInode uint64+ cancel context.CancelFunc+ log *slog.Logger+}++func NewLockWatcher(lockFile *os.File, cancel context.CancelFunc, log *slog.Logger) (*LockWatcher, error) {+ inode, err := getFileInode(lockFile)+ if err != nil {+ return nil, err+ }++ return &LockWatcher{+ originalInode: inode,+ cancel: cancel,+ log: log,+ }, nil+}++func (w *LockWatcher) Run(ctx context.Context) {+ ticker := time.NewTicker(lockWatchInterval)+ defer ticker.Stop()++ for {+ select {+ case <-ctx.Done():+ return+ case <-ticker.C:+ w.check()+ }+ }+}++func (w *LockWatcher) check() {+ info, err := os.Stat(lockFileName)+ if err != nil {+ w.log.Error("Lock file disappeared, shutting down", "file", lockFileName, "error", err)+ w.cancel()++ return+ }++ currentInode, err := getStatInode(info)+ if err != nil {+ w.log.Error("Failed to read lock file inode, shutting down", "error", err)+ w.cancel()++ return+ }++ if currentInode != w.originalInode {+ w.log.Error("Lock file was replaced (inode changed), shutting down",+ "originalInode", w.originalInode,+ "currentInode", currentInode,+ )+ w.cancel()+ }+}++func getFileInode(f *os.File) (uint64, error) {+ info, err := f.Stat()+ if err != nil {+ return 0, err+ }++ return getStatInode(info)+}++func getStatInode(info os.FileInfo) (uint64, error) {+ stat, ok := info.Sys().(*syscall.Stat_t)+ if !ok {+ return 0, os.ErrInvalid+ }++ return stat.Ino, nil+}diff --git a/agent/verification/internal/features/start/lock_watcher_test.go b/agent/verification/internal/features/start/lock_watcher_test.gonew file mode 100644index 00000000..cc5ef1d2--- /dev/null+++ b/agent/verification/internal/features/start/lock_watcher_test.go@@ -0,0 +1,110 @@+//go:build !windows++package start++import (+ "context"+ "os"+ "testing"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ "databasus-verification-agent/internal/logger"+)++func Test_NewLockWatcher_CapturesInode(t *testing.T) {+ setupTempDir(t)+ log := logger.GetLogger()++ lockFile, err := AcquireLock(log)+ require.NoError(t, err)+ defer ReleaseLock(lockFile)++ _, cancel := context.WithCancel(t.Context())+ defer cancel()++ watcher, err := NewLockWatcher(lockFile, cancel, log)+ require.NoError(t, err)+ assert.NotZero(t, watcher.originalInode)+}++func Test_LockWatcher_FileUnchanged_ContextNotCancelled(t *testing.T) {+ setupTempDir(t)+ log := logger.GetLogger()++ lockFile, err := AcquireLock(log)+ require.NoError(t, err)+ defer ReleaseLock(lockFile)++ ctx, cancel := context.WithCancel(t.Context())+ defer cancel()++ watcher, err := NewLockWatcher(lockFile, cancel, log)+ require.NoError(t, err)++ watcher.check()+ watcher.check()+ watcher.check()++ select {+ case <-ctx.Done():+ t.Fatal("context should not be cancelled when lock file is unchanged")+ default:+ }+}++func Test_LockWatcher_FileDeleted_CancelsContext(t *testing.T) {+ setupTempDir(t)+ log := logger.GetLogger()++ lockFile, err := AcquireLock(log)+ require.NoError(t, err)+ defer ReleaseLock(lockFile)++ ctx, cancel := context.WithCancel(t.Context())+ defer cancel()++ watcher, err := NewLockWatcher(lockFile, cancel, log)+ require.NoError(t, err)++ err = os.Remove(lockFileName)+ require.NoError(t, err)++ watcher.check()++ select {+ case <-ctx.Done():+ default:+ t.Fatal("context should be cancelled when lock file is deleted")+ }+}++func Test_LockWatcher_FileReplacedWithDifferentInode_CancelsContext(t *testing.T) {+ setupTempDir(t)+ log := logger.GetLogger()++ lockFile, err := AcquireLock(log)+ require.NoError(t, err)+ defer ReleaseLock(lockFile)++ ctx, cancel := context.WithCancel(t.Context())+ defer cancel()++ watcher, err := NewLockWatcher(lockFile, cancel, log)+ require.NoError(t, err)++ err = os.Remove(lockFileName)+ require.NoError(t, err)++ err = os.WriteFile(lockFileName, []byte("99999\n"), 0o644)+ require.NoError(t, err)++ watcher.check()++ select {+ case <-ctx.Done():+ default:+ t.Fatal("context should be cancelled when lock file inode changes")+ }+}diff --git a/agent/verification/internal/features/start/lock_watcher_windows.go b/agent/verification/internal/features/start/lock_watcher_windows.gonew file mode 100644index 00000000..3b41ba8e--- /dev/null+++ b/agent/verification/internal/features/start/lock_watcher_windows.go@@ -0,0 +1,17 @@+//go:build windows++package start++import (+ "context"+ "log/slog"+ "os"+)++type LockWatcher struct{}++func NewLockWatcher(_ *os.File, _ context.CancelFunc, _ *slog.Logger) (*LockWatcher, error) {+ return &LockWatcher{}, nil+}++func (w *LockWatcher) Run(_ context.Context) {}diff --git a/agent/verification/internal/features/start/lock_windows.go b/agent/verification/internal/features/start/lock_windows.gonew file mode 100644index 00000000..c8fa44ed--- /dev/null+++ b/agent/verification/internal/features/start/lock_windows.go@@ -0,0 +1,18 @@+package start++import (+ "log/slog"+ "os"+)++func AcquireLock(log *slog.Logger) (*os.File, error) {+ log.Warn("Process locking is not supported on Windows, skipping")++ return nil, nil+}++func ReleaseLock(f *os.File) {+ if f != nil {+ _ = f.Close()+ }+}diff --git a/agent/verification/internal/features/start/spawner.go b/agent/verification/internal/features/start/spawner.gonew file mode 100644index 00000000..12082875--- /dev/null+++ b/agent/verification/internal/features/start/spawner.go@@ -0,0 +1,28 @@+package start++import (+ "context"++ "databasus-verification-agent/internal/features/container"+ "databasus-verification-agent/internal/features/runner"+)++type containerManagerSpawner struct {+ containerManager *container.Manager+}++func (s containerManagerSpawner) Spawn(+ ctx context.Context, req runner.SpawnRequest,+) (runner.JobContainer, error) {+ jobContainer, err := s.containerManager.Spawn(ctx, container.SpawnRequest{+ PgMajor: req.PgMajor,+ CPUPerJob: req.CPUPerJob,+ RAMMbPerJob: req.RAMMbPerJob,+ VerificationID: req.VerificationID,+ })+ if err != nil {+ return nil, err+ }++ return jobContainer, nil+}diff --git a/agent/verification/internal/features/start/start.go b/agent/verification/internal/features/start/start.gonew file mode 100644index 00000000..4de30639--- /dev/null+++ b/agent/verification/internal/features/start/start.go@@ -0,0 +1,142 @@+package start++import (+ "bufio"+ "context"+ "fmt"+ "log/slog"+ "os"+ "os/signal"+ "runtime"+ "sync"+ "syscall"+ "time"++ "databasus-verification-agent/internal/config"+ "databasus-verification-agent/internal/features/api"+ "databasus-verification-agent/internal/features/container"+ "databasus-verification-agent/internal/features/heartbeat"+ "databasus-verification-agent/internal/features/restore"+ "databasus-verification-agent/internal/features/runner"+ "databasus-verification-agent/internal/features/upgrade"+ "databasus-verification-agent/internal/features/verifier"+)++func Start(cfg *config.Config, agentVersion string, isDev bool, log *slog.Logger) error {+ if _, err := cfg.Validate(); err != nil {+ return err+ }++ if runtime.GOOS == "windows" {+ return RunDaemon(cfg, agentVersion, isDev, log)+ }++ pid, err := spawnDaemon(log)+ if err != nil {+ return err+ }++ fmt.Printf("Agent started in background (PID %d)\n", pid)++ return nil+}++func RunDaemon(cfg *config.Config, agentVersion string, isDev bool, log *slog.Logger) error {+ capacity, err := cfg.Validate()+ if err != nil {+ return err+ }++ if err := cfg.ValidateTransport(isStdinTTY(), bufio.NewReader(os.Stdin)); err != nil {+ return err+ }++ lockFile, err := AcquireLock(log)+ if err != nil {+ return err+ }+ defer ReleaseLock(lockFile)++ ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)+ defer cancel()++ watcher, err := NewLockWatcher(lockFile, cancel, log)+ if err != nil {+ return fmt.Errorf("failed to initialize lock watcher: %w", err)+ }+ go watcher.Run(ctx)++ apiClient := api.NewClient(cfg.DatabasusHost, cfg.Token, cfg.AgentID, log)++ engine, err := container.NewDockerEngine()+ if err != nil {+ return err+ }++ containerManager := container.NewManager(engine, cfg.AgentID, log)+ if err := containerManager.StartupSelfCheck(ctx); err != nil {+ return err+ }++ // Start fresh: remove any container leaked by a prior ungraceful death+ // before claiming the first job. Safe to wipe unconditionally because the+ // lock guarantees a single agent owns no live container the instant it+ // starts.+ containerManager.PurgeContainers(ctx)++ pool := runner.NewPool(capacity.MaxConcurrentJobs)+ heartbeater := heartbeat.NewHeartbeater(apiClient, capacity, log)+ verificationRunner := runner.NewRunner(+ apiClient, capacity, pool,+ containerManagerSpawner{containerManager: containerManager},+ restore.NewRestorer(log),+ verifier.NewVerifier(log),+ heartbeater,+ log,+ )++ var backgroundUpgrader *upgrade.BackgroundUpgrader+ if agentVersion != "dev" && !isDev {+ backgroundUpgrader = upgrade.NewBackgroundUpgrader(apiClient, agentVersion, isDev, cancel, log)+ go backgroundUpgrader.Run(ctx)+ }++ log.Info("Agent started")++ var wg sync.WaitGroup+ wg.Go(func() { heartbeater.Run(ctx) })+ wg.Go(func() { verificationRunner.Run(ctx) })++ <-ctx.Done()++ // verificationRunner.Run drains in-flight jobs (pool.Wait) before it+ // returns, so wg.Wait only completes once every container is torn down —+ // strictly before any re-exec on self-update.+ wg.Wait()++ if backgroundUpgrader != nil {+ backgroundUpgrader.WaitForCompletion(30 * time.Second)++ if backgroundUpgrader.IsUpgraded() {+ // The deferred ReleaseLock runs before this returns to the caller,+ // freeing the flock and removing the lock file. The caller then+ // syscall.Exec's the same PID with os.Args unchanged, so the new+ // image re-enters via the same subcommand (`run` or `_run`) and+ // re-acquires the lock cleanly with no contender.+ return upgrade.ErrUpgradeRestart+ }+ }++ log.Info("Agent stopped")++ return nil+}++func isStdinTTY() bool {+ info, err := os.Stdin.Stat()+ if err != nil {+ return false+ }++ return info.Mode()&os.ModeCharDevice != 0+}diff --git a/agent/verification/internal/features/upgrade/background_upgrader.go b/agent/verification/internal/features/upgrade/background_upgrader.gonew file mode 100644index 00000000..71313429--- /dev/null+++ b/agent/verification/internal/features/upgrade/background_upgrader.go@@ -0,0 +1,95 @@+package upgrade++import (+ "context"+ "fmt"+ "log/slog"+ "sync/atomic"+ "time"++ "databasus-verification-agent/internal/features/api"+)++const backgroundCheckInterval = 10 * time.Second++type BackgroundUpgrader struct {+ apiClient *api.Client+ currentVersion string+ isDev bool+ cancel context.CancelFunc+ hasRun atomic.Bool+ isUpgraded atomic.Bool+ log *slog.Logger+ done chan struct{}+}++func NewBackgroundUpgrader(+ apiClient *api.Client,+ currentVersion string,+ isDev bool,+ cancel context.CancelFunc,+ log *slog.Logger,+) *BackgroundUpgrader {+ return &BackgroundUpgrader{+ apiClient,+ currentVersion,+ isDev,+ cancel,+ atomic.Bool{},+ atomic.Bool{},+ log,+ make(chan struct{}),+ }+}++func (u *BackgroundUpgrader) Run(ctx context.Context) {+ if u.hasRun.Swap(true) {+ panic(fmt.Sprintf("%T.Run() called multiple times", u))+ }++ defer close(u.done)++ ticker := time.NewTicker(backgroundCheckInterval)+ defer ticker.Stop()++ for {+ select {+ case <-ctx.Done():+ return+ case <-ticker.C:+ if u.checkAndUpgrade() {+ return+ }+ }+ }+}++func (u *BackgroundUpgrader) IsUpgraded() bool {+ return u.isUpgraded.Load()+}++func (u *BackgroundUpgrader) WaitForCompletion(timeout time.Duration) {+ select {+ case <-u.done:+ case <-time.After(timeout):+ }+}++func (u *BackgroundUpgrader) checkAndUpgrade() bool {+ isUpgraded, err := CheckAndUpdate(u.apiClient, u.currentVersion, u.isDev, u.log)+ if err != nil {+ u.log.Warn("Background update check failed", "error", err)++ return false+ }++ if !isUpgraded {+ return false+ }++ u.log.Info("Background upgrade complete, restarting...")+ u.isUpgraded.Store(true)+ u.cancel()++ return true+}diff --git a/agent/verification/internal/features/upgrade/errors.go b/agent/verification/internal/features/upgrade/errors.gonew file mode 100644index 00000000..ddecc64e--- /dev/null+++ b/agent/verification/internal/features/upgrade/errors.go@@ -0,0 +1,5 @@+package upgrade++import "errors"++var ErrUpgradeRestart = errors.New("agent upgraded, restart required")diff --git a/agent/verification/internal/features/upgrade/upgrader.go b/agent/verification/internal/features/upgrade/upgrader.gonew file mode 100644index 00000000..7eb35359--- /dev/null+++ b/agent/verification/internal/features/upgrade/upgrader.go@@ -0,0 +1,106 @@+package upgrade++import (+ "context"+ "fmt"+ "log/slog"+ "os"+ "os/exec"+ "runtime"+ "strings"+ "time"++ "databasus-verification-agent/internal/features/api"+)++// verifyBinaryTimeout bounds the freshly-downloaded binary's `version` probe so+// a corrupt or wrong-arch binary that hangs cannot wedge startup or the+// background-upgrade goroutine. A var so tests can shrink it.+var verifyBinaryTimeout = 30 * time.Second++// binaryDownloadTimeout bounds the agent self-download. The streaming HTTP+// client has no client-level timeout (it is shared with the long-lived backup+// stream), so the deadline is scoped per call here.+const binaryDownloadTimeout = 10 * time.Minute++// CheckAndUpdate checks if a new version is available and upgrades the binary on disk.+// Returns (true, nil) if the binary was upgraded, (false, nil) if already up to date,+// or (false, err) on failure. Callers are responsible for re-exec or restart signaling.+func CheckAndUpdate(apiClient *api.Client, currentVersion string, isDev bool, log *slog.Logger) (bool, error) {+ if isDev {+ log.Info("Skipping update check (development mode)")++ return false, nil+ }++ serverVersion, err := apiClient.FetchServerVersion(context.Background())+ if err != nil {+ log.Warn("Could not reach server for update check", "error", err)++ return false, fmt.Errorf(+ "unable to check version, please verify Databasus server is available: %w",+ err,+ )+ }++ if serverVersion == currentVersion {+ log.Info("Agent version is up to date", "version", currentVersion)++ return false, nil+ }++ log.Info("Updating agent...", "current", currentVersion, "target", serverVersion)++ selfPath, err := os.Executable()+ if err != nil {+ return false, fmt.Errorf("failed to determine executable path: %w", err)+ }++ tempPath := selfPath + ".update"++ defer func() {+ _ = os.Remove(tempPath)+ }()++ downloadCtx, cancelDownload := context.WithTimeout(context.Background(), binaryDownloadTimeout)+ defer cancelDownload()++ if err := apiClient.DownloadVerificationAgentBinary(downloadCtx, runtime.GOARCH, tempPath); err != nil {+ return false, fmt.Errorf("failed to download update: %w", err)+ }++ if err := os.Chmod(tempPath, 0o755); err != nil {+ return false, fmt.Errorf("failed to set permissions on update: %w", err)+ }++ if err := verifyBinary(tempPath, serverVersion); err != nil {+ return false, fmt.Errorf("update verification failed: %w", err)+ }++ if err := os.Rename(tempPath, selfPath); err != nil {+ return false, fmt.Errorf("failed to replace binary (try --skip-update if this persists): %w", err)+ }++ log.Info("Agent binary updated", "version", serverVersion)++ return true, nil+}++func verifyBinary(binaryPath, expectedVersion string) error {+ ctx, cancel := context.WithTimeout(context.Background(), verifyBinaryTimeout)+ defer cancel()++ cmd := exec.CommandContext(ctx, binaryPath, "version")++ output, err := cmd.Output()+ if err != nil {+ return fmt.Errorf("binary failed to execute: %w", err)+ }++ reportedVersion := strings.TrimSpace(string(output))+ if reportedVersion != expectedVersion {+ return fmt.Errorf("version mismatch: expected %q, got %q", expectedVersion, reportedVersion)+ }++ return nil+}diff --git a/agent/verification/internal/features/upgrade/upgrader_test.go b/agent/verification/internal/features/upgrade/upgrader_test.gonew file mode 100644index 00000000..455b77d9--- /dev/null+++ b/agent/verification/internal/features/upgrade/upgrader_test.go@@ -0,0 +1,166 @@+package upgrade++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "os"+ "os/exec"+ "path/filepath"+ "runtime"+ "sync/atomic"+ "testing"+ "time"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ "databasus-verification-agent/internal/features/api"+ "databasus-verification-agent/internal/testutil"+)++func goBuildHelper(t *testing.T, mainSrc string) string {+ t.Helper()++ dir := t.TempDir()+ src := filepath.Join(dir, "main.go")+ require.NoError(t, os.WriteFile(src, []byte(mainSrc), 0o644))++ bin := filepath.Join(dir, "helper")+ if runtime.GOOS == "windows" {+ bin += ".exe"+ }++ out, err := exec.Command("go", "build", "-o", bin, src).CombinedOutput()+ require.NoError(t, err, "build helper: %s", out)++ return bin+}++func buildVersionHelper(t *testing.T, version string) string {+ t.Helper()++ return goBuildHelper(t, "package main\n"++ "import (\"fmt\"; \"os\")\n"++ "func main(){ if len(os.Args)>1 && os.Args[1]==\"version\" { fmt.Println(\""++ version+"\"); return }; os.Exit(2) }\n")+}++func buildHangingHelper(t *testing.T) string {+ t.Helper()++ return goBuildHelper(t, "package main\n"++ "import \"time\"\n"++ "func main(){ time.Sleep(30 * time.Second) }\n")+}++func Test_VerifyBinary_WhenVersionMatches_ReturnsNil(t *testing.T) {+ helper := buildVersionHelper(t, "v2.0.0")++ require.NoError(t, verifyBinary(helper, "v2.0.0"))+}++func Test_VerifyBinary_WhenVersionMismatch_ReturnsError(t *testing.T) {+ helper := buildVersionHelper(t, "v2.0.0")++ err := verifyBinary(helper, "v9.9.9")++ require.Error(t, err)+ assert.Contains(t, err.Error(), "version mismatch")+}++func Test_VerifyBinary_WhenBinaryNotExecutable_ReturnsError(t *testing.T) {+ notBinary := filepath.Join(t.TempDir(), "not-a-binary")+ require.NoError(t, os.WriteFile(notBinary, []byte("plain text"), 0o644))++ require.Error(t, verifyBinary(notBinary, "v1.0.0"))+}++func Test_VerifyBinary_WhenBinaryHangs_TimesOutInsteadOfBlocking(t *testing.T) {+ original := verifyBinaryTimeout+ verifyBinaryTimeout = 200 * time.Millisecond+ t.Cleanup(func() { verifyBinaryTimeout = original })++ hanging := buildHangingHelper(t)++ start := time.Now()+ err := verifyBinary(hanging, "v1.0.0")+ elapsed := time.Since(start)++ require.Error(t, err)+ assert.Less(t, elapsed, 10*time.Second, "verifyBinary must abort on timeout, not block")+ assert.NotContains(t, err.Error(), "version mismatch")+}++func Test_CheckAndUpdate_WhenDevelopmentMode_DoesNotContactServer(t *testing.T) {+ var hits atomic.Int32++ server := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {+ hits.Add(1)+ }))+ t.Cleanup(server.Close)++ client := api.NewClient(server.URL, "", "", testutil.DiscardLogger())++ upgraded, err := CheckAndUpdate(client, "v1.0.0", true, testutil.DiscardLogger())++ require.NoError(t, err)+ assert.False(t, upgraded)+ assert.Equal(t, int32(0), hits.Load())+}++func Test_CheckAndUpdate_WhenServerVersionMatches_DoesNotDownload(t *testing.T) {+ var downloadHits atomic.Int32++ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path == "/api/v1/system/version" {+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(map[string]string{"version": "v1.0.0"})+ return+ }++ downloadHits.Add(1)+ }))+ t.Cleanup(server.Close)++ client := api.NewClient(server.URL, "", "", testutil.DiscardLogger())++ upgraded, err := CheckAndUpdate(client, "v1.0.0", false, testutil.DiscardLogger())++ require.NoError(t, err)+ assert.False(t, upgraded)+ assert.Equal(t, int32(0), downloadHits.Load())+}++func Test_CheckAndUpdate_WhenServerUnreachable_ReturnsError(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {}))+ server.Close()++ client := api.NewClient(server.URL, "", "", testutil.DiscardLogger())++ upgraded, err := CheckAndUpdate(client, "v1.0.0", false, testutil.DiscardLogger())++ require.Error(t, err)+ assert.False(t, upgraded)+ assert.Contains(t, err.Error(), "unable to check version")+}++func Test_BackgroundUpgrader_WhenDevelopmentMode_NeverUpgrades(t *testing.T) {+ client := api.NewClient("http://127.0.0.1:0", "", "", testutil.DiscardLogger())+ upgrader := NewBackgroundUpgrader(client, "v1.0.0", true, func() {}, testutil.DiscardLogger())++ assert.False(t, upgrader.checkAndUpgrade())+ assert.False(t, upgrader.IsUpgraded())+}++func Test_BackgroundUpgrader_WhenRunCalledTwice_Panics(t *testing.T) {+ client := api.NewClient("http://127.0.0.1:0", "", "", testutil.DiscardLogger())+ ctx, cancel := context.WithCancel(t.Context())+ upgrader := NewBackgroundUpgrader(client, "v1.0.0", true, cancel, testutil.DiscardLogger())++ cancel()+ upgrader.Run(ctx)++ assert.Panics(t, func() { upgrader.Run(ctx) })+}diff --git a/agent/verification/internal/features/verifier/verifier.go b/agent/verification/internal/features/verifier/verifier.gonew file mode 100644index 00000000..8ed62d47--- /dev/null+++ b/agent/verification/internal/features/verifier/verifier.go@@ -0,0 +1,194 @@+// Package verifier runs the post-restore check tiers against the restored+// container over the host-published port. It returns stats and an error; it+// does NOT classify the failure — the runner decides (a dead connection is+// agent infra, a reachable DB with an impossible tier-1 result is a bad+// backup).+package verifier++import (+ "context"+ "fmt"+ "log/slog"+ "time"++ "github.com/jackc/pgx/v5"++ "databasus-verification-agent/internal/features/dbconn"+)++const (+ queryTimeout = 30 * time.Second+ probeTimeout = 5 * time.Second+ analyzeTimeoutMin = 60 * time.Second+ analyzeTimeoutMax = 10 * time.Minute++ excludedSchemas = "'pg_catalog','information_schema','pg_toast'"+ // information_schema.schemata on PG 12 exposes per-session pg_temp_N and+ // pg_toast_temp_N namespaces that PG 13+ hides; the regex filters them so+ // SchemaCount / TableCount / tableStats stay consistent across majors.+ excludedSchemaRegex = `^pg_(temp|toast_temp)_`++ dbSizeSQL = `SELECT pg_database_size(current_database())`+ schemaCountSQL = `SELECT count(*) FROM information_schema.schemata ` ++ `WHERE schema_name NOT IN (` + excludedSchemas + `) ` ++ `AND schema_name !~ '` + excludedSchemaRegex + `'`+ tableCountSQL = `SELECT count(*) FROM information_schema.tables ` ++ `WHERE table_schema NOT IN (` + excludedSchemas + `) ` ++ `AND table_schema !~ '` + excludedSchemaRegex + `' ` ++ `AND table_type = 'BASE TABLE'`+ tableStatsSQL = `SELECT n.nspname, c.relname, c.reltuples::bigint ` ++ `FROM pg_class c JOIN pg_namespace n ON c.relnamespace = n.oid ` ++ `WHERE c.relkind = 'r' ` ++ `AND n.nspname NOT IN (` + excludedSchemas + `) ` ++ `AND n.nspname !~ '` + excludedSchemaRegex + `' ` ++ `ORDER BY c.reltuples DESC LIMIT 100`+ fkCountSQL = `SELECT count(*) FROM information_schema.referential_constraints`+)++type TableStat struct {+ SchemaName string+ Name string+ RowCount int64+}++type Stats struct {+ DBSizeBytes int64+ SchemaCount int+ TableCount int+ TableStats []TableStat+ FKCount int+}++type Verifier struct {+ analyzeTimeoutMax time.Duration+ log *slog.Logger+}++func NewVerifier(log *slog.Logger) *Verifier {+ return &Verifier{analyzeTimeoutMax: analyzeTimeoutMax, log: log}+}++func (v *Verifier) CollectStats(ctx context.Context, conn dbconn.Conn) (Stats, error) {+ pgConn, err := pgx.Connect(ctx, conn.DSN())+ if err != nil {+ return Stats{}, fmt.Errorf("connect restored db: %w", err)+ }+ defer func() { _ = pgConn.Close(ctx) }()++ var stats Stats++ if err := collectRequiredStat(ctx, pgConn, dbSizeSQL, &stats.DBSizeBytes); err != nil {+ return Stats{}, fmt.Errorf("tier 1 database size: %w", err)+ }++ collectOptionalStat(ctx, v.log, pgConn, schemaCountSQL, &stats.SchemaCount, "tier 2 schema count unavailable")+ collectOptionalStat(ctx, v.log, pgConn, tableCountSQL, &stats.TableCount, "tier 3 table count unavailable")++ stats.TableStats = v.collectTableStats(ctx, pgConn, stats.DBSizeBytes)++ collectOptionalStat(ctx, v.log, pgConn, fkCountSQL, &stats.FKCount, "tier 5 fk metadata unavailable")++ return stats, nil+}++// Best-effort: any failure yields nil, never an error — a large DB whose+// ANALYZE exceeds the budget is expected, not a verification failure.+func (v *Verifier) collectTableStats(+ ctx context.Context,+ pgConn *pgx.Conn,+ dbSizeBytes int64,+) []TableStat {+ analyzeCtx, cancel := context.WithTimeout(+ ctx, computeAnalyzeTimeout(dbSizeBytes, v.analyzeTimeoutMax))+ defer cancel()++ if _, err := pgConn.Exec(analyzeCtx, "ANALYZE"); err != nil {+ v.log.Warn("tier 4 skipped: ANALYZE failed or timed out", "error", err)+ return nil+ }++ queryCtx, cancel := context.WithTimeout(ctx, queryTimeout)+ defer cancel()++ rows, err := pgConn.Query(queryCtx, tableStatsSQL)+ if err != nil {+ v.log.Warn("tier 4 table stats unavailable", "error", err)+ return nil+ }+ defer rows.Close()++ var tableStats []TableStat+ for rows.Next() {+ var stat TableStat+ if err := rows.Scan(&stat.SchemaName, &stat.Name, &stat.RowCount); err != nil {+ v.log.Warn("tier 4 row scan failed", "error", err)+ return nil+ }++ tableStats = append(tableStats, stat)+ }++ if err := rows.Err(); err != nil {+ v.log.Warn("tier 4 row iteration failed", "error", err)+ return nil+ }++ return tableStats+}++// ProbeConnAlive is the runner's disambiguator: a failed tier with a dead+// connection is agent infra (retry), a failed tier on a live connection is a+// broken restored DB (terminal).+func ProbeConnAlive(ctx context.Context, conn dbconn.Conn) bool {+ probeCtx, cancel := context.WithTimeout(ctx, probeTimeout)+ defer cancel()++ pgConn, err := pgx.Connect(probeCtx, conn.DSN())+ if err != nil {+ return false+ }+ defer func() { _ = pgConn.Close(probeCtx) }()++ return pgConn.Ping(probeCtx) == nil+}++func collectRequiredStat[T any](ctx context.Context, pgConn *pgx.Conn, sql string, dest *T) error {+ queryCtx, cancel := context.WithTimeout(ctx, queryTimeout)+ defer cancel()++ return pgConn.QueryRow(queryCtx, sql).Scan(dest)+}++func collectOptionalStat[T any](+ ctx context.Context,+ log *slog.Logger,+ pgConn *pgx.Conn,+ sql string,+ dest *T,+ label string,+) {+ if err := collectRequiredStat(ctx, pgConn, sql, dest); err != nil {+ log.Warn(label, "error", err)+ }+}++// computeAnalyzeTimeout scales the ANALYZE budget with database size: a flat+// 30s makes tier-4 stats reliably absent on exactly the large databases they+// matter for.+func computeAnalyzeTimeout(dbSizeBytes int64, maxTimeout time.Duration) time.Duration {+ const bytesPerGB = 1024 * 1024 * 1024+ const perGB = 30 * time.Second++ gb := float64(dbSizeBytes) / bytesPerGB++ scaled := analyzeTimeoutMin + time.Duration(gb*float64(perGB))+ if scaled < analyzeTimeoutMin {+ return analyzeTimeoutMin+ }++ if scaled > maxTimeout {+ return maxTimeout+ }++ return scaled+}diff --git a/agent/verification/internal/features/verifier/verifier_test.go b/agent/verification/internal/features/verifier/verifier_test.gonew file mode 100644index 00000000..60a466a9--- /dev/null+++ b/agent/verification/internal/features/verifier/verifier_test.go@@ -0,0 +1,38 @@+package verifier++import (+ "strings"+ "testing"+ "time"++ "github.com/stretchr/testify/assert"+)++func Test_ComputeAnalyzeTimeout_ScalesWithSizeWithinFloorAndCap(t *testing.T) {+ maxTimeout := 10 * time.Minute++ // Empty DB → exactly the 60s floor; a tiny DB stays close to it.+ assert.Equal(t, analyzeTimeoutMin, computeAnalyzeTimeout(0, maxTimeout))+ tiny := computeAnalyzeTimeout(50*1024*1024, maxTimeout)+ assert.GreaterOrEqual(t, tiny, analyzeTimeoutMin)+ assert.Less(t, tiny, analyzeTimeoutMin+2*time.Second)++ // 10 GB → 60s + 10*30s = 360s, below the cap.+ assert.Equal(t, 360*time.Second, computeAnalyzeTimeout(10*1024*1024*1024, maxTimeout))++ // Huge DB → capped at maxTimeout, never unbounded.+ assert.Equal(t, maxTimeout, computeAnalyzeTimeout(500*1024*1024*1024, maxTimeout))+}++func Test_TierQueries_ExcludeSystemSchemas(t *testing.T) {+ for _, sql := range []string{schemaCountSQL, tableCountSQL, tableStatsSQL} {+ assert.Contains(t, sql, "pg_catalog")+ assert.Contains(t, sql, "information_schema")+ assert.Contains(t, sql, "pg_toast")+ assert.Contains(t, sql, excludedSchemaRegex)+ }++ assert.True(t, strings.HasPrefix(dbSizeSQL, "SELECT pg_database_size"))+ assert.Contains(t, tableCountSQL, "BASE TABLE")+ assert.Contains(t, tableStatsSQL, "LIMIT 100")+}diff --git a/agent/verification/internal/logger/logger.go b/agent/verification/internal/logger/logger.gonew file mode 100644index 00000000..253fcc56--- /dev/null+++ b/agent/verification/internal/logger/logger.go@@ -0,0 +1,115 @@+package logger++import (+ "fmt"+ "io"+ "log/slog"+ "os"+ "sync"+ "time"+)++const (+ logFileName = "databasus-verification.log"+ oldLogFileName = "databasus-verification.log.old"+ maxLogFileSize = 5 * 1024 * 1024 // 5MB+)++type rotatingWriter struct {+ mu sync.Mutex+ file *os.File+ currentSize int64+ maxSize int64+ logPath string+ oldLogPath string+}++func (w *rotatingWriter) Write(p []byte) (int, error) {+ w.mu.Lock()+ defer w.mu.Unlock()++ if w.currentSize+int64(len(p)) > w.maxSize {+ if err := w.rotate(); err != nil {+ return 0, fmt.Errorf("failed to rotate log file: %w", err)+ }+ }++ n, err := w.file.Write(p)+ w.currentSize += int64(n)++ return n, err+}++func (w *rotatingWriter) rotate() error {+ if err := w.file.Close(); err != nil {+ return fmt.Errorf("failed to close %s: %w", w.logPath, err)+ }++ if err := os.Remove(w.oldLogPath); err != nil && !os.IsNotExist(err) {+ return fmt.Errorf("failed to remove %s: %w", w.oldLogPath, err)+ }++ if err := os.Rename(w.logPath, w.oldLogPath); err != nil {+ return fmt.Errorf("failed to rename %s to %s: %w", w.logPath, w.oldLogPath, err)+ }++ f, err := os.OpenFile(w.logPath, os.O_CREATE|os.O_WRONLY, 0o644)+ if err != nil {+ return fmt.Errorf("failed to create new %s: %w", w.logPath, err)+ }++ w.file = f+ w.currentSize = 0++ return nil+}++var loggerInstance *slog.Logger++var initLogger = sync.OnceFunc(initialize)++func GetLogger() *slog.Logger {+ initLogger()+ return loggerInstance+}++func initialize() {+ writer := buildWriter()++ loggerInstance = slog.New(slog.NewTextHandler(writer, &slog.HandlerOptions{+ Level: slog.LevelInfo,+ ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {+ if a.Key == slog.TimeKey {+ a.Value = slog.StringValue(time.Now().Format("2006/01/02 15:04:05"))+ }+ if a.Key == slog.LevelKey {+ return slog.Attr{}+ }++ return a+ },+ }))+}++func buildWriter() io.Writer {+ f, err := os.OpenFile(logFileName, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)+ if err != nil {+ fmt.Fprintf(os.Stderr, "Warning: failed to open %s for logging: %v\n", logFileName, err)+ return os.Stdout+ }++ var currentSize int64+ if info, err := f.Stat(); err == nil {+ currentSize = info.Size()+ }++ rw := &rotatingWriter{+ file: f,+ currentSize: currentSize,+ maxSize: maxLogFileSize,+ logPath: logFileName,+ oldLogPath: oldLogFileName,+ }++ return io.MultiWriter(os.Stdout, rw)+}diff --git a/agent/verification/internal/testutil/testutil.go b/agent/verification/internal/testutil/testutil.gonew file mode 100644index 00000000..0a9b20b0--- /dev/null+++ b/agent/verification/internal/testutil/testutil.go@@ -0,0 +1,11 @@+// Package testutil holds helpers shared across the verification agent's+// package tests.+package testutil++import "log/slog"++// DiscardLogger returns a no-op logger so tests don't write to the rotating+// log file or stdout.+func DiscardLogger() *slog.Logger {+ return slog.New(slog.DiscardHandler)+}diff --git a/backend/CLAUDE.md b/backend/CLAUDE.mdindex eb15a17b..a0bdb7a2 100644--- a/backend/CLAUDE.md+++ b/backend/CLAUDE.md@@ -9,6 +9,7 @@ For project-wide engineering philosophy, naming, and lint/format commands, see t- [Spacing between logical statements](#spacing-between-logical-statements)- [Comments](#comments)+- [File organization](#file-organization)- [Controllers](#controllers)- [Dependency injection (DI)](#dependency-injection-di)- [Background services](#background-services)@@ -88,6 +89,29 @@ func CreateValidLogItems(count int, uniqueID string) []logs_receiving.LogItemReq---+## File organization++One responsibility per file. Don't dump a whole package into one file — split+by role so a reader can find a type by its filename. Conventional names within+a feature package:++- `doc.go` — package doc comment, once the package spans more than one file+- `<feature>.go` — the core type and its methods (the orchestrator/executor)+- `dto.go` — request/response and cross-package data + interface seams+- `errors.go` — sentinel errors (`var Err... = errors.New(...)`)+- `enums.go` — typed-constant groups (`type Status string` + its values)+- `constants.go` — package-level constants that aren't an enum+- background loops, reapers, and pools get their own file (`reaper.go`, `pool.go`)++Only create a file when there is real content for it — an empty `enums.go` or+`constants.go` is noise, not structure. Test files mirror the source split:+`restorer.go` → `restorer_test.go`, `diskexhaustion.go` →+`diskexhaustion_test.go`. The CRUD layout — `controller.go`, `service.go`,+`repository.go`, `model.go`, `dto.go`, `di.go` — is the same principle applied+to a Gin/GORM feature.++---+## Controllers- One controller per feature, combining all routes for that feature.diff --git a/backend/Makefile b/backend/Makefileindex 35268c74..d14ec212 100644--- a/backend/Makefile+++ b/backend/Makefile@@ -3,11 +3,11 @@run:go run cmd/main.go+# cleanup_test_db resets the metadata DB AND each test PG container+# (drops leftover roles/databases and recreates testdb) so containers+# stay usable across runs - tests that REVOKE on public or create+# per-run roles would otherwise poison subsequent pg_dump calls.test:- # cleanup_test_db resets the metadata DB AND each test PG container- # (drops leftover roles/databases and recreates testdb) so containers- # stay usable across runs - tests that REVOKE on public or create- # per-run roles would otherwise poison subsequent pg_dump calls.go run ./cmd/cleanup_test_dbgoose -dir ./migrations postgres "$(GOOSE_TEST_DBSTRING)" upgo test -p=1 -count=1 -failfast -timeout 15m ./internal/...diff --git a/backend/cmd/main.go b/backend/cmd/main.goindex 080586a5..14a1db9f 100644--- a/backend/cmd/main.go+++ b/backend/cmd/main.go@@ -46,6 +46,9 @@ import (users_controllers "databasus-backend/internal/features/users/controllers"users_middleware "databasus-backend/internal/features/users/middleware"users_services "databasus-backend/internal/features/users/services"+ verification_agents "databasus-backend/internal/features/verification/agents"+ verification_config "databasus-backend/internal/features/verification/config"+ verification_runs "databasus-backend/internal/features/verification/runs"workspaces_controllers "databasus-backend/internal/features/workspaces/controllers"cache_utils "databasus-backend/internal/util/cache"env_utils "databasus-backend/internal/util/env"@@ -225,6 +228,8 @@ func setUpRoutes(r *gin.Engine) {backups_controllers.GetBackupController().RegisterPublicRoutes(v1)backups_controllers.GetPostgresWalBackupController().RegisterRoutes(v1)databases.GetDatabaseController().RegisterPublicRoutes(v1)+ verification_agents.GetAgentFacingController().RegisterRoutes(v1)+ verification_runs.GetVerificationAgentController().RegisterRoutes(v1)if config.GetEnv().IsCloud {billing_paddle.GetPaddleBillingController().RegisterPublicRoutes(v1)@@ -254,6 +259,9 @@ func setUpRoutes(r *gin.Engine) {users_controllers.GetManagementController().RegisterRoutes(protected)users_controllers.GetSettingsController().RegisterRoutes(protected)billing.GetBillingController().RegisterRoutes(protected)+ verification_agents.GetAgentController().RegisterRoutes(protected)+ verification_config.GetVerificationConfigController().RegisterRoutes(protected)+ verification_runs.GetVerificationController().RegisterRoutes(protected)}func setUpDependencies() {@@ -265,6 +273,8 @@ func setUpDependencies() {notifiers.SetupDependencies()storages.SetupDependencies()backups_config.SetupDependencies()+ verification_config.SetupDependencies()+ verification_runs.SetupDependencies()task_cancellation.SetupDependencies()billing.SetupDependencies()@@ -317,6 +327,10 @@ func runBackgroundTasks(log *slog.Logger) {backuping.GetBackupsScheduler().Run(ctx)})+ go runWithPanicLogging(log, "verification scheduler", func() {+ verification_runs.GetVerificationScheduler().Run(ctx)+ })+go runWithPanicLogging(log, "backup cleaner background service", func() {backuping.GetBackupCleaner().Run(ctx)})diff --git a/backend/internal/features/backups/backups/backuping/cleaner_gfs_test.go b/backend/internal/features/backups/backups/backuping/cleaner_gfs_test.goindex 87b2d0c5..dc753ce5 100644--- a/backend/internal/features/backups/backups/backuping/cleaner_gfs_test.go+++ b/backend/internal/features/backups/backups/backuping/cleaner_gfs_test.go@@ -400,7 +400,6 @@ func Test_CleanByGFS_KeepsCorrectBackupsPerSlot(t *testing.T) {RetentionGfsMonths: 0,RetentionGfsYears: 0,StorageID: &storage.ID,- BackupIntervalID: interval.ID,BackupInterval: interval,}_, err := backups_config.GetBackupConfigService().SaveBackupConfig(backupConfig)@@ -475,7 +474,6 @@ func Test_CleanByGFS_WithWeeklyAndMonthlySlots_KeepsWiderSpread(t *testing.T) {RetentionGfsMonths: 1,RetentionGfsYears: 0,StorageID: &storage.ID,- BackupIntervalID: interval.ID,BackupInterval: interval,}_, err := backups_config.GetBackupConfigService().SaveBackupConfig(backupConfig)@@ -551,7 +549,6 @@ func Test_CleanByGFS_WithHourlySlots_KeepsCorrectBackups(t *testing.T) {RetentionPolicyType: backups_config.RetentionPolicyTypeGFS,RetentionGfsHours: 3,StorageID: &testStorage.ID,- BackupIntervalID: interval.ID,BackupInterval: interval,}_, err := backups_config.GetBackupConfigService().SaveBackupConfig(backupConfig)@@ -627,7 +624,6 @@ func Test_CleanByGFS_SkipsRecentBackup_WhenNotInKeepSet(t *testing.T) {RetentionPolicyType: backups_config.RetentionPolicyTypeGFS,RetentionGfsDays: 1,StorageID: &storage.ID,- BackupIntervalID: interval.ID,BackupInterval: interval,}_, err := backups_config.GetBackupConfigService().SaveBackupConfig(backupConfig)@@ -733,7 +729,6 @@ func Test_CleanByGFS_With20DailyBackups_KeepsOnlyExpectedCount(t *testing.T) {RetentionGfsWeeks: 4,RetentionGfsMonths: 1,StorageID: &testStorage.ID,- BackupIntervalID: interval.ID,BackupInterval: interval,}_, err := backups_config.GetBackupConfigService().SaveBackupConfig(backupConfig)@@ -814,7 +809,6 @@ func Test_CleanByGFS_WithMultipleBackupsPerDay_KeepsOnlyOnePerDailySlot(t *testiRetentionGfsDays: 7,RetentionGfsWeeks: 4,StorageID: &testStorage.ID,- BackupIntervalID: interval.ID,BackupInterval: interval,}_, err := backups_config.GetBackupConfigService().SaveBackupConfig(backupConfig)@@ -907,7 +901,6 @@ func Test_CleanByGFS_With24HourlySlotsAnd23DailyBackups_DeletesExcessBackups(t *RetentionGfsMonths: 12,RetentionGfsYears: 3,StorageID: &testStorage.ID,- BackupIntervalID: interval.ID,BackupInterval: interval,}_, err := backups_config.GetBackupConfigService().SaveBackupConfig(backupConfig)@@ -977,7 +970,6 @@ func Test_CleanByGFS_WithDisabledHourlySlotsAnd23DailyBackups_DeletesExcessBackuRetentionGfsMonths: 12,RetentionGfsYears: 3,StorageID: &testStorage.ID,- BackupIntervalID: interval.ID,BackupInterval: interval,}_, err := backups_config.GetBackupConfigService().SaveBackupConfig(backupConfig)@@ -1044,7 +1036,6 @@ func Test_CleanByGFS_WithDailySlotsAndWeeklyBackups_DeletesExcessBackups(t *testRetentionGfsDays: 7,RetentionGfsWeeks: 4,StorageID: &testStorage.ID,- BackupIntervalID: interval.ID,BackupInterval: interval,}_, err := backups_config.GetBackupConfigService().SaveBackupConfig(backupConfig)@@ -1126,7 +1117,6 @@ func Test_CleanByGFS_WithWeeklySlotsAndMonthlyBackups_DeletesExcessBackups(t *teRetentionGfsWeeks: 52,RetentionGfsMonths: 3,StorageID: &testStorage.ID,- BackupIntervalID: interval.ID,BackupInterval: interval,}_, err := backups_config.GetBackupConfigService().SaveBackupConfig(backupConfig)diff --git a/backend/internal/features/backups/backups/backuping/cleaner_test.go b/backend/internal/features/backups/backups/backuping/cleaner_test.goindex aab88ad5..8c4ceb18 100644--- a/backend/internal/features/backups/backups/backuping/cleaner_test.go+++ b/backend/internal/features/backups/backups/backuping/cleaner_test.go@@ -21,7 +21,6 @@ import (users_enums "databasus-backend/internal/features/users/enums"users_testing "databasus-backend/internal/features/users/testing"workspaces_testing "databasus-backend/internal/features/workspaces/testing"- "databasus-backend/internal/storage""databasus-backend/internal/util/logger""databasus-backend/internal/util/period")@@ -55,7 +54,6 @@ func Test_CleanOldBackups_DeletesBackupsOlderThanRetentionTimePeriod(t *testing.RetentionPolicyType: backups_config.RetentionPolicyTypeTimePeriod,RetentionTimePeriod: period.PeriodWeek,StorageID: &storage.ID,- BackupIntervalID: interval.ID,BackupInterval: interval,Encryption: backups_config.BackupEncryptionEncrypted,}@@ -134,7 +132,6 @@ func Test_CleanOldBackups_SkipsDatabaseWithForeverRetentionPeriod(t *testing.T)RetentionPolicyType: backups_config.RetentionPolicyTypeTimePeriod,RetentionTimePeriod: period.PeriodForever,StorageID: &storage.ID,- BackupIntervalID: interval.ID,BackupInterval: interval,Encryption: backups_config.BackupEncryptionEncrypted,}@@ -192,7 +189,6 @@ func Test_CleanExceededBackups_WhenUnderStorageLimit_NoBackupsDeleted(t *testingRetentionPolicyType: backups_config.RetentionPolicyTypeTimePeriod,RetentionTimePeriod: period.PeriodForever,StorageID: &storage.ID,- BackupIntervalID: interval.ID,BackupInterval: interval,Encryption: backups_config.BackupEncryptionEncrypted,}@@ -254,7 +250,6 @@ func Test_CleanExceededBackups_WhenOverStorageLimit_DeletesOldestBackups(t *testRetentionPolicyType: backups_config.RetentionPolicyTypeTimePeriod,RetentionTimePeriod: period.PeriodForever,StorageID: &storage.ID,- BackupIntervalID: interval.ID,BackupInterval: interval,Encryption: backups_config.BackupEncryptionEncrypted,}@@ -331,7 +326,6 @@ func Test_CleanExceededBackups_SkipsInProgressBackups(t *testing.T) {RetentionPolicyType: backups_config.RetentionPolicyTypeTimePeriod,RetentionTimePeriod: period.PeriodForever,StorageID: &storage.ID,- BackupIntervalID: interval.ID,BackupInterval: interval,Encryption: backups_config.BackupEncryptionEncrypted,}@@ -418,7 +412,6 @@ func Test_CleanExceededBackups_WithZeroStorageLimit_RemovesAllBackups(t *testingRetentionPolicyType: backups_config.RetentionPolicyTypeTimePeriod,RetentionTimePeriod: period.PeriodForever,StorageID: &storage.ID,- BackupIntervalID: interval.ID,BackupInterval: interval,Encryption: backups_config.BackupEncryptionEncrypted,}@@ -550,7 +543,6 @@ func Test_CleanByCount_KeepsNewestNBackups_DeletesOlder(t *testing.T) {RetentionPolicyType: backups_config.RetentionPolicyTypeCount,RetentionCount: 3,StorageID: &storage.ID,- BackupIntervalID: interval.ID,BackupInterval: interval,Encryption: backups_config.BackupEncryptionEncrypted,}@@ -623,7 +615,6 @@ func Test_CleanByCount_WhenUnderLimit_NoBackupsDeleted(t *testing.T) {RetentionPolicyType: backups_config.RetentionPolicyTypeCount,RetentionCount: 10,StorageID: &storage.ID,- BackupIntervalID: interval.ID,BackupInterval: interval,Encryption: backups_config.BackupEncryptionEncrypted,}@@ -681,7 +672,6 @@ func Test_CleanByCount_DoesNotDeleteInProgressBackups(t *testing.T) {RetentionPolicyType: backups_config.RetentionPolicyTypeCount,RetentionCount: 2,StorageID: &storage.ID,- BackupIntervalID: interval.ID,BackupInterval: interval,Encryption: backups_config.BackupEncryptionEncrypted,}@@ -807,7 +797,6 @@ func Test_CleanByTimePeriod_SkipsRecentBackup_EvenIfOlderThanRetention(t *testinRetentionPolicyType: backups_config.RetentionPolicyTypeTimePeriod,RetentionTimePeriod: period.PeriodDay,StorageID: &storage.ID,- BackupIntervalID: interval.ID,BackupInterval: interval,Encryption: backups_config.BackupEncryptionEncrypted,}@@ -879,7 +868,6 @@ func Test_CleanByCount_SkipsRecentBackup_EvenIfOverLimit(t *testing.T) {RetentionPolicyType: backups_config.RetentionPolicyTypeCount,RetentionCount: 2,StorageID: &storage.ID,- BackupIntervalID: interval.ID,BackupInterval: interval,Encryption: backups_config.BackupEncryptionEncrypted,}@@ -982,7 +970,6 @@ func Test_CleanExceededBackups_SkipsRecentBackup_WhenOverStorageLimit(t *testingRetentionPolicyType: backups_config.RetentionPolicyTypeTimePeriod,RetentionTimePeriod: period.PeriodForever,StorageID: &storage.ID,- BackupIntervalID: interval.ID,BackupInterval: interval,Encryption: backups_config.BackupEncryptionEncrypted,}@@ -1059,7 +1046,6 @@ func Test_CleanExceededStorageBackups_WhenNonCloud_SkipsCleanup(t *testing.T) {RetentionPolicyType: backups_config.RetentionPolicyTypeTimePeriod,RetentionTimePeriod: period.PeriodForever,StorageID: &storage.ID,- BackupIntervalID: interval.ID,BackupInterval: interval,Encryption: backups_config.BackupEncryptionEncrypted,}@@ -1338,7 +1324,6 @@ func Test_CleanByRetentionPolicy_DoesNotDeleteOnlyCompletedFullWalBackup(t *testRetentionPolicyType: backups_config.RetentionPolicyTypeTimePeriod,RetentionTimePeriod: period.PeriodDay,StorageID: &storage.ID,- BackupIntervalID: interval.ID,BackupInterval: interval,Encryption: backups_config.BackupEncryptionNone,}@@ -1491,7 +1476,6 @@ func createWalRetentionFixture(RetentionTimePeriod: period.PeriodDay,RetentionCount: 2,StorageID: &storage.ID,- BackupIntervalID: interval.ID,BackupInterval: interval,Encryption: backups_config.BackupEncryptionEncrypted,}@@ -1625,17 +1609,11 @@ func testLogger() *slog.Logger {return logger.GetLogger().With("task_name", "test")}-func createTestInterval() *intervals.Interval {+func createTestInterval() intervals.Interval {timeOfDay := "04:00"- interval := &intervals.Interval{- Interval: intervals.IntervalDaily,- TimeOfDay: &timeOfDay,- }- err := storage.GetDb().Create(interval).Error- if err != nil {- panic(err)+ return intervals.Interval{+ Type: intervals.IntervalDaily,+ TimeOfDay: &timeOfDay,}-- return interval}diff --git a/backend/internal/features/backups/backups/backuping/di.go b/backend/internal/features/backups/backups/backuping/di.goindex ec5ce4fc..33748ef9 100644--- a/backend/internal/features/backups/backups/backuping/di.go+++ b/backend/internal/features/backups/backups/backuping/di.go@@ -78,6 +78,7 @@ var backupsScheduler = &BackupsScheduler{make(map[uuid.UUID]BackupToNodeRelation),sync.Mutex{},backuperNode,+ []backups_core.BackupCompletionListener{},atomic.Bool{},}diff --git a/backend/internal/features/backups/backups/backuping/scheduler.go b/backend/internal/features/backups/backups/backuping/scheduler.goindex 9cc62bde..e778e219 100644--- a/backend/internal/features/backups/backups/backuping/scheduler.go+++ b/backend/internal/features/backups/backups/backuping/scheduler.go@@ -39,9 +39,17 @@ type BackupsScheduler struct {backupToNodeRelationsMtx sync.MutexbackuperNode *BackuperNode+ backupCompletionListeners []backups_core.BackupCompletionListener+hasRun atomic.Bool}+func (s *BackupsScheduler) AddBackupCompletionListener(+ listener backups_core.BackupCompletionListener,+) {+ s.backupCompletionListeners = append(s.backupCompletionListeners, listener)+}+func (s *BackupsScheduler) Run(ctx context.Context) {if s.hasRun.Swap(true) {panic(fmt.Sprintf("%T.Run() called multiple times", s))@@ -329,10 +337,6 @@ func (s *BackupsScheduler) runPendingBackups() error {}for _, backupConfig := range enabledBackupConfigs {- if backupConfig.BackupInterval == nil {- continue- }-lastBackup, err := s.backupRepository.FindLastByDatabaseID(backupConfig.DatabaseID)if err != nil {s.logger.Error(@@ -359,7 +363,7 @@ func (s *BackupsScheduler) runPendingBackups() error {"databaseId",backupConfig.DatabaseID,"intervalType",- backupConfig.BackupInterval.Interval,+ backupConfig.BackupInterval.Type,)database, err := s.databaseService.GetDatabaseByID(backupConfig.DatabaseID)@@ -500,6 +504,10 @@ func (s *BackupsScheduler) onBackupCompleted(nodeID, backupID uuid.UUID) {return}+ for _, listener := range s.backupCompletionListeners {+ go listener.OnBackupCompleted(backupID)+ }+s.backupToNodeRelationsMtx.Lock()relation, exists := s.backupToNodeRelations[nodeID]if !exists {diff --git a/backend/internal/features/backups/backups/backuping/scheduler_test.go b/backend/internal/features/backups/backups/backuping/scheduler_test.goindex c715ec0b..85025b65 100644--- a/backend/internal/features/backups/backups/backuping/scheduler_test.go+++ b/backend/internal/features/backups/backups/backuping/scheduler_test.go@@ -102,8 +102,8 @@ func Test_RunPendingBackups_ByDatabaseType_OnlySchedulesNonAgentManagedBackups(tassert.NoError(t, err)timeOfDay := "04:00"- backupConfig.BackupInterval = &intervals.Interval{- Interval: intervals.IntervalDaily,+ backupConfig.BackupInterval = intervals.Interval{+ Type: intervals.IntervalDaily,TimeOfDay: &timeOfDay,}backupConfig.IsBackupsEnabled = true@@ -177,8 +177,8 @@ func Test_RunPendingBackups_WhenLastBackupWasYesterday_CreatesNewBackup(t *testiassert.NoError(t, err)timeOfDay := "04:00"- backupConfig.BackupInterval = &intervals.Interval{- Interval: intervals.IntervalDaily,+ backupConfig.BackupInterval = intervals.Interval{+ Type: intervals.IntervalDaily,TimeOfDay: &timeOfDay,}backupConfig.IsBackupsEnabled = true@@ -247,8 +247,8 @@ func Test_RunPendingBackups_WhenLastBackupWasRecentlyCompleted_SkipsBackup(t *teassert.NoError(t, err)timeOfDay := "04:00"- backupConfig.BackupInterval = &intervals.Interval{- Interval: intervals.IntervalDaily,+ backupConfig.BackupInterval = intervals.Interval{+ Type: intervals.IntervalDaily,TimeOfDay: &timeOfDay,}backupConfig.IsBackupsEnabled = true@@ -316,8 +316,8 @@ func Test_RunPendingBackups_WhenLastBackupFailedAndRetriesDisabled_SkipsBackup(tassert.NoError(t, err)timeOfDay := "04:00"- backupConfig.BackupInterval = &intervals.Interval{- Interval: intervals.IntervalDaily,+ backupConfig.BackupInterval = intervals.Interval{+ Type: intervals.IntervalDaily,TimeOfDay: &timeOfDay,}backupConfig.IsBackupsEnabled = true@@ -389,8 +389,8 @@ func Test_RunPendingBackups_WhenLastBackupFailedAndRetriesEnabled_CreatesNewBackassert.NoError(t, err)timeOfDay := "04:00"- backupConfig.BackupInterval = &intervals.Interval{- Interval: intervals.IntervalDaily,+ backupConfig.BackupInterval = intervals.Interval{+ Type: intervals.IntervalDaily,TimeOfDay: &timeOfDay,}backupConfig.IsBackupsEnabled = true@@ -463,8 +463,8 @@ func Test_RunPendingBackups_WhenFailedBackupsExceedMaxRetries_SkipsBackup(t *tesassert.NoError(t, err)timeOfDay := "04:00"- backupConfig.BackupInterval = &intervals.Interval{- Interval: intervals.IntervalDaily,+ backupConfig.BackupInterval = intervals.Interval{+ Type: intervals.IntervalDaily,TimeOfDay: &timeOfDay,}backupConfig.IsBackupsEnabled = true@@ -535,8 +535,8 @@ func Test_RunPendingBackups_WhenBackupsDisabled_SkipsBackup(t *testing.T) {assert.NoError(t, err)timeOfDay := "04:00"- backupConfig.BackupInterval = &intervals.Interval{- Interval: intervals.IntervalDaily,+ backupConfig.BackupInterval = intervals.Interval{+ Type: intervals.IntervalDaily,TimeOfDay: &timeOfDay,}backupConfig.IsBackupsEnabled = false@@ -605,8 +605,8 @@ func Test_CheckDeadNodesAndFailBackups_WhenNodeDies_FailsBackupAndCleansUpRegistassert.NoError(t, err)timeOfDay := "04:00"- backupConfig.BackupInterval = &intervals.Interval{- Interval: intervals.IntervalDaily,+ backupConfig.BackupInterval = intervals.Interval{+ Type: intervals.IntervalDaily,TimeOfDay: &timeOfDay,}backupConfig.IsBackupsEnabled = true@@ -709,8 +709,8 @@ func Test_OnBackupCompleted_WhenTaskIsNotBackup_SkipsProcessing(t *testing.T) {assert.NoError(t, err)timeOfDay := "04:00"- backupConfig.BackupInterval = &intervals.Interval{- Interval: intervals.IntervalDaily,+ backupConfig.BackupInterval = intervals.Interval{+ Type: intervals.IntervalDaily,TimeOfDay: &timeOfDay,}backupConfig.IsBackupsEnabled = true@@ -887,8 +887,8 @@ func Test_FailBackupsInProgress_WhenSchedulerStarts_CancelsBackupsAndUpdatesStatassert.NoError(t, err)timeOfDay := "04:00"- backupConfig.BackupInterval = &intervals.Interval{- Interval: intervals.IntervalDaily,+ backupConfig.BackupInterval = intervals.Interval{+ Type: intervals.IntervalDaily,TimeOfDay: &timeOfDay,}backupConfig.IsBackupsEnabled = true@@ -1001,8 +1001,8 @@ func Test_StartBackup_WhenBackupCompletes_DecrementsActiveTaskCount(t *testing.Tassert.NoError(t, err)timeOfDay := "04:00"- backupConfig.BackupInterval = &intervals.Interval{- Interval: intervals.IntervalDaily,+ backupConfig.BackupInterval = intervals.Interval{+ Type: intervals.IntervalDaily,TimeOfDay: &timeOfDay,}backupConfig.IsBackupsEnabled = true@@ -1105,8 +1105,8 @@ func Test_StartBackup_WhenBackupFails_DecrementsActiveTaskCount(t *testing.T) {assert.NoError(t, err)timeOfDay := "04:00"- backupConfig.BackupInterval = &intervals.Interval{- Interval: intervals.IntervalDaily,+ backupConfig.BackupInterval = intervals.Interval{+ Type: intervals.IntervalDaily,TimeOfDay: &timeOfDay,}backupConfig.IsBackupsEnabled = true@@ -1200,8 +1200,8 @@ func Test_StartBackup_WhenBackupAlreadyInProgress_SkipsNewBackup(t *testing.T) {assert.NoError(t, err)timeOfDay := "04:00"- backupConfig.BackupInterval = &intervals.Interval{- Interval: intervals.IntervalDaily,+ backupConfig.BackupInterval = intervals.Interval{+ Type: intervals.IntervalDaily,TimeOfDay: &timeOfDay,}backupConfig.IsBackupsEnabled = true@@ -1272,8 +1272,8 @@ func Test_RunPendingBackups_WhenLastBackupFailedWithIsSkipRetry_SkipsBackupEvenWassert.NoError(t, err)timeOfDay := "04:00"- backupConfig.BackupInterval = &intervals.Interval{- Interval: intervals.IntervalDaily,+ backupConfig.BackupInterval = intervals.Interval{+ Type: intervals.IntervalDaily,TimeOfDay: &timeOfDay,}backupConfig.IsBackupsEnabled = true@@ -1375,8 +1375,8 @@ func Test_StartBackup_When2BackupsStartedForDifferentDatabases_BothUseCasesAreCaassert.NoError(t, err)timeOfDay := "04:00"- backupConfig1.BackupInterval = &intervals.Interval{- Interval: intervals.IntervalDaily,+ backupConfig1.BackupInterval = intervals.Interval{+ Type: intervals.IntervalDaily,TimeOfDay: &timeOfDay,}backupConfig1.IsBackupsEnabled = true@@ -1393,8 +1393,8 @@ func Test_StartBackup_When2BackupsStartedForDifferentDatabases_BothUseCasesAreCaGetBackupConfigByDbId(database2.ID)assert.NoError(t, err)- backupConfig2.BackupInterval = &intervals.Interval{- Interval: intervals.IntervalDaily,+ backupConfig2.BackupInterval = intervals.Interval{+ Type: intervals.IntervalDaily,TimeOfDay: &timeOfDay,}backupConfig2.IsBackupsEnabled = true@@ -1612,8 +1612,8 @@ func Test_RunPendingBackups_WhenCloudAndSubscriptionExpired_SilentlySkips(t *tesassert.NoError(t, err)timeOfDay := "04:00"- backupConfig.BackupInterval = &intervals.Interval{- Interval: intervals.IntervalDaily,+ backupConfig.BackupInterval = intervals.Interval{+ Type: intervals.IntervalDaily,TimeOfDay: &timeOfDay,}backupConfig.IsBackupsEnabled = true@@ -1739,8 +1739,8 @@ func Test_RunPendingBackups_WhenNotCloudAndSubscriptionExpired_ProceedsNormally(assert.NoError(t, err)timeOfDay := "04:00"- backupConfig.BackupInterval = &intervals.Interval{- Interval: intervals.IntervalDaily,+ backupConfig.BackupInterval = intervals.Interval{+ Type: intervals.IntervalDaily,TimeOfDay: &timeOfDay,}backupConfig.IsBackupsEnabled = truediff --git a/backend/internal/features/backups/backups/backuping/testing.go b/backend/internal/features/backups/backups/backuping/testing.goindex 7e8c2552..b31c5da9 100644--- a/backend/internal/features/backups/backups/backuping/testing.go+++ b/backend/internal/features/backups/backups/backuping/testing.go@@ -20,10 +20,77 @@ import (workspaces_controllers "databasus-backend/internal/features/workspaces/controllers"workspaces_services "databasus-backend/internal/features/workspaces/services"workspaces_testing "databasus-backend/internal/features/workspaces/testing"+ "databasus-backend/internal/storage""databasus-backend/internal/util/encryption""databasus-backend/internal/util/logger")+func seedBackup(t *testing.T, label string, backup *backups_core.Backup) *backups_core.Backup {+ t.Helper()++ if err := storage.GetDb().Create(backup).Error; err != nil {+ t.Fatalf("seed %s backup: %v", label, err)+ }++ return backup+}++func SeedTestBackup(+ t *testing.T,+ databaseID, storageID uuid.UUID,+ sizeMb float64,+) *backups_core.Backup {+ t.Helper()++ return seedBackup(t, "completed", &backups_core.Backup{+ ID: uuid.New(),+ FileName: "test-backup-" + uuid.New().String(),+ DatabaseID: databaseID,+ StorageID: storageID,+ Status: backups_core.BackupStatusCompleted,+ BackupSizeMb: sizeMb,+ BackupRawDbSizeMb: sizeMb,+ CreatedAt: time.Now().UTC(),+ })+}++func SeedTestWalSegmentBackup(+ t *testing.T,+ databaseID, storageID uuid.UUID,+) *backups_core.Backup {+ t.Helper()++ walType := backups_core.PgWalBackupTypeWalSegment++ return seedBackup(t, "wal segment", &backups_core.Backup{+ ID: uuid.New(),+ FileName: "test-wal-segment-" + uuid.New().String(),+ DatabaseID: databaseID,+ StorageID: storageID,+ Status: backups_core.BackupStatusCompleted,+ PgWalBackupType: &walType,+ CreatedAt: time.Now().UTC(),+ })+}++// SeedInProgressTestBackup inserts an IN_PROGRESS backup row so MakeBackup can+// pick it up and drive it through to completion (mirrors backuper_test.go's+// manual setup, but reusable across packages).+func SeedInProgressTestBackup(+ t *testing.T,+ databaseID, storageID uuid.UUID,+) *backups_core.Backup {+ t.Helper()++ return seedBackup(t, "in-progress", &backups_core.Backup{+ ID: uuid.New(),+ DatabaseID: databaseID,+ StorageID: storageID,+ Status: backups_core.BackupStatusInProgress,+ CreatedAt: time.Now().UTC(),+ })+}+func CreateTestRouter() *gin.Engine {router := workspaces_testing.CreateTestRouter(workspaces_controllers.GetWorkspaceController(),@@ -99,6 +166,7 @@ func CreateTestScheduler(billingService BillingService) *BackupsScheduler {make(map[uuid.UUID]BackupToNodeRelation),sync.Mutex{},CreateTestBackuperNode(),+ []backups_core.BackupCompletionListener{},atomic.Bool{},}}diff --git a/backend/internal/features/backups/backups/controllers/postgres_wal_controller_test.go b/backend/internal/features/backups/backups/controllers/postgres_wal_controller_test.goindex d505020a..ba10f261 100644--- a/backend/internal/features/backups/backups/controllers/postgres_wal_controller_test.go+++ b/backend/internal/features/backups/backups/controllers/postgres_wal_controller_test.go@@ -624,14 +624,14 @@ func Test_GetNextFullBackupTime_WithValidToken_HasFullBackup_ReturnsTime(t *test{name: "hourly interval returns future time",interval: &intervals.Interval{- Interval: intervals.IntervalHourly,+ Type: intervals.IntervalHourly,},checkHourMin: false,},{name: "cron interval returns future time",interval: &intervals.Interval{- Interval: intervals.IntervalCron,+ Type: intervals.IntervalCron,CronExpression: &cronExpr,},checkHourMin: false,@@ -639,7 +639,7 @@ func Test_GetNextFullBackupTime_WithValidToken_HasFullBackup_ReturnsTime(t *test{name: "daily interval with custom time 14:30",interval: &intervals.Interval{- Interval: intervals.IntervalDaily,+ Type: intervals.IntervalDaily,TimeOfDay: &customTime,},expectedHour: 14,@@ -662,7 +662,7 @@ func Test_GetNextFullBackupTime_WithValidToken_HasFullBackup_ReturnsTime(t *testhttp.StatusOK, &cfg,)- cfg.BackupInterval = tt.interval+ cfg.BackupInterval = *tt.intervaltest_utils.MakePostRequestAndUnmarshal(t, router,@@ -1668,6 +1668,6 @@ func setBackupsEnabled(func setHourlyInterval(t *testing.T, router *gin.Engine, databaseID uuid.UUID, ownerToken string) {mutateBackupConfig(t, router, databaseID, ownerToken, func(cfg *backups_config.BackupConfig) {- cfg.BackupInterval = &intervals.Interval{Interval: intervals.IntervalHourly}+ cfg.BackupInterval = intervals.Interval{Type: intervals.IntervalHourly}})}diff --git a/backend/internal/features/backups/backups/core/enums.go b/backend/internal/features/backups/backups/core/enums.goindex cc422b48..08511f42 100644--- a/backend/internal/features/backups/backups/core/enums.go+++ b/backend/internal/features/backups/backups/core/enums.go@@ -15,3 +15,11 @@ const (PgWalUploadTypeBasebackup PgWalUploadType = "basebackup"PgWalUploadTypeWal PgWalUploadType = "wal")++type RestoreVerificationStatus string++const (+ RestoreVerificationStatusNotVerified RestoreVerificationStatus = "NOT_VERIFIED"+ RestoreVerificationStatusVerifiedSuccessful RestoreVerificationStatus = "VERIFIED_SUCCESSFUL"+ RestoreVerificationStatusVerificationFailed RestoreVerificationStatus = "VERIFICATION_FAILED"+)diff --git a/backend/internal/features/backups/backups/core/interfaces.go b/backend/internal/features/backups/backups/core/interfaces.goindex cdff8fbf..c848db48 100644--- a/backend/internal/features/backups/backups/core/interfaces.go+++ b/backend/internal/features/backups/backups/core/interfaces.go@@ -3,6 +3,8 @@ package backups_coreimport ("context"+ "github.com/google/uuid"+usecases_common "databasus-backend/internal/features/backups/backups/common"backups_config "databasus-backend/internal/features/backups/config""databasus-backend/internal/features/databases"@@ -32,3 +34,7 @@ type CreateBackupUsecase interface {type BackupRemoveListener interface {OnBeforeBackupRemove(backup *Backup) error}++type BackupCompletionListener interface {+ OnBackupCompleted(backupID uuid.UUID)+}diff --git a/backend/internal/features/backups/backups/core/model.go b/backend/internal/features/backups/backups/core/model.goindex 89fc96ad..aad66d1b 100644--- a/backend/internal/features/backups/backups/core/model.go+++ b/backend/internal/features/backups/backups/core/model.go@@ -28,6 +28,8 @@ type Backup struct {FailMessage *string `json:"failMessage" gorm:"column:fail_message"`IsSkipRetry bool `json:"isSkipRetry" gorm:"column:is_skip_retry;type:boolean;not null"`+ RestoreVerificationStatus RestoreVerificationStatus `json:"restoreVerificationStatus" gorm:"column:restore_verification_status;type:text;not null;default:'NOT_VERIFIED'"`+BackupSizeMb float64 `json:"backupSizeMb" gorm:"column:backup_size_mb;default:0"`BackupRawDbSizeMb float64 `json:"backupRawDbSizeMb" gorm:"column:backup_raw_db_size_mb;default:0"`diff --git a/backend/internal/features/backups/backups/core/repository.go b/backend/internal/features/backups/backups/core/repository.goindex 5a0b1693..33f96b23 100644--- a/backend/internal/features/backups/backups/core/repository.go+++ b/backend/internal/features/backups/backups/core/repository.go@@ -30,6 +30,22 @@ func (r *BackupRepository) Save(backup *Backup) error {Error}+func (r *BackupRepository) UpdateRestoreVerificationStatus(+ backupID uuid.UUID,+ status RestoreVerificationStatus,+) error {+ if backupID == uuid.Nil {+ return errors.New("backup ID is required")+ }++ return storage.+ GetDb().+ Model(&Backup{}).+ Where("id = ?", backupID).+ Update("restore_verification_status", status).+ Error+}+func (r *BackupRepository) ExistsCompletedSince(databaseID uuid.UUID,since time.Time,@@ -338,6 +354,29 @@ func (r *BackupRepository) FindLatestCompleted(return &backup, nil}+func (r *BackupRepository) FindLatestVerifiableBackup(+ databaseID uuid.UUID,+) (*Backup, error) {+ var backup Backup++ err := storage.GetDb().+ Where(+ "database_id = ? AND status = ? AND pg_wal_backup_type IS NULL",+ databaseID, BackupStatusCompleted,+ ).+ Order("created_at DESC").+ First(&backup).Error+ if err != nil {+ if errors.Is(err, gorm.ErrRecordNotFound) {+ return nil, nil+ }++ return nil, err+ }++ return &backup, nil+}+func (r *BackupRepository) FindLastCompletedFullWalBackupByDatabaseID(databaseID uuid.UUID,) (*Backup, error) {diff --git a/backend/internal/features/backups/backups/services/postgres_wal_service.go b/backend/internal/features/backups/backups/services/postgres_wal_service.goindex 2f3e58ba..8c434548 100644--- a/backend/internal/features/backups/backups/services/postgres_wal_service.go+++ b/backend/internal/features/backups/backups/services/postgres_wal_service.go@@ -331,10 +331,6 @@ func (s *PostgreWalBackupService) GetNextFullBackupTime(return &backups_dto.GetNextFullBackupTimeResponse{NextFullBackupTime: nil}, nil}- if backupConfig.BackupInterval == nil {- return nil, fmt.Errorf("no backup interval configured for database %s", database.ID)- }-lastFullBackup, err := s.backupRepository.FindLastCompletedFullWalBackupByDatabaseID(database.ID,)diff --git a/backend/internal/features/backups/backups/services/service.go b/backend/internal/features/backups/backups/services/service.goindex 0be96135..14e6d008 100644--- a/backend/internal/features/backups/backups/services/service.go+++ b/backend/internal/features/backups/backups/services/service.go@@ -212,6 +212,13 @@ func (s *BackupService) GetBackup(backupID uuid.UUID) (*backups_core.Backup, errreturn s.backupRepository.FindByID(backupID)}+func (s *BackupService) SetRestoreVerificationStatus(+ backupID uuid.UUID,+ status backups_core.RestoreVerificationStatus,+) error {+ return s.backupRepository.UpdateRestoreVerificationStatus(backupID, status)+}+func (s *BackupService) CancelBackup(user *users_models.User,backupID uuid.UUID,@@ -440,6 +447,12 @@ func (s *BackupService) ValidateDownloadToken(return s.downloadTokenService.ValidateAndConsume(token)}+func (s *BackupService) GetLatestVerifiableBackup(+ databaseID uuid.UUID,+) (*backups_core.Backup, error) {+ return s.backupRepository.FindLatestVerifiableBackup(databaseID)+}+func (s *BackupService) GetBackupFileWithoutAuth(backupID uuid.UUID,) (io.ReadCloser, *backups_core.Backup, *databases.Database, error) {diff --git a/backend/internal/features/backups/config/controller_test.go b/backend/internal/features/backups/config/controller_test.goindex fbc7136b..958a0902 100644--- a/backend/internal/features/backups/config/controller_test.go+++ b/backend/internal/features/backups/config/controller_test.go@@ -120,8 +120,8 @@ func Test_SaveBackupConfig_PermissionsEnforced(t *testing.T) {IsBackupsEnabled: true,RetentionPolicyType: RetentionPolicyTypeTimePeriod,RetentionTimePeriod: period.PeriodWeek,- BackupInterval: &intervals.Interval{- Interval: intervals.IntervalDaily,+ BackupInterval: intervals.Interval{+ Type: intervals.IntervalDaily,TimeOfDay: &timeOfDay,},SendNotificationsOn: []BackupNotificationType{@@ -173,8 +173,8 @@ func Test_SaveBackupConfig_WhenUserIsNotWorkspaceMember_ReturnsForbidden(t *testIsBackupsEnabled: true,RetentionPolicyType: RetentionPolicyTypeTimePeriod,RetentionTimePeriod: period.PeriodWeek,- BackupInterval: &intervals.Interval{- Interval: intervals.IntervalDaily,+ BackupInterval: intervals.Interval{+ Type: intervals.IntervalDaily,TimeOfDay: &timeOfDay,},SendNotificationsOn: []BackupNotificationType{@@ -421,8 +421,8 @@ func Test_SaveBackupConfig_WithEncryptionNone_ConfigSaved(t *testing.T) {IsBackupsEnabled: true,RetentionPolicyType: RetentionPolicyTypeTimePeriod,RetentionTimePeriod: period.PeriodWeek,- BackupInterval: &intervals.Interval{- Interval: intervals.IntervalDaily,+ BackupInterval: intervals.Interval{+ Type: intervals.IntervalDaily,TimeOfDay: &timeOfDay,},SendNotificationsOn: []BackupNotificationType{@@ -466,8 +466,8 @@ func Test_SaveBackupConfig_WithEncryptionEncrypted_ConfigSaved(t *testing.T) {IsBackupsEnabled: true,RetentionPolicyType: RetentionPolicyTypeTimePeriod,RetentionTimePeriod: period.PeriodWeek,- BackupInterval: &intervals.Interval{- Interval: intervals.IntervalDaily,+ BackupInterval: intervals.Interval{+ Type: intervals.IntervalDaily,TimeOfDay: &timeOfDay,},SendNotificationsOn: []BackupNotificationType{@@ -764,8 +764,8 @@ func Test_TransferDatabase_ToNewStorage_DatabaseTransferd(t *testing.T) {IsBackupsEnabled: true,RetentionPolicyType: RetentionPolicyTypeTimePeriod,RetentionTimePeriod: period.PeriodWeek,- BackupInterval: &intervals.Interval{- Interval: intervals.IntervalDaily,+ BackupInterval: intervals.Interval{+ Type: intervals.IntervalDaily,TimeOfDay: &timeOfDay,},Storage: sourceStorage,@@ -851,8 +851,8 @@ func Test_TransferDatabase_WithExistingStorage_DatabaseAndStorageTransferd(t *teIsBackupsEnabled: true,RetentionPolicyType: RetentionPolicyTypeTimePeriod,RetentionTimePeriod: period.PeriodWeek,- BackupInterval: &intervals.Interval{- Interval: intervals.IntervalDaily,+ BackupInterval: intervals.Interval{+ Type: intervals.IntervalDaily,TimeOfDay: &timeOfDay,},Storage: storage,@@ -949,8 +949,8 @@ func Test_TransferDatabase_StorageHasOtherDBs_CannotTransfer(t *testing.T) {IsBackupsEnabled: true,RetentionPolicyType: RetentionPolicyTypeTimePeriod,RetentionTimePeriod: period.PeriodWeek,- BackupInterval: &intervals.Interval{- Interval: intervals.IntervalDaily,+ BackupInterval: intervals.Interval{+ Type: intervals.IntervalDaily,TimeOfDay: &timeOfDay,},Storage: storage,@@ -976,8 +976,8 @@ func Test_TransferDatabase_StorageHasOtherDBs_CannotTransfer(t *testing.T) {IsBackupsEnabled: true,RetentionPolicyType: RetentionPolicyTypeTimePeriod,RetentionTimePeriod: period.PeriodWeek,- BackupInterval: &intervals.Interval{- Interval: intervals.IntervalDaily,+ BackupInterval: intervals.Interval{+ Type: intervals.IntervalDaily,TimeOfDay: &timeOfDay,},Storage: storage,@@ -1053,8 +1053,8 @@ func Test_TransferDatabase_WithNotifiers_NotifiersTransferred(t *testing.T) {IsBackupsEnabled: true,RetentionPolicyType: RetentionPolicyTypeTimePeriod,RetentionTimePeriod: period.PeriodWeek,- BackupInterval: &intervals.Interval{- Interval: intervals.IntervalDaily,+ BackupInterval: intervals.Interval{+ Type: intervals.IntervalDaily,TimeOfDay: &timeOfDay,},Storage: sourceStorage,@@ -1174,8 +1174,8 @@ func Test_TransferDatabase_NotifierHasOtherDBs_NotifierSkipped(t *testing.T) {IsBackupsEnabled: true,RetentionPolicyType: RetentionPolicyTypeTimePeriod,RetentionTimePeriod: period.PeriodWeek,- BackupInterval: &intervals.Interval{- Interval: intervals.IntervalDaily,+ BackupInterval: intervals.Interval{+ Type: intervals.IntervalDaily,TimeOfDay: &timeOfDay,},Storage: sourceStorage,@@ -1297,8 +1297,8 @@ func Test_TransferDatabase_WithMultipleNotifiers_OnlyExclusiveOnesTransferred(tIsBackupsEnabled: true,RetentionPolicyType: RetentionPolicyTypeTimePeriod,RetentionTimePeriod: period.PeriodWeek,- BackupInterval: &intervals.Interval{- Interval: intervals.IntervalDaily,+ BackupInterval: intervals.Interval{+ Type: intervals.IntervalDaily,TimeOfDay: &timeOfDay,},Storage: sourceStorage,@@ -1397,8 +1397,8 @@ func Test_TransferDatabase_WithTargetNotifiers_NotifiersAssigned(t *testing.T) {IsBackupsEnabled: true,RetentionPolicyType: RetentionPolicyTypeTimePeriod,RetentionTimePeriod: period.PeriodWeek,- BackupInterval: &intervals.Interval{- Interval: intervals.IntervalDaily,+ BackupInterval: intervals.Interval{+ Type: intervals.IntervalDaily,TimeOfDay: &timeOfDay,},Storage: sourceStorage,@@ -1478,8 +1478,8 @@ func Test_TransferDatabase_TargetNotifierFromDifferentWorkspace_ReturnsBadRequesIsBackupsEnabled: true,RetentionPolicyType: RetentionPolicyTypeTimePeriod,RetentionTimePeriod: period.PeriodWeek,- BackupInterval: &intervals.Interval{- Interval: intervals.IntervalDaily,+ BackupInterval: intervals.Interval{+ Type: intervals.IntervalDaily,TimeOfDay: &timeOfDay,},Storage: sourceStorage,@@ -1544,8 +1544,8 @@ func Test_TransferDatabase_TargetStorageFromDifferentWorkspace_ReturnsBadRequestIsBackupsEnabled: true,RetentionPolicyType: RetentionPolicyTypeTimePeriod,RetentionTimePeriod: period.PeriodWeek,- BackupInterval: &intervals.Interval{- Interval: intervals.IntervalDaily,+ BackupInterval: intervals.Interval{+ Type: intervals.IntervalDaily,TimeOfDay: &timeOfDay,},Storage: sourceStorage,@@ -1604,8 +1604,8 @@ func Test_SaveBackupConfig_WithSystemStorage_CanBeUsedByAnyDatabase(t *testing.TIsBackupsEnabled: true,RetentionPolicyType: RetentionPolicyTypeTimePeriod,RetentionTimePeriod: period.PeriodWeek,- BackupInterval: &intervals.Interval{- Interval: intervals.IntervalDaily,+ BackupInterval: intervals.Interval{+ Type: intervals.IntervalDaily,TimeOfDay: &timeOfDay,},StorageID: ®ularStorageB.ID,@@ -1656,8 +1656,8 @@ func Test_SaveBackupConfig_WithSystemStorage_CanBeUsedByAnyDatabase(t *testing.TIsBackupsEnabled: true,RetentionPolicyType: RetentionPolicyTypeTimePeriod,RetentionTimePeriod: period.PeriodWeek,- BackupInterval: &intervals.Interval{- Interval: intervals.IntervalDaily,+ BackupInterval: intervals.Interval{+ Type: intervals.IntervalDaily,TimeOfDay: &timeOfDay,},StorageID: &savedSystemStorage.ID,diff --git a/backend/internal/features/backups/config/model.go b/backend/internal/features/backups/config/model.goindex 51f483b9..4753be23 100644--- a/backend/internal/features/backups/config/model.go+++ b/backend/internal/features/backups/config/model.go@@ -2,6 +2,7 @@ package backups_configimport ("errors"+ "fmt""strings""github.com/google/uuid"@@ -28,8 +29,7 @@ type BackupConfig struct {RetentionGfsMonths int `json:"retentionGfsMonths" gorm:"column:retention_gfs_months;type:int;not null;default:0"`RetentionGfsYears int `json:"retentionGfsYears" gorm:"column:retention_gfs_years;type:int;not null;default:0"`- BackupIntervalID uuid.UUID `json:"backupIntervalId" gorm:"column:backup_interval_id;type:uuid;not null"`- BackupInterval *intervals.Interval `json:"backupInterval,omitzero" gorm:"foreignKey:BackupIntervalID"`+ BackupInterval intervals.Interval `json:"backupInterval" gorm:"embedded"`Storage *storages.Storage `json:"storage" gorm:"foreignKey:StorageID"`StorageID *uuid.UUID `json:"storageId" gorm:"column:storage_id;type:uuid;"`@@ -81,8 +81,8 @@ func (b *BackupConfig) AfterFind(tx *gorm.DB) error {}func (b *BackupConfig) Validate() error {- if b.BackupIntervalID == uuid.Nil && b.BackupInterval == nil {- return errors.New("backup interval is required")+ if err := b.BackupInterval.Validate(); err != nil {+ return fmt.Errorf("backup interval: %w", err)}if err := b.validateRetentionPolicy(); err != nil {@@ -119,7 +119,6 @@ func (b *BackupConfig) Copy(newDatabaseID uuid.UUID) *BackupConfig {RetentionGfsWeeks: b.RetentionGfsWeeks,RetentionGfsMonths: b.RetentionGfsMonths,RetentionGfsYears: b.RetentionGfsYears,- BackupIntervalID: uuid.Nil,BackupInterval: b.BackupInterval.Copy(),StorageID: b.StorageID,SendNotificationsOn: b.SendNotificationsOn,diff --git a/backend/internal/features/backups/config/model_test.go b/backend/internal/features/backups/config/model_test.goindex 7bdbe525..94280cfa 100644--- a/backend/internal/features/backups/config/model_test.go+++ b/backend/internal/features/backups/config/model_test.go@@ -11,13 +11,12 @@ import ("databasus-backend/internal/util/period")-func Test_Validate_WhenIntervalIsMissing_ValidationFails(t *testing.T) {+func Test_Validate_WhenIntervalTypeIsMissing_ValidationFails(t *testing.T) {config := createValidBackupConfig()- config.BackupIntervalID = uuid.Nil- config.BackupInterval = nil+ config.BackupInterval = intervals.Interval{}err := config.Validate()- assert.EqualError(t, err, "backup interval is required")+ assert.ErrorContains(t, err, "backup interval")}func Test_Validate_WhenRetryEnabledButMaxTriesIsZero_ValidationFails(t *testing.T) {@@ -151,15 +150,12 @@ func enableCloud(t *testing.T) {}func createValidBackupConfig() *BackupConfig {- intervalID := uuid.New()-return &BackupConfig{DatabaseID: uuid.New(),IsBackupsEnabled: true,RetentionPolicyType: RetentionPolicyTypeTimePeriod,RetentionTimePeriod: period.PeriodMonth,- BackupIntervalID: intervalID,- BackupInterval: &intervals.Interval{ID: intervalID},+ BackupInterval: intervals.Interval{Type: intervals.IntervalHourly},SendNotificationsOn: []BackupNotificationType{},IsRetryIfFailed: false,MaxFailedTriesCount: 3,diff --git a/backend/internal/features/backups/config/repository.go b/backend/internal/features/backups/config/repository.goindex c24b1e68..4be1c33a 100644--- a/backend/internal/features/backups/config/repository.go+++ b/backend/internal/features/backups/config/repository.go@@ -14,41 +14,11 @@ type BackupConfigRepository struct{}func (r *BackupConfigRepository) Save(backupConfig *BackupConfig,) (*BackupConfig, error) {- db := storage.GetDb()-- err := db.Transaction(func(tx *gorm.DB) error {- // Handle BackupInterval- if backupConfig.BackupInterval != nil {- if backupConfig.BackupInterval.ID == uuid.Nil {- if err := tx.Create(backupConfig.BackupInterval).Error; err != nil {- return err- }-- backupConfig.BackupIntervalID = backupConfig.BackupInterval.ID- } else {- if err := tx.Save(backupConfig.BackupInterval).Error; err != nil {- return err- }-- backupConfig.BackupIntervalID = backupConfig.BackupInterval.ID- }- }-- // Set storage ID- if backupConfig.Storage != nil && backupConfig.Storage.ID != uuid.Nil {- backupConfig.StorageID = &backupConfig.Storage.ID- }-- // Use Save which handles both create and update based on primary key- if err := tx.Save(backupConfig).- Omit("BackupInterval", "Storage").- Error; err != nil {- return err- }+ if backupConfig.Storage != nil && backupConfig.Storage.ID != uuid.Nil {+ backupConfig.StorageID = &backupConfig.Storage.ID+ }- return nil- })- if err != nil {+ if err := storage.GetDb().Save(backupConfig).Omit("Storage").Error; err != nil {return nil, err}@@ -60,7 +30,6 @@ func (r *BackupConfigRepository) FindByDatabaseID(databaseID uuid.UUID) (*Backupif err := storage.GetDb().- Preload("BackupInterval").Preload("Storage").Preload("Storage.LocalStorage").Preload("Storage.S3Storage").@@ -87,7 +56,6 @@ func (r *BackupConfigRepository) GetWithEnabledBackups() ([]*BackupConfig, errorif err := storage.GetDb().- Preload("BackupInterval").Preload("Storage").Preload("Storage.LocalStorage").Preload("Storage.S3Storage").diff --git a/backend/internal/features/backups/config/service.go b/backend/internal/features/backups/config/service.goindex 44cfb2a2..17dd56ed 100644--- a/backend/internal/features/backups/config/service.go+++ b/backend/internal/features/backups/config/service.go@@ -306,8 +306,8 @@ func (s *BackupConfigService) initializeDefaultConfig(IsBackupsEnabled: false,RetentionPolicyType: RetentionPolicyTypeTimePeriod,RetentionTimePeriod: period.Period3Month,- BackupInterval: &intervals.Interval{- Interval: intervals.IntervalDaily,+ BackupInterval: intervals.Interval{+ Type: intervals.IntervalDaily,TimeOfDay: &timeOfDay,},SendNotificationsOn: []BackupNotificationType{diff --git a/backend/internal/features/backups/config/storages_test.go b/backend/internal/features/backups/config/storages_test.goindex e0ef6c82..42f4e437 100644--- a/backend/internal/features/backups/config/storages_test.go+++ b/backend/internal/features/backups/config/storages_test.go@@ -39,8 +39,8 @@ func Test_AttachStorageFromSameWorkspace_SuccessfullyAttached(t *testing.T) {IsBackupsEnabled: true,RetentionPolicyType: RetentionPolicyTypeTimePeriod,RetentionTimePeriod: period.PeriodWeek,- BackupInterval: &intervals.Interval{- Interval: intervals.IntervalDaily,+ BackupInterval: intervals.Interval{+ Type: intervals.IntervalDaily,TimeOfDay: &timeOfDay,},Storage: storage,@@ -92,8 +92,8 @@ func Test_AttachStorageFromDifferentWorkspace_ReturnsForbidden(t *testing.T) {IsBackupsEnabled: true,RetentionPolicyType: RetentionPolicyTypeTimePeriod,RetentionTimePeriod: period.PeriodWeek,- BackupInterval: &intervals.Interval{- Interval: intervals.IntervalDaily,+ BackupInterval: intervals.Interval{+ Type: intervals.IntervalDaily,TimeOfDay: &timeOfDay,},Storage: storage,@@ -137,8 +137,8 @@ func Test_DeleteStorageWithAttachedDatabases_CannotDelete(t *testing.T) {IsBackupsEnabled: true,RetentionPolicyType: RetentionPolicyTypeTimePeriod,RetentionTimePeriod: period.PeriodWeek,- BackupInterval: &intervals.Interval{- Interval: intervals.IntervalDaily,+ BackupInterval: intervals.Interval{+ Type: intervals.IntervalDaily,TimeOfDay: &timeOfDay,},Storage: storage,@@ -198,8 +198,8 @@ func Test_TransferStorageWithAttachedDatabase_CannotTransfer(t *testing.T) {IsBackupsEnabled: true,RetentionPolicyType: RetentionPolicyTypeTimePeriod,RetentionTimePeriod: period.PeriodWeek,- BackupInterval: &intervals.Interval{- Interval: intervals.IntervalDaily,+ BackupInterval: intervals.Interval{+ Type: intervals.IntervalDaily,TimeOfDay: &timeOfDay,},Storage: storage,diff --git a/backend/internal/features/backups/config/testing.go b/backend/internal/features/backups/config/testing.goindex 0e02bb89..7d8c9994 100644--- a/backend/internal/features/backups/config/testing.go+++ b/backend/internal/features/backups/config/testing.go@@ -19,8 +19,8 @@ func EnableBackupsForTestDatabase(IsBackupsEnabled: true,RetentionPolicyType: RetentionPolicyTypeTimePeriod,RetentionTimePeriod: period.PeriodDay,- BackupInterval: &intervals.Interval{- Interval: intervals.IntervalDaily,+ BackupInterval: intervals.Interval{+ Type: intervals.IntervalDaily,TimeOfDay: &timeOfDay,},StorageID: &storage.ID,diff --git a/backend/internal/features/databases/databases/mariadb/model_test.go b/backend/internal/features/databases/databases/mariadb/model_test.goindex 0d61f77c..911ce1dc 100644--- a/backend/internal/features/databases/databases/mariadb/model_test.go+++ b/backend/internal/features/databases/databases/mariadb/model_test.go@@ -988,6 +988,42 @@ func Test_ParseGrantPrivileges_ReturnsExpectedTokens(t *testing.T) {}}+func Test_HideSensitiveData_WhenCalled_ClearsPasswordAndPreservesOtherFields(t *testing.T) {+ databaseName := "appdb"+ mariadbModel := &MariadbDatabase{+ Version: tools.MariadbVersion114,+ Host: "db.example.com",+ Port: 3306,+ Username: "appuser",+ Password: "supersecret",+ Database: &databaseName,+ IsHttps: true,+ IsExcludeEvents: true,+ ExcludeTables: []string{"audit_logs"},+ Privileges: "SELECT, INSERT",+ }++ mariadbModel.HideSensitiveData()++ assert.Empty(t, mariadbModel.Password)+ assert.Equal(t, "db.example.com", mariadbModel.Host)+ assert.Equal(t, 3306, mariadbModel.Port)+ assert.Equal(t, "appuser", mariadbModel.Username)+ assert.Equal(t, &databaseName, mariadbModel.Database)+ assert.True(t, mariadbModel.IsHttps)+ assert.True(t, mariadbModel.IsExcludeEvents)+ assert.Equal(t, []string{"audit_logs"}, mariadbModel.ExcludeTables)+ assert.Equal(t, "SELECT, INSERT", mariadbModel.Privileges)+}++func Test_HideSensitiveData_WhenReceiverIsNil_DoesNotPanic(t *testing.T) {+ var mariadbModel *MariadbDatabase++ assert.NotPanics(t, func() {+ mariadbModel.HideSensitiveData()+ })+}+func connectToMariadbContainer(t *testing.T,port string,diff --git a/backend/internal/features/databases/databases/mongodb/model_test.go b/backend/internal/features/databases/databases/mongodb/model_test.goindex 9ed9e950..3037916e 100644--- a/backend/internal/features/databases/databases/mongodb/model_test.go+++ b/backend/internal/features/databases/databases/mongodb/model_test.go@@ -416,6 +416,46 @@ func Test_GetRawDbSizeMb_Mongodb_ReturnsPositiveSize(t *testing.T) {assert.Greater(t, sizeMB, 0.0, "raw db size should be > 0 after inserting documents")}+func Test_HideSensitiveData_WhenCalled_ClearsPasswordAndPreservesOtherFields(t *testing.T) {+ port := 27017+ mongodbModel := &MongodbDatabase{+ Version: tools.MongodbVersion7,+ Host: "db.example.com",+ Port: &port,+ Username: "appuser",+ Password: "supersecret",+ Database: "appdb",+ AuthDatabase: "admin",+ IsHttps: true,+ IsSrv: true,+ IsDirectConnection: true,+ CpuCount: 4,+ ExcludeCollections: []string{"audit_logs"},+ }++ mongodbModel.HideSensitiveData()++ assert.Empty(t, mongodbModel.Password)+ assert.Equal(t, "db.example.com", mongodbModel.Host)+ assert.Equal(t, &port, mongodbModel.Port)+ assert.Equal(t, "appuser", mongodbModel.Username)+ assert.Equal(t, "appdb", mongodbModel.Database)+ assert.Equal(t, "admin", mongodbModel.AuthDatabase)+ assert.True(t, mongodbModel.IsHttps)+ assert.True(t, mongodbModel.IsSrv)+ assert.True(t, mongodbModel.IsDirectConnection)+ assert.Equal(t, 4, mongodbModel.CpuCount)+ assert.Equal(t, []string{"audit_logs"}, mongodbModel.ExcludeCollections)+}++func Test_HideSensitiveData_WhenReceiverIsNil_DoesNotPanic(t *testing.T) {+ var mongodbModel *MongodbDatabase++ assert.NotPanics(t, func() {+ mongodbModel.HideSensitiveData()+ })+}+func connectToMongodbContainer(t *testing.T,port string,diff --git a/backend/internal/features/databases/databases/mysql/model_test.go b/backend/internal/features/databases/databases/mysql/model_test.goindex 9f0e0c86..00d15f1f 100644--- a/backend/internal/features/databases/databases/mysql/model_test.go+++ b/backend/internal/features/databases/databases/mysql/model_test.go@@ -921,6 +921,42 @@ func Test_ParseGrantPrivileges_ReturnsExpectedTokens(t *testing.T) {}}+func Test_HideSensitiveData_WhenCalled_ClearsPasswordAndPreservesOtherFields(t *testing.T) {+ databaseName := "appdb"+ mysqlModel := &MysqlDatabase{+ Version: tools.MysqlVersion80,+ Host: "db.example.com",+ Port: 3306,+ Username: "appuser",+ Password: "supersecret",+ Database: &databaseName,+ IsHttps: true,+ ExcludeTables: []string{"audit_logs"},+ Privileges: "SELECT, INSERT",+ IsZstdSupported: true,+ }++ mysqlModel.HideSensitiveData()++ assert.Empty(t, mysqlModel.Password)+ assert.Equal(t, "db.example.com", mysqlModel.Host)+ assert.Equal(t, 3306, mysqlModel.Port)+ assert.Equal(t, "appuser", mysqlModel.Username)+ assert.Equal(t, &databaseName, mysqlModel.Database)+ assert.True(t, mysqlModel.IsHttps)+ assert.Equal(t, []string{"audit_logs"}, mysqlModel.ExcludeTables)+ assert.Equal(t, "SELECT, INSERT", mysqlModel.Privileges)+ assert.True(t, mysqlModel.IsZstdSupported)+}++func Test_HideSensitiveData_WhenReceiverIsNil_DoesNotPanic(t *testing.T) {+ var mysqlModel *MysqlDatabase++ assert.NotPanics(t, func() {+ mysqlModel.HideSensitiveData()+ })+}+func connectToMysqlContainer(t *testing.T,port string,diff --git a/backend/internal/features/databases/databases/postgresql/model_test.go b/backend/internal/features/databases/databases/postgresql/model_test.goindex 57a02942..c3d892c8 100644--- a/backend/internal/features/databases/databases/postgresql/model_test.go+++ b/backend/internal/features/databases/databases/postgresql/model_test.go@@ -1606,6 +1606,44 @@ func Test_GetRawDbSizeMb_Postgresql_ReturnsPositiveSize(t *testing.T) {assert.Greater(t, sizeMB, 0.0, "raw db size should be > 0 after inserting data")}+func Test_HideSensitiveData_WhenCalled_ClearsPasswordAndPreservesOtherFields(t *testing.T) {+ databaseName := "appdb"+ pgModel := &PostgresqlDatabase{+ Version: tools.GetPostgresqlVersionEnum("16"),+ BackupType: PostgresBackupTypePgDump,+ Host: "db.example.com",+ Port: 5432,+ Username: "appuser",+ Password: "supersecret",+ Database: &databaseName,+ IsHttps: true,+ IncludeSchemas: []string{"public"},+ ExcludeTables: []string{"audit_logs"},+ CpuCount: 4,+ }++ pgModel.HideSensitiveData()++ assert.Empty(t, pgModel.Password)+ assert.Equal(t, "db.example.com", pgModel.Host)+ assert.Equal(t, 5432, pgModel.Port)+ assert.Equal(t, "appuser", pgModel.Username)+ assert.Equal(t, &databaseName, pgModel.Database)+ assert.True(t, pgModel.IsHttps)+ assert.Equal(t, PostgresBackupTypePgDump, pgModel.BackupType)+ assert.Equal(t, []string{"public"}, pgModel.IncludeSchemas)+ assert.Equal(t, []string{"audit_logs"}, pgModel.ExcludeTables)+ assert.Equal(t, 4, pgModel.CpuCount)+}++func Test_HideSensitiveData_WhenReceiverIsNil_DoesNotPanic(t *testing.T) {+ var pgModel *PostgresqlDatabase++ assert.NotPanics(t, func() {+ pgModel.HideSensitiveData()+ })+}+func connectToPostgresContainer(t *testing.T, port string) *PostgresContainer {dbName := "testdb"password := "testpassword"diff --git a/backend/internal/features/intervals/model.go b/backend/internal/features/intervals/model.goindex 1ecce9bb..0949a3de 100644--- a/backend/internal/features/intervals/model.go+++ b/backend/internal/features/intervals/model.go@@ -5,30 +5,26 @@ import ("fmt""time"- "github.com/google/uuid""github.com/robfig/cron/v3"- "gorm.io/gorm")type Interval struct {- ID uuid.UUID `json:"id" gorm:"primaryKey;type:uuid;default:gen_random_uuid()"`- Interval IntervalType `json:"interval" gorm:"type:text;not null"`-- TimeOfDay *string `json:"timeOfDay" gorm:"type:text;"`- // only for WEEKLY- Weekday *int `json:"weekday,omitempty" gorm:"type:int"`- // only for MONTHLY- DayOfMonth *int `json:"dayOfMonth,omitempty" gorm:"type:int"`- // only for CRON- CronExpression *string `json:"cronExpression,omitempty" gorm:"type:text"`-}+ Type IntervalType `json:"type" gorm:"column:interval_type;type:text;not null"`-func (i *Interval) BeforeSave(tx *gorm.DB) error {- return i.Validate()+ TimeOfDay *string `json:"timeOfDay" gorm:"column:time_of_day;type:text"`+ Weekday *int `json:"weekday,omitempty" gorm:"column:weekday;type:int"`+ DayOfMonth *int `json:"dayOfMonth,omitempty" gorm:"column:day_of_month;type:int"`+ CronExpression *string `json:"cronExpression,omitempty" gorm:"column:cron_expression;type:text"`}func (i *Interval) Validate() error {- if i.Interval == IntervalDaily || i.Interval == IntervalWeekly || i.Interval == IntervalMonthly {+ switch i.Type {+ case IntervalHourly, IntervalDaily, IntervalWeekly, IntervalMonthly, IntervalCron:+ default:+ return fmt.Errorf("invalid interval type: %q", i.Type)+ }++ if i.Type == IntervalDaily || i.Type == IntervalWeekly || i.Type == IntervalMonthly {if i.TimeOfDay == nil {return errors.New("time of day is required for daily, weekly and monthly intervals")}@@ -38,7 +34,7 @@ func (i *Interval) Validate() error {}}- if i.Interval == IntervalWeekly {+ if i.Type == IntervalWeekly {if i.Weekday == nil {return errors.New("weekday is required for weekly intervals")}@@ -49,7 +45,7 @@ func (i *Interval) Validate() error {}}- if i.Interval == IntervalMonthly {+ if i.Type == IntervalMonthly {if i.DayOfMonth == nil {return errors.New("day of month is required for monthly intervals")}@@ -59,7 +55,7 @@ func (i *Interval) Validate() error {}}- if i.Interval == IntervalCron {+ if i.Type == IntervalCron {if i.CronExpression == nil || *i.CronExpression == "" {return errors.New("cron expression is required for cron intervals")}@@ -79,7 +75,7 @@ func (i *Interval) ShouldTriggerBackup(now time.Time, lastBackupTime *time.Time)return true}- switch i.Interval {+ switch i.Type {case IntervalHourly:return now.Sub(*lastBackupTime) >= time.Hourcase IntervalDaily:@@ -102,7 +98,7 @@ func (i *Interval) NextTriggerTime(now time.Time, lastBackupTime *time.Time) *tireturn nil}- switch i.Interval {+ switch i.Type {case IntervalHourly:next := lastBackupTime.Add(time.Hour)return &next@@ -127,10 +123,9 @@ func (i *Interval) NextTriggerTime(now time.Time, lastBackupTime *time.Time) *ti}}-func (i *Interval) Copy() *Interval {- return &Interval{- ID: uuid.Nil,- Interval: i.Interval,+func (i *Interval) Copy() Interval {+ return Interval{+ Type: i.Type,TimeOfDay: i.TimeOfDay,Weekday: i.Weekday,DayOfMonth: i.DayOfMonth,diff --git a/backend/internal/features/intervals/model_test.go b/backend/internal/features/intervals/model_test.goindex 47a91c72..e0e4173e 100644--- a/backend/internal/features/intervals/model_test.go+++ b/backend/internal/features/intervals/model_test.go@@ -4,15 +4,13 @@ import ("testing""time"- "github.com/google/uuid""github.com/stretchr/testify/assert""github.com/stretchr/testify/require")func TestInterval_ShouldTriggerBackup_Hourly(t *testing.T) {interval := &Interval{- ID: uuid.New(),- Interval: IntervalHourly,+ Type: IntervalHourly,}baseTime := time.Date(2024, 1, 15, 12, 0, 0, 0, time.UTC)@@ -44,8 +42,7 @@ func TestInterval_ShouldTriggerBackup_Hourly(t *testing.T) {func TestInterval_ShouldTriggerBackup_Daily(t *testing.T) {timeOfDay := "09:00"interval := &Interval{- ID: uuid.New(),- Interval: IntervalDaily,+ Type: IntervalDaily,TimeOfDay: &timeOfDay,}@@ -111,8 +108,7 @@ func TestInterval_ShouldTriggerBackup_Daily(t *testing.T) {func(t *testing.T) {timeOfDay := "21:00"interval := &Interval{- ID: uuid.New(),- Interval: IntervalDaily,+ Type: IntervalDaily,TimeOfDay: &timeOfDay,}@@ -127,8 +123,7 @@ func TestInterval_ShouldTriggerBackup_Daily(t *testing.T) {t.Run("Catch up previous time slot", func(t *testing.T) {timeOfDay := "21:00"interval := &Interval{- ID: uuid.New(),- Interval: IntervalDaily,+ Type: IntervalDaily,TimeOfDay: &timeOfDay,}@@ -145,8 +140,7 @@ func TestInterval_ShouldTriggerBackup_Weekly(t *testing.T) {timeOfDay := "15:00"weekday := 3 // Wednesday (0=Sunday, 1=Monday, ..., 3=Wednesday)interval := &Interval{- ID: uuid.New(),- Interval: IntervalWeekly,+ Type: IntervalWeekly,TimeOfDay: &timeOfDay,Weekday: &weekday,}@@ -304,8 +298,7 @@ func TestInterval_ShouldTriggerBackup_Weekly(t *testing.T) {timeOfDay := "00:00"weekday := 5 // Friday (0=Sunday, 1=Monday, ..., 5=Friday)fridayInterval := &Interval{- ID: uuid.New(),- Interval: IntervalWeekly,+ Type: IntervalWeekly,TimeOfDay: &timeOfDay,Weekday: &weekday,}@@ -338,8 +331,7 @@ func TestInterval_ShouldTriggerBackup_Monthly(t *testing.T) {timeOfDay := "08:00"dayOfMonth := 10interval := &Interval{- ID: uuid.New(),- Interval: IntervalMonthly,+ Type: IntervalMonthly,TimeOfDay: &timeOfDay,DayOfMonth: &dayOfMonth,}@@ -461,8 +453,7 @@ func TestInterval_ShouldTriggerBackup_Monthly(t *testing.T) {func TestInterval_ShouldTriggerBackup_Cron(t *testing.T) {cronExpr := "0 2 * * *" // Daily at 2:00 AMinterval := &Interval{- ID: uuid.New(),- Interval: IntervalCron,+ Type: IntervalCron,CronExpression: &cronExpr,}@@ -503,8 +494,7 @@ func TestInterval_ShouldTriggerBackup_Cron(t *testing.T) {t.Run("Weekly cron expression: 0 3 * * 1 (Monday at 3 AM)", func(t *testing.T) {weeklyCron := "0 3 * * 1" // Every Monday at 3 AMweeklyInterval := &Interval{- ID: uuid.New(),- Interval: IntervalCron,+ Type: IntervalCron,CronExpression: &weeklyCron,}@@ -520,8 +510,7 @@ func TestInterval_ShouldTriggerBackup_Cron(t *testing.T) {t.Run("Complex cron expression: 30 4 1,15 * * (1st and 15th at 4:30 AM)", func(t *testing.T) {complexCron := "30 4 1,15 * *" // 1st and 15th of each month at 4:30 AMcomplexInterval := &Interval{- ID: uuid.New(),- Interval: IntervalCron,+ Type: IntervalCron,CronExpression: &complexCron,}@@ -537,8 +526,7 @@ func TestInterval_ShouldTriggerBackup_Cron(t *testing.T) {t.Run("Every 6 hours cron expression: 0 */6 * * *", func(t *testing.T) {sixHourlyCron := "0 */6 * * *" // Every 6 hours (0:00, 6:00, 12:00, 18:00)sixHourlyInterval := &Interval{- ID: uuid.New(),- Interval: IntervalCron,+ Type: IntervalCron,CronExpression: &sixHourlyCron,}@@ -554,8 +542,7 @@ func TestInterval_ShouldTriggerBackup_Cron(t *testing.T) {t.Run("Invalid cron expression returns false", func(t *testing.T) {invalidCron := "invalid cron"invalidInterval := &Interval{- ID: uuid.New(),- Interval: IntervalCron,+ Type: IntervalCron,CronExpression: &invalidCron,}@@ -569,8 +556,7 @@ func TestInterval_ShouldTriggerBackup_Cron(t *testing.T) {t.Run("Empty cron expression returns false", func(t *testing.T) {emptyCron := ""emptyInterval := &Interval{- ID: uuid.New(),- Interval: IntervalCron,+ Type: IntervalCron,CronExpression: &emptyCron,}@@ -583,8 +569,7 @@ func TestInterval_ShouldTriggerBackup_Cron(t *testing.T) {t.Run("Nil cron expression returns false", func(t *testing.T) {nilInterval := &Interval{- ID: uuid.New(),- Interval: IntervalCron,+ Type: IntervalCron,CronExpression: nil,}@@ -599,8 +584,7 @@ func TestInterval_ShouldTriggerBackup_Cron(t *testing.T) {func TestInterval_Validate(t *testing.T) {t.Run("Daily interval requires time of day", func(t *testing.T) {interval := &Interval{- ID: uuid.New(),- Interval: IntervalDaily,+ Type: IntervalDaily,}err := interval.Validate()assert.Error(t, err)@@ -610,8 +594,7 @@ func TestInterval_Validate(t *testing.T) {t.Run("Weekly interval requires weekday", func(t *testing.T) {timeOfDay := "09:00"interval := &Interval{- ID: uuid.New(),- Interval: IntervalWeekly,+ Type: IntervalWeekly,TimeOfDay: &timeOfDay,}err := interval.Validate()@@ -622,8 +605,7 @@ func TestInterval_Validate(t *testing.T) {t.Run("Monthly interval requires day of month", func(t *testing.T) {timeOfDay := "09:00"interval := &Interval{- ID: uuid.New(),- Interval: IntervalMonthly,+ Type: IntervalMonthly,TimeOfDay: &timeOfDay,}err := interval.Validate()@@ -633,8 +615,7 @@ func TestInterval_Validate(t *testing.T) {t.Run("Hourly interval is valid without additional fields", func(t *testing.T) {interval := &Interval{- ID: uuid.New(),- Interval: IntervalHourly,+ Type: IntervalHourly,}err := interval.Validate()assert.NoError(t, err)@@ -644,8 +625,7 @@ func TestInterval_Validate(t *testing.T) {timeOfDay := "09:00"weekday := 1interval := &Interval{- ID: uuid.New(),- Interval: IntervalWeekly,+ Type: IntervalWeekly,TimeOfDay: &timeOfDay,Weekday: &weekday,}@@ -656,8 +636,7 @@ func TestInterval_Validate(t *testing.T) {t.Run("Daily interval with invalid time of day is invalid", func(t *testing.T) {timeOfDay := "25:00"interval := &Interval{- ID: uuid.New(),- Interval: IntervalDaily,+ Type: IntervalDaily,TimeOfDay: &timeOfDay,}err := interval.Validate()@@ -668,8 +647,7 @@ func TestInterval_Validate(t *testing.T) {t.Run("Daily interval with empty time of day is invalid", func(t *testing.T) {timeOfDay := ""interval := &Interval{- ID: uuid.New(),- Interval: IntervalDaily,+ Type: IntervalDaily,TimeOfDay: &timeOfDay,}err := interval.Validate()@@ -681,8 +659,7 @@ func TestInterval_Validate(t *testing.T) {timeOfDay := "09:00"weekday := 8interval := &Interval{- ID: uuid.New(),- Interval: IntervalWeekly,+ Type: IntervalWeekly,TimeOfDay: &timeOfDay,Weekday: &weekday,}@@ -695,8 +672,7 @@ func TestInterval_Validate(t *testing.T) {timeOfDay := "09:00"weekday := -1interval := &Interval{- ID: uuid.New(),- Interval: IntervalWeekly,+ Type: IntervalWeekly,TimeOfDay: &timeOfDay,Weekday: &weekday,}@@ -709,8 +685,7 @@ func TestInterval_Validate(t *testing.T) {timeOfDay := "09:00"weekday := 7interval := &Interval{- ID: uuid.New(),- Interval: IntervalWeekly,+ Type: IntervalWeekly,TimeOfDay: &timeOfDay,Weekday: &weekday,}@@ -722,8 +697,7 @@ func TestInterval_Validate(t *testing.T) {timeOfDay := "09:00"dayOfMonth := 15interval := &Interval{- ID: uuid.New(),- Interval: IntervalMonthly,+ Type: IntervalMonthly,TimeOfDay: &timeOfDay,DayOfMonth: &dayOfMonth,}@@ -735,8 +709,7 @@ func TestInterval_Validate(t *testing.T) {timeOfDay := "09:00"dayOfMonth := 0interval := &Interval{- ID: uuid.New(),- Interval: IntervalMonthly,+ Type: IntervalMonthly,TimeOfDay: &timeOfDay,DayOfMonth: &dayOfMonth,}@@ -749,8 +722,7 @@ func TestInterval_Validate(t *testing.T) {timeOfDay := "09:00"dayOfMonth := 32interval := &Interval{- ID: uuid.New(),- Interval: IntervalMonthly,+ Type: IntervalMonthly,TimeOfDay: &timeOfDay,DayOfMonth: &dayOfMonth,}@@ -763,8 +735,7 @@ func TestInterval_Validate(t *testing.T) {timeOfDay := "09:00"dayOfMonth := 31interval := &Interval{- ID: uuid.New(),- Interval: IntervalMonthly,+ Type: IntervalMonthly,TimeOfDay: &timeOfDay,DayOfMonth: &dayOfMonth,}@@ -774,8 +745,7 @@ func TestInterval_Validate(t *testing.T) {t.Run("Cron interval requires cron expression", func(t *testing.T) {interval := &Interval{- ID: uuid.New(),- Interval: IntervalCron,+ Type: IntervalCron,}err := interval.Validate()assert.Error(t, err)@@ -785,8 +755,7 @@ func TestInterval_Validate(t *testing.T) {t.Run("Cron interval with empty expression is invalid", func(t *testing.T) {emptyCron := ""interval := &Interval{- ID: uuid.New(),- Interval: IntervalCron,+ Type: IntervalCron,CronExpression: &emptyCron,}err := interval.Validate()@@ -797,8 +766,7 @@ func TestInterval_Validate(t *testing.T) {t.Run("Cron interval with invalid expression is invalid", func(t *testing.T) {invalidCron := "invalid cron"interval := &Interval{- ID: uuid.New(),- Interval: IntervalCron,+ Type: IntervalCron,CronExpression: &invalidCron,}err := interval.Validate()@@ -809,8 +777,7 @@ func TestInterval_Validate(t *testing.T) {t.Run("Valid cron interval with daily expression", func(t *testing.T) {cronExpr := "0 2 * * *" // Daily at 2 AMinterval := &Interval{- ID: uuid.New(),- Interval: IntervalCron,+ Type: IntervalCron,CronExpression: &cronExpr,}err := interval.Validate()@@ -820,8 +787,7 @@ func TestInterval_Validate(t *testing.T) {t.Run("Valid cron interval with complex expression", func(t *testing.T) {cronExpr := "30 4 1,15 * *" // 1st and 15th of each month at 4:30 AMinterval := &Interval{- ID: uuid.New(),- Interval: IntervalCron,+ Type: IntervalCron,CronExpression: &cronExpr,}err := interval.Validate()@@ -833,14 +799,14 @@ func TestInterval_NextTriggerTime_NilLastBackup(t *testing.T) {now := time.Date(2024, 1, 15, 12, 0, 0, 0, time.UTC)t.Run("Hourly with nil lastBackup returns nil", func(t *testing.T) {- interval := &Interval{ID: uuid.New(), Interval: IntervalHourly}+ interval := &Interval{Type: IntervalHourly}result := interval.NextTriggerTime(now, nil)assert.Nil(t, result)})t.Run("Daily with nil lastBackup returns nil", func(t *testing.T) {timeOfDay := "09:00"- interval := &Interval{ID: uuid.New(), Interval: IntervalDaily, TimeOfDay: &timeOfDay}+ interval := &Interval{Type: IntervalDaily, TimeOfDay: &timeOfDay}result := interval.NextTriggerTime(now, nil)assert.Nil(t, result)})@@ -849,8 +815,7 @@ func TestInterval_NextTriggerTime_NilLastBackup(t *testing.T) {timeOfDay := "15:00"weekday := 3interval := &Interval{- ID: uuid.New(),- Interval: IntervalWeekly,+ Type: IntervalWeekly,TimeOfDay: &timeOfDay,Weekday: &weekday,}@@ -862,8 +827,7 @@ func TestInterval_NextTriggerTime_NilLastBackup(t *testing.T) {timeOfDay := "08:00"dayOfMonth := 10interval := &Interval{- ID: uuid.New(),- Interval: IntervalMonthly,+ Type: IntervalMonthly,TimeOfDay: &timeOfDay,DayOfMonth: &dayOfMonth,}@@ -873,14 +837,14 @@ func TestInterval_NextTriggerTime_NilLastBackup(t *testing.T) {t.Run("Cron with nil lastBackup returns nil", func(t *testing.T) {cronExpr := "0 2 * * *"- interval := &Interval{ID: uuid.New(), Interval: IntervalCron, CronExpression: &cronExpr}+ interval := &Interval{Type: IntervalCron, CronExpression: &cronExpr}result := interval.NextTriggerTime(now, nil)assert.Nil(t, result)})}func TestInterval_NextTriggerTime_Hourly(t *testing.T) {- interval := &Interval{ID: uuid.New(), Interval: IntervalHourly}+ interval := &Interval{Type: IntervalHourly}now := time.Date(2024, 1, 15, 12, 0, 0, 0, time.UTC)t.Run("Returns lastBackup + 1 hour", func(t *testing.T) {@@ -902,7 +866,7 @@ func TestInterval_NextTriggerTime_Hourly(t *testing.T) {func TestInterval_NextTriggerTime_Daily(t *testing.T) {timeOfDay := "09:00"- interval := &Interval{ID: uuid.New(), Interval: IntervalDaily, TimeOfDay: &timeOfDay}+ interval := &Interval{Type: IntervalDaily, TimeOfDay: &timeOfDay}t.Run("Before today's slot: returns today's slot", func(t *testing.T) {now := time.Date(2024, 1, 15, 8, 0, 0, 0, time.UTC)@@ -936,8 +900,7 @@ func TestInterval_NextTriggerTime_Weekly(t *testing.T) {timeOfDay := "15:00"weekday := 3 // Wednesdayinterval := &Interval{- ID: uuid.New(),- Interval: IntervalWeekly,+ Type: IntervalWeekly,TimeOfDay: &timeOfDay,Weekday: &weekday,}@@ -968,8 +931,7 @@ func TestInterval_NextTriggerTime_Weekly(t *testing.T) {fridayTimeOfDay := "00:00"fridayWeekday := 5 // FridayfridayInterval := &Interval{- ID: uuid.New(),- Interval: IntervalWeekly,+ Type: IntervalWeekly,TimeOfDay: &fridayTimeOfDay,Weekday: &fridayWeekday,}@@ -989,8 +951,7 @@ func TestInterval_NextTriggerTime_Monthly(t *testing.T) {timeOfDay := "08:00"dayOfMonth := 10interval := &Interval{- ID: uuid.New(),- Interval: IntervalMonthly,+ Type: IntervalMonthly,TimeOfDay: &timeOfDay,DayOfMonth: &dayOfMonth,}@@ -1026,7 +987,7 @@ func TestInterval_NextTriggerTime_Monthly(t *testing.T) {func TestInterval_NextTriggerTime_Cron(t *testing.T) {t.Run("Daily cron: returns next trigger after lastBackup", func(t *testing.T) {cronExpr := "0 2 * * *" // Daily at 2:00 AM- interval := &Interval{ID: uuid.New(), Interval: IntervalCron, CronExpression: &cronExpr}+ interval := &Interval{Type: IntervalCron, CronExpression: &cronExpr}now := time.Date(2024, 1, 15, 10, 0, 0, 0, time.UTC)lastBackup := time.Date(2024, 1, 14, 2, 0, 0, 0, time.UTC)@@ -1038,7 +999,7 @@ func TestInterval_NextTriggerTime_Cron(t *testing.T) {t.Run("Complex cron: 1st and 15th at 4:30", func(t *testing.T) {cronExpr := "30 4 1,15 * *"- interval := &Interval{ID: uuid.New(), Interval: IntervalCron, CronExpression: &cronExpr}+ interval := &Interval{Type: IntervalCron, CronExpression: &cronExpr}now := time.Date(2024, 1, 10, 10, 0, 0, 0, time.UTC)lastBackup := time.Date(2024, 1, 1, 4, 30, 0, 0, time.UTC)@@ -1050,7 +1011,7 @@ func TestInterval_NextTriggerTime_Cron(t *testing.T) {t.Run("Invalid cron expression returns nil", func(t *testing.T) {invalidCron := "invalid cron"- interval := &Interval{ID: uuid.New(), Interval: IntervalCron, CronExpression: &invalidCron}+ interval := &Interval{Type: IntervalCron, CronExpression: &invalidCron}now := time.Date(2024, 1, 15, 10, 0, 0, 0, time.UTC)lastBackup := time.Date(2024, 1, 14, 10, 0, 0, 0, time.UTC)@@ -1061,7 +1022,7 @@ func TestInterval_NextTriggerTime_Cron(t *testing.T) {t.Run("Empty cron expression returns nil", func(t *testing.T) {emptyCron := ""- interval := &Interval{ID: uuid.New(), Interval: IntervalCron, CronExpression: &emptyCron}+ interval := &Interval{Type: IntervalCron, CronExpression: &emptyCron}now := time.Date(2024, 1, 15, 10, 0, 0, 0, time.UTC)lastBackup := time.Date(2024, 1, 14, 10, 0, 0, 0, time.UTC)@@ -1071,7 +1032,7 @@ func TestInterval_NextTriggerTime_Cron(t *testing.T) {})t.Run("Nil cron expression returns nil", func(t *testing.T) {- interval := &Interval{ID: uuid.New(), Interval: IntervalCron, CronExpression: nil}+ interval := &Interval{Type: IntervalCron, CronExpression: nil}now := time.Date(2024, 1, 15, 10, 0, 0, 0, time.UTC)lastBackup := time.Date(2024, 1, 14, 10, 0, 0, 0, time.UTC)@@ -1082,7 +1043,7 @@ func TestInterval_NextTriggerTime_Cron(t *testing.T) {}func TestInterval_NextTriggerTime_UnknownInterval(t *testing.T) {- interval := &Interval{ID: uuid.New(), Interval: IntervalType("UNKNOWN")}+ interval := &Interval{Type: IntervalType("UNKNOWN")}now := time.Date(2024, 1, 15, 12, 0, 0, 0, time.UTC)lastBackup := time.Date(2024, 1, 14, 12, 0, 0, 0, time.UTC)diff --git a/backend/internal/features/system/agent/controller.go b/backend/internal/features/system/agent/controller.goindex ad1ebd18..a680dac5 100644--- a/backend/internal/features/system/agent/controller.go+++ b/backend/internal/features/system/agent/controller.go@@ -12,6 +12,7 @@ type AgentController struct{}func (c *AgentController) RegisterRoutes(router *gin.RouterGroup) {router.GET("/system/agent", c.DownloadAgent)+ router.GET("/system/verification-agent", c.DownloadVerificationAgent)}// DownloadAgent@@ -46,3 +47,36 @@ func (c *AgentController) DownloadAgent(ctx *gin.Context) {ctx.Header("Content-Disposition", "attachment; filename=databasus-agent")ctx.File(binaryPath)}++// DownloadVerificationAgent+// @Summary Download verification agent binary+// @Description Download the databasus-verification-agent binary for the specified architecture+// @Tags system/agent+// @Produce octet-stream+// @Param arch query string true "Target architecture" Enums(amd64, arm64)+// @Success 200 {file} binary+// @Failure 400 {object} map[string]string+// @Failure 404 {object} map[string]string+// @Router /system/verification-agent [get]+func (c *AgentController) DownloadVerificationAgent(ctx *gin.Context) {+ arch := ctx.Query("arch")+ if arch != "amd64" && arch != "arm64" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "arch must be amd64 or arm64"})+ return+ }++ binaryName := "databasus-verification-agent-linux-" + arch+ binaryPath := filepath.Join("agent-binaries", binaryName)++ if _, err := os.Stat(binaryPath); os.IsNotExist(err) {+ ctx.JSON(+ http.StatusNotFound,+ gin.H{"error": "verification agent binary not found for architecture: " + arch},+ )+ return+ }++ ctx.Header("Content-Type", "application/octet-stream")+ ctx.Header("Content-Disposition", "attachment; filename=databasus-verification-agent")+ ctx.File(binaryPath)+}diff --git a/backend/internal/features/system/healthcheck/di.go b/backend/internal/features/system/healthcheck/di.goindex 234b625e..0a5af382 100644--- a/backend/internal/features/system/healthcheck/di.go+++ b/backend/internal/features/system/healthcheck/di.go@@ -3,12 +3,14 @@ package system_healthcheckimport ("databasus-backend/internal/features/backups/backups/backuping""databasus-backend/internal/features/disk"+ verification_agents "databasus-backend/internal/features/verification/agents")var healthcheckService = &HealthcheckService{disk.GetDiskService(),backuping.GetBackupsScheduler(),backuping.GetBackuperNode(),+ verification_agents.GetAgentService(),}var healthcheckController = &HealthcheckController{diff --git a/backend/internal/features/system/healthcheck/service.go b/backend/internal/features/system/healthcheck/service.goindex fcbf6462..64203b5f 100644--- a/backend/internal/features/system/healthcheck/service.go+++ b/backend/internal/features/system/healthcheck/service.go@@ -3,11 +3,15 @@ package system_healthcheckimport ("context""errors"+ "fmt"+ "strings""time""databasus-backend/internal/config""databasus-backend/internal/features/backups/backups/backuping""databasus-backend/internal/features/disk"+ verification_agents "databasus-backend/internal/features/verification/agents"+ verification_runs "databasus-backend/internal/features/verification/runs""databasus-backend/internal/storage"cache_utils "databasus-backend/internal/util/cache""databasus-backend/internal/util/tools"@@ -17,6 +21,7 @@ type HealthcheckService struct {diskService *disk.DiskServicebackupBackgroundService *backuping.BackupsSchedulerbackuperNode *backuping.BackuperNode+ agentService *verification_agents.AgentService}func (s *HealthcheckService) IsHealthy() error {@@ -61,6 +66,23 @@ func (s *HealthcheckService) performHealthCheck() error {if !s.backupBackgroundService.IsBackupNodesAvailable() {return errors.New("no backup nodes available")}++ staleAgents, err := s.agentService.GetStaleAgents(verification_runs.StaleAgentThreshold)+ if err != nil {+ return errors.New("cannot query verification agents")+ }++ if len(staleAgents) > 0 {+ names := make([]string, len(staleAgents))+ for i, agent := range staleAgents {+ names[i] = agent.Name+ }++ return fmt.Errorf(+ "verification agents not seen for more than 5 minutes: %s",+ strings.Join(names, ", "),+ )+ }}if config.GetEnv().IsProcessingNode {diff --git a/backend/internal/features/telemetry/background_service_test.go b/backend/internal/features/telemetry/background_service_test.goindex 41e15286..940fcbbe 100644--- a/backend/internal/features/telemetry/background_service_test.go+++ b/backend/internal/features/telemetry/background_service_test.go@@ -52,6 +52,8 @@ func newBackgroundServiceUnderTest(t *testing.T, sender TelemetrySender) *Teleme&fakeStorageLister{},&fakeNotifierLister{},&fakeBackupChecker{},+ &fakeVerificationAgentLister{},+ &fakeVerificationConfigLister{},"9.9.9",slog.New(slog.DiscardHandler),)diff --git a/backend/internal/features/telemetry/di.go b/backend/internal/features/telemetry/di.goindex a5884874..1d024640 100644--- a/backend/internal/features/telemetry/di.go+++ b/backend/internal/features/telemetry/di.go@@ -9,6 +9,8 @@ import ("databasus-backend/internal/features/notifiers""databasus-backend/internal/features/storages"system_version "databasus-backend/internal/features/system/version"+ verification_agents "databasus-backend/internal/features/verification/agents"+ verification_config "databasus-backend/internal/features/verification/config""databasus-backend/internal/util/logger")@@ -27,6 +29,8 @@ var (storages.GetStorageService(),notifiers.GetNotifierService(),backups_services.GetBackupService(),+ verification_agents.GetAgentService(),+ verification_config.GetVerificationConfigService(),system_version.GetAppVersion(),telemetryLogger,)diff --git a/backend/internal/features/telemetry/dto.go b/backend/internal/features/telemetry/dto.goindex b73a78d9..9f9e31ab 100644--- a/backend/internal/features/telemetry/dto.go+++ b/backend/internal/features/telemetry/dto.go@@ -1,19 +1,34 @@package telemetrytype DatabaseEntry struct {- Type string `json:"type"`- Version string `json:"version"`- RawSizeMb int64 `json:"rawSizeMb,omitzero"`- BackupSizeMb int64 `json:"backupSizeMb,omitzero"`+ Type string `json:"type"`+ Version string `json:"version"`+ RawSizeMb int64 `json:"rawSizeMb,omitzero"`+ BackupSizeMb int64 `json:"backupSizeMb,omitzero"`+ Verification *DatabaseVerificationEntry `json:"verification,omitempty"`+}++type DatabaseVerificationEntry struct {+ IsEnabled bool `json:"isEnabled"`+ ScheduleType string `json:"scheduleType"`+ IntervalType string `json:"intervalType,omitempty"`+}++type VerificationAgentEntry struct {+ MaxCPU int `json:"maxCpu"`+ MaxRAMGb int `json:"maxRamGb"`+ MaxDiskGb int `json:"maxDiskGb"`+ MaxConcurrentJobs int `json:"maxConcurrentJobs"`}type CollectRequest struct {- InstanceID string `json:"instanceID"`- AppVersion string `json:"appVersion"`- OS string `json:"os"`- Arch string `json:"arch"`- InstalledAt string `json:"installedAt,omitempty"`- Databases []DatabaseEntry `json:"databases"`- Storages []string `json:"storages"`- Notifiers []string `json:"notifiers"`+ InstanceID string `json:"instanceID"`+ AppVersion string `json:"appVersion"`+ OS string `json:"os"`+ Arch string `json:"arch"`+ InstalledAt string `json:"installedAt,omitempty"`+ Databases []DatabaseEntry `json:"databases"`+ Storages []string `json:"storages"`+ Notifiers []string `json:"notifiers"`+ VerificationAgents []VerificationAgentEntry `json:"verificationAgents"`}diff --git a/backend/internal/features/telemetry/service.go b/backend/internal/features/telemetry/service.goindex 7dcc9f2c..e008ad0a 100644--- a/backend/internal/features/telemetry/service.go+++ b/backend/internal/features/telemetry/service.go@@ -14,6 +14,8 @@ import ("databasus-backend/internal/features/databases""databasus-backend/internal/features/notifiers""databasus-backend/internal/features/storages"+ verification_agents "databasus-backend/internal/features/verification/agents"+ verification_config "databasus-backend/internal/features/verification/config")const (@@ -42,15 +44,25 @@ type backupChecker interface {GetLatestCompletedBackup(databaseID uuid.UUID) (*backups_core.Backup, error)}+type verificationAgentLister interface {+ ListAgents() ([]*verification_agents.Agent, error)+}++type verificationConfigLister interface {+ ListEnabled() ([]*verification_config.BackupVerificationConfig, error)+}+type TelemetryService struct {- instanceLoader *InstanceFileLoader- sender TelemetrySender- databaseService databaseLister- storageService storageLister- notifierService notifierLister- backupService backupChecker- appVersion string- logger *slog.Logger+ instanceLoader *InstanceFileLoader+ sender TelemetrySender+ databaseService databaseLister+ storageService storageLister+ notifierService notifierLister+ backupService backupChecker+ verificationAgentService verificationAgentLister+ verificationConfigService verificationConfigLister+ appVersion string+ logger *slog.Logger}func NewTelemetryService(@@ -60,18 +72,22 @@ func NewTelemetryService(storageService storageLister,notifierService notifierLister,backupService backupChecker,+ verificationAgentService verificationAgentLister,+ verificationConfigService verificationConfigLister,appVersion string,logger *slog.Logger,) *TelemetryService {return &TelemetryService{- instanceLoader: instanceLoader,- sender: sender,- databaseService: databaseService,- storageService: storageService,- notifierService: notifierService,- backupService: backupService,- appVersion: appVersion,- logger: logger,+ instanceLoader: instanceLoader,+ sender: sender,+ databaseService: databaseService,+ storageService: storageService,+ notifierService: notifierService,+ backupService: backupService,+ verificationAgentService: verificationAgentService,+ verificationConfigService: verificationConfigService,+ appVersion: appVersion,+ logger: logger,}}@@ -81,7 +97,12 @@ func (s *TelemetryService) BuildAndSend(ctx context.Context) error {return nil}- databaseEntries, err := s.collectActiveDatabases()+ enabledConfigsByDatabaseID, err := s.loadEnabledVerificationConfigs()+ if err != nil {+ return err+ }++ databaseEntries, err := s.collectActiveDatabases(enabledConfigsByDatabaseID)if err != nil {return err}@@ -96,21 +117,46 @@ func (s *TelemetryService) BuildAndSend(ctx context.Context) error {return err}+ verificationAgents, err := s.collectVerificationAgents()+ if err != nil {+ return err+ }+req := &CollectRequest{- InstanceID: instance.InstanceID,- AppVersion: s.appVersion,- OS: runtime.GOOS,- Arch: runtime.GOARCH,- InstalledAt: instance.InstalledAt,- Databases: capDatabases(databaseEntries),- Storages: capStrings(storageTypes),- Notifiers: capStrings(notifierTypes),+ InstanceID: instance.InstanceID,+ AppVersion: s.appVersion,+ OS: runtime.GOOS,+ Arch: runtime.GOARCH,+ InstalledAt: instance.InstalledAt,+ Databases: capDatabases(databaseEntries),+ Storages: capStrings(storageTypes),+ Notifiers: capStrings(notifierTypes),+ VerificationAgents: capAgents(verificationAgents),}return s.sender.Send(ctx, req)}-func (s *TelemetryService) collectActiveDatabases() ([]DatabaseEntry, error) {+func (s *TelemetryService) loadEnabledVerificationConfigs() (+ map[uuid.UUID]*verification_config.BackupVerificationConfig,+ error,+) {+ enabledConfigs, err := s.verificationConfigService.ListEnabled()+ if err != nil {+ return nil, err+ }++ indexed := make(map[uuid.UUID]*verification_config.BackupVerificationConfig, len(enabledConfigs))+ for _, config := range enabledConfigs {+ indexed[config.DatabaseID] = config+ }++ return indexed, nil+}++func (s *TelemetryService) collectActiveDatabases(+ enabledConfigsByDatabaseID map[uuid.UUID]*verification_config.BackupVerificationConfig,+) ([]DatabaseEntry, error) {allDatabases, err := s.databaseService.GetAllDatabases()if err != nil {return nil, err@@ -138,12 +184,50 @@ func (s *TelemetryService) collectActiveDatabases() ([]DatabaseEntry, error) {return nil, err}+ if config, hasConfig := enabledConfigsByDatabaseID[db.ID]; hasConfig {+ entry.Verification = buildVerificationEntry(config)+ }+entries = append(entries, entry)}return entries, nil}+func buildVerificationEntry(+ config *verification_config.BackupVerificationConfig,+) *DatabaseVerificationEntry {+ entry := &DatabaseVerificationEntry{+ IsEnabled: true,+ ScheduleType: string(config.ScheduleType),+ }++ if config.ScheduleType == verification_config.VerificationScheduleInterval {+ entry.IntervalType = string(config.VerificationInterval.Type)+ }++ return entry+}++func (s *TelemetryService) collectVerificationAgents() ([]VerificationAgentEntry, error) {+ listedAgents, err := s.verificationAgentService.ListAgents()+ if err != nil {+ return nil, err+ }++ entries := make([]VerificationAgentEntry, 0, len(listedAgents))+ for _, agent := range listedAgents {+ entries = append(entries, VerificationAgentEntry{+ MaxCPU: agent.MaxCPU,+ MaxRAMGb: agent.MaxRAMGb,+ MaxDiskGb: agent.MaxDiskGb,+ MaxConcurrentJobs: agent.MaxConcurrentJobs,+ })+ }++ return entries, nil+}+func (s *TelemetryService) attachBackupSizes(entry *DatabaseEntry,databaseID uuid.UUID,@@ -267,3 +351,11 @@ func capDatabases(in []DatabaseEntry) []DatabaseEntry {return in}++func capAgents(in []VerificationAgentEntry) []VerificationAgentEntry {+ if len(in) > maxArrayEntries {+ return in[:maxArrayEntries]+ }++ return in+}diff --git a/backend/internal/features/telemetry/service_test.go b/backend/internal/features/telemetry/service_test.goindex a7950f1f..2c8f4f9b 100644--- a/backend/internal/features/telemetry/service_test.go+++ b/backend/internal/features/telemetry/service_test.go@@ -21,8 +21,11 @@ import ("databasus-backend/internal/features/databases/databases/mongodb""databasus-backend/internal/features/databases/databases/mysql""databasus-backend/internal/features/databases/databases/postgresql"+ "databasus-backend/internal/features/intervals""databasus-backend/internal/features/notifiers""databasus-backend/internal/features/storages"+ verification_agents "databasus-backend/internal/features/verification/agents"+ verification_config "databasus-backend/internal/features/verification/config""databasus-backend/internal/util/tools")@@ -91,12 +94,35 @@ func (f *fakeBackupChecker) GetLatestCompletedBackup(return f.latestBackups[databaseID], nil}+type fakeVerificationAgentLister struct {+ agents []*verification_agents.Agent+ err error+}++func (f *fakeVerificationAgentLister) ListAgents() ([]*verification_agents.Agent, error) {+ return f.agents, f.err+}++type fakeVerificationConfigLister struct {+ enabled []*verification_config.BackupVerificationConfig+ err error+}++func (f *fakeVerificationConfigLister) ListEnabled() (+ []*verification_config.BackupVerificationConfig,+ error,+) {+ return f.enabled, f.err+}+func newServiceUnderTest(t *testing.T,databaseLister databaseLister,storageLister storageLister,notifierLister notifierLister,backupChecker backupChecker,+ verificationAgentLister verificationAgentLister,+ verificationConfigLister verificationConfigLister,sender TelemetrySender,) *TelemetryService {t.Helper()@@ -112,6 +138,8 @@ func newServiceUnderTest(storageLister,notifierLister,backupChecker,+ verificationAgentLister,+ verificationConfigLister,"9.9.9",slog.New(slog.DiscardHandler),)@@ -176,6 +204,8 @@ func Test_BuildAndSend_ProducesExpectedRequest(t *testing.T) {{NotifierType: notifiers.NotifierTypeTelegram},}},&fakeBackupChecker{},+ &fakeVerificationAgentLister{},+ &fakeVerificationConfigLister{},sender,)@@ -221,6 +251,8 @@ func Test_BuildAndSend_PreservesStorageAndNotifierDuplicates(t *testing.T) {{NotifierType: notifiers.NotifierTypeTelegram},}},&fakeBackupChecker{},+ &fakeVerificationAgentLister{},+ &fakeVerificationConfigLister{},sender,)@@ -250,6 +282,8 @@ func Test_BuildAndSend_WhenInstanceFileFails_DoesNotCallSender(t *testing.T) {&fakeStorageLister{},&fakeNotifierLister{},&fakeBackupChecker{},+ &fakeVerificationAgentLister{},+ &fakeVerificationConfigLister{},"9.9.9",slog.New(slog.DiscardHandler),)@@ -268,6 +302,8 @@ func Test_BuildAndSend_WhenSenderFails_PropagatesError(t *testing.T) {&fakeStorageLister{},&fakeNotifierLister{},&fakeBackupChecker{},+ &fakeVerificationAgentLister{},+ &fakeVerificationConfigLister{},sender,)@@ -286,6 +322,8 @@ func Test_BuildAndSend_WhenDbHealthStatusAvailable_DbIncluded(t *testing.T) {&fakeStorageLister{},&fakeNotifierLister{},&fakeBackupChecker{},+ &fakeVerificationAgentLister{},+ &fakeVerificationConfigLister{},sender,)@@ -304,6 +342,8 @@ func Test_BuildAndSend_WhenDbHealthStatusUnavailable_DbExcluded(t *testing.T) {&fakeStorageLister{},&fakeNotifierLister{},&fakeBackupChecker{},+ &fakeVerificationAgentLister{},+ &fakeVerificationConfigLister{},sender,)@@ -322,6 +362,8 @@ func Test_BuildAndSend_WhenHealthcheckOffAndRecentBackup_DbIncluded(t *testing.T&fakeStorageLister{},&fakeNotifierLister{},&fakeBackupChecker{hasBackupSince: map[uuid.UUID]bool{db.ID: true}},+ &fakeVerificationAgentLister{},+ &fakeVerificationConfigLister{},sender,)@@ -341,6 +383,8 @@ func Test_BuildAndSend_WhenHealthcheckOffAndNoRecentBackup_DbExcluded(t *testing&fakeStorageLister{},&fakeNotifierLister{},&fakeBackupChecker{hasBackupSince: map[uuid.UUID]bool{}},+ &fakeVerificationAgentLister{},+ &fakeVerificationConfigLister{},sender,)@@ -360,6 +404,8 @@ func Test_BuildAndSend_WhenBackupCheckerFails_ReturnsError(t *testing.T) {&fakeStorageLister{},&fakeNotifierLister{},&fakeBackupChecker{err: checkerErr},+ &fakeVerificationAgentLister{},+ &fakeVerificationConfigLister{},sender,)@@ -383,6 +429,8 @@ func Test_BuildAndSend_WhenLatestBackupHasBothSizes_IncludesBoth(t *testing.T) {db.ID: {BackupSizeMb: 870.4, BackupRawDbSizeMb: 4321.7},},},+ &fakeVerificationAgentLister{},+ &fakeVerificationConfigLister{},sender,)@@ -409,6 +457,8 @@ func Test_BuildAndSend_WhenSizesAreSubMb_RoundsUpToOne(t *testing.T) {db.ID: {BackupSizeMb: 0.3, BackupRawDbSizeMb: 0.1},},},+ &fakeVerificationAgentLister{},+ &fakeVerificationConfigLister{},sender,)@@ -440,6 +490,8 @@ func Test_BuildAndSend_WhenRawSizeZero_IncludesOnlyBackupSize(t *testing.T) {db.ID: {BackupSizeMb: 100, BackupRawDbSizeMb: 0},},},+ &fakeVerificationAgentLister{},+ &fakeVerificationConfigLister{},sender,)@@ -471,6 +523,8 @@ func Test_BuildAndSend_WhenBackupSizeZero_IncludesOnlyRawSize(t *testing.T) {db.ID: {BackupSizeMb: 0, BackupRawDbSizeMb: 999},},},+ &fakeVerificationAgentLister{},+ &fakeVerificationConfigLister{},sender,)@@ -493,6 +547,8 @@ func Test_BuildAndSend_WhenNoCompletedBackup_OmitsBothSizes(t *testing.T) {&fakeStorageLister{},&fakeNotifierLister{},&fakeBackupChecker{},+ &fakeVerificationAgentLister{},+ &fakeVerificationConfigLister{},sender,)@@ -521,6 +577,8 @@ func Test_BuildAndSend_WhenLatestBackupLookupFails_ReturnsError(t *testing.T) {&fakeStorageLister{},&fakeNotifierLister{},&fakeBackupChecker{latestErr: lookupErr},+ &fakeVerificationAgentLister{},+ &fakeVerificationConfigLister{},sender,)@@ -530,6 +588,212 @@ func Test_BuildAndSend_WhenLatestBackupLookupFails_ReturnsError(t *testing.T) {assert.Empty(t, sender.calls)}+func Test_BuildAndSend_WhenAgentsRegistered_IncludesCapacityRows(t *testing.T) {+ registeredAgents := []*verification_agents.Agent{+ {+ ID: uuid.New(),+ Name: "agent-1",+ MaxCPU: 4,+ MaxRAMGb: 16,+ MaxDiskGb: 100,+ MaxConcurrentJobs: 2,+ },+ {+ ID: uuid.New(),+ Name: "agent-2",+ MaxCPU: 8,+ MaxRAMGb: 32,+ MaxDiskGb: 200,+ MaxConcurrentJobs: 4,+ },+ }++ sender := &fakeSender{}+ service := newServiceUnderTest(+ t,+ &fakeDatabaseLister{},+ &fakeStorageLister{},+ &fakeNotifierLister{},+ &fakeBackupChecker{},+ &fakeVerificationAgentLister{agents: registeredAgents},+ &fakeVerificationConfigLister{},+ sender,+ )++ require.NoError(t, service.BuildAndSend(context.Background()))+ require.Len(t, sender.calls, 1)++ assert.Equal(t, []VerificationAgentEntry{+ {MaxCPU: 4, MaxRAMGb: 16, MaxDiskGb: 100, MaxConcurrentJobs: 2},+ {MaxCPU: 8, MaxRAMGb: 32, MaxDiskGb: 200, MaxConcurrentJobs: 4},+ }, sender.calls[0].VerificationAgents)+}++func Test_BuildAndSend_WhenNoAgents_VerificationAgentsIsEmpty(t *testing.T) {+ sender := &fakeSender{}+ service := newServiceUnderTest(+ t,+ &fakeDatabaseLister{},+ &fakeStorageLister{},+ &fakeNotifierLister{},+ &fakeBackupChecker{},+ &fakeVerificationAgentLister{},+ &fakeVerificationConfigLister{},+ sender,+ )++ require.NoError(t, service.BuildAndSend(context.Background()))+ require.Len(t, sender.calls, 1)++ require.NotNil(t, sender.calls[0].VerificationAgents)+ assert.Empty(t, sender.calls[0].VerificationAgents)++ encoded, err := json.Marshal(sender.calls[0])+ require.NoError(t, err)+ assert.Contains(t, string(encoded), `"verificationAgents":[]`)+}++func Test_BuildAndSend_WhenDbHasAfterBackupConfig_VerificationBlockOmitsIntervalType(t *testing.T) {+ db := postgresDatabase("pg", availableStatus())++ sender := &fakeSender{}+ service := newServiceUnderTest(+ t,+ &fakeDatabaseLister{databases: []*databases.Database{db}},+ &fakeStorageLister{},+ &fakeNotifierLister{},+ &fakeBackupChecker{},+ &fakeVerificationAgentLister{},+ &fakeVerificationConfigLister{enabled: []*verification_config.BackupVerificationConfig{+ {+ DatabaseID: db.ID,+ IsScheduledVerificationEnabled: true,+ ScheduleType: verification_config.VerificationScheduleAfterBackup,+ },+ }},+ sender,+ )++ require.NoError(t, service.BuildAndSend(context.Background()))+ require.Len(t, sender.calls, 1)+ require.Len(t, sender.calls[0].Databases, 1)++ entry := sender.calls[0].Databases[0]+ require.NotNil(t, entry.Verification)+ assert.True(t, entry.Verification.IsEnabled)+ assert.Equal(t, "AFTER_BACKUP", entry.Verification.ScheduleType)+ assert.Empty(t, entry.Verification.IntervalType)++ encoded, err := json.Marshal(entry)+ require.NoError(t, err)+ assert.Contains(t, string(encoded), `"verification"`)+ assert.NotContains(t, string(encoded), "intervalType")+}++func Test_BuildAndSend_WhenDbHasIntervalDailyConfig_IncludesIntervalType(t *testing.T) {+ db := postgresDatabase("pg", availableStatus())++ sender := &fakeSender{}+ service := newServiceUnderTest(+ t,+ &fakeDatabaseLister{databases: []*databases.Database{db}},+ &fakeStorageLister{},+ &fakeNotifierLister{},+ &fakeBackupChecker{},+ &fakeVerificationAgentLister{},+ &fakeVerificationConfigLister{enabled: []*verification_config.BackupVerificationConfig{+ {+ DatabaseID: db.ID,+ IsScheduledVerificationEnabled: true,+ ScheduleType: verification_config.VerificationScheduleInterval,+ VerificationInterval: intervals.Interval{Type: intervals.IntervalDaily},+ },+ }},+ sender,+ )++ require.NoError(t, service.BuildAndSend(context.Background()))+ require.Len(t, sender.calls, 1)+ require.Len(t, sender.calls[0].Databases, 1)++ entry := sender.calls[0].Databases[0]+ require.NotNil(t, entry.Verification)+ assert.True(t, entry.Verification.IsEnabled)+ assert.Equal(t, "INTERVAL", entry.Verification.ScheduleType)+ assert.Equal(t, "DAILY", entry.Verification.IntervalType)++ encoded, err := json.Marshal(entry)+ require.NoError(t, err)+ assert.Contains(t, string(encoded), `"intervalType":"DAILY"`)+}++func Test_BuildAndSend_WhenDbHasNoEnabledConfig_VerificationBlockAbsent(t *testing.T) {+ db := postgresDatabase("pg", availableStatus())++ sender := &fakeSender{}+ service := newServiceUnderTest(+ t,+ &fakeDatabaseLister{databases: []*databases.Database{db}},+ &fakeStorageLister{},+ &fakeNotifierLister{},+ &fakeBackupChecker{},+ &fakeVerificationAgentLister{},+ &fakeVerificationConfigLister{},+ sender,+ )++ require.NoError(t, service.BuildAndSend(context.Background()))+ require.Len(t, sender.calls, 1)+ require.Len(t, sender.calls[0].Databases, 1)++ entry := sender.calls[0].Databases[0]+ assert.Nil(t, entry.Verification)++ encoded, err := json.Marshal(entry)+ require.NoError(t, err)+ assert.NotContains(t, string(encoded), "verification")+}++func Test_BuildAndSend_WhenVerificationAgentListFails_ReturnsError(t *testing.T) {+ listErr := errors.New("agents query exploded")+ sender := &fakeSender{}+ service := newServiceUnderTest(+ t,+ &fakeDatabaseLister{},+ &fakeStorageLister{},+ &fakeNotifierLister{},+ &fakeBackupChecker{},+ &fakeVerificationAgentLister{err: listErr},+ &fakeVerificationConfigLister{},+ sender,+ )++ err := service.BuildAndSend(context.Background())+ require.Error(t, err)+ assert.ErrorIs(t, err, listErr)+ assert.Empty(t, sender.calls)+}++func Test_BuildAndSend_WhenVerificationConfigListFails_ReturnsError(t *testing.T) {+ listErr := errors.New("configs query exploded")+ sender := &fakeSender{}+ service := newServiceUnderTest(+ t,+ &fakeDatabaseLister{},+ &fakeStorageLister{},+ &fakeNotifierLister{},+ &fakeBackupChecker{},+ &fakeVerificationAgentLister{},+ &fakeVerificationConfigLister{err: listErr},+ sender,+ )++ err := service.BuildAndSend(context.Background())+ require.Error(t, err)+ assert.ErrorIs(t, err, listErr)+ assert.Empty(t, sender.calls)+}+func writeFileForTest(path string) error {return os.WriteFile(path, []byte("x"), 0o600)}diff --git a/backend/internal/features/verification/agents/agent_controller.go b/backend/internal/features/verification/agents/agent_controller.gonew file mode 100644index 00000000..c1cec932--- /dev/null+++ b/backend/internal/features/verification/agents/agent_controller.go@@ -0,0 +1,58 @@+package verification_agents++import (+ "net/http"++ "github.com/gin-gonic/gin"+)++type AgentFacingController struct {+ agentService *AgentService+}++func (c *AgentFacingController) RegisterRoutes(router *gin.RouterGroup) {+ g := router.Group("/agent/verification/:agentId")+ g.Use(c.agentService.RequireAgentAuth())++ g.POST("/heartbeat", c.Heartbeat)+}++// Heartbeat+// @Summary Verification agent heartbeat+// @Description Called periodically by a verification agent to report capacity and refresh last-seen.+// @Description Authentication uses the agent's raw token (NOT a user JWT) — the same token returned at create/rotate.+// @Tags verification-agents+// @Accept json+// @Produce json+// @Param agentId path string true "Agent UUID"+// @Param Authorization header string true "Bearer <agent-token>"+// @Param request body HeartbeatRequest true "Capacity report"+// @Success 200 {object} HeartbeatResponse+// @Failure 400 {object} map[string]string+// @Failure 401 {object} map[string]string+// @Failure 429 {object} map[string]string+// @Router /agent/verification/{agentId}/heartbeat [post]+func (c *AgentFacingController) Heartbeat(ctx *gin.Context) {+ agent, ok := GetAgentFromContext(ctx)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "agent missing from context"})+ return+ }++ var request HeartbeatRequest+ if err := ctx.ShouldBindJSON(&request); err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ seenAt, abortVerificationIDs, err := c.agentService.Heartbeat(agent, &request)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, HeartbeatResponse{+ LastSeenAt: seenAt,+ AbortVerificationIDs: abortVerificationIDs,+ })+}diff --git a/backend/internal/features/verification/agents/agent_controller_test.go b/backend/internal/features/verification/agents/agent_controller_test.gonew file mode 100644index 00000000..5080116d--- /dev/null+++ b/backend/internal/features/verification/agents/agent_controller_test.go@@ -0,0 +1,423 @@+package verification_agents++import (+ "fmt"+ "net/http"+ "testing"+ "time"++ "github.com/google/uuid"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ users_enums "databasus-backend/internal/features/users/enums"+ users_testing "databasus-backend/internal/features/users/testing"+ "databasus-backend/internal/storage"+ test_utils "databasus-backend/internal/util/testing"+)++func Test_Heartbeat_WhenTokenIsValid_UpdatesCapacityAndLastSeen(t *testing.T) {+ cleanupAgents(t)++ router := createTestRouter()+ admin := users_testing.CreateTestUser(users_enums.UserRoleAdmin)++ createdAgent := CreateTestVerificationAgent(t, router, admin.Token, "hb-ok-"+uuid.New().String())++ beforeHeartbeat := time.Now().UTC()++ var heartbeatResponse HeartbeatResponse+ test_utils.MakePostRequestAndUnmarshal(+ t, router,+ heartbeatPathFor(createdAgent.Agent.ID),+ "Bearer "+createdAgent.Token,+ HeartbeatRequest{MaxCPU: 8, MaxRAMGb: 32, MaxDiskGb: 500, MaxConcurrentJobs: 4},+ http.StatusOK, &heartbeatResponse,+ )++ assert.WithinDuration(t, time.Now().UTC(), heartbeatResponse.LastSeenAt, 10*time.Second)+ assert.True(t, !heartbeatResponse.LastSeenAt.Before(beforeHeartbeat))++ var listedAgents []Agent+ test_utils.MakeGetRequestAndUnmarshal(+ t, router,+ "/api/v1/verification/agents",+ "Bearer "+admin.Token,+ http.StatusOK, &listedAgents,+ )++ var persistedAgent *Agent+ for i := range listedAgents {+ if listedAgents[i].ID == createdAgent.Agent.ID {+ persistedAgent = &listedAgents[i]+ }+ }+ require.NotNil(t, persistedAgent)+ assert.Equal(t, 8, persistedAgent.MaxCPU)+ assert.Equal(t, 32, persistedAgent.MaxRAMGb)+ assert.Equal(t, 500, persistedAgent.MaxDiskGb)+ assert.Equal(t, 4, persistedAgent.MaxConcurrentJobs)+ require.NotNil(t, persistedAgent.LastSeenAt)+ assert.WithinDuration(t, time.Now().UTC(), *persistedAgent.LastSeenAt, 10*time.Second)+}++func Test_Heartbeat_TwiceUpdatesSameRow(t *testing.T) {+ cleanupAgents(t)++ router := createTestRouter()+ admin := users_testing.CreateTestUser(users_enums.UserRoleAdmin)++ createdAgent := CreateTestVerificationAgent(t, router, admin.Token, "hb-twice-"+uuid.New().String())+ heartbeatPath := heartbeatPathFor(createdAgent.Agent.ID)++ var firstHeartbeat HeartbeatResponse+ test_utils.MakePostRequestAndUnmarshal(+ t, router, heartbeatPath, "Bearer "+createdAgent.Token,+ HeartbeatRequest{MaxCPU: 1}, http.StatusOK, &firstHeartbeat,+ )++ time.Sleep(10 * time.Millisecond)++ var secondHeartbeat HeartbeatResponse+ test_utils.MakePostRequestAndUnmarshal(+ t, router, heartbeatPath, "Bearer "+createdAgent.Token,+ HeartbeatRequest{MaxCPU: 2}, http.StatusOK, &secondHeartbeat,+ )++ assert.True(t, secondHeartbeat.LastSeenAt.After(firstHeartbeat.LastSeenAt) ||+ secondHeartbeat.LastSeenAt.Equal(firstHeartbeat.LastSeenAt))++ var listedAgents []Agent+ test_utils.MakeGetRequestAndUnmarshal(+ t, router, "/api/v1/verification/agents",+ "Bearer "+admin.Token, http.StatusOK, &listedAgents,+ )++ matchCount := 0+ for _, agent := range listedAgents {+ if agent.ID == createdAgent.Agent.ID {+ matchCount+++ assert.Equal(t, 2, agent.MaxCPU)+ }+ }+ assert.Equal(t, 1, matchCount)+}++func Test_Heartbeat_PersistsRamAsGb_NotMb(t *testing.T) {+ cleanupAgents(t)++ router := createTestRouter()+ admin := users_testing.CreateTestUser(users_enums.UserRoleAdmin)++ createdAgent := CreateTestVerificationAgent(t, router, admin.Token, "hb-gb-"+uuid.New().String())++ test_utils.MakePostRequest(+ t, router, heartbeatPathFor(createdAgent.Agent.ID), "Bearer "+createdAgent.Token,+ HeartbeatRequest{MaxRAMGb: 64}, http.StatusOK,+ )++ listResponse := test_utils.MakeGetRequest(+ t, router, "/api/v1/verification/agents",+ "Bearer "+admin.Token, http.StatusOK,+ )++ listBody := string(listResponse.Body)+ assert.Contains(t, listBody, `"maxRamGb":64`)+ assert.NotContains(t, listBody, "maxRamMb")+}++func Test_Heartbeat_WhenNoToken_ReturnsUnauthorized(t *testing.T) {+ cleanupAgents(t)++ router := createTestRouter()+ admin := users_testing.CreateTestUser(users_enums.UserRoleAdmin)++ createdAgent := CreateTestVerificationAgent(t, router, admin.Token, "hb-notoken-"+uuid.New().String())++ heartbeatResponse := test_utils.MakePostRequest(+ t, router, heartbeatPathFor(createdAgent.Agent.ID), "",+ HeartbeatRequest{}, http.StatusUnauthorized,+ )+ assert.Contains(t, string(heartbeatResponse.Body), "invalid agent credentials")+}++func Test_Heartbeat_WhenInvalidToken_ReturnsUnauthorized(t *testing.T) {+ cleanupAgents(t)++ router := createTestRouter()+ admin := users_testing.CreateTestUser(users_enums.UserRoleAdmin)++ createdAgent := CreateTestVerificationAgent(t, router, admin.Token, "hb-bad-"+uuid.New().String())++ heartbeatResponse := test_utils.MakePostRequest(+ t, router, heartbeatPathFor(createdAgent.Agent.ID),+ "Bearer "+uuid.New().String(),+ HeartbeatRequest{}, http.StatusUnauthorized,+ )+ assert.Contains(t, string(heartbeatResponse.Body), "invalid agent credentials")+}++func Test_Heartbeat_WhenUserJwtInsteadOfAgentToken_ReturnsUnauthorized(t *testing.T) {+ cleanupAgents(t)++ router := createTestRouter()+ admin := users_testing.CreateTestUser(users_enums.UserRoleAdmin)++ createdAgent := CreateTestVerificationAgent(t, router, admin.Token, "hb-jwt-"+uuid.New().String())++ test_utils.MakePostRequest(+ t, router, heartbeatPathFor(createdAgent.Agent.ID), "Bearer "+admin.Token,+ HeartbeatRequest{}, http.StatusUnauthorized,+ )+}++func Test_Heartbeat_WhenAgentIdInvalidUuid_ReturnsUnauthorized(t *testing.T) {+ cleanupAgents(t)++ router := createTestRouter()++ heartbeatResponse := test_utils.MakePostRequest(+ t, router, "/api/v1/agent/verification/not-a-uuid/heartbeat",+ "Bearer "+uuid.New().String(),+ HeartbeatRequest{}, http.StatusUnauthorized,+ )+ assert.Contains(t, string(heartbeatResponse.Body), "invalid agent credentials")+}++func Test_Heartbeat_WhenAgentIdUnknown_ReturnsUnauthorized(t *testing.T) {+ cleanupAgents(t)++ router := createTestRouter()++ heartbeatResponse := test_utils.MakePostRequest(+ t, router, heartbeatPathFor(uuid.New()),+ "Bearer "+uuid.New().String(),+ HeartbeatRequest{}, http.StatusUnauthorized,+ )+ assert.Contains(t, string(heartbeatResponse.Body), "invalid agent credentials")+}++func Test_Heartbeat_WhenAgentIdMismatchesToken_ReturnsUnauthorized(t *testing.T) {+ cleanupAgents(t)++ router := createTestRouter()+ admin := users_testing.CreateTestUser(users_enums.UserRoleAdmin)++ agentA := CreateTestVerificationAgent(t, router, admin.Token, "hb-mix-a-"+uuid.New().String())+ agentB := CreateTestVerificationAgent(t, router, admin.Token, "hb-mix-b-"+uuid.New().String())++ test_utils.MakePostRequest(+ t, router, heartbeatPathFor(agentA.Agent.ID), "Bearer "+agentA.Token,+ HeartbeatRequest{MaxCPU: 1}, http.StatusOK,+ )++ var lastSeenBeforeMismatch *time.Time+ storage.GetDb().Raw(`SELECT last_seen_at FROM verification_agents WHERE id = ?`,+ agentA.Agent.ID).Scan(&lastSeenBeforeMismatch)+ require.NotNil(t, lastSeenBeforeMismatch)++ time.Sleep(20 * time.Millisecond)++ heartbeatResponse := test_utils.MakePostRequest(+ t, router, heartbeatPathFor(agentA.Agent.ID), "Bearer "+agentB.Token,+ HeartbeatRequest{MaxCPU: 99}, http.StatusUnauthorized,+ )+ assert.Contains(t, string(heartbeatResponse.Body), "invalid agent credentials")++ var lastSeenAfterMismatch *time.Time+ storage.GetDb().Raw(`SELECT last_seen_at FROM verification_agents WHERE id = ?`,+ agentA.Agent.ID).Scan(&lastSeenAfterMismatch)+ require.NotNil(t, lastSeenAfterMismatch)+ assert.True(t, lastSeenAfterMismatch.Equal(*lastSeenBeforeMismatch),+ "mismatched-token heartbeat must not update last_seen_at")++ var persistedMaxCPU int+ storage.GetDb().Raw(`SELECT max_cpu FROM verification_agents WHERE id = ?`,+ agentA.Agent.ID).Scan(&persistedMaxCPU)+ assert.Equal(t, 1, persistedMaxCPU)+}++func Test_Heartbeat_AfterRotateToken_OldTokenReturnsUnauthorized(t *testing.T) {+ cleanupAgents(t)++ router := createTestRouter()+ admin := users_testing.CreateTestUser(users_enums.UserRoleAdmin)++ createdAgent := CreateTestVerificationAgent(t, router, admin.Token, "hb-rotate-"+uuid.New().String())+ originalToken := createdAgent.Token++ var rotation RotateTokenResponse+ test_utils.MakePostRequestAndUnmarshal(+ t, router,+ fmt.Sprintf("/api/v1/verification/agents/%s/rotate-token", createdAgent.Agent.ID),+ "Bearer "+admin.Token,+ map[string]any{},+ http.StatusOK, &rotation,+ )++ test_utils.MakePostRequest(+ t, router, heartbeatPathFor(createdAgent.Agent.ID), "Bearer "+originalToken,+ HeartbeatRequest{}, http.StatusUnauthorized,+ )++ test_utils.MakePostRequest(+ t, router, heartbeatPathFor(createdAgent.Agent.ID), "Bearer "+rotation.Token,+ HeartbeatRequest{}, http.StatusOK,+ )+}++func Test_Heartbeat_AfterDelete_ReturnsUnauthorized(t *testing.T) {+ cleanupAgents(t)++ router := createTestRouter()+ admin := users_testing.CreateTestUser(users_enums.UserRoleAdmin)++ createdAgent := CreateTestVerificationAgent(t, router, admin.Token, "hb-deleted-"+uuid.New().String())++ test_utils.MakeDeleteRequest(+ t, router,+ fmt.Sprintf("/api/v1/verification/agents/%s", createdAgent.Agent.ID),+ "Bearer "+admin.Token,+ http.StatusNoContent,+ )++ heartbeatResponse := test_utils.MakePostRequest(+ t, router, heartbeatPathFor(createdAgent.Agent.ID), "Bearer "+createdAgent.Token,+ HeartbeatRequest{}, http.StatusUnauthorized,+ )+ assert.Contains(t, string(heartbeatResponse.Body), "invalid agent credentials")+}++func Test_Heartbeat_AfterDelete_DoesNotUpdateLastSeen(t *testing.T) {+ cleanupAgents(t)++ router := createTestRouter()+ admin := users_testing.CreateTestUser(users_enums.UserRoleAdmin)++ createdAgent := CreateTestVerificationAgent(t, router, admin.Token, "hb-no-update-"+uuid.New().String())+ heartbeatPath := heartbeatPathFor(createdAgent.Agent.ID)++ test_utils.MakePostRequest(+ t, router, heartbeatPath, "Bearer "+createdAgent.Token,+ HeartbeatRequest{MaxCPU: 1}, http.StatusOK,+ )++ var lastSeenBeforeDelete *time.Time+ storage.GetDb().Raw(`SELECT last_seen_at FROM verification_agents WHERE id = ?`,+ createdAgent.Agent.ID).Scan(&lastSeenBeforeDelete)+ require.NotNil(t, lastSeenBeforeDelete)++ test_utils.MakeDeleteRequest(+ t, router,+ fmt.Sprintf("/api/v1/verification/agents/%s", createdAgent.Agent.ID),+ "Bearer "+admin.Token,+ http.StatusNoContent,+ )++ time.Sleep(20 * time.Millisecond)++ test_utils.MakePostRequest(+ t, router, heartbeatPath, "Bearer "+createdAgent.Token,+ HeartbeatRequest{MaxCPU: 99}, http.StatusUnauthorized,+ )++ var lastSeenAfterDelete *time.Time+ storage.GetDb().Raw(`SELECT last_seen_at FROM verification_agents WHERE id = ?`,+ createdAgent.Agent.ID).Scan(&lastSeenAfterDelete)+ require.NotNil(t, lastSeenAfterDelete)+ assert.True(t, lastSeenAfterDelete.Equal(*lastSeenBeforeDelete),+ "heartbeat against a soft-deleted agent must not update last_seen_at")++ var persistedMaxCPU int+ storage.GetDb().Raw(`SELECT max_cpu FROM verification_agents WHERE id = ?`,+ createdAgent.Agent.ID).Scan(&persistedMaxCPU)+ assert.Equal(t, 1, persistedMaxCPU,+ "heartbeat against a soft-deleted agent must not update capacity")+}++func Test_Heartbeat_RejectsNegativeCapacity(t *testing.T) {+ cleanupAgents(t)++ router := createTestRouter()+ admin := users_testing.CreateTestUser(users_enums.UserRoleAdmin)++ createdAgent := CreateTestVerificationAgent(t, router, admin.Token, "hb-neg-"+uuid.New().String())++ test_utils.MakePostRequest(+ t, router, heartbeatPathFor(createdAgent.Agent.ID), "Bearer "+createdAgent.Token,+ map[string]any{"maxCpu": -1}, http.StatusBadRequest,+ )+}++func Test_Heartbeat_OverPerAgentRateLimit_Returns429(t *testing.T) {+ cleanupAgents(t)++ router := createTestRouter()+ admin := users_testing.CreateTestUser(users_enums.UserRoleAdmin)++ createdAgent := CreateTestVerificationAgent(t, router, admin.Token, "hb-burst-"+uuid.New().String())+ heartbeatPath := heartbeatPathFor(createdAgent.Agent.ID)++ for range rateLimitAgentMax {+ response := test_utils.MakeRequest(t, router, test_utils.RequestOptions{+ Method: http.MethodPost,+ URL: heartbeatPath,+ AuthToken: "Bearer " + createdAgent.Token,+ Body: HeartbeatRequest{MaxCPU: 1},+ })+ require.Equal(t, http.StatusOK, response.StatusCode,+ "requests within the per-agent budget should succeed")+ }++ response := test_utils.MakeRequest(t, router, test_utils.RequestOptions{+ Method: http.MethodPost,+ URL: heartbeatPath,+ AuthToken: "Bearer " + createdAgent.Token,+ Body: HeartbeatRequest{MaxCPU: 1},+ })+ assert.Equal(t, http.StatusTooManyRequests, response.StatusCode,+ "the request past the per-agent budget should be rate-limited")+ assert.Contains(t, string(response.Body), "too many requests")+}++func Test_Heartbeat_InvalidUuidDoesNotConsumeRateLimit(t *testing.T) {+ cleanupAgents(t)++ router := createTestRouter()+ admin := users_testing.CreateTestUser(users_enums.UserRoleAdmin)++ createdAgent := CreateTestVerificationAgent(t, router, admin.Token, "hb-garbage-"+uuid.New().String())++ for range rateLimitAgentMax * 2 {+ response := test_utils.MakeRequest(t, router, test_utils.RequestOptions{+ Method: http.MethodPost,+ URL: "/api/v1/agent/verification/not-a-uuid/heartbeat",+ AuthToken: "Bearer " + createdAgent.Token,+ Body: HeartbeatRequest{},+ })+ require.Equal(t, http.StatusUnauthorized, response.StatusCode,+ "garbage-UUID requests must always reject as 401, never as 429")+ }++ test_utils.MakePostRequest(+ t, router, heartbeatPathFor(createdAgent.Agent.ID), "Bearer "+createdAgent.Token,+ HeartbeatRequest{MaxCPU: 1}, http.StatusOK,+ )+}++func Test_AdminEndpoint_WithAgentToken_ReturnsUnauthorized(t *testing.T) {+ cleanupAgents(t)++ router := createTestRouter()+ admin := users_testing.CreateTestUser(users_enums.UserRoleAdmin)++ createdAgent := CreateTestVerificationAgent(t, router, admin.Token, "cross-"+uuid.New().String())++ test_utils.MakePostRequest(+ t, router,+ "/api/v1/verification/agents",+ "Bearer "+createdAgent.Token,+ CreateAgentRequest{Name: "should-not-work"},+ http.StatusUnauthorized,+ )+}diff --git a/backend/internal/features/verification/agents/controller.go b/backend/internal/features/verification/agents/controller.gonew file mode 100644index 00000000..5eee7d98--- /dev/null+++ b/backend/internal/features/verification/agents/controller.go@@ -0,0 +1,185 @@+package verification_agents++import (+ "errors"+ "net/http"++ "github.com/gin-gonic/gin"+ "github.com/google/uuid"++ users_enums "databasus-backend/internal/features/users/enums"+ users_middleware "databasus-backend/internal/features/users/middleware"+)++type AgentController struct {+ agentService *AgentService+}++func (c *AgentController) RegisterRoutes(router *gin.RouterGroup) {+ publicAuth := router.Group("/verification/agents")+ publicAuth.GET("/availability", c.GetAvailability)++ adminOnly := router.Group("/verification/agents")+ adminOnly.Use(users_middleware.RequireRole(users_enums.UserRoleAdmin))++ adminOnly.POST("", c.CreateAgent)+ adminOnly.GET("", c.ListAgents)+ adminOnly.POST("/:id/rotate-token", c.RotateToken)+ adminOnly.DELETE("/:id", c.DeleteAgent)+}++// GetAvailability+// @Summary Get verification agent availability+// @Description Returns the count of live verification agents. Available to any authenticated user so the UI can decide whether to render verification-related actions. No agent identifiers or tokens are exposed.+// @Tags verification-agents+// @Produce json+// @Security BearerAuth+// @Success 200 {object} AvailabilityResponse+// @Failure 401 {object} map[string]string+// @Router /verification/agents/availability [get]+func (c *AgentController) GetAvailability(ctx *gin.Context) {+ count, err := c.agentService.CountLiveAgents()+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, AvailabilityResponse{+ Count: count,+ HasAgents: count > 0,+ })+}++// CreateAgent+// @Summary Create a verification agent+// @Description Create a new verification-worker agent (ADMIN only). The raw token is returned exactly once.+// @Tags verification-agents+// @Accept json+// @Produce json+// @Security BearerAuth+// @Param request body CreateAgentRequest true "Agent name"+// @Success 201 {object} CreatedAgentResponse+// @Failure 400 {object} map[string]string+// @Failure 401 {object} map[string]string+// @Failure 403 {object} map[string]string+// @Router /verification/agents [post]+func (c *AgentController) CreateAgent(ctx *gin.Context) {+ user, ok := users_middleware.GetUserFromContext(ctx)+ if !ok {+ ctx.JSON(http.StatusUnauthorized, gin.H{"error": "User not authenticated"})+ return+ }++ var request CreateAgentRequest+ if err := ctx.ShouldBindJSON(&request); err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ response, err := c.agentService.CreateAgent(user, &request)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusCreated, response)+}++// ListAgents+// @Summary List verification agents+// @Description List all live verification agents (ADMIN only).+// @Tags verification-agents+// @Produce json+// @Security BearerAuth+// @Success 200 {array} Agent+// @Failure 401 {object} map[string]string+// @Failure 403 {object} map[string]string+// @Router /verification/agents [get]+func (c *AgentController) ListAgents(ctx *gin.Context) {+ agents, err := c.agentService.ListAgents()+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, agents)+}++// RotateToken+// @Summary Rotate a verification agent's token+// @Description Mint a new token for the agent and invalidate the old one (ADMIN only). The raw token is returned exactly once.+// @Tags verification-agents+// @Produce json+// @Security BearerAuth+// @Param id path string true "Agent ID"+// @Success 200 {object} RotateTokenResponse+// @Failure 400 {object} map[string]string+// @Failure 401 {object} map[string]string+// @Failure 403 {object} map[string]string+// @Failure 404 {object} map[string]string+// @Router /verification/agents/{id}/rotate-token [post]+func (c *AgentController) RotateToken(ctx *gin.Context) {+ user, ok := users_middleware.GetUserFromContext(ctx)+ if !ok {+ ctx.JSON(http.StatusUnauthorized, gin.H{"error": "User not authenticated"})+ return+ }++ agentID, err := uuid.Parse(ctx.Param("id"))+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid agent ID"})+ return+ }++ token, err := c.agentService.RotateToken(user, agentID)+ if err != nil {+ if errors.Is(err, ErrAgentNotFound) {+ ctx.JSON(http.StatusNotFound, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, RotateTokenResponse{Token: token})+}++// DeleteAgent+// @Summary Delete a verification agent+// @Description Soft-delete a verification agent (ADMIN only). The agent's token is preserved so a still-running worker receives a 404 on its next heartbeat rather than a 401.+// @Tags verification-agents+// @Produce json+// @Security BearerAuth+// @Param id path string true "Agent ID"+// @Success 204+// @Failure 400 {object} map[string]string+// @Failure 401 {object} map[string]string+// @Failure 403 {object} map[string]string+// @Failure 404 {object} map[string]string+// @Router /verification/agents/{id} [delete]+func (c *AgentController) DeleteAgent(ctx *gin.Context) {+ user, ok := users_middleware.GetUserFromContext(ctx)+ if !ok {+ ctx.JSON(http.StatusUnauthorized, gin.H{"error": "User not authenticated"})+ return+ }++ agentID, err := uuid.Parse(ctx.Param("id"))+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid agent ID"})+ return+ }++ if err := c.agentService.DeleteAgent(user, agentID); err != nil {+ if errors.Is(err, ErrAgentNotFound) {+ ctx.JSON(http.StatusNotFound, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.Status(http.StatusNoContent)+}diff --git a/backend/internal/features/verification/agents/controller_test.go b/backend/internal/features/verification/agents/controller_test.gonew file mode 100644index 00000000..b2ca972c--- /dev/null+++ b/backend/internal/features/verification/agents/controller_test.go@@ -0,0 +1,655 @@+package verification_agents++import (+ "encoding/json"+ "fmt"+ "net/http"+ "testing"++ "github.com/gin-gonic/gin"+ "github.com/google/uuid"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ audit_logs "databasus-backend/internal/features/audit_logs"+ users_enums "databasus-backend/internal/features/users/enums"+ users_middleware "databasus-backend/internal/features/users/middleware"+ users_services "databasus-backend/internal/features/users/services"+ users_testing "databasus-backend/internal/features/users/testing"+ workspaces_controllers "databasus-backend/internal/features/workspaces/controllers"+ workspaces_testing "databasus-backend/internal/features/workspaces/testing"+ "databasus-backend/internal/storage"+ test_utils "databasus-backend/internal/util/testing"+)++func createTestRouter() *gin.Engine {+ gin.SetMode(gin.TestMode)+ router := gin.New()++ v1 := router.Group("/api/v1")+ protected := v1.Group("").Use(users_middleware.AuthMiddleware(users_services.GetUserService()))++ if routerGroup, ok := protected.(*gin.RouterGroup); ok {+ GetAgentController().RegisterRoutes(routerGroup)+ workspaces_controllers.GetWorkspaceController().RegisterRoutes(routerGroup)+ workspaces_controllers.GetMembershipController().RegisterRoutes(routerGroup)+ }++ GetAgentFacingController().RegisterRoutes(v1)++ audit_logs.SetupDependencies()++ return router+}++func cleanupAgents(t *testing.T) {+ t.Helper()+ if err := storage.GetDb().Exec("DELETE FROM verification_agents").Error; err != nil {+ t.Fatalf("failed to clean verification_agents: %v", err)+ }+}++func heartbeatPathFor(agentID uuid.UUID) string {+ return fmt.Sprintf("/api/v1/agent/verification/%s/heartbeat", agentID)+}++func Test_CreateAgent_WhenUserIsAdmin_AgentCreated(t *testing.T) {+ cleanupAgents(t)++ router := createTestRouter()+ admin := users_testing.CreateTestUser(users_enums.UserRoleAdmin)++ name := "test-agent-" + uuid.New().String()+ var createResponse CreatedAgentResponse+ test_utils.MakePostRequestAndUnmarshal(+ t, router,+ "/api/v1/verification/agents",+ "Bearer "+admin.Token,+ CreateAgentRequest{Name: name},+ http.StatusCreated, &createResponse,+ )++ assert.NotEmpty(t, createResponse.Token, "raw token should be returned exactly once")+ require.NotNil(t, createResponse.Agent)+ assert.Equal(t, name, createResponse.Agent.Name)+ assert.NotEqual(t, uuid.Nil, createResponse.Agent.ID)+ assert.Empty(t, createResponse.Agent.TokenHash, "token hash must never leave the server")++ var listedAgents []Agent+ test_utils.MakeGetRequestAndUnmarshal(+ t, router,+ "/api/v1/verification/agents",+ "Bearer "+admin.Token,+ http.StatusOK, &listedAgents,+ )++ foundCreatedAgent := false+ for _, agent := range listedAgents {+ if agent.ID == createResponse.Agent.ID {+ foundCreatedAgent = true+ assert.Equal(t, name, agent.Name)+ }+ }+ assert.True(t, foundCreatedAgent, "newly created agent should appear in the list response")+}++func Test_CreateAgent_ResponseJSON_NeverIncludesTokenHashOrDeletedAt(t *testing.T) {+ cleanupAgents(t)++ router := createTestRouter()+ admin := users_testing.CreateTestUser(users_enums.UserRoleAdmin)++ createResponse := test_utils.MakePostRequest(+ t, router,+ "/api/v1/verification/agents",+ "Bearer "+admin.Token,+ CreateAgentRequest{Name: "json-leak-test-" + uuid.New().String()},+ http.StatusCreated,+ )++ createBody := string(createResponse.Body)+ assert.NotContains(t, createBody, "tokenHash")+ assert.NotContains(t, createBody, "token_hash")+ assert.NotContains(t, createBody, "deletedAt")+ assert.NotContains(t, createBody, "deleted_at")+ assert.Contains(t, createBody, "maxRamGb", "RAM should be reported in GB, not MB")+ assert.NotContains(t, createBody, "maxRamMb")+}++func Test_CreateAgent_WhenUserIsMember_ReturnsForbidden(t *testing.T) {+ cleanupAgents(t)++ router := createTestRouter()+ member := users_testing.CreateTestUser(users_enums.UserRoleMember)++ test_utils.MakePostRequest(+ t, router,+ "/api/v1/verification/agents",+ "Bearer "+member.Token,+ CreateAgentRequest{Name: "x"},+ http.StatusForbidden,+ )+}++func Test_CreateAgent_WhenNoToken_ReturnsUnauthorized(t *testing.T) {+ cleanupAgents(t)++ router := createTestRouter()++ test_utils.MakePostRequest(+ t, router,+ "/api/v1/verification/agents",+ "",+ CreateAgentRequest{Name: "x"},+ http.StatusUnauthorized,+ )+}++func Test_CreateAgent_WhenUserIsWorkspaceOwner_StillReturnsForbidden(t *testing.T) {+ cleanupAgents(t)++ router := createTestRouter()+ member := users_testing.CreateTestUser(users_enums.UserRoleMember)+ workspace := workspaces_testing.CreateTestWorkspace("ws-"+uuid.New().String(), member, router)+ defer workspaces_testing.RemoveTestWorkspace(workspace, router)++ test_utils.MakePostRequest(+ t, router,+ "/api/v1/verification/agents",+ "Bearer "+member.Token,+ CreateAgentRequest{Name: "x"},+ http.StatusForbidden,+ )+}++func Test_ListAgents_WhenUserIsAdmin_ReturnsAll(t *testing.T) {+ cleanupAgents(t)++ router := createTestRouter()+ admin := users_testing.CreateTestUser(users_enums.UserRoleAdmin)++ CreateTestVerificationAgent(t, router, admin.Token, "agent-a-"+uuid.New().String())+ CreateTestVerificationAgent(t, router, admin.Token, "agent-b-"+uuid.New().String())++ var listedAgents []Agent+ test_utils.MakeGetRequestAndUnmarshal(+ t, router,+ "/api/v1/verification/agents",+ "Bearer "+admin.Token,+ http.StatusOK, &listedAgents,+ )++ assert.GreaterOrEqual(t, len(listedAgents), 2)+}++func Test_ListAgents_WhenUserIsMember_ReturnsForbidden(t *testing.T) {+ cleanupAgents(t)++ router := createTestRouter()+ member := users_testing.CreateTestUser(users_enums.UserRoleMember)++ test_utils.MakeGetRequest(+ t, router,+ "/api/v1/verification/agents",+ "Bearer "+member.Token,+ http.StatusForbidden,+ )+}++func Test_ListAgents_WhenNoToken_ReturnsUnauthorized(t *testing.T) {+ cleanupAgents(t)++ router := createTestRouter()++ test_utils.MakeGetRequest(+ t, router,+ "/api/v1/verification/agents",+ "",+ http.StatusUnauthorized,+ )+}++func Test_RotateToken_WhenUserIsAdmin_ReturnsNewToken_InvalidatesOld(t *testing.T) {+ cleanupAgents(t)++ router := createTestRouter()+ admin := users_testing.CreateTestUser(users_enums.UserRoleAdmin)++ createdAgent := CreateTestVerificationAgent(t, router, admin.Token, "rotate-test-"+uuid.New().String())+ originalToken := createdAgent.Token++ var firstRotation RotateTokenResponse+ test_utils.MakePostRequestAndUnmarshal(+ t, router,+ fmt.Sprintf("/api/v1/verification/agents/%s/rotate-token", createdAgent.Agent.ID),+ "Bearer "+admin.Token,+ map[string]any{},+ http.StatusOK, &firstRotation,+ )++ rotatedToken := firstRotation.Token+ assert.NotEmpty(t, rotatedToken)+ assert.NotEqual(t, originalToken, rotatedToken)++ var secondRotation RotateTokenResponse+ test_utils.MakePostRequestAndUnmarshal(+ t, router,+ fmt.Sprintf("/api/v1/verification/agents/%s/rotate-token", createdAgent.Agent.ID),+ "Bearer "+admin.Token,+ map[string]any{},+ http.StatusOK, &secondRotation,+ )+ assert.NotEqual(t, rotatedToken, secondRotation.Token)+}++func Test_RotateToken_WhenUserIsMember_ReturnsForbidden(t *testing.T) {+ cleanupAgents(t)++ router := createTestRouter()+ admin := users_testing.CreateTestUser(users_enums.UserRoleAdmin)+ member := users_testing.CreateTestUser(users_enums.UserRoleMember)++ createdAgent := CreateTestVerificationAgent(t, router, admin.Token, "rotate-forbid-"+uuid.New().String())++ test_utils.MakePostRequest(+ t, router,+ fmt.Sprintf("/api/v1/verification/agents/%s/rotate-token", createdAgent.Agent.ID),+ "Bearer "+member.Token,+ map[string]any{},+ http.StatusForbidden,+ )++ // Confirm the agent is still present after the forbidden attempt.+ var listedAgents []Agent+ test_utils.MakeGetRequestAndUnmarshal(+ t, router,+ "/api/v1/verification/agents",+ "Bearer "+admin.Token,+ http.StatusOK, &listedAgents,+ )++ foundCreatedAgent := false+ for _, agent := range listedAgents {+ if agent.ID == createdAgent.Agent.ID {+ foundCreatedAgent = true+ }+ }+ assert.True(t, foundCreatedAgent)+}++func Test_RotateToken_WhenNoToken_ReturnsUnauthorized(t *testing.T) {+ cleanupAgents(t)++ router := createTestRouter()++ test_utils.MakePostRequest(+ t, router,+ fmt.Sprintf("/api/v1/verification/agents/%s/rotate-token", uuid.New()),+ "",+ map[string]any{},+ http.StatusUnauthorized,+ )+}++func Test_RotateToken_OnUnknownID_Returns404(t *testing.T) {+ cleanupAgents(t)++ router := createTestRouter()+ admin := users_testing.CreateTestUser(users_enums.UserRoleAdmin)++ test_utils.MakePostRequest(+ t, router,+ fmt.Sprintf("/api/v1/verification/agents/%s/rotate-token", uuid.New()),+ "Bearer "+admin.Token,+ map[string]any{},+ http.StatusNotFound,+ )+}++func Test_RotateToken_OnSoftDeletedAgent_Returns404(t *testing.T) {+ cleanupAgents(t)++ router := createTestRouter()+ admin := users_testing.CreateTestUser(users_enums.UserRoleAdmin)++ createdAgent := CreateTestVerificationAgent(t, router, admin.Token, "rotate-deleted-"+uuid.New().String())++ test_utils.MakeDeleteRequest(+ t, router,+ fmt.Sprintf("/api/v1/verification/agents/%s", createdAgent.Agent.ID),+ "Bearer "+admin.Token,+ http.StatusNoContent,+ )++ test_utils.MakePostRequest(+ t, router,+ fmt.Sprintf("/api/v1/verification/agents/%s/rotate-token", createdAgent.Agent.ID),+ "Bearer "+admin.Token,+ map[string]any{},+ http.StatusNotFound,+ )+}++func Test_DeleteAgent_WhenUserIsAdmin_RemovesFromList(t *testing.T) {+ cleanupAgents(t)++ router := createTestRouter()+ admin := users_testing.CreateTestUser(users_enums.UserRoleAdmin)++ createdAgent := CreateTestVerificationAgent(t, router, admin.Token, "delete-test-"+uuid.New().String())++ test_utils.MakeDeleteRequest(+ t, router,+ fmt.Sprintf("/api/v1/verification/agents/%s", createdAgent.Agent.ID),+ "Bearer "+admin.Token,+ http.StatusNoContent,+ )++ var listedAgents []Agent+ test_utils.MakeGetRequestAndUnmarshal(+ t, router,+ "/api/v1/verification/agents",+ "Bearer "+admin.Token,+ http.StatusOK, &listedAgents,+ )+ for _, agent := range listedAgents {+ assert.NotEqual(t, createdAgent.Agent.ID, agent.ID, "deleted agent must not appear in list")+ }+}++func Test_DeleteAgent_WhenUserIsMember_ReturnsForbidden(t *testing.T) {+ cleanupAgents(t)++ router := createTestRouter()+ admin := users_testing.CreateTestUser(users_enums.UserRoleAdmin)+ member := users_testing.CreateTestUser(users_enums.UserRoleMember)++ createdAgent := CreateTestVerificationAgent(t, router, admin.Token, "delete-forbid-"+uuid.New().String())++ test_utils.MakeDeleteRequest(+ t, router,+ fmt.Sprintf("/api/v1/verification/agents/%s", createdAgent.Agent.ID),+ "Bearer "+member.Token,+ http.StatusForbidden,+ )++ var listedAgents []Agent+ test_utils.MakeGetRequestAndUnmarshal(+ t, router,+ "/api/v1/verification/agents",+ "Bearer "+admin.Token,+ http.StatusOK, &listedAgents,+ )++ foundCreatedAgent := false+ for _, agent := range listedAgents {+ if agent.ID == createdAgent.Agent.ID {+ foundCreatedAgent = true+ }+ }+ assert.True(t, foundCreatedAgent, "member should not have been able to delete the agent")+}++func Test_DeleteAgent_WhenNoToken_ReturnsUnauthorized(t *testing.T) {+ cleanupAgents(t)++ router := createTestRouter()++ test_utils.MakeDeleteRequest(+ t, router,+ fmt.Sprintf("/api/v1/verification/agents/%s", uuid.New()),+ "",+ http.StatusUnauthorized,+ )+}++func Test_DeleteAgent_OnUnknownID_Returns404(t *testing.T) {+ cleanupAgents(t)++ router := createTestRouter()+ admin := users_testing.CreateTestUser(users_enums.UserRoleAdmin)++ test_utils.MakeDeleteRequest(+ t, router,+ fmt.Sprintf("/api/v1/verification/agents/%s", uuid.New()),+ "Bearer "+admin.Token,+ http.StatusNotFound,+ )+}++func Test_DeleteAgent_Twice_SecondCallReturns404(t *testing.T) {+ cleanupAgents(t)++ router := createTestRouter()+ admin := users_testing.CreateTestUser(users_enums.UserRoleAdmin)++ createdAgent := CreateTestVerificationAgent(t, router, admin.Token, "delete-twice-"+uuid.New().String())++ test_utils.MakeDeleteRequest(+ t, router,+ fmt.Sprintf("/api/v1/verification/agents/%s", createdAgent.Agent.ID),+ "Bearer "+admin.Token,+ http.StatusNoContent,+ )++ test_utils.MakeDeleteRequest(+ t, router,+ fmt.Sprintf("/api/v1/verification/agents/%s", createdAgent.Agent.ID),+ "Bearer "+admin.Token,+ http.StatusNotFound,+ )++ // Confirm that the second (failed) delete did NOT write a duplicate audit log.+ var deleteAuditCount int64+ storage.GetDb().+ Raw(`SELECT count(*) FROM audit_logs WHERE message LIKE ?`,+ "verification agent deleted: "+createdAgent.Agent.Name).+ Scan(&deleteAuditCount)+ assert.Equal(t, int64(1), deleteAuditCount,+ "only the successful first delete should write an audit log row")+}++func Test_ListAgents_ExcludesSoftDeletedAgents(t *testing.T) {+ cleanupAgents(t)++ router := createTestRouter()+ admin := users_testing.CreateTestUser(users_enums.UserRoleAdmin)++ keptAgent := CreateTestVerificationAgent(t, router, admin.Token, "kept-"+uuid.New().String())+ deletedAgent := CreateTestVerificationAgent(t, router, admin.Token, "deleted-"+uuid.New().String())++ test_utils.MakeDeleteRequest(+ t, router,+ fmt.Sprintf("/api/v1/verification/agents/%s", deletedAgent.Agent.ID),+ "Bearer "+admin.Token,+ http.StatusNoContent,+ )++ var listedAgents []Agent+ test_utils.MakeGetRequestAndUnmarshal(+ t, router,+ "/api/v1/verification/agents",+ "Bearer "+admin.Token,+ http.StatusOK, &listedAgents,+ )++ foundKeptAgent := false+ for _, agent := range listedAgents {+ assert.NotEqual(t, deletedAgent.Agent.ID, agent.ID)+ if agent.ID == keptAgent.Agent.ID {+ foundKeptAgent = true+ }+ }+ assert.True(t, foundKeptAgent)++ // Both rows still exist physically, but only the deleted one has deleted_at set.+ var physicalRowCount int64+ storage.GetDb().Raw(`SELECT count(*) FROM verification_agents WHERE id IN (?, ?)`,+ keptAgent.Agent.ID, deletedAgent.Agent.ID).Scan(&physicalRowCount)+ assert.Equal(t, int64(2), physicalRowCount, "soft-delete must preserve the row")++ var softDeletedRowCount int64+ storage.GetDb().Raw(`SELECT count(*) FROM verification_agents WHERE id = ? AND deleted_at IS NOT NULL`,+ deletedAgent.Agent.ID).Scan(&softDeletedRowCount)+ assert.Equal(t, int64(1), softDeletedRowCount)+}++func Test_CreateAgent_WritesAuditLog(t *testing.T) {+ cleanupAgents(t)++ router := createTestRouter()+ admin := users_testing.CreateTestUser(users_enums.UserRoleAdmin)++ name := "audit-test-" + uuid.New().String()+ CreateTestVerificationAgent(t, router, admin.Token, name)++ var auditRow struct {+ UserID *uuid.UUID+ WorkspaceID *uuid.UUID+ Message string+ }+ err := storage.GetDb().+ Raw(`SELECT user_id, workspace_id, message FROM audit_logs WHERE message = ?`,+ "verification agent created: "+name).+ Scan(&auditRow).Error+ require.NoError(t, err)++ require.NotNil(t, auditRow.UserID, "audit log must reference the admin who created the agent")+ assert.Equal(t, admin.UserID, *auditRow.UserID)+ assert.Nil(t, auditRow.WorkspaceID, "verification agents are system-global - workspace_id must be NULL")+}++// Helper to confirm the raw token shape (hex of 32 chars).+func Test_CreateAgent_TokenIsHex32(t *testing.T) {+ cleanupAgents(t)++ router := createTestRouter()+ admin := users_testing.CreateTestUser(users_enums.UserRoleAdmin)++ createdAgent := CreateTestVerificationAgent(t, router, admin.Token, "hex-token-"+uuid.New().String())++ assert.Len(t, createdAgent.Token, 32, "token is uuid-without-dashes (32 hex chars)")+ assert.NotContains(t, createdAgent.Token, "-")+}++func Test_GetAvailability_WhenUserIsMember_ReturnsCountWithoutAgentDetails(t *testing.T) {+ cleanupAgents(t)++ router := createTestRouter()+ admin := users_testing.CreateTestUser(users_enums.UserRoleAdmin)+ member := users_testing.CreateTestUser(users_enums.UserRoleMember)++ CreateTestVerificationAgent(t, router, admin.Token, "avail-a-"+uuid.New().String())+ CreateTestVerificationAgent(t, router, admin.Token, "avail-b-"+uuid.New().String())++ availabilityResponse := test_utils.MakeGetRequest(+ t, router,+ "/api/v1/verification/agents/availability",+ "Bearer "+member.Token,+ http.StatusOK,+ )++ var availability AvailabilityResponse+ require.NoError(t, json.Unmarshal(availabilityResponse.Body, &availability))+ assert.Equal(t, int64(2), availability.Count)+ assert.True(t, availability.HasAgents)++ availabilityBody := string(availabilityResponse.Body)+ assert.NotContains(t, availabilityBody, "tokenHash")+ assert.NotContains(t, availabilityBody, "token_hash")+ assert.NotContains(t, availabilityBody, "\"id\"")+ assert.NotContains(t, availabilityBody, "\"name\"")+ assert.NotContains(t, availabilityBody, "lastSeenAt")+}++func Test_GetAvailability_WhenNoAgents_ReturnsZeroAndFalse(t *testing.T) {+ cleanupAgents(t)++ router := createTestRouter()+ member := users_testing.CreateTestUser(users_enums.UserRoleMember)++ var availability AvailabilityResponse+ test_utils.MakeGetRequestAndUnmarshal(+ t, router,+ "/api/v1/verification/agents/availability",+ "Bearer "+member.Token,+ http.StatusOK, &availability,+ )++ assert.Equal(t, int64(0), availability.Count)+ assert.False(t, availability.HasAgents)+}++func Test_GetAvailability_WhenNoToken_ReturnsUnauthorized(t *testing.T) {+ cleanupAgents(t)++ router := createTestRouter()++ test_utils.MakeGetRequest(+ t, router,+ "/api/v1/verification/agents/availability",+ "",+ http.StatusUnauthorized,+ )+}++func Test_GetAvailability_ExcludesSoftDeletedAgents(t *testing.T) {+ cleanupAgents(t)++ router := createTestRouter()+ admin := users_testing.CreateTestUser(users_enums.UserRoleAdmin)+ member := users_testing.CreateTestUser(users_enums.UserRoleMember)++ keptAgent := CreateTestVerificationAgent(t, router, admin.Token, "avail-kept-"+uuid.New().String())+ deletedAgent := CreateTestVerificationAgent(t, router, admin.Token, "avail-deleted-"+uuid.New().String())++ test_utils.MakeDeleteRequest(+ t, router,+ fmt.Sprintf("/api/v1/verification/agents/%s", deletedAgent.Agent.ID),+ "Bearer "+admin.Token,+ http.StatusNoContent,+ )++ var availability AvailabilityResponse+ test_utils.MakeGetRequestAndUnmarshal(+ t, router,+ "/api/v1/verification/agents/availability",+ "Bearer "+member.Token,+ http.StatusOK, &availability,+ )++ assert.Equal(t, int64(1), availability.Count)+ assert.True(t, availability.HasAgents)+ assert.NotEqual(t, uuid.Nil, keptAgent.Agent.ID)+}++// Confirms the live-list JSON does not include internal-only fields like deleted_at.+func Test_ListAgents_JSONShape_NoInternalFields(t *testing.T) {+ cleanupAgents(t)++ router := createTestRouter()+ admin := users_testing.CreateTestUser(users_enums.UserRoleAdmin)++ CreateTestVerificationAgent(t, router, admin.Token, "shape-"+uuid.New().String())++ listResponse := test_utils.MakeGetRequest(+ t, router,+ "/api/v1/verification/agents",+ "Bearer "+admin.Token,+ http.StatusOK,+ )++ listBody := string(listResponse.Body)+ assert.NotContains(t, listBody, "tokenHash")+ assert.NotContains(t, listBody, "deletedAt")++ var agentJsonMaps []map[string]any+ require.NoError(t, json.Unmarshal(listResponse.Body, &agentJsonMaps))+ require.NotEmpty(t, agentJsonMaps)+ _, hasName := agentJsonMaps[0]["name"]+ assert.True(t, hasName)+ _, hasMaxRamGb := agentJsonMaps[0]["maxRamGb"]+ assert.True(t, hasMaxRamGb)+ _, hasMaxRamMb := agentJsonMaps[0]["maxRamMb"]+ assert.False(t, hasMaxRamMb, "RAM is in GB - the legacy 'maxRamMb' key must not appear")+}diff --git a/backend/internal/features/verification/agents/di.go b/backend/internal/features/verification/agents/di.gonew file mode 100644index 00000000..e00341bf--- /dev/null+++ b/backend/internal/features/verification/agents/di.go@@ -0,0 +1,37 @@+package verification_agents++import (+ audit_logs "databasus-backend/internal/features/audit_logs"+ cache_utils "databasus-backend/internal/util/cache"+ "databasus-backend/internal/util/logger"+)++var agentRepository = &AgentRepository{}++var agentService = &AgentService{+ agentRepository,+ audit_logs.GetAuditLogService(),+ cache_utils.NewRateLimiter(cache_utils.GetValkeyClient()),+ logger.GetLogger(),+ nil,+}++var agentController = &AgentController{+ agentService,+}++var agentFacingController = &AgentFacingController{+ agentService,+}++func GetAgentService() *AgentService {+ return agentService+}++func GetAgentController() *AgentController {+ return agentController+}++func GetAgentFacingController() *AgentFacingController {+ return agentFacingController+}diff --git a/backend/internal/features/verification/agents/dto.go b/backend/internal/features/verification/agents/dto.gonew file mode 100644index 00000000..f2149cf8--- /dev/null+++ b/backend/internal/features/verification/agents/dto.go@@ -0,0 +1,44 @@+package verification_agents++import (+ "time"++ "github.com/google/uuid"+)++type CreateAgentRequest struct {+ Name string `json:"name" binding:"required,min=1,max=200"`+}++type CreatedAgentResponse struct {+ Agent *Agent `json:"agent"`+ Token string `json:"token"`+}++type RotateTokenResponse struct {+ Token string `json:"token"`+}++type AvailabilityResponse struct {+ Count int64 `json:"count"`+ HasAgents bool `json:"hasAgents"`+}++type HeartbeatRequest struct {+ MaxCPU int `json:"maxCpu" binding:"min=0"`+ MaxRAMGb int `json:"maxRamGb" binding:"min=0"`+ MaxDiskGb int `json:"maxDiskGb" binding:"min=0"`+ MaxConcurrentJobs int `json:"maxConcurrentJobs" binding:"min=0"`++ // What the agent thinks it's running. Server returns the+ // subset to abort if some information is outdated+ CurrentVerificationIDs []uuid.UUID `json:"currentVerificationIds"`+}++type HeartbeatResponse struct {+ LastSeenAt time.Time `json:"lastSeenAt"`++ // IDs that vanished, were flipped to CANCELED or are no longer owned+ // by this agent. So it needs to drop them.+ AbortVerificationIDs []uuid.UUID `json:"abortVerificationIds"`+}diff --git a/backend/internal/features/verification/agents/errors.go b/backend/internal/features/verification/agents/errors.gonew file mode 100644index 00000000..22d2fe99--- /dev/null+++ b/backend/internal/features/verification/agents/errors.go@@ -0,0 +1,8 @@+package verification_agents++import "errors"++var (+ ErrAgentNotFound = errors.New("verification agent not found")+ ErrInvalidAgentToken = errors.New("invalid agent token")+)diff --git a/backend/internal/features/verification/agents/listeners.go b/backend/internal/features/verification/agents/listeners.gonew file mode 100644index 00000000..c16eb30e--- /dev/null+++ b/backend/internal/features/verification/agents/listeners.go@@ -0,0 +1,7 @@+package verification_agents++import "github.com/google/uuid"++type AgentHeartbeatedListener interface {+ OnAgentHeartbeated(agent *Agent, currentVerificationIDs []uuid.UUID) ([]uuid.UUID, error)+}diff --git a/backend/internal/features/verification/agents/middleware.go b/backend/internal/features/verification/agents/middleware.gonew file mode 100644index 00000000..af518ee6--- /dev/null+++ b/backend/internal/features/verification/agents/middleware.go@@ -0,0 +1,87 @@+package verification_agents++import (+ "net/http"+ "strings"+ "time"++ "github.com/gin-gonic/gin"+ "github.com/google/uuid"+)++const (+ agentContextKey = "verification_agent"++ rateLimitAgentEndpoint = "verification-agent-id"+ rateLimitAgentMax = 10+ rateLimitAgentWindow = time.Second++ genericAuthError = "invalid agent credentials"+)++func (s *AgentService) RequireAgentAuth() gin.HandlerFunc {+ return func(ctx *gin.Context) {+ clientIP := ctx.ClientIP()++ agentID, err := uuid.Parse(ctx.Param("agentId"))+ if err != nil {+ s.logger.Warn("verification agent auth failure",+ "client_ip", clientIP, "reason", "invalid_uuid")+ ctx.AbortWithStatusJSON(http.StatusUnauthorized,+ gin.H{"error": genericAuthError})++ return+ }++ isAllowed, rateLimitErr := s.rateLimiter.CheckLimit(+ agentID.String(), rateLimitAgentEndpoint,+ rateLimitAgentMax, rateLimitAgentWindow,+ )+ if rateLimitErr != nil {+ s.logger.Error("verification agent rate limit check failed",+ "error", rateLimitErr, "agent_id", agentID, "client_ip", clientIP)+ } else if !isAllowed {+ s.logger.Warn("verification agent per-agent rate limit hit",+ "agent_id", agentID, "client_ip", clientIP)+ ctx.AbortWithStatusJSON(http.StatusTooManyRequests,+ gin.H{"error": "too many requests"})++ return+ }++ header := ctx.GetHeader("Authorization")+ token := strings.TrimPrefix(header, "Bearer ")+ if token == "" || token == header {+ s.logger.Warn("verification agent auth failure",+ "client_ip", clientIP, "agent_id", agentID, "reason", "missing_token")+ ctx.AbortWithStatusJSON(http.StatusUnauthorized,+ gin.H{"error": genericAuthError})++ return+ }++ agent, err := s.VerifyAgentCredentials(agentID, token)+ if err != nil {+ s.logger.Warn("verification agent auth failure",+ "client_ip", clientIP, "agent_id", agentID, "reason", "invalid_credentials")+ ctx.AbortWithStatusJSON(http.StatusUnauthorized,+ gin.H{"error": genericAuthError})++ return+ }++ ctx.Set(agentContextKey, agent)+ ctx.Next()+ }+}++func GetAgentFromContext(ctx *gin.Context) (*Agent, bool) {+ v, exists := ctx.Get(agentContextKey)+ if !exists {+ return nil, false+ }++ agent, ok := v.(*Agent)++ return agent, ok+}diff --git a/backend/internal/features/verification/agents/model.go b/backend/internal/features/verification/agents/model.gonew file mode 100644index 00000000..2162180d--- /dev/null+++ b/backend/internal/features/verification/agents/model.go@@ -0,0 +1,37 @@+package verification_agents++import (+ "time"++ "github.com/google/uuid"+)++type Agent struct {+ ID uuid.UUID `json:"id" gorm:"column:id"`+ Name string `json:"name" gorm:"column:name"`+ TokenHash string `json:"-" gorm:"column:token_hash"`++ MaxCPU int `json:"maxCpu" gorm:"column:max_cpu"`+ MaxRAMGb int `json:"maxRamGb" gorm:"column:max_ram_gb"`+ MaxDiskGb int `json:"maxDiskGb" gorm:"column:max_disk_gb"`+ MaxConcurrentJobs int `json:"maxConcurrentJobs" gorm:"column:max_concurrent_jobs"`++ LastSeenAt *time.Time `json:"lastSeenAt,omitzero" gorm:"column:last_seen_at"`+ CreatedAt time.Time `json:"createdAt" gorm:"column:created_at"`+ DeletedAt *time.Time `json:"-" gorm:"column:deleted_at"`+}++func (Agent) TableName() string {+ return "verification_agents"+}++func (a *Agent) IsDeleted() bool {+ return a.DeletedAt != nil+}++type AgentCapacity struct {+ MaxCPU int+ MaxRAMGb int+ MaxDiskGb int+ MaxConcurrentJobs int+}diff --git a/backend/internal/features/verification/agents/repository.go b/backend/internal/features/verification/agents/repository.gonew file mode 100644index 00000000..61dba724--- /dev/null+++ b/backend/internal/features/verification/agents/repository.go@@ -0,0 +1,129 @@+package verification_agents++import (+ "errors"+ "time"++ "github.com/google/uuid"+ "gorm.io/gorm"++ "databasus-backend/internal/storage"+)++type AgentRepository struct{}++func (r *AgentRepository) Create(agent *Agent) error {+ if agent.ID == uuid.Nil {+ agent.ID = uuid.New()+ }++ return storage.GetDb().Create(agent).Error+}++func (r *AgentRepository) FindAll() ([]*Agent, error) {+ agents := make([]*Agent, 0)++ err := storage.GetDb().+ Where("deleted_at IS NULL").+ Order("created_at DESC").+ Find(&agents).Error++ return agents, err+}++func (r *AgentRepository) CountLive() (int64, error) {+ var count int64++ err := storage.GetDb().+ Model(&Agent{}).+ Where("deleted_at IS NULL").+ Count(&count).Error++ return count, err+}++func (r *AgentRepository) FindByID(id uuid.UUID) (*Agent, error) {+ var agent Agent++ err := storage.GetDb().+ Where("id = ?", id).+ First(&agent).Error+ if err != nil {+ if errors.Is(err, gorm.ErrRecordNotFound) {+ return nil, nil+ }++ return nil, err+ }++ return &agent, nil+}++func (r *AgentRepository) UpdateTokenHash(id uuid.UUID, tokenHash string) error {+ result := storage.GetDb().+ Model(&Agent{}).+ Where("id = ? AND deleted_at IS NULL", id).+ Update("token_hash", tokenHash)+ if result.Error != nil {+ return result.Error+ }++ if result.RowsAffected == 0 {+ return ErrAgentNotFound+ }++ return nil+}++func (r *AgentRepository) UpdateCapacityAndLastSeen(+ id uuid.UUID,+ capacity AgentCapacity,+ seenAt time.Time,+) error {+ result := storage.GetDb().+ Model(&Agent{}).+ Where("id = ?", id).+ Updates(map[string]any{+ "max_cpu": capacity.MaxCPU,+ "max_ram_gb": capacity.MaxRAMGb,+ "max_disk_gb": capacity.MaxDiskGb,+ "max_concurrent_jobs": capacity.MaxConcurrentJobs,+ "last_seen_at": seenAt,+ })+ if result.Error != nil {+ return result.Error+ }++ if result.RowsAffected == 0 {+ return ErrAgentNotFound+ }++ return nil+}++func (r *AgentRepository) SoftDelete(id uuid.UUID, deletedAt time.Time) error {+ result := storage.GetDb().+ Model(&Agent{}).+ Where("id = ? AND deleted_at IS NULL", id).+ Update("deleted_at", deletedAt)+ if result.Error != nil {+ return result.Error+ }++ if result.RowsAffected == 0 {+ return ErrAgentNotFound+ }++ return nil+}++func (r *AgentRepository) FindStale(staleBefore time.Time) ([]*Agent, error) {+ agents := make([]*Agent, 0)++ err := storage.GetDb().+ Where("deleted_at IS NULL AND COALESCE(last_seen_at, created_at) < ?", staleBefore).+ Order("created_at DESC").+ Find(&agents).Error++ return agents, err+}diff --git a/backend/internal/features/verification/agents/service.go b/backend/internal/features/verification/agents/service.gonew file mode 100644index 00000000..c17e90f3--- /dev/null+++ b/backend/internal/features/verification/agents/service.go@@ -0,0 +1,204 @@+package verification_agents++import (+ "crypto/sha256"+ "crypto/subtle"+ "fmt"+ "log/slog"+ "strings"+ "time"++ "github.com/google/uuid"++ audit_logs "databasus-backend/internal/features/audit_logs"+ users_models "databasus-backend/internal/features/users/models"+ cache_utils "databasus-backend/internal/util/cache"+)++type AgentService struct {+ agentRepository *AgentRepository+ auditLogService *audit_logs.AuditLogService+ rateLimiter *cache_utils.RateLimiter+ logger *slog.Logger++ heartbeatListeners []AgentHeartbeatedListener+}++func (s *AgentService) AddAgentHeartbeatedListener(listener AgentHeartbeatedListener) {+ s.heartbeatListeners = append(s.heartbeatListeners, listener)+}++func (s *AgentService) CreateAgent(+ user *users_models.User,+ req *CreateAgentRequest,+) (*CreatedAgentResponse, error) {+ plainToken := newPlainToken()+ tokenHash := hashAgentToken(plainToken)++ agent := &Agent{+ ID: uuid.New(),+ Name: req.Name,+ TokenHash: tokenHash,+ CreatedAt: time.Now().UTC(),+ }++ if err := s.agentRepository.Create(agent); err != nil {+ return nil, err+ }++ s.auditLogService.WriteAuditLog(+ fmt.Sprintf("verification agent created: %s", agent.Name),+ &user.ID,+ nil,+ )++ return &CreatedAgentResponse{+ Agent: agent,+ Token: plainToken,+ }, nil+}++func (s *AgentService) ListAgents() ([]*Agent, error) {+ return s.agentRepository.FindAll()+}++func (s *AgentService) CountLiveAgents() (int64, error) {+ return s.agentRepository.CountLive()+}++func (s *AgentService) GetStaleAgents(threshold time.Duration) ([]*Agent, error) {+ return s.agentRepository.FindStale(time.Now().UTC().Add(-threshold))+}++func (s *AgentService) RotateToken(+ user *users_models.User,+ agentID uuid.UUID,+) (string, error) {+ agent, err := s.agentRepository.FindByID(agentID)+ if err != nil {+ return "", err+ }+ if agent == nil || agent.IsDeleted() {+ return "", ErrAgentNotFound+ }++ plainToken := newPlainToken()+ tokenHash := hashAgentToken(plainToken)++ if err := s.agentRepository.UpdateTokenHash(agentID, tokenHash); err != nil {+ return "", err+ }++ s.auditLogService.WriteAuditLog(+ fmt.Sprintf("verification agent token rotated: %s", agent.Name),+ &user.ID,+ nil,+ )++ return plainToken, nil+}++func (s *AgentService) DeleteAgent(user *users_models.User, agentID uuid.UUID) error {+ agent, err := s.agentRepository.FindByID(agentID)+ if err != nil {+ return err+ }+ if agent == nil || agent.IsDeleted() {+ return ErrAgentNotFound+ }++ if err := s.agentRepository.SoftDelete(agentID, time.Now().UTC()); err != nil {+ return err+ }++ s.auditLogService.WriteAuditLog(+ fmt.Sprintf("verification agent deleted: %s", agent.Name),+ &user.ID,+ nil,+ )++ return nil+}++func (s *AgentService) VerifyAgentCredentials(+ agentID uuid.UUID,+ rawToken string,+) (*Agent, error) {+ if rawToken == "" {+ return nil, ErrInvalidAgentToken+ }++ agent, err := s.agentRepository.FindByID(agentID)+ if err != nil {+ return nil, err+ }+ if agent == nil || agent.IsDeleted() {+ return nil, ErrInvalidAgentToken+ }++ incomingHash := hashAgentToken(rawToken)+ if subtle.ConstantTimeCompare([]byte(agent.TokenHash), []byte(incomingHash)) != 1 {+ return nil, ErrInvalidAgentToken+ }++ return agent, nil+}++func (s *AgentService) GetAgentByID(id uuid.UUID) (*Agent, error) {+ return s.agentRepository.FindByID(id)+}++func (s *AgentService) Heartbeat(+ agent *Agent,+ req *HeartbeatRequest,+) (seenAt time.Time, abortVerificationIDs []uuid.UUID, err error) {+ now := time.Now().UTC()++ err = s.agentRepository.UpdateCapacityAndLastSeen(+ agent.ID,+ AgentCapacity{+ MaxCPU: req.MaxCPU,+ MaxRAMGb: req.MaxRAMGb,+ MaxDiskGb: req.MaxDiskGb,+ MaxConcurrentJobs: req.MaxConcurrentJobs,+ },+ now,+ )+ if err != nil {+ return time.Time{}, nil, err+ }++ abortSet := make(map[uuid.UUID]struct{})+ for _, listener := range s.heartbeatListeners {+ listenerAborts, listenerErr := listener.OnAgentHeartbeated(agent, req.CurrentVerificationIDs)+ if listenerErr != nil {+ s.logger.Error(+ "agent heartbeated listener failed",+ "error", listenerErr,+ "agent_id", agent.ID,+ )++ continue+ }++ for _, id := range listenerAborts {+ abortSet[id] = struct{}{}+ }+ }++ abortVerificationIDs = make([]uuid.UUID, 0, len(abortSet))+ for id := range abortSet {+ abortVerificationIDs = append(abortVerificationIDs, id)+ }++ return now, abortVerificationIDs, nil+}++func newPlainToken() string {+ return strings.ReplaceAll(uuid.New().String(), "-", "")+}++func hashAgentToken(token string) string {+ hash := sha256.Sum256([]byte(token))+ return fmt.Sprintf("%x", hash)+}diff --git a/backend/internal/features/verification/agents/service_test.go b/backend/internal/features/verification/agents/service_test.gonew file mode 100644index 00000000..71db42e1--- /dev/null+++ b/backend/internal/features/verification/agents/service_test.go@@ -0,0 +1,119 @@+package verification_agents++import (+ "testing"+ "time"++ "github.com/google/uuid"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ users_enums "databasus-backend/internal/features/users/enums"+ users_testing "databasus-backend/internal/features/users/testing"+ "databasus-backend/internal/storage"+)++func setAgentTimestamps(+ t *testing.T,+ agentID uuid.UUID,+ lastSeenAt *time.Time,+ createdAt time.Time,+) {+ t.Helper()++ err := storage.GetDb().+ Model(&Agent{}).+ Where("id = ?", agentID).+ Updates(map[string]any{+ "last_seen_at": lastSeenAt,+ "created_at": createdAt,+ }).Error+ require.NoError(t, err)+}++func Test_GetStaleAgents_WhenAgentHeartbeatedRecently_ReturnsEmpty(t *testing.T) {+ cleanupAgents(t)++ router := createTestRouter()+ admin := users_testing.CreateTestUser(users_enums.UserRoleAdmin)++ createdAgent := CreateTestVerificationAgent(t, router, admin.Token, "fresh-"+uuid.New().String())+ recentHeartbeat := time.Now().UTC().Add(-1 * time.Minute)+ setAgentTimestamps(t, createdAgent.Agent.ID, &recentHeartbeat, time.Now().UTC().Add(-1*time.Hour))++ staleAgents, err := GetAgentService().GetStaleAgents(5 * time.Minute)+ require.NoError(t, err)++ assert.Empty(t, staleAgents)+}++func Test_GetStaleAgents_WhenAgentLastSeenBeforeThreshold_ReturnsAgent(t *testing.T) {+ cleanupAgents(t)++ router := createTestRouter()+ admin := users_testing.CreateTestUser(users_enums.UserRoleAdmin)++ createdAgent := CreateTestVerificationAgent(t, router, admin.Token, "stale-"+uuid.New().String())+ oldHeartbeat := time.Now().UTC().Add(-10 * time.Minute)+ setAgentTimestamps(t, createdAgent.Agent.ID, &oldHeartbeat, oldHeartbeat)++ staleAgents, err := GetAgentService().GetStaleAgents(5 * time.Minute)+ require.NoError(t, err)++ require.Len(t, staleAgents, 1)+ assert.Equal(t, createdAgent.Agent.ID, staleAgents[0].ID)+}++func Test_GetStaleAgents_WhenAgentNeverHeartbeatedButCreatedRecently_ReturnsEmpty(t *testing.T) {+ cleanupAgents(t)++ router := createTestRouter()+ admin := users_testing.CreateTestUser(users_enums.UserRoleAdmin)++ createdAgent := CreateTestVerificationAgent(t, router, admin.Token, "newborn-"+uuid.New().String())+ setAgentTimestamps(t, createdAgent.Agent.ID, nil, time.Now().UTC())++ staleAgents, err := GetAgentService().GetStaleAgents(5 * time.Minute)+ require.NoError(t, err)++ assert.Empty(t, staleAgents)+}++func Test_GetStaleAgents_WhenAgentNeverHeartbeatedAndCreatedOld_ReturnsAgent(t *testing.T) {+ cleanupAgents(t)++ router := createTestRouter()+ admin := users_testing.CreateTestUser(users_enums.UserRoleAdmin)++ createdAgent := CreateTestVerificationAgent(t, router, admin.Token, "ghost-"+uuid.New().String())+ setAgentTimestamps(t, createdAgent.Agent.ID, nil, time.Now().UTC().Add(-10*time.Minute))++ staleAgents, err := GetAgentService().GetStaleAgents(5 * time.Minute)+ require.NoError(t, err)++ require.Len(t, staleAgents, 1)+ assert.Equal(t, createdAgent.Agent.ID, staleAgents[0].ID)+}++func Test_GetStaleAgents_WhenStaleAgentSoftDeleted_ReturnsEmpty(t *testing.T) {+ cleanupAgents(t)++ router := createTestRouter()+ admin := users_testing.CreateTestUser(users_enums.UserRoleAdmin)++ createdAgent := CreateTestVerificationAgent(t, router, admin.Token, "retired-"+uuid.New().String())+ oldHeartbeat := time.Now().UTC().Add(-10 * time.Minute)+ setAgentTimestamps(t, createdAgent.Agent.ID, &oldHeartbeat, oldHeartbeat)++ deletedAt := time.Now().UTC()+ err := storage.GetDb().+ Model(&Agent{}).+ Where("id = ?", createdAgent.Agent.ID).+ Update("deleted_at", deletedAt).Error+ require.NoError(t, err)++ staleAgents, err := GetAgentService().GetStaleAgents(5 * time.Minute)+ require.NoError(t, err)++ assert.Empty(t, staleAgents)+}diff --git a/backend/internal/features/verification/agents/testing.go b/backend/internal/features/verification/agents/testing.gonew file mode 100644index 00000000..ebeb0be3--- /dev/null+++ b/backend/internal/features/verification/agents/testing.go@@ -0,0 +1,68 @@+package verification_agents++import (+ "context"+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/gin-gonic/gin"+ "github.com/google/uuid"++ test_utils "databasus-backend/internal/util/testing"+)++func CreateTestVerificationAgent(+ t *testing.T,+ router *gin.Engine,+ adminToken, name string,+) *CreatedAgentResponse {+ t.Helper()++ var response CreatedAgentResponse+ test_utils.MakePostRequestAndUnmarshal(+ t,+ router,+ "/api/v1/verification/agents",+ "Bearer "+adminToken,+ CreateAgentRequest{Name: name},+ http.StatusCreated,+ &response,+ )++ return &response+}++// RemoveTestVerificationAgent is the idempotent counterpart to CreateTestVerificationAgent.+// It tolerates 404 so tests that explicitly delete the agent in their body can still defer+// this helper without the defer panicking.+func RemoveTestVerificationAgent(+ t *testing.T,+ router *gin.Engine,+ adminToken string,+ agentID uuid.UUID,+) {+ t.Helper()++ req, err := http.NewRequestWithContext(+ context.Background(),+ http.MethodDelete,+ "/api/v1/verification/agents/"+agentID.String(),+ nil,+ )+ if err != nil {+ t.Fatalf("build delete agent request: %v", err)+ }++ req.Header.Set("Authorization", "Bearer "+adminToken)++ resp := httptest.NewRecorder()+ router.ServeHTTP(resp, req)++ if resp.Code != http.StatusNoContent && resp.Code != http.StatusNotFound {+ t.Fatalf(+ "remove test verification agent: unexpected status %d, body=%s",+ resp.Code, resp.Body.String(),+ )+ }+}diff --git a/backend/internal/features/verification/config/controller.go b/backend/internal/features/verification/config/controller.gonew file mode 100644index 00000000..3e6b4742--- /dev/null+++ b/backend/internal/features/verification/config/controller.go@@ -0,0 +1,93 @@+package verification_config++import (+ "net/http"++ "github.com/gin-gonic/gin"+ "github.com/google/uuid"++ users_middleware "databasus-backend/internal/features/users/middleware"+)++type VerificationConfigController struct {+ verificationConfigService *VerificationConfigService+}++func (c *VerificationConfigController) RegisterRoutes(router *gin.RouterGroup) {+ router.GET("/verification-config/:databaseId", c.GetByDatabaseID)+ router.PUT("/verification-config/:databaseId", c.Save)+}++// GetByDatabaseID+// @Summary Get backup verification configuration+// @Description Get backup verification configuration for a specific database. Lazily creates a disabled default on first read.+// @Tags verification-config+// @Produce json+// @Security BearerAuth+// @Param databaseId path string true "Database ID"+// @Success 200 {object} BackupVerificationConfig+// @Failure 400 {object} map[string]string+// @Failure 401 {object} map[string]string+// @Router /verification-config/{databaseId} [get]+func (c *VerificationConfigController) GetByDatabaseID(ctx *gin.Context) {+ user, ok := users_middleware.GetUserFromContext(ctx)+ if !ok {+ ctx.JSON(http.StatusUnauthorized, gin.H{"error": "User not authenticated"})+ return+ }++ databaseID, err := uuid.Parse(ctx.Param("databaseId"))+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid database ID"})+ return+ }++ config, err := c.verificationConfigService.GetByDatabaseID(user, databaseID)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, config)+}++// Save+// @Summary Save backup verification configuration+// @Description Create or update backup verification configuration for a database. Verification cannot be enabled for WAL-based PostgreSQL databases.+// @Tags verification-config+// @Accept json+// @Produce json+// @Security BearerAuth+// @Param databaseId path string true "Database ID"+// @Param request body SaveBackupVerificationConfigDTO true "Verification configuration"+// @Success 200 {object} BackupVerificationConfig+// @Failure 400 {object} map[string]string+// @Failure 401 {object} map[string]string+// @Router /verification-config/{databaseId} [put]+func (c *VerificationConfigController) Save(ctx *gin.Context) {+ user, ok := users_middleware.GetUserFromContext(ctx)+ if !ok {+ ctx.JSON(http.StatusUnauthorized, gin.H{"error": "User not authenticated"})+ return+ }++ databaseID, err := uuid.Parse(ctx.Param("databaseId"))+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid database ID"})+ return+ }++ var req SaveBackupVerificationConfigDTO+ if err := ctx.ShouldBindJSON(&req); err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ config, err := c.verificationConfigService.Save(user, databaseID, &req)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, config)+}diff --git a/backend/internal/features/verification/config/controller_test.go b/backend/internal/features/verification/config/controller_test.gonew file mode 100644index 00000000..d58b7e73--- /dev/null+++ b/backend/internal/features/verification/config/controller_test.go@@ -0,0 +1,459 @@+package verification_config++import (+ "encoding/json"+ "net/http"+ "testing"++ "github.com/gin-gonic/gin"+ "github.com/google/uuid"+ "github.com/stretchr/testify/assert"++ "databasus-backend/internal/features/databases"+ "databasus-backend/internal/features/databases/databases/postgresql"+ "databasus-backend/internal/features/intervals"+ users_enums "databasus-backend/internal/features/users/enums"+ users_testing "databasus-backend/internal/features/users/testing"+ workspaces_controllers "databasus-backend/internal/features/workspaces/controllers"+ workspaces_testing "databasus-backend/internal/features/workspaces/testing"+ test_utils "databasus-backend/internal/util/testing"+)++func createTestRouter() *gin.Engine {+ return workspaces_testing.CreateTestRouter(+ workspaces_controllers.GetWorkspaceController(),+ workspaces_controllers.GetMembershipController(),+ databases.GetDatabaseController(),+ GetVerificationConfigController(),+ )+}++func newEnabledRequest() SaveBackupVerificationConfigDTO {+ return SaveBackupVerificationConfigDTO{+ IsScheduledVerificationEnabled: true,+ ScheduleType: VerificationScheduleInterval,+ VerificationInterval: intervals.Interval{+ Type: intervals.IntervalWeekly,+ TimeOfDay: new("04:00"),+ Weekday: new(0),+ },+ SendNotificationsOn: []VerificationNotificationType{+ NotificationVerificationFailed,+ },+ }+}++func createTestDatabaseViaAPI(+ name string,+ workspaceID uuid.UUID,+ token string,+ router *gin.Engine,+) *databases.Database {+ request := databases.Database{+ WorkspaceID: &workspaceID,+ Name: name,+ Type: databases.DatabaseTypePostgres,+ Postgresql: databases.GetTestPostgresConfig(),+ }++ w := workspaces_testing.MakeAPIRequest(+ router,+ "POST",+ "/api/v1/databases/create",+ "Bearer "+token,+ request,+ )++ if w.Code != http.StatusCreated {+ panic("Failed to create database")+ }++ var database databases.Database+ if err := json.Unmarshal(w.Body.Bytes(), &database); err != nil {+ panic(err)+ }++ return &database+}++func createTestWalDatabaseViaAPI(+ name string,+ workspaceID uuid.UUID,+ token string,+ router *gin.Engine,+) *databases.Database {+ request := databases.Database{+ WorkspaceID: &workspaceID,+ Name: name,+ Type: databases.DatabaseTypePostgres,+ Postgresql: &postgresql.PostgresqlDatabase{+ BackupType: postgresql.PostgresBackupTypeWalV1,+ CpuCount: 1,+ },+ }++ w := workspaces_testing.MakeAPIRequest(+ router,+ "POST",+ "/api/v1/databases/create",+ "Bearer "+token,+ request,+ )++ if w.Code != http.StatusCreated {+ panic("Failed to create WAL database")+ }++ var database databases.Database+ if err := json.Unmarshal(w.Body.Bytes(), &database); err != nil {+ panic(err)+ }++ return &database+}++func Test_GetByDatabaseID_WhenNoRowExists_LazyCreatesDisabledDefault(t *testing.T) {+ router := createTestRouter()+ owner := users_testing.CreateTestUser(users_enums.UserRoleMember)+ workspace := workspaces_testing.CreateTestWorkspace("Test Workspace", owner, router)+ database := createTestDatabaseViaAPI("Test Database", workspace.ID, owner.Token, router)++ var response BackupVerificationConfig+ test_utils.MakeGetRequestAndUnmarshal(+ t,+ router,+ "/api/v1/verification-config/"+database.ID.String(),+ "Bearer "+owner.Token,+ http.StatusOK,+ &response,+ )++ assert.Equal(t, database.ID, response.DatabaseID)+ assert.False(t, response.IsScheduledVerificationEnabled)+ assert.Equal(t, VerificationScheduleAfterBackup, response.ScheduleType)+ assert.Equal(t, intervals.IntervalWeekly, response.VerificationInterval.Type)+ assert.NotNil(t, response.VerificationInterval.TimeOfDay)+ assert.Equal(t, "04:00", *response.VerificationInterval.TimeOfDay)+ assert.NotNil(t, response.VerificationInterval.Weekday)+ assert.Equal(t, 0, *response.VerificationInterval.Weekday)+ assert.Equal(+ t,+ []VerificationNotificationType{NotificationVerificationFailed},+ response.SendNotificationsOn,+ )++ databases.RemoveTestDatabase(database)+ workspaces_testing.RemoveTestWorkspace(workspace, router)+}++func Test_GetByDatabaseID_WhenUserNotInWorkspace_ReturnsError(t *testing.T) {+ router := createTestRouter()+ owner := users_testing.CreateTestUser(users_enums.UserRoleMember)+ workspace := workspaces_testing.CreateTestWorkspace("Test Workspace", owner, router)+ database := createTestDatabaseViaAPI("Test Database", workspace.ID, owner.Token, router)++ nonMember := users_testing.CreateTestUser(users_enums.UserRoleMember)++ resp := test_utils.MakeGetRequest(+ t,+ router,+ "/api/v1/verification-config/"+database.ID.String(),+ "Bearer "+nonMember.Token,+ http.StatusBadRequest,+ )+ assert.Contains(t, string(resp.Body), "insufficient permissions")++ databases.RemoveTestDatabase(database)+ workspaces_testing.RemoveTestWorkspace(workspace, router)+}++func Test_Save_AsOwner_PersistsAndReturns(t *testing.T) {+ router := createTestRouter()+ owner := users_testing.CreateTestUser(users_enums.UserRoleMember)+ workspace := workspaces_testing.CreateTestWorkspace("Test Workspace", owner, router)+ database := createTestDatabaseViaAPI("Test Database", workspace.ID, owner.Token, router)++ request := newEnabledRequest()+ request.SendNotificationsOn = []VerificationNotificationType{+ NotificationVerificationSuccess,+ NotificationVerificationFailed,+ }++ var response BackupVerificationConfig+ test_utils.MakePutRequestAndUnmarshal(+ t,+ router,+ "/api/v1/verification-config/"+database.ID.String(),+ "Bearer "+owner.Token,+ request,+ http.StatusOK,+ &response,+ )++ assert.Equal(t, database.ID, response.DatabaseID)+ assert.True(t, response.IsScheduledVerificationEnabled)+ assert.Equal(t, intervals.IntervalWeekly, response.VerificationInterval.Type)+ assert.ElementsMatch(t,+ []VerificationNotificationType{+ NotificationVerificationSuccess,+ NotificationVerificationFailed,+ },+ response.SendNotificationsOn,+ )++ var fetched BackupVerificationConfig+ test_utils.MakeGetRequestAndUnmarshal(+ t,+ router,+ "/api/v1/verification-config/"+database.ID.String(),+ "Bearer "+owner.Token,+ http.StatusOK,+ &fetched,+ )+ assert.True(t, fetched.IsScheduledVerificationEnabled)+ assert.ElementsMatch(t,+ []VerificationNotificationType{+ NotificationVerificationSuccess,+ NotificationVerificationFailed,+ },+ fetched.SendNotificationsOn,+ )++ databases.RemoveTestDatabase(database)+ workspaces_testing.RemoveTestWorkspace(workspace, router)+}++func Test_Save_AsViewer_RejectedWithPermissionError(t *testing.T) {+ router := createTestRouter()+ owner := users_testing.CreateTestUser(users_enums.UserRoleMember)+ workspace := workspaces_testing.CreateTestWorkspace("Test Workspace", owner, router)+ database := createTestDatabaseViaAPI("Test Database", workspace.ID, owner.Token, router)++ viewer := users_testing.CreateTestUser(users_enums.UserRoleMember)+ workspaces_testing.AddMemberToWorkspace(+ workspace,+ viewer,+ users_enums.WorkspaceRoleViewer,+ owner.Token,+ router,+ )++ resp := test_utils.MakePutRequest(+ t,+ router,+ "/api/v1/verification-config/"+database.ID.String(),+ "Bearer "+viewer.Token,+ newEnabledRequest(),+ http.StatusBadRequest,+ )+ assert.Contains(t, string(resp.Body), "insufficient permissions")++ databases.RemoveTestDatabase(database)+ workspaces_testing.RemoveTestWorkspace(workspace, router)+}++func Test_Save_WhenIsScheduledVerificationEnabledTrue_OnWalDatabase_Rejected(t *testing.T) {+ router := createTestRouter()+ owner := users_testing.CreateTestUser(users_enums.UserRoleMember)+ workspace := workspaces_testing.CreateTestWorkspace("Test Workspace", owner, router)+ database := createTestWalDatabaseViaAPI("Test WAL Database", workspace.ID, owner.Token, router)++ resp := test_utils.MakePutRequest(+ t,+ router,+ "/api/v1/verification-config/"+database.ID.String(),+ "Bearer "+owner.Token,+ newEnabledRequest(),+ http.StatusBadRequest,+ )+ assert.Contains(t, string(resp.Body), "WAL")++ databases.RemoveTestDatabase(database)+ workspaces_testing.RemoveTestWorkspace(workspace, router)+}++func Test_Save_WhenIsScheduledVerificationEnabledFalse_OnWalDatabase_Allowed(t *testing.T) {+ router := createTestRouter()+ owner := users_testing.CreateTestUser(users_enums.UserRoleMember)+ workspace := workspaces_testing.CreateTestWorkspace("Test Workspace", owner, router)+ database := createTestWalDatabaseViaAPI("Test WAL Database", workspace.ID, owner.Token, router)++ request := newEnabledRequest()+ request.IsScheduledVerificationEnabled = false++ var response BackupVerificationConfig+ test_utils.MakePutRequestAndUnmarshal(+ t,+ router,+ "/api/v1/verification-config/"+database.ID.String(),+ "Bearer "+owner.Token,+ request,+ http.StatusOK,+ &response,+ )+ assert.False(t, response.IsScheduledVerificationEnabled)++ databases.RemoveTestDatabase(database)+ workspaces_testing.RemoveTestWorkspace(workspace, router)+}++func Test_Save_WhenEnabled_WithInvalidInterval_ReturnsValidationError(t *testing.T) {+ router := createTestRouter()+ owner := users_testing.CreateTestUser(users_enums.UserRoleMember)+ workspace := workspaces_testing.CreateTestWorkspace("Test Workspace", owner, router)+ database := createTestDatabaseViaAPI("Test Database", workspace.ID, owner.Token, router)++ request := newEnabledRequest()+ request.VerificationInterval = intervals.Interval{+ Type: intervals.IntervalCron,+ }++ resp := test_utils.MakePutRequest(+ t,+ router,+ "/api/v1/verification-config/"+database.ID.String(),+ "Bearer "+owner.Token,+ request,+ http.StatusBadRequest,+ )+ assert.Contains(t, string(resp.Body), "cron expression")++ databases.RemoveTestDatabase(database)+ workspaces_testing.RemoveTestWorkspace(workspace, router)+}++func Test_Save_WithInvalidNotificationType_ReturnsValidationError(t *testing.T) {+ router := createTestRouter()+ owner := users_testing.CreateTestUser(users_enums.UserRoleMember)+ workspace := workspaces_testing.CreateTestWorkspace("Test Workspace", owner, router)+ database := createTestDatabaseViaAPI("Test Database", workspace.ID, owner.Token, router)++ request := newEnabledRequest()+ request.SendNotificationsOn = []VerificationNotificationType{+ VerificationNotificationType("VERIFICATION_EXPIRED"),+ }++ resp := test_utils.MakePutRequest(+ t,+ router,+ "/api/v1/verification-config/"+database.ID.String(),+ "Bearer "+owner.Token,+ request,+ http.StatusBadRequest,+ )+ assert.Contains(t, string(resp.Body), "invalid verification notification type")++ databases.RemoveTestDatabase(database)+ workspaces_testing.RemoveTestWorkspace(workspace, router)+}++func Test_Save_WhenScheduleTypeAfterBackup_SkipsIntervalValidationAndPersists(t *testing.T) {+ router := createTestRouter()+ owner := users_testing.CreateTestUser(users_enums.UserRoleMember)+ workspace := workspaces_testing.CreateTestWorkspace("Test Workspace", owner, router)+ database := createTestDatabaseViaAPI("Test Database", workspace.ID, owner.Token, router)++ request := SaveBackupVerificationConfigDTO{+ IsScheduledVerificationEnabled: true,+ ScheduleType: VerificationScheduleAfterBackup,+ // Deliberately invalid as a time interval — must be ignored in after-backup mode.+ VerificationInterval: intervals.Interval{Type: intervals.IntervalCron},+ SendNotificationsOn: []VerificationNotificationType{NotificationVerificationFailed},+ }++ var response BackupVerificationConfig+ test_utils.MakePutRequestAndUnmarshal(+ t,+ router,+ "/api/v1/verification-config/"+database.ID.String(),+ "Bearer "+owner.Token,+ request,+ http.StatusOK,+ &response,+ )++ assert.True(t, response.IsScheduledVerificationEnabled)+ assert.Equal(t, VerificationScheduleAfterBackup, response.ScheduleType)++ var fetched BackupVerificationConfig+ test_utils.MakeGetRequestAndUnmarshal(+ t,+ router,+ "/api/v1/verification-config/"+database.ID.String(),+ "Bearer "+owner.Token,+ http.StatusOK,+ &fetched,+ )+ assert.Equal(t, VerificationScheduleAfterBackup, fetched.ScheduleType)++ databases.RemoveTestDatabase(database)+ workspaces_testing.RemoveTestWorkspace(workspace, router)+}++func Test_Save_WhenScheduleTypeInvalid_ReturnsValidationError(t *testing.T) {+ router := createTestRouter()+ owner := users_testing.CreateTestUser(users_enums.UserRoleMember)+ workspace := workspaces_testing.CreateTestWorkspace("Test Workspace", owner, router)+ database := createTestDatabaseViaAPI("Test Database", workspace.ID, owner.Token, router)++ request := newEnabledRequest()+ request.ScheduleType = VerificationScheduleType("WHENEVER")++ resp := test_utils.MakePutRequest(+ t,+ router,+ "/api/v1/verification-config/"+database.ID.String(),+ "Bearer "+owner.Token,+ request,+ http.StatusBadRequest,+ )+ assert.Contains(t, string(resp.Body), "invalid verification schedule type")++ databases.RemoveTestDatabase(database)+ workspaces_testing.RemoveTestWorkspace(workspace, router)+}++func Test_OnDatabaseCopied_CopiesConfigOntoNewDatabase(t *testing.T) {+ router := createTestRouter()+ owner := users_testing.CreateTestUser(users_enums.UserRoleMember)+ workspace := workspaces_testing.CreateTestWorkspace("Test Workspace", owner, router)+ source := createTestDatabaseViaAPI("Source Database", workspace.ID, owner.Token, router)+ target := createTestDatabaseViaAPI("Target Database", workspace.ID, owner.Token, router)++ saveRequest := newEnabledRequest()+ saveRequest.SendNotificationsOn = []VerificationNotificationType{+ NotificationVerificationSuccess,+ NotificationVerificationFailed,+ }++ var saved BackupVerificationConfig+ test_utils.MakePutRequestAndUnmarshal(+ t,+ router,+ "/api/v1/verification-config/"+source.ID.String(),+ "Bearer "+owner.Token,+ saveRequest,+ http.StatusOK,+ &saved,+ )++ verificationConfigService.OnDatabaseCopied(source.ID, target.ID)++ copied, err := verificationConfigRepository.GetByDatabaseID(target.ID)+ assert.NoError(t, err)+ assert.NotNil(t, copied)+ assert.Equal(t, target.ID, copied.DatabaseID)+ assert.True(t, copied.IsScheduledVerificationEnabled)+ assert.Equal(t, intervals.IntervalWeekly, copied.VerificationInterval.Type)+ assert.ElementsMatch(t,+ []VerificationNotificationType{+ NotificationVerificationSuccess,+ NotificationVerificationFailed,+ },+ copied.SendNotificationsOn,+ )++ databases.RemoveTestDatabase(source)+ databases.RemoveTestDatabase(target)+ workspaces_testing.RemoveTestWorkspace(workspace, router)+}diff --git a/backend/internal/features/verification/config/di.go b/backend/internal/features/verification/config/di.gonew file mode 100644index 00000000..22f18ab7--- /dev/null+++ b/backend/internal/features/verification/config/di.go@@ -0,0 +1,36 @@+package verification_config++import (+ "sync"++ "databasus-backend/internal/features/audit_logs"+ "databasus-backend/internal/features/databases"+ workspaces_services "databasus-backend/internal/features/workspaces/services"+ "databasus-backend/internal/util/logger"+)++var verificationConfigRepository = &VerificationConfigRepository{}++var verificationConfigService = &VerificationConfigService{+ verificationConfigRepository,+ databases.GetDatabaseService(),+ workspaces_services.GetWorkspaceService(),+ audit_logs.GetAuditLogService(),+ logger.GetLogger(),+}++var verificationConfigController = &VerificationConfigController{+ verificationConfigService,+}++func GetVerificationConfigService() *VerificationConfigService {+ return verificationConfigService+}++func GetVerificationConfigController() *VerificationConfigController {+ return verificationConfigController+}++var SetupDependencies = sync.OnceFunc(func() {+ databases.GetDatabaseService().AddDbCopyListener(verificationConfigService)+})diff --git a/backend/internal/features/verification/config/dto.go b/backend/internal/features/verification/config/dto.gonew file mode 100644index 00000000..468feba9--- /dev/null+++ b/backend/internal/features/verification/config/dto.go@@ -0,0 +1,12 @@+package verification_config++import (+ "databasus-backend/internal/features/intervals"+)++type SaveBackupVerificationConfigDTO struct {+ IsScheduledVerificationEnabled bool `json:"isScheduledVerificationEnabled"`+ ScheduleType VerificationScheduleType `json:"scheduleType"`+ VerificationInterval intervals.Interval `json:"verificationInterval"`+ SendNotificationsOn []VerificationNotificationType `json:"sendNotificationsOn"`+}diff --git a/backend/internal/features/verification/config/enums.go b/backend/internal/features/verification/config/enums.gonew file mode 100644index 00000000..7e28db99--- /dev/null+++ b/backend/internal/features/verification/config/enums.go@@ -0,0 +1,15 @@+package verification_config++type VerificationNotificationType string++const (+ NotificationVerificationSuccess VerificationNotificationType = "VERIFICATION_SUCCESS"+ NotificationVerificationFailed VerificationNotificationType = "VERIFICATION_FAILED"+)++type VerificationScheduleType string++const (+ VerificationScheduleInterval VerificationScheduleType = "INTERVAL"+ VerificationScheduleAfterBackup VerificationScheduleType = "AFTER_BACKUP"+)diff --git a/backend/internal/features/verification/config/model.go b/backend/internal/features/verification/config/model.gonew file mode 100644index 00000000..d4095175--- /dev/null+++ b/backend/internal/features/verification/config/model.go@@ -0,0 +1,96 @@+package verification_config++import (+ "fmt"+ "slices"+ "strings"+ "time"++ "github.com/google/uuid"+ "gorm.io/gorm"++ "databasus-backend/internal/features/intervals"+)++type BackupVerificationConfig struct {+ DatabaseID uuid.UUID `json:"databaseId" gorm:"column:database_id;type:uuid;primaryKey;not null"`++ IsScheduledVerificationEnabled bool `json:"isScheduledVerificationEnabled" gorm:"column:is_scheduled_verification_enabled;type:boolean;not null;default:false"`++ ScheduleType VerificationScheduleType `json:"scheduleType" gorm:"column:schedule_type;type:text;not null;default:'AFTER_BACKUP'"`+ VerificationInterval intervals.Interval `json:"verificationInterval" gorm:"embedded"`++ SendNotificationsOn []VerificationNotificationType `json:"sendNotificationsOn" gorm:"-"`+ SendNotificationsOnString string `json:"-" gorm:"column:send_notifications_on;type:text;not null;default:''"`++ CreatedAt time.Time `json:"createdAt" gorm:"column:created_at"`+ UpdatedAt time.Time `json:"updatedAt" gorm:"column:updated_at"`+}++func (BackupVerificationConfig) TableName() string {+ return "backup_verification_configs"+}++func (c *BackupVerificationConfig) BeforeSave(tx *gorm.DB) error {+ if len(c.SendNotificationsOn) > 0 {+ notificationTypes := make([]string, len(c.SendNotificationsOn))++ for i, notificationType := range c.SendNotificationsOn {+ notificationTypes[i] = string(notificationType)+ }++ c.SendNotificationsOnString = strings.Join(notificationTypes, ",")+ } else {+ c.SendNotificationsOnString = ""+ }++ return nil+}++func (c *BackupVerificationConfig) AfterFind(tx *gorm.DB) error {+ if c.SendNotificationsOnString != "" {+ notificationTypes := strings.Split(c.SendNotificationsOnString, ",")+ c.SendNotificationsOn = make([]VerificationNotificationType, len(notificationTypes))++ for i, notificationType := range notificationTypes {+ c.SendNotificationsOn[i] = VerificationNotificationType(notificationType)+ }+ } else {+ c.SendNotificationsOn = []VerificationNotificationType{}+ }++ return nil+}++func (c *BackupVerificationConfig) Validate() error {+ if c.ScheduleType != VerificationScheduleInterval && c.ScheduleType != VerificationScheduleAfterBackup {+ return fmt.Errorf("invalid verification schedule type: %q", c.ScheduleType)+ }++ if c.IsScheduledVerificationEnabled && c.ScheduleType == VerificationScheduleInterval {+ if err := c.VerificationInterval.Validate(); err != nil {+ return fmt.Errorf("verification interval: %w", err)+ }+ }++ for _, n := range c.SendNotificationsOn {+ switch n {+ case NotificationVerificationSuccess,+ NotificationVerificationFailed:+ default:+ return fmt.Errorf("invalid verification notification type: %q", n)+ }+ }++ return nil+}++func (c *BackupVerificationConfig) Copy(newDatabaseID uuid.UUID) *BackupVerificationConfig {+ return &BackupVerificationConfig{+ DatabaseID: newDatabaseID,+ IsScheduledVerificationEnabled: c.IsScheduledVerificationEnabled,+ ScheduleType: c.ScheduleType,+ VerificationInterval: c.VerificationInterval.Copy(),+ SendNotificationsOn: slices.Clone(c.SendNotificationsOn),+ }+}diff --git a/backend/internal/features/verification/config/repository.go b/backend/internal/features/verification/config/repository.gonew file mode 100644index 00000000..8f219ba9--- /dev/null+++ b/backend/internal/features/verification/config/repository.go@@ -0,0 +1,45 @@+package verification_config++import (+ "errors"++ "github.com/google/uuid"+ "gorm.io/gorm"++ "databasus-backend/internal/storage"+)++type VerificationConfigRepository struct{}++func (r *VerificationConfigRepository) Save(config *BackupVerificationConfig) error {+ return storage.GetDb().Save(config).Error+}++func (r *VerificationConfigRepository) GetByDatabaseID(+ databaseID uuid.UUID,+) (*BackupVerificationConfig, error) {+ var config BackupVerificationConfig++ if err := storage.+ GetDb().+ Where("database_id = ?", databaseID).+ First(&config).Error; err != nil {+ if errors.Is(err, gorm.ErrRecordNotFound) {+ return nil, nil+ }++ return nil, err+ }++ return &config, nil+}++func (r *VerificationConfigRepository) FindAllEnabled() ([]*BackupVerificationConfig, error) {+ configs := make([]*BackupVerificationConfig, 0)++ err := storage.GetDb().+ Where("is_scheduled_verification_enabled = ?", true).+ Find(&configs).Error++ return configs, err+}diff --git a/backend/internal/features/verification/config/service.go b/backend/internal/features/verification/config/service.gonew file mode 100644index 00000000..bff4b9ae--- /dev/null+++ b/backend/internal/features/verification/config/service.go@@ -0,0 +1,189 @@+package verification_config++import (+ "errors"+ "fmt"+ "log/slog"++ "github.com/google/uuid"++ "databasus-backend/internal/features/audit_logs"+ "databasus-backend/internal/features/databases"+ "databasus-backend/internal/features/databases/databases/postgresql"+ "databasus-backend/internal/features/intervals"+ users_models "databasus-backend/internal/features/users/models"+ workspaces_services "databasus-backend/internal/features/workspaces/services"+)++type VerificationConfigService struct {+ verificationConfigRepository *VerificationConfigRepository+ databaseService *databases.DatabaseService+ workspaceService *workspaces_services.WorkspaceService+ auditLogService *audit_logs.AuditLogService+ logger *slog.Logger+}++func (s *VerificationConfigService) GetByDatabaseID(+ user *users_models.User,+ databaseID uuid.UUID,+) (*BackupVerificationConfig, error) {+ database, err := s.databaseService.GetDatabaseByID(databaseID)+ if err != nil {+ return nil, err+ }++ if database.WorkspaceID == nil {+ return nil, errors.New("cannot access verification config for databases without workspace")+ }++ canAccess, _, err := s.workspaceService.CanUserAccessWorkspace(*database.WorkspaceID, user)+ if err != nil {+ return nil, err+ }+ if !canAccess {+ return nil, errors.New("insufficient permissions to view verification config")+ }++ config, err := s.verificationConfigRepository.GetByDatabaseID(database.ID)+ if err != nil {+ return nil, err+ }++ if config == nil {+ if err := s.initializeDefaultConfig(database.ID); err != nil {+ return nil, err+ }++ config, err = s.verificationConfigRepository.GetByDatabaseID(database.ID)+ if err != nil {+ return nil, err+ }+ }++ return config, nil+}++func (s *VerificationConfigService) Save(+ user *users_models.User,+ databaseID uuid.UUID,+ req *SaveBackupVerificationConfigDTO,+) (*BackupVerificationConfig, error) {+ database, err := s.databaseService.GetDatabaseByID(databaseID)+ if err != nil {+ return nil, err+ }++ if database.WorkspaceID == nil {+ return nil, errors.New("cannot modify verification config for databases without workspace")+ }++ canManage, err := s.workspaceService.CanUserManageDBs(*database.WorkspaceID, user)+ if err != nil {+ return nil, err+ }+ if !canManage {+ return nil, errors.New("insufficient permissions to modify verification config")+ }++ if req.IsScheduledVerificationEnabled &&+ database.Postgresql != nil &&+ database.Postgresql.BackupType == postgresql.PostgresBackupTypeWalV1 {+ return nil, errors.New("verification cannot be enabled for WAL-based databases")+ }++ config, err := s.verificationConfigRepository.GetByDatabaseID(database.ID)+ if err != nil {+ return nil, err+ }++ if config == nil {+ if err := s.initializeDefaultConfig(database.ID); err != nil {+ return nil, err+ }++ config, err = s.verificationConfigRepository.GetByDatabaseID(database.ID)+ if err != nil {+ return nil, err+ }+ }++ config.IsScheduledVerificationEnabled = req.IsScheduledVerificationEnabled+ config.ScheduleType = req.ScheduleType+ config.VerificationInterval = req.VerificationInterval+ config.SendNotificationsOn = req.SendNotificationsOn++ if err := config.Validate(); err != nil {+ return nil, err+ }++ if err := s.verificationConfigRepository.Save(config); err != nil {+ return nil, err+ }++ s.auditLogService.WriteAuditLog(+ fmt.Sprintf("Backup verification config updated for database '%s'", database.Name),+ &user.ID,+ database.WorkspaceID,+ )++ return config, nil+}++func (s *VerificationConfigService) GetByDatabaseIDNoAuth(+ databaseID uuid.UUID,+) (*BackupVerificationConfig, error) {+ return s.verificationConfigRepository.GetByDatabaseID(databaseID)+}++func (s *VerificationConfigService) ListEnabled() ([]*BackupVerificationConfig, error) {+ return s.verificationConfigRepository.FindAllEnabled()+}++func (s *VerificationConfigService) OnDatabaseCopied(originalDatabaseID, newDatabaseID uuid.UUID) {+ originalConfig, err := s.verificationConfigRepository.GetByDatabaseID(originalDatabaseID)+ if err != nil {+ s.logger.Error(+ "failed to load source verification config on database copy",+ "error", err,+ "database_id", originalDatabaseID,+ )+ return+ }++ if originalConfig == nil {+ if err := s.initializeDefaultConfig(newDatabaseID); err != nil {+ s.logger.Error(+ "failed to initialize default verification config on database copy",+ "error", err,+ "database_id", newDatabaseID,+ )+ }+ return+ }++ newConfig := originalConfig.Copy(newDatabaseID)++ if err := s.verificationConfigRepository.Save(newConfig); err != nil {+ s.logger.Error(+ "failed to save verification config on database copy",+ "error", err,+ "database_id", newDatabaseID,+ )+ }+}++func (s *VerificationConfigService) initializeDefaultConfig(databaseID uuid.UUID) error {+ return s.verificationConfigRepository.Save(&BackupVerificationConfig{+ DatabaseID: databaseID,+ IsScheduledVerificationEnabled: false,+ ScheduleType: VerificationScheduleAfterBackup,+ VerificationInterval: intervals.Interval{+ Type: intervals.IntervalWeekly,+ TimeOfDay: new("04:00"),+ Weekday: new(0),+ },+ SendNotificationsOn: []VerificationNotificationType{+ NotificationVerificationFailed,+ },+ })+}diff --git a/backend/internal/features/verification/config/testing.go b/backend/internal/features/verification/config/testing.gonew file mode 100644index 00000000..bb40d305--- /dev/null+++ b/backend/internal/features/verification/config/testing.go@@ -0,0 +1,34 @@+package verification_config++import (+ "net/http"+ "testing"++ "github.com/gin-gonic/gin"+ "github.com/google/uuid"++ test_utils "databasus-backend/internal/util/testing"+)++func SaveVerificationConfigViaAPI(+ t *testing.T,+ router *gin.Engine,+ userToken string,+ databaseID uuid.UUID,+ request SaveBackupVerificationConfigDTO,+) *BackupVerificationConfig {+ t.Helper()++ var response BackupVerificationConfig+ test_utils.MakePutRequestAndUnmarshal(+ t,+ router,+ "/api/v1/verification-config/"+databaseID.String(),+ "Bearer "+userToken,+ request,+ http.StatusOK,+ &response,+ )++ return &response+}diff --git a/backend/internal/features/verification/runs/after_backup_verification_test.go b/backend/internal/features/verification/runs/after_backup_verification_test.gonew file mode 100644index 00000000..a66f4a12--- /dev/null+++ b/backend/internal/features/verification/runs/after_backup_verification_test.go@@ -0,0 +1,357 @@+package verification_runs++import (+ "testing"+ "time"++ "github.com/gin-gonic/gin"+ "github.com/google/uuid"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ "databasus-backend/internal/features/backups/backups/backuping"+ backups_config "databasus-backend/internal/features/backups/config"+ "databasus-backend/internal/features/databases"+ "databasus-backend/internal/features/notifiers"+ "databasus-backend/internal/features/storages"+ users_enums "databasus-backend/internal/features/users/enums"+ users_testing "databasus-backend/internal/features/users/testing"+ verification_config "databasus-backend/internal/features/verification/config"+ workspaces_testing "databasus-backend/internal/features/workspaces/testing"+)++func enableAfterBackupVerificationViaAPI(+ t *testing.T,+ router *gin.Engine,+ userToken string,+ databaseID uuid.UUID,+) {+ t.Helper()++ verification_config.SaveVerificationConfigViaAPI(t, router, userToken, databaseID,+ verification_config.SaveBackupVerificationConfigDTO{+ IsScheduledVerificationEnabled: true,+ ScheduleType: verification_config.VerificationScheduleAfterBackup,+ })+}++func Test_CreateScheduledRuns_WhenScheduleTypeAfterBackup_DoesNotCreateTimeBasedRun(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)++ backuping.SeedTestBackup(t, database.ID, testStorage.ID, 100)++ enableAfterBackupVerificationViaAPI(t, router, owner.Token, database.ID)++ scheduler := GetVerificationScheduler()+ require.NoError(t, scheduler.createScheduledRuns())++ rows := ListVerificationsByDatabaseViaAPI(t, router, owner.Token, database.ID)+ assert.Empty(t, rows, "after-backup config must never get a time-based scheduled run")+}++func Test_OnBackupCompleted_WhenScheduleTypeAfterBackup_EnqueuesPendingRun(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.SeedTestBackup(t, database.ID, testStorage.ID, 100)++ enableAfterBackupVerificationViaAPI(t, router, owner.Token, database.ID)++ GetVerificationService().OnBackupCompleted(backup.ID)++ rows := ListVerificationsByDatabaseViaAPI(t, router, owner.Token, database.ID)+ require.Len(t, rows, 1)+ assert.Equal(t, VerificationStatusPending, rows[0].Status)+ assert.Equal(t, VerificationTriggerAfterBackup, rows[0].Trigger)+ assert.Equal(t, backup.ID, rows[0].BackupID)+}++func Test_OnBackupCompleted_WhenPendingAfterBackupExists_CancelsOldAndEnqueuesNew(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)++ firstBackup := backuping.SeedTestBackup(t, database.ID, testStorage.ID, 100)++ enableAfterBackupVerificationViaAPI(t, router, owner.Token, database.ID)++ service := GetVerificationService()+ service.OnBackupCompleted(firstBackup.ID)++ rows := ListVerificationsByDatabaseViaAPI(t, router, owner.Token, database.ID)+ require.Len(t, rows, 1)+ firstRunID := rows[0].ID++ newerBackup := backuping.SeedTestBackup(t, database.ID, testStorage.ID, 150)+ service.OnBackupCompleted(newerBackup.ID)++ rowsAfter := ListVerificationsByDatabaseViaAPI(t, router, owner.Token, database.ID)+ require.Len(t, rowsAfter, 2)++ var pendingCount int+ for _, row := range rowsAfter {+ if row.ID == firstRunID {+ assert.Equal(t, VerificationStatusCanceled, row.Status, "old PENDING must be canceled")+ continue+ }++ pendingCount+++ assert.Equal(t, VerificationStatusPending, row.Status)+ assert.Equal(t, VerificationTriggerAfterBackup, row.Trigger)+ assert.Equal(t, newerBackup.ID, row.BackupID, "fresh run must point at the newest backup")+ }+ assert.Equal(t, 1, pendingCount, "queue must stay bounded at one PENDING after-backup run")+}++func Test_OnBackupCompleted_WhenManualVerificationPending_LeavesItAndStillEnqueuesAfterBackup(+ 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.SeedTestBackup(t, database.ID, testStorage.ID, 100)++ enableAfterBackupVerificationViaAPI(t, router, owner.Token, database.ID)++ manualRun := EnqueueManualVerificationViaAPI(t, router, owner.Token, backup.ID)++ GetVerificationService().OnBackupCompleted(backup.ID)++ manualAfter := GetVerificationByIDViaAPI(t, router, owner.Token, manualRun.ID)+ assert.Equal(+ t,+ VerificationStatusPending,+ manualAfter.Status,+ "a user-triggered MANUAL run must survive a backup completion",+ )+ assert.Equal(t, VerificationTriggerManual, manualAfter.Trigger)++ rows := ListVerificationsByDatabaseViaAPI(t, router, owner.Token, database.ID)+ require.Len(t, rows, 2, "manual run plus the new after-backup run")++ var afterBackupPending int+ for _, row := range rows {+ if row.Trigger == VerificationTriggerAfterBackup && row.Status == VerificationStatusPending {+ afterBackupPending+++ assert.Equal(t, backup.ID, row.BackupID)+ }+ }+ assert.Equal(t, 1, afterBackupPending, "after-backup run still enqueued alongside the manual one")+}++func Test_OnBackupCompleted_WhenScheduleTypeInterval_DoesNothing(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.SeedTestBackup(t, database.ID, testStorage.ID, 100)++ enableHourlyVerificationViaAPI(t, router, owner.Token, database.ID)++ GetVerificationService().OnBackupCompleted(backup.ID)++ rows := ListVerificationsByDatabaseViaAPI(t, router, owner.Token, database.ID)+ assert.Empty(t, rows, "interval-mode config must ignore backup-completion events")+}++func Test_OnBackupCompleted_WhenDisabled_DoesNothing(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.SeedTestBackup(t, database.ID, testStorage.ID, 100)++ verification_config.SaveVerificationConfigViaAPI(t, router, owner.Token, database.ID,+ verification_config.SaveBackupVerificationConfigDTO{+ IsScheduledVerificationEnabled: false,+ ScheduleType: verification_config.VerificationScheduleAfterBackup,+ })++ GetVerificationService().OnBackupCompleted(backup.ID)++ rows := ListVerificationsByDatabaseViaAPI(t, router, owner.Token, database.ID)+ assert.Empty(t, rows, "disabled config must not enqueue after-backup verifications")+}++func Test_OnBackupCompleted_WhenNoVerifiableBackup_DoesNothing(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)++ walBackup := backuping.SeedTestWalSegmentBackup(t, database.ID, testStorage.ID)++ enableAfterBackupVerificationViaAPI(t, router, owner.Token, database.ID)++ GetVerificationService().OnBackupCompleted(walBackup.ID)++ rows := ListVerificationsByDatabaseViaAPI(t, router, owner.Token, database.ID)+ assert.Empty(t, rows, "a WAL-only database has no verifiable backup to enqueue")+}++func Test_MakeBackup_WhenAfterBackupConfigured_SchedulesAndReplacesPendingVerification(+ 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)++ backups_config.EnableBackupsForTestDatabase(database.ID, testStorage)+ enableAfterBackupVerificationViaAPI(t, router, owner.Token, database.ID)++ // Start the real backups scheduler singleton so it subscribes to the+ // backup-completion channel — the seam the verification listener is wired+ // onto by verification_runs.SetupDependencies (called in createTestRouter).+ stopScheduler := backuping.StartSchedulerForTest(t, backuping.GetBackupsScheduler())+ defer stopScheduler()++ backupNode := backuping.CreateTestBackuperNodeWithUseCase(&backuping.CreateSuccessBackupUsecase{})++ // completeBackup reproduces the BackuperNode's backupHandler exactly:+ // MakeBackup drives the backup to COMPLETED, then completion is published on+ // the channel. A fresh node UUID stands in for an unknown/restarted node —+ // the listener must still fire (the fan-out runs before the node-relation+ // bookkeeping early-returns).+ completeBackup := func() uuid.UUID {+ backup := backuping.SeedInProgressTestBackup(t, database.ID, testStorage.ID)+ backupNode.MakeBackup(backup.ID, false)+ require.NoError(+ t,+ backuping.GetBackupNodesRegistry().PublishBackupCompletion(uuid.New(), backup.ID),+ )++ return backup.ID+ }++ waitForSinglePending := func(expectedBackupID uuid.UUID) *RestoreVerification {+ t.Helper()++ deadline := time.Now().Add(15 * time.Second)+ for time.Now().Before(deadline) {+ var pending []*RestoreVerification+ for _, row := range ListVerificationsByDatabaseViaAPI(t, router, owner.Token, database.ID) {+ if row.Status == VerificationStatusPending {+ pending = append(pending, row)+ }+ }++ if len(pending) == 1 && pending[0].BackupID == expectedBackupID {+ return pending[0]+ }++ time.Sleep(100 * time.Millisecond)+ }++ t.Fatalf("timed out waiting for a single PENDING after-backup verification on backup %s", expectedBackupID)+ return nil+ }++ // First completed backup → exactly one PENDING after-backup verification.+ firstBackupID := completeBackup()+ firstRun := waitForSinglePending(firstBackupID)+ assert.Equal(t, VerificationTriggerAfterBackup, firstRun.Trigger)++ // Second completed backup while the first run is still PENDING → the stale+ // PENDING run is canceled and a fresh one is scheduled for the newer backup.+ secondBackupID := completeBackup()+ secondRun := waitForSinglePending(secondBackupID)++ // Terminalize the remaining PENDING run even if an assertion below aborts —+ // FindOldestPendingClaimablesTop100 spans the shared test DB, so a leaked+ // PENDING run could be claimed by a later test's agent.+ defer CancelVerificationViaAPI(t, router, owner.Token, secondRun.ID)++ assert.NotEqual(t, firstRun.ID, secondRun.ID)+ assert.Equal(t, VerificationTriggerAfterBackup, secondRun.Trigger)++ firstFinal := GetVerificationByIDViaAPI(t, router, owner.Token, firstRun.ID)+ assert.Equal(+ t,+ VerificationStatusCanceled,+ firstFinal.Status,+ "a newer completed backup must cancel the still-PENDING after-backup run",+ )+}diff --git a/backend/internal/features/verification/runs/agent_controller.go b/backend/internal/features/verification/runs/agent_controller.gonew file mode 100644index 00000000..b4eda6d2--- /dev/null+++ b/backend/internal/features/verification/runs/agent_controller.go@@ -0,0 +1,173 @@+package verification_runs++import (+ "fmt"+ "io"+ "log/slog"+ "net/http"++ "github.com/gin-gonic/gin"+ "github.com/google/uuid"++ verification_agents "databasus-backend/internal/features/verification/agents"+)++type VerificationAgentController struct {+ verificationService *VerificationService+ agentService *verification_agents.AgentService+ logger *slog.Logger+}++func (c *VerificationAgentController) RegisterRoutes(router *gin.RouterGroup) {+ g := router.Group("/agent/verifications/:agentId")+ g.Use(c.agentService.RequireAgentAuth())++ g.POST("/claim", c.Claim)+ g.GET("/:id/backup-stream", c.BackupStream)+ g.POST("/:id/report", c.Report)+}++// Claim+// @Summary Claim next verification job+// @Description Called by a verification agent. Returns the oldest PENDING verification that fits the agent's disk budget, or 204 if nothing fits.+// @Tags verification-agents+// @Accept json+// @Produce json+// @Param agentId path string true "Agent UUID"+// @Param Authorization header string true "Bearer <agent-token>"+// @Param request body ClaimRequest true "Agent capacity"+// @Success 200 {object} JobAssignment+// @Success 204+// @Failure 400 {object} map[string]string+// @Failure 401 {object} map[string]string+// @Router /agent/verifications/{agentId}/claim [post]+func (c *VerificationAgentController) Claim(ctx *gin.Context) {+ agent, ok := verification_agents.GetAgentFromContext(ctx)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "agent missing from context"})+ return+ }++ var req ClaimRequest+ if err := ctx.ShouldBindJSON(&req); err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ assignment, err := c.verificationService.ClaimVerification(agent, &req)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ if assignment == nil {+ ctx.Status(http.StatusNoContent)+ return+ }++ ctx.JSON(http.StatusOK, assignment)+}++// BackupStream+// @Summary Stream the backup file for a verification+// @Description Streams the decrypted backup file to the agent that owns this RUNNING verification. Same bytes the user-facing /backups/{id}/download endpoint returns.+// @Tags verification-agents+// @Produce application/octet-stream+// @Param agentId path string true "Agent UUID"+// @Param id path string true "Verification UUID"+// @Param Authorization header string true "Bearer <agent-token>"+// @Success 200+// @Failure 400 {object} map[string]string+// @Failure 401 {object} map[string]string+// @Failure 410 {object} map[string]string+// @Router /agent/verifications/{agentId}/{id}/backup-stream [get]+func (c *VerificationAgentController) BackupStream(ctx *gin.Context) {+ agent, ok := verification_agents.GetAgentFromContext(ctx)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "agent missing from context"})+ return+ }++ verificationID, err := uuid.Parse(ctx.Param("id"))+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid verification ID"})+ return+ }++ reader, err := c.verificationService.GetBackupFile(agent, verificationID)+ if err != nil {+ ctx.JSON(http.StatusGone, gin.H{"error": err.Error(), "reason": "gone"})+ return+ }++ defer func() {+ if closeErr := reader.Close(); closeErr != nil {+ c.logger.Error(+ "failed to close backup reader",+ "error", closeErr,+ "verification_id", verificationID,+ )+ }+ }()++ ctx.Header("Content-Type", "application/octet-stream")+ ctx.Header(+ "Content-Disposition",+ fmt.Sprintf(`attachment; filename="verification-%s.dump"`, verificationID),+ )++ if _, err := io.Copy(ctx.Writer, reader); err != nil {+ c.logger.Error(+ "failed to stream backup to agent",+ "error", err,+ "verification_id", verificationID,+ )+ }+}++// Report+// @Summary Submit verification result+// @Description Agent reports COMPLETED (with stats) or FAILED. CAS-guarded: stale or foreign reports get 410.+// @Tags verification-agents+// @Accept json+// @Produce json+// @Param agentId path string true "Agent UUID"+// @Param id path string true "Verification UUID"+// @Param Authorization header string true "Bearer <agent-token>"+// @Param request body ReportRequest true "Report payload"+// @Success 204+// @Failure 400 {object} map[string]string+// @Failure 401 {object} map[string]string+// @Failure 410 {object} map[string]string+// @Router /agent/verifications/{agentId}/{id}/report [post]+func (c *VerificationAgentController) Report(ctx *gin.Context) {+ agent, ok := verification_agents.GetAgentFromContext(ctx)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "agent missing from context"})+ return+ }++ verificationID, err := uuid.Parse(ctx.Param("id"))+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid verification ID"})+ return+ }++ var req ReportRequest+ if err := ctx.ShouldBindJSON(&req); err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if err := c.verificationService.SubmitReport(agent, verificationID, &req); err != nil {+ if err.Error() == "verification gone" {+ ctx.JSON(http.StatusGone, gin.H{"reason": "gone"})+ return+ }++ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ ctx.Status(http.StatusNoContent)+}diff --git a/backend/internal/features/verification/runs/agent_controller_test.go b/backend/internal/features/verification/runs/agent_controller_test.gonew file mode 100644index 00000000..a4d03739--- /dev/null+++ b/backend/internal/features/verification/runs/agent_controller_test.go@@ -0,0 +1,821 @@+package verification_runs++import (+ "fmt"+ "net/http"+ "testing"+ "time"++ "github.com/google/uuid"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ "databasus-backend/internal/features/backups/backups/backuping"+ backups_core "databasus-backend/internal/features/backups/backups/core"+ "databasus-backend/internal/features/databases"+ "databasus-backend/internal/features/notifiers"+ "databasus-backend/internal/features/storages"+ users_enums "databasus-backend/internal/features/users/enums"+ users_testing "databasus-backend/internal/features/users/testing"+ verification_agents "databasus-backend/internal/features/verification/agents"+ workspaces_testing "databasus-backend/internal/features/workspaces/testing"+ "databasus-backend/internal/storage"+ test_utils "databasus-backend/internal/util/testing"+)++func claimPathFor(agentID uuid.UUID) string {+ return fmt.Sprintf("/api/v1/agent/verifications/%s/claim", agentID)+}++func reportPathFor(agentID, verificationID uuid.UUID) string {+ return fmt.Sprintf("/api/v1/agent/verifications/%s/%s/report", agentID, verificationID)+}++func Test_ClaimVerification_WhenPendingFitsBudget_ReturnsJobAssignment(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.SeedTestBackup(t, database.ID, testStorage.ID, 100)++ enqueued := EnqueueManualVerificationViaAPI(t, router, owner.Token, backup.ID)++ agent := verification_agents.CreateTestVerificationAgent(t, router, owner.Token, "claim-test-"+uuid.New().String())+ defer verification_agents.RemoveTestVerificationAgent(t, router, owner.Token, agent.Agent.ID)++ assignment := ClaimVerificationViaAPI(+ t, router, agent.Agent.ID, agent.Token,+ AgentCapacity{MaxCPU: 4, MaxRAMMb: 4096, MaxDiskGb: 50, MaxConcurrentJobs: 2},+ )++ assert.Equal(t, enqueued.ID, assignment.VerificationID)+ assert.Equal(t, backup.ID, assignment.BackupID)+ assert.InDelta(t, 100, assignment.BackupSizeMb, 0.001)+ assert.InDelta(t, float64(EstimateRequiredForRestoreDiskMb(backup)), assignment.MaxContainerDiskMb, 0.001)+ require.NotNil(t, assignment.Database)+ assert.Equal(t, databases.DatabaseTypePostgres, assignment.Database.Type)+ require.NotNil(t, assignment.Database.Postgresql)+ assert.Equal(t, "16", string(assignment.Database.Postgresql.Version))++ updated := GetVerificationByIDViaAPI(t, router, owner.Token, enqueued.ID)+ assert.Equal(t, VerificationStatusRunning, updated.Status)+ require.NotNil(t, updated.AgentID)+ assert.Equal(t, agent.Agent.ID, *updated.AgentID)+}++func Test_ClaimVerification_WhenBackupTooBigForBudget_DoNotAssignJobWithoutError(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)++ largeBackup := backuping.SeedTestBackup(t, database.ID, testStorage.ID, 100*1024)++ EnqueueManualVerificationViaAPI(t, router, owner.Token, largeBackup.ID)++ agent := verification_agents.CreateTestVerificationAgent(t, router, owner.Token, "no-room-"+uuid.New().String())+ defer verification_agents.RemoveTestVerificationAgent(t, router, owner.Token, agent.Agent.ID)++ test_utils.MakePostRequest(+ t, router,+ claimPathFor(agent.Agent.ID),+ "Bearer "+agent.Token,+ ClaimRequest{Capacity: AgentCapacity{MaxCPU: 4, MaxRAMMb: 4096, MaxDiskGb: 1, MaxConcurrentJobs: 2}},+ http.StatusNoContent,+ )+}++func Test_ClaimVerification_WhenMultiplePendingFit_ReturnsOldestThatFitsBudget(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)++ databaseSmall := databases.CreateTestDatabase(workspace.ID, testStorage, notifier)+ defer databases.RemoveTestDatabase(databaseSmall)+ databaseBig := databases.CreateTestDatabase(workspace.ID, testStorage, notifier)+ defer databases.RemoveTestDatabase(databaseBig)++ oldBig := backuping.SeedTestBackup(t, databaseBig.ID, testStorage.ID, 4*1024)+ youngSmall := backuping.SeedTestBackup(t, databaseSmall.ID, testStorage.ID, 100)++ oldVerification := EnqueueManualVerificationViaAPI(t, router, owner.Token, oldBig.ID)+ require.NoError(t, storage.GetDb().+ Model(&RestoreVerification{}).+ Where("id = ?", oldVerification.ID).+ Update("created_at", time.Now().UTC().Add(-1*time.Hour)).Error)++ youngVerification := EnqueueManualVerificationViaAPI(t, router, owner.Token, youngSmall.ID)++ agent := verification_agents.CreateTestVerificationAgent(t, router, owner.Token, "size-pick-"+uuid.New().String())+ defer verification_agents.RemoveTestVerificationAgent(t, router, owner.Token, agent.Agent.ID)++ assignment := ClaimVerificationViaAPI(+ t, router, agent.Agent.ID, agent.Token,+ AgentCapacity{MaxCPU: 4, MaxRAMMb: 4096, MaxDiskGb: 5, MaxConcurrentJobs: 2},+ )++ assert.Equal(+ t, youngVerification.ID, assignment.VerificationID,+ "the older oversized verification must be skipped by the fit check, not picked over the younger one that fits",+ )+}++func Test_ClaimVerification_WhenAgentHasRunningRows_DeductsTheirSizeFromBudget(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)++ databaseRunning := databases.CreateTestDatabase(workspace.ID, testStorage, notifier)+ defer databases.RemoveTestDatabase(databaseRunning)+ databasePending := databases.CreateTestDatabase(workspace.ID, testStorage, notifier)+ defer databases.RemoveTestDatabase(databasePending)++ bigBackup := backuping.SeedTestBackup(t, databaseRunning.ID, testStorage.ID, 1000)+ pendingBackup := backuping.SeedTestBackup(t, databasePending.ID, testStorage.ID, 1000)++ agent := verification_agents.CreateTestVerificationAgent(t, router, owner.Token, "budget-"+uuid.New().String())+ defer verification_agents.RemoveTestVerificationAgent(t, router, owner.Token, agent.Agent.ID)++ EnqueueManualVerificationViaAPI(t, router, owner.Token, bigBackup.ID)++ roomyCapacity := ClaimRequest{+ Capacity: AgentCapacity{MaxCPU: 4, MaxRAMMb: 4096, MaxDiskGb: 50, MaxConcurrentJobs: 2},+ }++ var firstAssignment JobAssignment+ test_utils.MakePostRequestAndUnmarshal(+ t, router,+ claimPathFor(agent.Agent.ID),+ "Bearer "+agent.Token,+ roomyCapacity,+ http.StatusOK, &firstAssignment,+ )+ assert.Equal(t, bigBackup.ID, firstAssignment.BackupID)++ EnqueueManualVerificationViaAPI(t, router, owner.Token, pendingBackup.ID)++ test_utils.MakePostRequest(+ t, router,+ claimPathFor(agent.Agent.ID),+ "Bearer "+agent.Token,+ ClaimRequest{Capacity: AgentCapacity{MaxCPU: 4, MaxRAMMb: 4096, MaxDiskGb: 4, MaxConcurrentJobs: 2}},+ http.StatusNoContent,+ )+}++func Test_ClaimVerification_WhenAlreadyClaimedByAnotherAgent_OnlyReassignsAfterCancelAndReschedule(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.SeedTestBackup(t, database.ID, testStorage.ID, 100)++ originalRow := EnqueueManualVerificationViaAPI(t, router, owner.Token, backup.ID)++ agentA := verification_agents.CreateTestVerificationAgent(t, router, owner.Token, "a-"+uuid.New().String())+ defer verification_agents.RemoveTestVerificationAgent(t, router, owner.Token, agentA.Agent.ID)+ agentB := verification_agents.CreateTestVerificationAgent(t, router, owner.Token, "b-"+uuid.New().String())+ defer verification_agents.RemoveTestVerificationAgent(t, router, owner.Token, agentB.Agent.ID)++ capacity := AgentCapacity{MaxCPU: 4, MaxRAMMb: 4096, MaxDiskGb: 50, MaxConcurrentJobs: 2}++ firstAssignment := ClaimVerificationViaAPI(t, router, agentA.Agent.ID, agentA.Token, capacity)+ assert.Equal(t, originalRow.ID, firstAssignment.VerificationID)++ test_utils.MakePostRequest(+ t, router,+ claimPathFor(agentB.Agent.ID),+ "Bearer "+agentB.Token,+ ClaimRequest{Capacity: capacity},+ http.StatusNoContent,+ )++ afterFirstClaim := GetVerificationByIDViaAPI(t, router, owner.Token, originalRow.ID)+ require.NotNil(t, afterFirstClaim.AgentID)+ assert.Equal(t, agentA.Agent.ID, *afterFirstClaim.AgentID)++ require.NoError(t, storage.GetDb().+ Model(&RestoreVerification{}).+ Where("id = ?", originalRow.ID).+ Update("status", VerificationStatusCanceled).Error)++ test_utils.MakePostRequest(+ t, router,+ claimPathFor(agentB.Agent.ID),+ "Bearer "+agentB.Token,+ ClaimRequest{Capacity: capacity},+ http.StatusNoContent,+ )++ rescheduledRow := EnqueueManualVerificationViaAPI(t, router, owner.Token, backup.ID)++ secondAssignment := ClaimVerificationViaAPI(t, router, agentB.Agent.ID, agentB.Token, capacity)+ assert.Equal(t, rescheduledRow.ID, secondAssignment.VerificationID)+ assert.NotEqual(t, originalRow.ID, secondAssignment.VerificationID)++ finalOriginal := GetVerificationByIDViaAPI(t, router, owner.Token, originalRow.ID)+ require.NotNil(t, finalOriginal.AgentID)+ assert.Equal(t, agentA.Agent.ID, *finalOriginal.AgentID, "original row's owner must never have flipped to agent B")+}++func Test_SubmitReport_WhenStatusCompleted_PersistsResultsAndTableStats(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.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},+ )++ rowCount := int64(1234)+ tableCount := 5+ schemaCount := 1+ // Healthy restore: well above minRestoredSizeRatio (20%) of the seeded+ // 100 MB raw size, so the size guard does not flag it.+ dbSize := int64(80_000_000)+ restoreMs := int64(8000)+ verifyMs := int64(2000)++ report := ReportRequest{+ Status: VerificationStatusCompleted,+ PgRestoreExitCode: new(int),+ RestoreDurationMs: &restoreMs,+ VerifyDurationMs: &verifyMs,+ DBSizeBytesAfterRestore: &dbSize,+ TableCount: &tableCount,+ SchemaCount: &schemaCount,+ TableStats: []ReportTableStat{+ {SchemaName: "public", Name: "users", RowCount: rowCount},+ {SchemaName: "public", Name: "orders", RowCount: 7},+ },+ }++ 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)+ require.NotNil(t, final.FinishedAt)+ require.Len(t, final.TableStats, 2)++ verifiedBackup := GetBackupViaAPI(t, router, owner.Token, database.ID, backup.ID)+ assert.Equal(+ t,+ backups_core.RestoreVerificationStatusVerifiedSuccessful,+ verifiedBackup.RestoreVerificationStatus,+ "a terminal COMPLETED verification must stamp the backup VERIFIED_SUCCESSFUL",+ )+}++func Test_SubmitReport_WhenRowWasReapedWhileAgentWasSilent_Returns410(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.SeedTestBackup(t, database.ID, testStorage.ID, 100)++ agent := verification_agents.CreateTestVerificationAgent(t, router, owner.Token, "silent-"+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},+ )++ require.NoError(t, GetVerificationScheduler().reapStaleRuns())++ test_utils.MakePostRequest(+ t, router,+ reportPathFor(agent.Agent.ID, assignment.VerificationID),+ "Bearer "+agent.Token,+ ReportRequest{Status: VerificationStatusCompleted},+ http.StatusGone,+ )+}++func Test_SubmitReport_WhenAgentReportsBackupRejected_StoresMessageVerbatimAndTerminal(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.SeedTestBackup(t, database.ID, testStorage.ID, 100)+ agent := verification_agents.CreateTestVerificationAgent(t, router, owner.Token, "fail-"+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},+ )++ pgRestoreExit := 1+ verbatimMessage := "pg_restore: server closed connection unexpectedly"+ report := ReportRequest{+ Status: VerificationStatusFailed,+ PgRestoreExitCode: &pgRestoreExit,+ FailMessage: &verbatimMessage,+ }++ 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,+ VerificationStatusFailed,+ final.Status,+ "pg_restore non-zero exit is backup-side → terminal immediately",+ )+ assert.Equal(t, 1, final.AttemptCount, "backup-side failure must NOT advance the attempt counter")+ require.NotNil(t, final.FailMessage)+ assert.Equal(t, verbatimMessage, *final.FailMessage)++ rejectedBackup := GetBackupViaAPI(t, router, owner.Token, database.ID, backup.ID)+ assert.Equal(+ t,+ backups_core.RestoreVerificationStatusVerificationFailed,+ rejectedBackup.RestoreVerificationStatus,+ "a PG-error terminal failure must stamp the backup VERIFICATION_FAILED",+ )+}++func Test_SubmitReport_WhenAgentReportsDiskLimitExceeded_MarksTerminalWithoutRetry(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.SeedTestBackup(t, database.ID, testStorage.ID, 100)+ agent := verification_agents.CreateTestVerificationAgent(t, router, owner.Token, "disk-"+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},+ )++ // FailureKind drives the verdict even though PgRestoreExitCode is nil (which+ // would otherwise be the retryable agent-side path) — the per-job disk+ // budget is server-computed, so exceeding it is terminal, not retried.+ diskKind := string(FailureReasonDiskLimitExceeded)+ verbatimMessage := "restore exceeded job disk budget of 200 MB"+ report := ReportRequest{+ Status: VerificationStatusFailed,+ FailureKind: &diskKind,+ FailMessage: &verbatimMessage,+ }++ 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,+ VerificationStatusFailed,+ final.Status,+ "exceeding the server-computed disk budget is terminal",+ )+ assert.Equal(t, 1, final.AttemptCount, "disk-limit failure must NOT advance the attempt counter")+ require.NotNil(t, final.FailMessage)+ assert.Equal(t, verbatimMessage, *final.FailMessage)++ rejectedBackup := GetBackupViaAPI(t, router, owner.Token, database.ID, backup.ID)+ assert.Equal(+ t,+ backups_core.RestoreVerificationStatusVerificationFailed,+ rejectedBackup.RestoreVerificationStatus,+ "a terminal disk-limit failure must stamp the backup VERIFICATION_FAILED",+ )+}++func Test_SubmitReport_WhenAgentSetupFailedWithRetriesRemaining_RequeuesVerification(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.SeedTestBackup(t, database.ID, testStorage.ID, 100)+ agent := verification_agents.CreateTestVerificationAgent(t, router, owner.Token, "retry-"+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},+ )++ // PgRestoreExitCode==nil → agent-side (setup failure), eligible for retry.+ failMessage := "download torn before pg_restore could run"+ test_utils.MakePostRequest(+ t, router,+ reportPathFor(agent.Agent.ID, assignment.VerificationID),+ "Bearer "+agent.Token,+ ReportRequest{Status: VerificationStatusFailed, FailMessage: &failMessage},+ http.StatusNoContent,+ )++ requeued := GetVerificationByIDViaAPI(t, router, owner.Token, assignment.VerificationID)+ assert.Equal(t, VerificationStatusPending, requeued.Status, "must requeue, not go terminal")+ assert.Equal(t, 2, requeued.AttemptCount, "attempt counter must advance")+ assert.Nil(t, requeued.AgentID, "agent ownership must be released on requeue")+ assert.Nil(t, requeued.FailMessage, "fail message must be cleared so next attempt starts clean")+ assert.Nil(t, requeued.StartedAt)+ assert.Nil(t, requeued.FinishedAt)++ requeuedBackup := GetBackupViaAPI(t, router, owner.Token, database.ID, backup.ID)+ assert.Equal(+ t,+ backups_core.RestoreVerificationStatusNotVerified,+ requeuedBackup.RestoreVerificationStatus,+ "a requeued (non-terminal) agent-side failure must leave the backup NOT_VERIFIED",+ )+}++func Test_SubmitReport_WhenAgentSetupFailedRepeatedly_MarksTerminalAfterMaxAttempts(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.SeedTestBackup(t, database.ID, testStorage.ID, 100)+ agent := verification_agents.CreateTestVerificationAgent(t, router, owner.Token, "exhaust-"+uuid.New().String())+ defer verification_agents.RemoveTestVerificationAgent(t, router, owner.Token, agent.Agent.ID)++ enqueued := EnqueueManualVerificationViaAPI(t, router, owner.Token, backup.ID)++ failMessages := []string{+ "setup failure: attempt 1",+ "setup failure: attempt 2",+ "setup failure: attempt 3 (terminal)",+ }++ for attempt, failMessage := range failMessages {+ claim := ClaimVerificationViaAPI(+ t, router, agent.Agent.ID, agent.Token,+ AgentCapacity{MaxCPU: 4, MaxRAMMb: 4096, MaxDiskGb: 50, MaxConcurrentJobs: 2},+ )+ require.Equal(t, enqueued.ID, claim.VerificationID,+ "requeued row must be the same verification, not a fresh one (attempt %d)", attempt+1)++ test_utils.MakePostRequest(+ t, router,+ reportPathFor(agent.Agent.ID, claim.VerificationID),+ "Bearer "+agent.Token,+ ReportRequest{Status: VerificationStatusFailed, FailMessage: &failMessage},+ http.StatusNoContent,+ )+ }++ final := GetVerificationByIDViaAPI(t, router, owner.Token, enqueued.ID)+ assert.Equal(t, VerificationStatusFailed, final.Status, "third failure exhausts MaxAgentSideAttempts → terminal")+ assert.Equal(t, MaxAgentSideAttempts, final.AttemptCount, "attempt counter stays at the exhausted value")+ require.NotNil(t, final.FailMessage)+ assert.Equal(t, failMessages[len(failMessages)-1], *final.FailMessage,+ "terminal message is the last agent-reported one verbatim")++ failedAfterAllRetriesBackup := GetBackupViaAPI(t, router, owner.Token, database.ID, backup.ID)+ assert.Equal(+ t,+ backups_core.RestoreVerificationStatusVerificationFailed,+ failedAfterAllRetriesBackup.RestoreVerificationStatus,+ "agent-side failures that exhaust all retries are terminal → backup VERIFICATION_FAILED",+ )+}++func Test_SubmitReport_WhenCompletedButRestoredSizeBelow20Percent_MarksTerminalWithoutRetry(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 with a recorded raw DB size of 100 MB ≈ 104_857_600 bytes — the 20%+ // floor is therefore ~20 MB. Reporting a 1 MB restored DB must trip the guard.+ backup := backuping.SeedTestBackup(t, database.ID, testStorage.ID, 100)++ agent := verification_agents.CreateTestVerificationAgent(+ t,+ router,+ owner.Token,+ "tiny-restore-"+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},+ )++ tinyRestoredSize := int64(1_000_000) // 1 MB ≪ 20% of 100 MB+ test_utils.MakePostRequest(+ t, router,+ reportPathFor(agent.Agent.ID, assignment.VerificationID),+ "Bearer "+agent.Token,+ ReportRequest{+ Status: VerificationStatusCompleted,+ PgRestoreExitCode: new(int),+ DBSizeBytesAfterRestore: &tinyRestoredSize,+ },+ http.StatusNoContent,+ )++ final := GetVerificationByIDViaAPI(t, router, owner.Token, assignment.VerificationID)+ assert.Equal(t, VerificationStatusFailed, final.Status,+ "size guard converts a too-small COMPLETED into a terminal FAILED")+ assert.Equal(t, 1, final.AttemptCount, "backup-side failure must NOT advance the attempt counter")+ require.NotNil(t, final.FailMessage)+ assert.Contains(t, *final.FailMessage, "less than 20%")++ tooSmallBackup := GetBackupViaAPI(t, router, owner.Token, database.ID, backup.ID)+ assert.Equal(+ t,+ backups_core.RestoreVerificationStatusVerificationFailed,+ tooSmallBackup.RestoreVerificationStatus,+ "a too-small restore routes through the failure path → backup VERIFICATION_FAILED, never successful",+ )+}++func Test_Heartbeat_WhenReportedJobIsCanceledOrDeleted_ReturnsItAsAbortID(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)++ databaseRunning := databases.CreateTestDatabase(workspace.ID, testStorage, notifier)+ defer databases.RemoveTestDatabase(databaseRunning)+ databaseCanceled := databases.CreateTestDatabase(workspace.ID, testStorage, notifier)+ defer databases.RemoveTestDatabase(databaseCanceled)++ runningBackup := backuping.SeedTestBackup(t, databaseRunning.ID, testStorage.ID, 100)+ canceledBackup := backuping.SeedTestBackup(t, databaseCanceled.ID, testStorage.ID, 100)++ agent := verification_agents.CreateTestVerificationAgent(t, router, owner.Token, "hb-"+uuid.New().String())+ defer verification_agents.RemoveTestVerificationAgent(t, router, owner.Token, agent.Agent.ID)++ roomyCapacity := AgentCapacity{MaxCPU: 4, MaxRAMMb: 4096, MaxDiskGb: 50, MaxConcurrentJobs: 2}++ EnqueueManualVerificationViaAPI(t, router, owner.Token, runningBackup.ID)+ stillRunning := ClaimVerificationViaAPI(t, router, agent.Agent.ID, agent.Token, roomyCapacity)++ EnqueueManualVerificationViaAPI(t, router, owner.Token, canceledBackup.ID)+ canceled := ClaimVerificationViaAPI(t, router, agent.Agent.ID, agent.Token, roomyCapacity)+ require.NoError(t, storage.GetDb().+ Model(&RestoreVerification{}).+ Where("id = ?", canceled.VerificationID).+ Update("status", VerificationStatusCanceled).Error)++ deletedRowID := uuid.New()++ currentIDs := []uuid.UUID{stillRunning.VerificationID, canceled.VerificationID, deletedRowID}++ var heartbeatResponse verification_agents.HeartbeatResponse+ test_utils.MakePostRequestAndUnmarshal(+ t, router,+ fmt.Sprintf("/api/v1/agent/verification/%s/heartbeat", agent.Agent.ID),+ "Bearer "+agent.Token,+ verification_agents.HeartbeatRequest{+ MaxCPU: 1, MaxRAMGb: 1, MaxDiskGb: 1, MaxConcurrentJobs: 1,+ CurrentVerificationIDs: currentIDs,+ },+ http.StatusOK, &heartbeatResponse,+ )++ require.Len(t, heartbeatResponse.AbortVerificationIDs, 2)++ abortSet := map[uuid.UUID]struct{}{}+ for _, id := range heartbeatResponse.AbortVerificationIDs {+ abortSet[id] = struct{}{}+ }+ _, canceledAborted := abortSet[canceled.VerificationID]+ _, deletedAborted := abortSet[deletedRowID]+ _, stillOursAborted := abortSet[stillRunning.VerificationID]++ assert.True(t, canceledAborted, "canceled row must be in abort list")+ assert.True(t, deletedAborted, "row that no longer exists must be in abort list")+ assert.False(t, stillOursAborted, "still-running row owned by this agent must not be aborted")+}++func Test_CancelVerification_WhenRunning_AgentHeartbeatReturnsIDAsAbort(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.SeedTestBackup(t, database.ID, testStorage.ID, 100)++ agent := verification_agents.CreateTestVerificationAgent(+ t,+ router,+ owner.Token,+ "cancel-running-"+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},+ )++ CancelVerificationViaAPI(t, router, owner.Token, assignment.VerificationID)++ var heartbeatResponse verification_agents.HeartbeatResponse+ test_utils.MakePostRequestAndUnmarshal(+ t, router,+ fmt.Sprintf("/api/v1/agent/verification/%s/heartbeat", agent.Agent.ID),+ "Bearer "+agent.Token,+ verification_agents.HeartbeatRequest{+ MaxCPU: 1, MaxRAMGb: 1, MaxDiskGb: 1, MaxConcurrentJobs: 1,+ CurrentVerificationIDs: []uuid.UUID{assignment.VerificationID},+ },+ http.StatusOK, &heartbeatResponse,+ )++ require.Len(t, heartbeatResponse.AbortVerificationIDs, 1,+ "agent must learn about the user-cancel on its next heartbeat")+ assert.Equal(t, assignment.VerificationID, heartbeatResponse.AbortVerificationIDs[0])++ canceled := GetVerificationByIDViaAPI(t, router, owner.Token, assignment.VerificationID)+ assert.Equal(t, VerificationStatusCanceled, canceled.Status)++ canceledBackup := GetBackupViaAPI(t, router, owner.Token, database.ID, backup.ID)+ assert.Equal(+ t,+ backups_core.RestoreVerificationStatusNotVerified,+ canceledBackup.RestoreVerificationStatus,+ "cancellation bypasses the terminal hook → backup stays NOT_VERIFIED",+ )+}++func Test_GetBackups_WhenBackupNeverVerified_StatusIsNotVerified(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.SeedTestBackup(t, database.ID, testStorage.ID, 100)++ freshBackup := GetBackupViaAPI(t, router, owner.Token, database.ID, backup.ID)+ assert.Equal(+ t,+ backups_core.RestoreVerificationStatusNotVerified,+ freshBackup.RestoreVerificationStatus,+ "a backup that was never verified defaults to NOT_VERIFIED via the column default",+ )+}diff --git a/backend/internal/features/verification/runs/capacity.go b/backend/internal/features/verification/runs/capacity.gonew file mode 100644index 00000000..e8221df1--- /dev/null+++ b/backend/internal/features/verification/runs/capacity.go@@ -0,0 +1,60 @@+package verification_runs++import (+ "math"++ backups_core "databasus-backend/internal/features/backups/backups/core"+)++// diskCostPerJobGapMb is the per-job safe gap added on top of the downloaded+// backup file and the restored database. Covers WAL, indexes, sort/temp spills,+// FS slack and small fixed costs that don't scale with backup size.+const diskCostPerJobGapMb = 1024++// IsVerificationFitWithinRemainedDiskCapacity reports whether+// running candidateBackup on this agent alongside runningBackups+// stays within the agent's declared disk capacity.+func IsVerificationFitWithinRemainedDiskCapacity(+ capacity AgentCapacity,+ runningBackups []*backups_core.Backup,+ candidateBackup *backups_core.Backup,+) bool {+ if capacity.MaxDiskGb <= 0 || candidateBackup == nil {+ return false+ }++ totalBudgetMb := int64(capacity.MaxDiskGb) * 1024+ usedMb := sumEstimatedRequiredDiskMb(runningBackups)+ candidateCostMb := EstimateRequiredForRestoreDiskMb(candidateBackup)++ return usedMb+candidateCostMb <= totalBudgetMb+}++// EstimateRequiredForRestoreDiskMb estimates expected job's on-disk cost.+//+// Includes:+// - Space needed for backup file (if archived - decompressed on the fly while streaming)+// - Space needed for restored database+// - Safe gap (WAL, indexes, sort/temp spills, FS slack)+func EstimateRequiredForRestoreDiskMb(backup *backups_core.Backup) int64 {+ archiveSizeMb := backup.BackupSizeMb+ if archiveSizeMb < 0 {+ archiveSizeMb = 0+ }++ restoredSizeMb := backup.BackupRawDbSizeMb+ if restoredSizeMb < 0 {+ restoredSizeMb = 0+ }++ return int64(math.Ceil(archiveSizeMb+restoredSizeMb)) + diskCostPerJobGapMb+}++func sumEstimatedRequiredDiskMb(backups []*backups_core.Backup) int64 {+ var total int64+ for _, backup := range backups {+ total += EstimateRequiredForRestoreDiskMb(backup)+ }++ return total+}diff --git a/backend/internal/features/verification/runs/capacity_test.go b/backend/internal/features/verification/runs/capacity_test.gonew file mode 100644index 00000000..f3ac461e--- /dev/null+++ b/backend/internal/features/verification/runs/capacity_test.go@@ -0,0 +1,136 @@+package verification_runs++import (+ "testing"++ "github.com/stretchr/testify/assert"++ backups_core "databasus-backend/internal/features/backups/backups/core"+)++func backupWithSize(archiveMb, restoredMb float64) *backups_core.Backup {+ return &backups_core.Backup{+ BackupSizeMb: archiveMb,+ BackupRawDbSizeMb: restoredMb,+ }+}++func Test_DoesVerificationFit_AcrossScenarios_RespectsAgentBudget(t *testing.T) {+ cases := []struct {+ name string+ capacity AgentCapacity+ runningBackups []*backups_core.Backup+ candidate *backups_core.Backup+ wantFits bool+ }{+ {+ name: "empty agent fits small candidate",+ capacity: AgentCapacity{MaxDiskGb: 10},+ runningBackups: nil,+ candidate: backupWithSize(50, 100),+ wantFits: true,+ },+ {+ name: "empty agent fits candidate at exact budget boundary",+ capacity: AgentCapacity{MaxDiskGb: 10},+ runningBackups: nil,+ // archive + restored + per-job gap = 10240 (full 10 GB budget)+ candidate: backupWithSize(4000, 5216),+ wantFits: true,+ },+ {+ name: "empty agent rejects candidate one MB over budget",+ capacity: AgentCapacity{MaxDiskGb: 10},+ runningBackups: nil,+ candidate: backupWithSize(4000, 5217),+ wantFits: false,+ },+ {+ name: "one running, room for another small",+ capacity: AgentCapacity{MaxDiskGb: 10},+ runningBackups: []*backups_core.Backup{+ backupWithSize(50, 200),+ },+ candidate: backupWithSize(50, 200),+ wantFits: true,+ },+ {+ name: "one running, restored size of candidate blows budget",+ capacity: AgentCapacity{MaxDiskGb: 10},+ runningBackups: []*backups_core.Backup{+ backupWithSize(500, 4000),+ },+ candidate: backupWithSize(500, 4000),+ wantFits: false,+ },+ {+ name: "three concurrent small jobs fit in 20 GB",+ capacity: AgentCapacity{MaxDiskGb: 20},+ runningBackups: []*backups_core.Backup{+ backupWithSize(100, 500),+ backupWithSize(100, 500),+ backupWithSize(100, 500),+ },+ candidate: backupWithSize(100, 500),+ wantFits: true,+ },+ {+ name: "per-job gap saturation: three RUNNING already over a 5 GB agent",+ capacity: AgentCapacity{MaxDiskGb: 5},+ runningBackups: []*backups_core.Backup{+ backupWithSize(100, 400),+ backupWithSize(100, 400),+ backupWithSize(100, 400),+ },+ candidate: backupWithSize(10, 10),+ wantFits: false,+ },+ {+ name: "zero-size candidate still consumes the per-job gap and fits",+ capacity: AgentCapacity{MaxDiskGb: 10},+ runningBackups: nil,+ candidate: backupWithSize(0, 0),+ wantFits: true,+ },+ {+ name: "negative sizes clamp to zero and still fit",+ capacity: AgentCapacity{MaxDiskGb: 10},+ runningBackups: nil,+ candidate: backupWithSize(-50, -100),+ wantFits: true,+ },+ {+ name: "zero-capacity agent rejects everything",+ capacity: AgentCapacity{MaxDiskGb: 0},+ runningBackups: nil,+ candidate: backupWithSize(1, 1),+ wantFits: false,+ },+ {+ name: "nil candidate is rejected",+ capacity: AgentCapacity{MaxDiskGb: 10},+ runningBackups: nil,+ candidate: nil,+ wantFits: false,+ },+ {+ name: "raw DB size dominates archive size in the cost",+ capacity: AgentCapacity{MaxDiskGb: 2},+ runningBackups: nil,+ candidate: backupWithSize(10, 2000),+ wantFits: false,+ },+ }++ for _, testCase := range cases {+ t.Run(testCase.name, func(t *testing.T) {+ fits := IsVerificationFitWithinRemainedDiskCapacity(+ testCase.capacity,+ testCase.runningBackups,+ testCase.candidate,+ )++ assert.Equal(t, testCase.wantFits, fits)+ })+ }+}diff --git a/backend/internal/features/verification/runs/claim_sanitization_test.go b/backend/internal/features/verification/runs/claim_sanitization_test.gonew file mode 100644index 00000000..a9a247d1--- /dev/null+++ b/backend/internal/features/verification/runs/claim_sanitization_test.go@@ -0,0 +1,95 @@+package verification_runs++import (+ "testing"++ "github.com/google/uuid"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ "databasus-backend/internal/features/backups/backups/backuping"+ "databasus-backend/internal/features/databases"+ "databasus-backend/internal/features/notifiers"+ "databasus-backend/internal/features/storages"+ users_enums "databasus-backend/internal/features/users/enums"+ users_testing "databasus-backend/internal/features/users/testing"+ verification_agents "databasus-backend/internal/features/verification/agents"+ workspaces_testing "databasus-backend/internal/features/workspaces/testing"+)++// Test_ClaimVerification_AssignmentDatabase_StripsSensitiveData locks down the+// agent-facing wire shape: anything that could leak credentials, tokens or+// notifier secrets must be empty when the JobAssignment leaves the server.+func Test_ClaimVerification_AssignmentDatabase_StripsSensitiveData(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)++ require.NotNil(t, database.Postgresql)+ require.NotEmpty(t, database.Postgresql.Password,+ "fixture must persist a password so we can prove HideSensitiveData stripped it")++ backup := backuping.SeedTestBackup(t, database.ID, testStorage.ID, 100)+ agent := verification_agents.CreateTestVerificationAgent(+ t, router, owner.Token, "sanitize-"+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},+ )++ require.NotNil(t, assignment.Database, "assignment must carry the database row")++ cases := []struct {+ name string+ check func(t *testing.T, db *databases.Database)+ }{+ {+ name: "postgres password is stripped",+ check: func(t *testing.T, db *databases.Database) {+ require.NotNil(t, db.Postgresql)+ assert.Empty(t, db.Postgresql.Password)+ },+ },+ {+ name: "notifiers are stripped (carry webhook URLs and SMTP creds)",+ check: func(t *testing.T, db *databases.Database) {+ assert.Empty(t, db.Notifiers)+ },+ },+ {+ name: "agent token is absent",+ check: func(t *testing.T, db *databases.Database) {+ assert.Nil(t, db.AgentToken)+ },+ },+ {+ name: "non-sensitive identifying fields are preserved",+ check: func(t *testing.T, db *databases.Database) {+ assert.Equal(t, database.ID, db.ID)+ assert.Equal(t, databases.DatabaseTypePostgres, db.Type)+ require.NotNil(t, db.Postgresql)+ assert.Equal(t, "16", string(db.Postgresql.Version))+ },+ },+ }++ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ tc.check(t, assignment.Database)+ })+ }+}diff --git a/backend/internal/features/verification/runs/constants.go b/backend/internal/features/verification/runs/constants.gonew file mode 100644index 00000000..4ad4f6c8--- /dev/null+++ b/backend/internal/features/verification/runs/constants.go@@ -0,0 +1,31 @@+package verification_runs++import "time"++// MaxAgentSideAttempts caps how many times an agent-side failure may be retried+// before going terminal. Backup-side failures (BackupRejected, RestoredTooSmall)+// and fleet-side failures (UnclaimedTooLong) ignore this and terminal immediately.+const MaxAgentSideAttempts = 3++// minRestoredSizeRatio guards against silent backup corruption where pg_restore+// "succeeds" but produces a near-empty database. A restored DB below this ratio+// of the original raw size is treated as a backup failure.+const minRestoredSizeRatio = 0.20++// StaleAgentThreshold is how long an agent may go without a heartbeat before+// it is considered offline. The verification scheduler uses it to abandon+// jobs claimed by a silent agent; the system healthcheck uses it to surface+// dead agents that have not been retired.+// Declared as var (not const) so tests can shrink it via reassignment.+var StaleAgentThreshold = 5 * time.Minute++// agentJobReclaimGrace is the minimum age a RUNNING verification must reach+// before the backend may reclaim it from a still-online agent that no longer+// reports it. The claim transaction flips a row RUNNING and+// stamps started_at before the owning agent has registered the job and sent+// its next heartbeat, so a just-claimed row is legitimately absent from the+// owner's heartbeat for up to one cycle. This grace (~3x the agent's 30s+// heartbeat interval) keeps it safe until the owner has had at least one full+// cycle to report it. Keyed off the fixed heartbeat cadence, not the variable+// claim backoff. Declared as var (not const) so tests can shrink it.+var agentJobReclaimGrace = 90 * time.Seconddiff --git a/backend/internal/features/verification/runs/controller.go b/backend/internal/features/verification/runs/controller.gonew file mode 100644index 00000000..30293cbd--- /dev/null+++ b/backend/internal/features/verification/runs/controller.go@@ -0,0 +1,161 @@+package verification_runs++import (+ "net/http"++ "github.com/gin-gonic/gin"+ "github.com/google/uuid"++ users_middleware "databasus-backend/internal/features/users/middleware"+)++type VerificationController struct {+ verificationService *VerificationService+}++func (c *VerificationController) RegisterRoutes(router *gin.RouterGroup) {+ router.POST("/verifications/enqueue", c.EnqueueManual)+ router.POST("/verifications/:id/cancel", c.Cancel)+ router.GET("/verifications/:id", c.GetByID)+ router.GET("/verifications/by-database/:databaseId", c.ListByDatabase)+}++// EnqueueManual+// @Summary Enqueue manual backup verification+// @Description Trigger a one-off verification of the chosen backup. Returns 400 if a manual verification is already pending or running for the same database — cancel it first.+// @Tags verifications+// @Accept json+// @Produce json+// @Security BearerAuth+// @Param request body EnqueueManualRequest true "Manual verification request"+// @Success 200 {object} RestoreVerification+// @Failure 400 {object} map[string]string+// @Failure 401 {object} map[string]string+// @Router /verifications/enqueue [post]+func (c *VerificationController) EnqueueManual(ctx *gin.Context) {+ user, ok := users_middleware.GetUserFromContext(ctx)+ if !ok {+ ctx.JSON(http.StatusUnauthorized, gin.H{"error": "User not authenticated"})+ return+ }++ var req EnqueueManualRequest+ if err := ctx.ShouldBindJSON(&req); err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ verification, err := c.verificationService.EnqueueManualVerification(user, req.BackupID)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, verification)+}++// Cancel+// @Summary Cancel a pending or running verification+// @Description Marks a PENDING or RUNNING verification as CANCELED. For RUNNING rows the agent stops on its next heartbeat. Returns 400 if the verification is already terminal.+// @Tags verifications+// @Produce json+// @Security BearerAuth+// @Param id path string true "Verification ID"+// @Success 204+// @Failure 400 {object} map[string]string+// @Failure 401 {object} map[string]string+// @Router /verifications/{id}/cancel [post]+func (c *VerificationController) Cancel(ctx *gin.Context) {+ user, ok := users_middleware.GetUserFromContext(ctx)+ if !ok {+ ctx.JSON(http.StatusUnauthorized, gin.H{"error": "User not authenticated"})+ return+ }++ verificationID, err := uuid.Parse(ctx.Param("id"))+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid verification ID"})+ return+ }++ if err := c.verificationService.CancelVerification(user, verificationID); err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ ctx.Status(http.StatusNoContent)+}++// GetByID+// @Summary Get verification by id+// @Description Returns one verification row with its per-table stats preloaded.+// @Tags verifications+// @Produce json+// @Security BearerAuth+// @Param id path string true "Verification ID"+// @Success 200 {object} RestoreVerification+// @Failure 400 {object} map[string]string+// @Failure 401 {object} map[string]string+// @Router /verifications/{id} [get]+func (c *VerificationController) GetByID(ctx *gin.Context) {+ user, ok := users_middleware.GetUserFromContext(ctx)+ if !ok {+ ctx.JSON(http.StatusUnauthorized, gin.H{"error": "User not authenticated"})+ return+ }++ verificationID, err := uuid.Parse(ctx.Param("id"))+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid verification ID"})+ return+ }++ verification, err := c.verificationService.GetVerificationByID(user, verificationID)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, verification)+}++// ListByDatabase+// @Summary List verifications by database+// @Description Returns verifications for the given database, newest first. Per-table stats are NOT included — use GetByID for that.+// @Tags verifications+// @Produce json+// @Security BearerAuth+// @Param databaseId path string true "Database ID"+// @Param limit query int false "Limit number of results" default(10)+// @Param offset query int false "Offset for pagination" default(0)+// @Success 200 {object} GetVerificationsResponse+// @Failure 400 {object} map[string]string+// @Failure 401 {object} map[string]string+// @Router /verifications/by-database/{databaseId} [get]+func (c *VerificationController) ListByDatabase(ctx *gin.Context) {+ user, ok := users_middleware.GetUserFromContext(ctx)+ if !ok {+ ctx.JSON(http.StatusUnauthorized, gin.H{"error": "User not authenticated"})+ return+ }++ databaseID, err := uuid.Parse(ctx.Param("databaseId"))+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid database ID"})+ return+ }++ var req GetVerificationsRequest+ if err := ctx.ShouldBindQuery(&req); err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ response, err := c.verificationService.GetVerificationsByDatabaseID(user, databaseID, req.Limit, req.Offset)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, response)+}diff --git a/backend/internal/features/verification/runs/controller_test.go b/backend/internal/features/verification/runs/controller_test.gonew file mode 100644index 00000000..9a136522--- /dev/null+++ b/backend/internal/features/verification/runs/controller_test.go@@ -0,0 +1,621 @@+package verification_runs++import (+ "encoding/json"+ "net/http"+ "testing"+ "time"++ "github.com/gin-gonic/gin"+ "github.com/google/uuid"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ "databasus-backend/internal/features/audit_logs"+ "databasus-backend/internal/features/backups/backups/backuping"+ backups_controllers "databasus-backend/internal/features/backups/backups/controllers"+ "databasus-backend/internal/features/databases"+ "databasus-backend/internal/features/notifiers"+ "databasus-backend/internal/features/storages"+ users_enums "databasus-backend/internal/features/users/enums"+ users_middleware "databasus-backend/internal/features/users/middleware"+ users_services "databasus-backend/internal/features/users/services"+ users_testing "databasus-backend/internal/features/users/testing"+ verification_agents "databasus-backend/internal/features/verification/agents"+ verification_config "databasus-backend/internal/features/verification/config"+ workspaces_controllers "databasus-backend/internal/features/workspaces/controllers"+ workspaces_testing "databasus-backend/internal/features/workspaces/testing"+ "databasus-backend/internal/storage"+ test_utils "databasus-backend/internal/util/testing"+)++func createTestRouter() *gin.Engine {+ gin.SetMode(gin.TestMode)+ router := gin.New()++ v1 := router.Group("/api/v1")+ protected := v1.Group("").Use(users_middleware.AuthMiddleware(users_services.GetUserService()))++ if routerGroup, ok := protected.(*gin.RouterGroup); ok {+ workspaces_controllers.GetWorkspaceController().RegisterRoutes(routerGroup)+ workspaces_controllers.GetMembershipController().RegisterRoutes(routerGroup)+ databases.GetDatabaseController().RegisterRoutes(routerGroup)+ backups_controllers.GetBackupController().RegisterRoutes(routerGroup)+ GetVerificationController().RegisterRoutes(routerGroup)+ verification_agents.GetAgentController().RegisterRoutes(routerGroup)+ verification_config.GetVerificationConfigController().RegisterRoutes(routerGroup)+ }++ verification_agents.GetAgentFacingController().RegisterRoutes(v1)+ GetVerificationAgentController().RegisterRoutes(v1)++ audit_logs.SetupDependencies()+ verification_config.SetupDependencies()+ SetupDependencies()++ return router+}++func walDatabaseForWorkspace(workspaceID uuid.UUID, notifier *notifiers.Notifier) *databases.Database {+ return databases.CreateTestPostgresWalDatabase(workspaceID, notifier)+}++func Test_EnqueueManualVerification_AsOwner_CreatesPendingRow(t *testing.T) {+ router := createTestRouter()+ owner := users_testing.CreateTestUser(users_enums.UserRoleMember)+ 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.SeedTestBackup(t, database.ID, testStorage.ID, 500)++ var verification RestoreVerification+ test_utils.MakePostRequestAndUnmarshal(+ t, router,+ "/api/v1/verifications/enqueue",+ "Bearer "+owner.Token,+ EnqueueManualRequest{BackupID: backup.ID},+ http.StatusOK, &verification,+ )++ assert.Equal(t, VerificationStatusPending, verification.Status)+ assert.Equal(t, VerificationTriggerManual, verification.Trigger)+ assert.Equal(t, backup.ID, verification.BackupID)+ assert.Equal(t, database.ID, verification.DatabaseID)+ assert.Equal(t, 1, verification.AttemptCount)+ assert.Nil(t, verification.AgentID)+}++func Test_EnqueueManualVerification_WhenBackupIsWalSegment_Returns400(t *testing.T) {+ router := createTestRouter()+ owner := users_testing.CreateTestUser(users_enums.UserRoleMember)+ 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)++ walSegment := backuping.SeedTestWalSegmentBackup(t, database.ID, testStorage.ID)++ resp := test_utils.MakePostRequest(+ t, router,+ "/api/v1/verifications/enqueue",+ "Bearer "+owner.Token,+ EnqueueManualRequest{BackupID: walSegment.ID},+ http.StatusBadRequest,+ )+ assert.Contains(t, string(resp.Body), "WAL")+}++func Test_EnqueueManualVerification_WhenDatabaseUsesWalBackups_Returns400(t *testing.T) {+ router := createTestRouter()+ owner := users_testing.CreateTestUser(users_enums.UserRoleMember)+ 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)++ walDatabase := walDatabaseForWorkspace(workspace.ID, notifier)+ defer databases.RemoveTestDatabase(walDatabase)++ backup := backuping.SeedTestBackup(t, walDatabase.ID, testStorage.ID, 100)++ resp := test_utils.MakePostRequest(+ t, router,+ "/api/v1/verifications/enqueue",+ "Bearer "+owner.Token,+ EnqueueManualRequest{BackupID: backup.ID},+ http.StatusBadRequest,+ )+ assert.Contains(t, string(resp.Body), "WAL")+}++func Test_EnqueueManualVerification_WhenManualPendingExists_Returns400(t *testing.T) {+ router := createTestRouter()+ owner := users_testing.CreateTestUser(users_enums.UserRoleMember)+ 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)++ firstBackup := backuping.SeedTestBackup(t, database.ID, testStorage.ID, 100)+ secondBackup := backuping.SeedTestBackup(t, database.ID, testStorage.ID, 200)++ var firstVerification RestoreVerification+ test_utils.MakePostRequestAndUnmarshal(+ t, router, "/api/v1/verifications/enqueue", "Bearer "+owner.Token,+ EnqueueManualRequest{BackupID: firstBackup.ID},+ http.StatusOK, &firstVerification,+ )++ resp := test_utils.MakePostRequest(+ t, router, "/api/v1/verifications/enqueue", "Bearer "+owner.Token,+ EnqueueManualRequest{BackupID: secondBackup.ID},+ http.StatusBadRequest,+ )+ assert.Contains(t, string(resp.Body), "please cancel it first")++ firstAfter := GetVerificationByIDViaAPI(t, router, owner.Token, firstVerification.ID)+ assert.Equal(t, VerificationStatusPending, firstAfter.Status,+ "first manual verification must remain PENDING — the second enqueue was rejected, not a displacement")++ rows := ListVerificationsByDatabaseViaAPI(t, router, owner.Token, database.ID)+ assert.Len(t, rows, 1, "rejected enqueue must not create a second row")+}++func Test_EnqueueManualVerification_WhenRunningExists_Returns400(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.SeedTestBackup(t, database.ID, testStorage.ID, 100)++ agent := verification_agents.CreateTestVerificationAgent(t, router, owner.Token, "running-"+uuid.New().String())+ defer verification_agents.RemoveTestVerificationAgent(t, router, owner.Token, agent.Agent.ID)++ EnqueueManualVerificationViaAPI(t, router, owner.Token, backup.ID)+ ClaimVerificationViaAPI(+ t, router, agent.Agent.ID, agent.Token,+ AgentCapacity{MaxCPU: 4, MaxRAMMb: 4096, MaxDiskGb: 50, MaxConcurrentJobs: 2},+ )++ resp := test_utils.MakePostRequest(+ t, router, "/api/v1/verifications/enqueue", "Bearer "+owner.Token,+ EnqueueManualRequest{BackupID: backup.ID},+ http.StatusBadRequest,+ )+ assert.Contains(t, string(resp.Body), "please cancel it first")+}++func Test_EnqueueManualVerification_WhenScheduledNonTerminalExists_DoesNotDisplaceIt(t *testing.T) {+ router := createTestRouter()+ owner := users_testing.CreateTestUser(users_enums.UserRoleMember)+ 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.SeedTestBackup(t, database.ID, testStorage.ID, 100)++ scheduledRow := &RestoreVerification{+ ID: uuid.New(),+ DatabaseID: database.ID,+ BackupID: backup.ID,+ Trigger: VerificationTriggerScheduled,+ Status: VerificationStatusPending,+ AttemptCount: 1,+ CreatedAt: time.Now().UTC(),+ }+ require.NoError(t, storage.GetDb().Create(scheduledRow).Error)++ var manualVerification RestoreVerification+ test_utils.MakePostRequestAndUnmarshal(+ t, router, "/api/v1/verifications/enqueue", "Bearer "+owner.Token,+ EnqueueManualRequest{BackupID: backup.ID},+ http.StatusOK, &manualVerification,+ )++ scheduledAfter := GetVerificationByIDViaAPI(t, router, owner.Token, scheduledRow.ID)+ assert.Equal(+ t,+ VerificationStatusPending,+ scheduledAfter.Status,+ "scheduled row must not be displaced by a manual enqueue",+ )+ assert.Equal(t, VerificationTriggerScheduled, scheduledAfter.Trigger)++ manualAfter := GetVerificationByIDViaAPI(t, router, owner.Token, manualVerification.ID)+ assert.Equal(t, VerificationStatusPending, manualAfter.Status)+ assert.Equal(t, VerificationTriggerManual, manualAfter.Trigger)++ rows := ListVerificationsByDatabaseViaAPI(t, router, owner.Token, database.ID)+ require.Len(t, rows, 2, "exactly one scheduled and one manual non-terminal row should coexist")++ var manualCount, scheduledCount int+ for _, row := range rows {+ switch row.Trigger {+ case VerificationTriggerManual:+ manualCount+++ case VerificationTriggerScheduled:+ scheduledCount+++ }+ }+ assert.Equal(t, 1, manualCount)+ assert.Equal(t, 1, scheduledCount)+}++func Test_EnqueueManualVerification_AsNonWorkspaceMember_ReturnsForbidden(t *testing.T) {+ router := createTestRouter()+ owner := users_testing.CreateTestUser(users_enums.UserRoleMember)+ 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.SeedTestBackup(t, database.ID, testStorage.ID, 100)++ outsider := users_testing.CreateTestUser(users_enums.UserRoleMember)++ resp := test_utils.MakePostRequest(+ t, router, "/api/v1/verifications/enqueue", "Bearer "+outsider.Token,+ EnqueueManualRequest{BackupID: backup.ID},+ http.StatusBadRequest,+ )+ assert.Contains(t, string(resp.Body), "insufficient permissions")+}++func Test_GetVerificationByID_ReturnsTableStats_WhileListByDatabaseOmitsThem(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.SeedTestBackup(t, database.ID, testStorage.ID, 100)+ agent := verification_agents.CreateTestVerificationAgent(t, router, owner.Token, "stats-"+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},+ )++ test_utils.MakePostRequest(+ t, router,+ "/api/v1/agent/verifications/"+agent.Agent.ID.String()+"/"+assignment.VerificationID.String()+"/report",+ "Bearer "+agent.Token,+ ReportRequest{+ Status: VerificationStatusCompleted,+ TableStats: []ReportTableStat{+ {SchemaName: "public", Name: "users", RowCount: 42},+ },+ },+ http.StatusNoContent,+ )++ detail := GetVerificationByIDViaAPI(t, router, owner.Token, assignment.VerificationID)+ require.Len(t, detail.TableStats, 1)+ assert.Equal(t, "users", detail.TableStats[0].Name)+ assert.Equal(t, int64(42), detail.TableStats[0].RowCount)++ listResponse := test_utils.MakeGetRequest(+ t, router,+ "/api/v1/verifications/by-database/"+database.ID.String(),+ "Bearer "+owner.Token,+ http.StatusOK,+ )++ var listed struct {+ Verifications []map[string]any `json:"verifications"`+ }+ require.NoError(t, json.Unmarshal(listResponse.Body, &listed))+ require.Len(t, listed.Verifications, 1)++ _, hasTableStats := listed.Verifications[0]["tableStats"]+ assert.False(t, hasTableStats, "list endpoint must not include tableStats")+}++func Test_ListVerificationsByDatabase_WithLimit_CapsRowsAndReturnsTotal(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.SeedTestBackup(t, database.ID, testStorage.ID, 100)++ for range 3 {+ verification := EnqueueManualVerificationViaAPI(t, router, owner.Token, backup.ID)+ CancelVerificationViaAPI(t, router, owner.Token, verification.ID)+ }++ var page GetVerificationsResponse+ test_utils.MakeGetRequestAndUnmarshal(+ t, router,+ "/api/v1/verifications/by-database/"+database.ID.String()+"?limit=2&offset=0",+ "Bearer "+owner.Token,+ http.StatusOK,+ &page,+ )++ assert.Len(t, page.Verifications, 2)+ assert.Equal(t, int64(3), page.Total)+ assert.Equal(t, 2, page.Limit)+ assert.Equal(t, 0, page.Offset)+}++func Test_CancelVerification_AsOwner_FlipsToCanceled(t *testing.T) {+ router := createTestRouter()+ owner := users_testing.CreateTestUser(users_enums.UserRoleMember)+ 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.SeedTestBackup(t, database.ID, testStorage.ID, 100)++ enqueued := EnqueueManualVerificationViaAPI(t, router, owner.Token, backup.ID)++ CancelVerificationViaAPI(t, router, owner.Token, enqueued.ID)++ canceled := GetVerificationByIDViaAPI(t, router, owner.Token, enqueued.ID)+ assert.Equal(t, VerificationStatusCanceled, canceled.Status)+ require.NotNil(t, canceled.FinishedAt)+}++func Test_CancelVerification_WhenAlreadyCompleted_Returns400(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.SeedTestBackup(t, database.ID, testStorage.ID, 100)+ agent := verification_agents.CreateTestVerificationAgent(+ t,+ router,+ owner.Token,+ "cancel-completed-"+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},+ )++ test_utils.MakePostRequest(+ t, router,+ "/api/v1/agent/verifications/"+agent.Agent.ID.String()+"/"+assignment.VerificationID.String()+"/report",+ "Bearer "+agent.Token,+ ReportRequest{Status: VerificationStatusCompleted, PgRestoreExitCode: new(int)},+ http.StatusNoContent,+ )++ resp := test_utils.MakePostRequest(+ t, router,+ "/api/v1/verifications/"+assignment.VerificationID.String()+"/cancel",+ "Bearer "+owner.Token,+ nil,+ http.StatusBadRequest,+ )+ assert.Contains(t, string(resp.Body), "not cancellable")++ final := GetVerificationByIDViaAPI(t, router, owner.Token, assignment.VerificationID)+ assert.Equal(t, VerificationStatusCompleted, final.Status)+}++func Test_CancelVerification_AsNonWorkspaceMember_ReturnsForbidden(t *testing.T) {+ router := createTestRouter()+ owner := users_testing.CreateTestUser(users_enums.UserRoleMember)+ 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.SeedTestBackup(t, database.ID, testStorage.ID, 100)+ enqueued := EnqueueManualVerificationViaAPI(t, router, owner.Token, backup.ID)++ outsider := users_testing.CreateTestUser(users_enums.UserRoleMember)++ resp := test_utils.MakePostRequest(+ t, router,+ "/api/v1/verifications/"+enqueued.ID.String()+"/cancel",+ "Bearer "+outsider.Token,+ nil,+ http.StatusBadRequest,+ )+ assert.Contains(t, string(resp.Body), "insufficient permissions")++ stillPending := GetVerificationByIDViaAPI(t, router, owner.Token, enqueued.ID)+ assert.Equal(t, VerificationStatusPending, stillPending.Status)+}++func Test_CancelVerification_WithAgentToken_Returns401(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.SeedTestBackup(t, database.ID, testStorage.ID, 100)+ enqueued := EnqueueManualVerificationViaAPI(t, router, owner.Token, backup.ID)++ agent := verification_agents.CreateTestVerificationAgent(+ t, router, owner.Token, "cancel-agent-rejected-"+uuid.New().String(),+ )+ defer verification_agents.RemoveTestVerificationAgent(t, router, owner.Token, agent.Agent.ID)++ test_utils.MakePostRequest(+ t, router,+ "/api/v1/verifications/"+enqueued.ID.String()+"/cancel",+ "Bearer "+agent.Token,+ nil,+ http.StatusUnauthorized,+ )++ stillPending := GetVerificationByIDViaAPI(t, router, owner.Token, enqueued.ID)+ assert.Equal(t, VerificationStatusPending, stillPending.Status)+}++func Test_DeleteDatabase_RemovesVerifications_ViaCascade(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)++ backup := backuping.SeedTestBackup(t, database.ID, testStorage.ID, 100)+ enqueued := EnqueueManualVerificationViaAPI(t, router, owner.Token, backup.ID)++ test_utils.MakeDeleteRequest(+ t, router,+ "/api/v1/databases/"+database.ID.String(),+ "Bearer "+owner.Token,+ http.StatusNoContent,+ )++ var remainingVerifications int64+ require.NoError(t, storage.GetDb().+ Model(&RestoreVerification{}).+ Where("id = ?", enqueued.ID).+ Count(&remainingVerifications).Error)+ assert.Zero(t, remainingVerifications, "verification row must be cascade-deleted with its database")+}++func Test_DeleteBackup_RemovesVerifications_ViaCascade(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.SeedTestBackup(t, database.ID, testStorage.ID, 100)+ enqueued := EnqueueManualVerificationViaAPI(t, router, owner.Token, backup.ID)++ test_utils.MakeDeleteRequest(+ t, router,+ "/api/v1/backups/"+backup.ID.String(),+ "Bearer "+owner.Token,+ http.StatusNoContent,+ )++ var remainingVerifications int64+ require.NoError(t, storage.GetDb().+ Model(&RestoreVerification{}).+ Where("id = ?", enqueued.ID).+ Count(&remainingVerifications).Error)+ assert.Zero(t, remainingVerifications, "verification row must be cascade-deleted with its backup")+}diff --git a/backend/internal/features/verification/runs/di.go b/backend/internal/features/verification/runs/di.gonew file mode 100644index 00000000..3a27d7bb--- /dev/null+++ b/backend/internal/features/verification/runs/di.go@@ -0,0 +1,71 @@+package verification_runs++import (+ "sync"+ "sync/atomic"++ "databasus-backend/internal/features/audit_logs"+ "databasus-backend/internal/features/backups/backups/backuping"+ backups_services "databasus-backend/internal/features/backups/backups/services"+ "databasus-backend/internal/features/databases"+ "databasus-backend/internal/features/notifiers"+ verification_agents "databasus-backend/internal/features/verification/agents"+ verification_config "databasus-backend/internal/features/verification/config"+ workspaces_services "databasus-backend/internal/features/workspaces/services"+ "databasus-backend/internal/util/logger"+)++var verificationRepository = &VerificationRepository{}++var verificationService = &VerificationService{+ verificationRepository,+ databases.GetDatabaseService(),+ backups_services.GetBackupService(),+ verification_config.GetVerificationConfigService(),+ notifiers.GetNotifierService(),+ workspaces_services.GetWorkspaceService(),+ audit_logs.GetAuditLogService(),+ logger.GetLogger(),+}++var verificationScheduler = &VerificationScheduler{+ verificationRepository,+ verificationService,+ verification_config.GetVerificationConfigService(),+ verification_agents.GetAgentService(),+ backups_services.GetBackupService(),+ databases.GetDatabaseService(),+ logger.GetLogger(),+ atomic.Bool{},+}++var verificationController = &VerificationController{+ verificationService,+}++var verificationAgentController = &VerificationAgentController{+ verificationService,+ verification_agents.GetAgentService(),+ logger.GetLogger(),+}++func GetVerificationService() *VerificationService {+ return verificationService+}++func GetVerificationScheduler() *VerificationScheduler {+ return verificationScheduler+}++func GetVerificationController() *VerificationController {+ return verificationController+}++func GetVerificationAgentController() *VerificationAgentController {+ return verificationAgentController+}++var SetupDependencies = sync.OnceFunc(func() {+ verification_agents.GetAgentService().AddAgentHeartbeatedListener(verificationService)+ backuping.GetBackupsScheduler().AddBackupCompletionListener(verificationService)+})diff --git a/backend/internal/features/verification/runs/dto.go b/backend/internal/features/verification/runs/dto.gonew file mode 100644index 00000000..397cbf95--- /dev/null+++ b/backend/internal/features/verification/runs/dto.go@@ -0,0 +1,61 @@+package verification_runs++import (+ "github.com/google/uuid"++ "databasus-backend/internal/features/databases"+)++type EnqueueManualRequest struct {+ BackupID uuid.UUID `json:"backupId" binding:"required"`+}++type GetVerificationsRequest struct {+ Limit int `form:"limit"`+ Offset int `form:"offset"`+}++type GetVerificationsResponse struct {+ Verifications []*RestoreVerification `json:"verifications"`+ Total int64 `json:"total"`+ Limit int `json:"limit"`+ Offset int `json:"offset"`+}++type AgentCapacity struct {+ MaxCPU int `json:"maxCpu" binding:"min=0"`+ MaxRAMMb int `json:"maxRamMb" binding:"min=0"`+ MaxDiskGb int `json:"maxDiskGb" binding:"min=0"`+ MaxConcurrentJobs int `json:"maxConcurrentJobs" binding:"min=0"`+}++type ClaimRequest struct {+ Capacity AgentCapacity `json:"capacity"`+}++type JobAssignment struct {+ VerificationID uuid.UUID `json:"verificationId"`+ BackupID uuid.UUID `json:"backupId"`+ BackupSizeMb float64 `json:"backupSizeMb"`+ MaxContainerDiskMb float64 `json:"maxContainerDiskMb"`+ Database *databases.Database `json:"database"`+}++type ReportTableStat struct {+ SchemaName string `json:"schemaName" binding:"required"`+ Name string `json:"name" binding:"required"`+ RowCount int64 `json:"rowCount"`+}++type ReportRequest struct {+ Status VerificationStatus `json:"status" binding:"required,oneof=COMPLETED FAILED"`+ PgRestoreExitCode *int `json:"pgRestoreExitCode"`+ FailureKind *string `json:"failureKind"`+ RestoreDurationMs *int64 `json:"restoreDurationMs"`+ VerifyDurationMs *int64 `json:"verifyDurationMs"`+ DBSizeBytesAfterRestore *int64 `json:"dbSizeBytesAfterRestore"`+ TableCount *int `json:"tableCount"`+ SchemaCount *int `json:"schemaCount"`+ TableStats []ReportTableStat `json:"tableStats"`+ FailMessage *string `json:"failMessage"`+}diff --git a/backend/internal/features/verification/runs/enums.go b/backend/internal/features/verification/runs/enums.gonew file mode 100644index 00000000..35d57c86--- /dev/null+++ b/backend/internal/features/verification/runs/enums.go@@ -0,0 +1,36 @@+package verification_runs++type VerificationStatus string++const (+ VerificationStatusPending VerificationStatus = "PENDING"+ VerificationStatusRunning VerificationStatus = "RUNNING"+ VerificationStatusCompleted VerificationStatus = "COMPLETED"+ VerificationStatusFailed VerificationStatus = "FAILED"+ VerificationStatusCanceled VerificationStatus = "CANCELED"+)++type VerificationTrigger string++const (+ VerificationTriggerManual VerificationTrigger = "MANUAL"+ VerificationTriggerScheduled VerificationTrigger = "SCHEDULED"+ VerificationTriggerAfterBackup VerificationTrigger = "AFTER_BACKUP"+)++type FailureReason string++// Agent-side reasons are retried up to MaxAgentSideAttempts because the same+// input may succeed on the next agent. Backup-side reasons go terminal on the+// first failure — retrying the same dump produces the same rejection and only+// delays the user notification.+const (+ FailureReasonAgentLostContact FailureReason = "AGENT_LOST_CONTACT" // reaper: agent stopped heartbeating mid-run+ FailureReasonAgentRemoved FailureReason = "AGENT_REMOVED" // reaper: owning agent was deleted; requeue so another agent can pick it up+ FailureReasonAgentSetupFailed FailureReason = "AGENT_SETUP_FAILED" // agent reported FAILED before pg_restore ran (download/container/OOM)+ FailureReasonAgentDroppedJob FailureReason = "AGENT_DROPPED_JOB" // heartbeat: still-online agent stopped reporting a RUNNING job it owns+ FailureReasonBackupRejected FailureReason = "BACKUP_REJECTED" // agent reported FAILED with pg_restore non-zero exit+ FailureReasonDiskLimitExceeded FailureReason = "DISK_LIMIT_EXCEEDED" // restore exceeded the server-computed per-job disk budget; terminal (the same budget fails identically on retry)+ FailureReasonRestoredTooSmall FailureReason = "RESTORED_TOO_SMALL" // restored DB is below minRestoredSizeRatio of the recorded raw size+ FailureReasonUnclaimedTooLong FailureReason = "UNCLAIMED_TOO_LONG" // PENDING row sat unclaimed past maxPendingDuration+)diff --git a/backend/internal/features/verification/runs/heartbeat_reclaim_test.go b/backend/internal/features/verification/runs/heartbeat_reclaim_test.gonew file mode 100644index 00000000..e003e30e--- /dev/null+++ b/backend/internal/features/verification/runs/heartbeat_reclaim_test.go@@ -0,0 +1,287 @@+package verification_runs++import (+ "testing"+ "time"++ "github.com/gin-gonic/gin"+ "github.com/google/uuid"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ "databasus-backend/internal/features/backups/backups/backuping"+ "databasus-backend/internal/features/databases"+ "databasus-backend/internal/features/notifiers"+ "databasus-backend/internal/features/storages"+ users_enums "databasus-backend/internal/features/users/enums"+ users_testing "databasus-backend/internal/features/users/testing"+ verification_agents "databasus-backend/internal/features/verification/agents"+ workspaces_testing "databasus-backend/internal/features/workspaces/testing"+ "databasus-backend/internal/storage"+)++func shrinkReclaimGrace(t *testing.T, grace time.Duration) {+ t.Helper()++ original := agentJobReclaimGrace+ agentJobReclaimGrace = grace++ t.Cleanup(func() { agentJobReclaimGrace = original })+}++func newReclaimFixture(+ t *testing.T,+) (router *gin.Engine, ownerToken string, database *databases.Database, storageID uuid.UUID) {+ t.Helper()++ router = createTestRouter()+ owner := users_testing.CreateTestUser(users_enums.UserRoleAdmin)++ workspace := workspaces_testing.CreateTestWorkspace("ws "+uuid.New().String(), owner, router)+ t.Cleanup(func() { workspaces_testing.RemoveTestWorkspace(workspace, router) })++ testStorage := storages.CreateTestStorage(workspace.ID)+ t.Cleanup(func() { storages.RemoveTestStorage(testStorage.ID) })++ notifier := notifiers.CreateTestNotifier(workspace.ID)+ t.Cleanup(func() { notifiers.RemoveTestNotifier(notifier) })++ database = databases.CreateTestDatabase(workspace.ID, testStorage, notifier)+ t.Cleanup(func() { databases.RemoveTestDatabase(database) })++ return router, owner.Token, database, testStorage.ID+}++func newReclaimAgent(+ t *testing.T,+ router *gin.Engine,+ ownerToken string,+) *verification_agents.CreatedAgentResponse {+ t.Helper()++ agent := verification_agents.CreateTestVerificationAgent(+ t, router, ownerToken, "reclaim-"+uuid.New().String(),+ )+ t.Cleanup(func() {+ verification_agents.RemoveTestVerificationAgent(t, router, ownerToken, agent.Agent.ID)+ })++ return agent+}++func claimRunningJob(+ t *testing.T,+ router *gin.Engine,+ ownerToken string,+ agent *verification_agents.CreatedAgentResponse,+ backupID uuid.UUID,+) *JobAssignment {+ t.Helper()++ EnqueueManualVerificationViaAPI(t, router, ownerToken, backupID)++ return ClaimVerificationViaAPI(+ t, router, agent.Agent.ID, agent.Token,+ AgentCapacity{MaxCPU: 4, MaxRAMMb: 4096, MaxDiskGb: 50, MaxConcurrentJobs: 2},+ )+}++func backdateStartedAt(t *testing.T, verificationID uuid.UUID) {+ t.Helper()++ require.NoError(t, storage.GetDb().+ Model(&RestoreVerification{}).+ Where("id = ?", verificationID).+ Update("started_at", time.Now().UTC().Add(-1*time.Hour)).Error)+}++func Test_OnAgentHeartbeated_WhenLiveAgentDropsRunningJobPastGrace_Requeues(t *testing.T) {+ shrinkReclaimGrace(t, 1*time.Millisecond)++ router, ownerToken, database, storageID := newReclaimFixture(t)+ agent := newReclaimAgent(t, router, ownerToken)++ backup := backuping.SeedTestBackup(t, database.ID, storageID, 100)+ assignment := claimRunningJob(t, router, ownerToken, agent, backup.ID)+ backdateStartedAt(t, assignment.VerificationID)++ _, err := GetVerificationService().OnAgentHeartbeated(agent.Agent, nil)+ require.NoError(t, err)++ requeued := GetVerificationByIDViaAPI(t, router, ownerToken, assignment.VerificationID)+ assert.Equal(t, VerificationStatusPending, requeued.Status)+ assert.Equal(t, 2, requeued.AttemptCount)+ assert.Nil(t, requeued.AgentID)+ assert.Nil(t, requeued.FailMessage)+}++func Test_OnAgentHeartbeated_WhenJobStillReportedByAgent_DoesNotRequeue(t *testing.T) {+ shrinkReclaimGrace(t, 1*time.Millisecond)++ router, ownerToken, database, storageID := newReclaimFixture(t)+ agent := newReclaimAgent(t, router, ownerToken)++ backup := backuping.SeedTestBackup(t, database.ID, storageID, 100)+ assignment := claimRunningJob(t, router, ownerToken, agent, backup.ID)+ backdateStartedAt(t, assignment.VerificationID)++ _, err := GetVerificationService().OnAgentHeartbeated(+ agent.Agent, []uuid.UUID{assignment.VerificationID},+ )+ require.NoError(t, err)++ stillRunning := GetVerificationByIDViaAPI(t, router, ownerToken, assignment.VerificationID)+ assert.Equal(t, VerificationStatusRunning, stillRunning.Status,+ "a job the agent still reports must not be reclaimed")+ assert.Equal(t, 1, stillRunning.AttemptCount)+ require.NotNil(t, stillRunning.AgentID)+ assert.Equal(t, agent.Agent.ID, *stillRunning.AgentID)+}++func Test_OnAgentHeartbeated_WhenRunningJobWithinGrace_DoesNotRequeue(t *testing.T) {+ shrinkReclaimGrace(t, 1*time.Hour)++ router, ownerToken, database, storageID := newReclaimFixture(t)+ agent := newReclaimAgent(t, router, ownerToken)++ backup := backuping.SeedTestBackup(t, database.ID, storageID, 100)+ assignment := claimRunningJob(t, router, ownerToken, agent, backup.ID)++ _, err := GetVerificationService().OnAgentHeartbeated(agent.Agent, nil)+ require.NoError(t, err)++ stillRunning := GetVerificationByIDViaAPI(t, router, ownerToken, assignment.VerificationID)+ assert.Equal(t, VerificationStatusRunning, stillRunning.Status,+ "a freshly-claimed job within the grace window must not be reclaimed")+ assert.Equal(t, 1, stillRunning.AttemptCount)+}++func Test_OnAgentHeartbeated_WhenDroppedJobAtMaxAttempts_MarksTerminal(t *testing.T) {+ shrinkReclaimGrace(t, 1*time.Millisecond)++ router, ownerToken, database, storageID := newReclaimFixture(t)+ agent := newReclaimAgent(t, router, ownerToken)++ backup := backuping.SeedTestBackup(t, database.ID, storageID, 100)+ assignment := claimRunningJob(t, router, ownerToken, agent, backup.ID)++ require.NoError(t, storage.GetDb().+ Model(&RestoreVerification{}).+ Where("id = ?", assignment.VerificationID).+ Updates(map[string]any{+ "attempt_count": MaxAgentSideAttempts,+ "started_at": time.Now().UTC().Add(-1 * time.Hour),+ }).Error)++ _, err := GetVerificationService().OnAgentHeartbeated(agent.Agent, nil)+ require.NoError(t, err)++ final := GetVerificationByIDViaAPI(t, router, ownerToken, assignment.VerificationID)+ assert.Equal(t, VerificationStatusFailed, final.Status)+ assert.Equal(t, MaxAgentSideAttempts, final.AttemptCount, "terminal must not advance attempt_count")+ require.NotNil(t, final.FinishedAt)+ require.NotNil(t, final.FailMessage)+ assert.Contains(t, *final.FailMessage, "dropped by its still-online agent")+}++func Test_OnAgentHeartbeated_WhenJobAlreadyCompleted_DoesNotResurrect(t *testing.T) {+ shrinkReclaimGrace(t, 1*time.Millisecond)++ router, ownerToken, database, storageID := newReclaimFixture(t)+ agent := newReclaimAgent(t, router, ownerToken)++ backup := backuping.SeedTestBackup(t, database.ID, storageID, 100)+ assignment := claimRunningJob(t, router, ownerToken, agent, backup.ID)++ require.NoError(t, storage.GetDb().+ Model(&RestoreVerification{}).+ Where("id = ?", assignment.VerificationID).+ Updates(map[string]any{+ "status": VerificationStatusCompleted,+ "finished_at": time.Now().UTC(),+ "started_at": time.Now().UTC().Add(-1 * time.Hour),+ }).Error)++ _, err := GetVerificationService().OnAgentHeartbeated(agent.Agent, nil)+ require.NoError(t, err)++ final := GetVerificationByIDViaAPI(t, router, ownerToken, assignment.VerificationID)+ assert.Equal(t, VerificationStatusCompleted, final.Status,+ "a concurrently-completed row must not be resurrected by the reclaim")+}++func Test_OnAgentHeartbeated_WhenAgentDropsOneStillRunsAnother_ReclaimsOnlyDropped(t *testing.T) {+ shrinkReclaimGrace(t, 1*time.Millisecond)++ 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)++ databaseKept := databases.CreateTestDatabase(workspace.ID, testStorage, notifier)+ defer databases.RemoveTestDatabase(databaseKept)++ databaseDropped := databases.CreateTestDatabase(workspace.ID, testStorage, notifier)+ defer databases.RemoveTestDatabase(databaseDropped)++ agent := newReclaimAgent(t, router, owner.Token)++ backupKept := backuping.SeedTestBackup(t, databaseKept.ID, testStorage.ID, 100)+ backupDropped := backuping.SeedTestBackup(t, databaseDropped.ID, testStorage.ID, 100)++ kept := claimRunningJob(t, router, owner.Token, agent, backupKept.ID)+ dropped := claimRunningJob(t, router, owner.Token, agent, backupDropped.ID)+ backdateStartedAt(t, kept.VerificationID)+ backdateStartedAt(t, dropped.VerificationID)++ aborts, err := GetVerificationService().OnAgentHeartbeated(+ agent.Agent, []uuid.UUID{kept.VerificationID},+ )+ require.NoError(t, err)+ assert.Empty(t, aborts, "a job still RUNNING and owned must not be in the abort list")++ keptRow := GetVerificationByIDViaAPI(t, router, owner.Token, kept.VerificationID)+ assert.Equal(t, VerificationStatusRunning, keptRow.Status)+ assert.Equal(t, 1, keptRow.AttemptCount)++ droppedRow := GetVerificationByIDViaAPI(t, router, owner.Token, dropped.VerificationID)+ assert.Equal(t, VerificationStatusPending, droppedRow.Status)+ assert.Equal(t, 2, droppedRow.AttemptCount)+ assert.Nil(t, droppedRow.AgentID)+}++func Test_OnAgentHeartbeated_WhenAgentReportsNoLongerOwnedJob_ReturnsItInAbortList(t *testing.T) {+ shrinkReclaimGrace(t, 1*time.Millisecond)++ router, ownerToken, database, storageID := newReclaimFixture(t)+ agent := newReclaimAgent(t, router, ownerToken)++ backup := backuping.SeedTestBackup(t, database.ID, storageID, 100)+ assignment := claimRunningJob(t, router, ownerToken, agent, backup.ID)++ require.NoError(t, storage.GetDb().+ Model(&RestoreVerification{}).+ Where("id = ?", assignment.VerificationID).+ Updates(map[string]any{+ "status": VerificationStatusCompleted,+ "finished_at": time.Now().UTC(),+ }).Error)++ aborts, err := GetVerificationService().OnAgentHeartbeated(+ agent.Agent, []uuid.UUID{assignment.VerificationID},+ )+ require.NoError(t, err)++ assert.Contains(t, aborts, assignment.VerificationID,+ "a job the agent still reports but the backend no longer owns as RUNNING must be returned for abort")++ final := GetVerificationByIDViaAPI(t, router, ownerToken, assignment.VerificationID)+ assert.Equal(t, VerificationStatusCompleted, final.Status,+ "computing the abort list must not mutate the row")+}diff --git a/backend/internal/features/verification/runs/interfaces.go b/backend/internal/features/verification/runs/interfaces.gonew file mode 100644index 00000000..bba44e24--- /dev/null+++ b/backend/internal/features/verification/runs/interfaces.go@@ -0,0 +1,9 @@+package verification_runs++import (+ "databasus-backend/internal/features/notifiers"+)++type NotificationSender interface {+ SendNotification(notifier *notifiers.Notifier, title, message string)+}diff --git a/backend/internal/features/verification/runs/model.go b/backend/internal/features/verification/runs/model.gonew file mode 100644index 00000000..12226d90--- /dev/null+++ b/backend/internal/features/verification/runs/model.go@@ -0,0 +1,50 @@+package verification_runs++import (+ "time"++ "github.com/google/uuid"+)++type RestoreVerification struct {+ ID uuid.UUID `json:"id" gorm:"column:id;type:uuid;primaryKey"`+ DatabaseID uuid.UUID `json:"databaseId" gorm:"column:database_id;type:uuid;not null"`+ BackupID uuid.UUID `json:"backupId" gorm:"column:backup_id;type:uuid;not null"`+ AgentID *uuid.UUID `json:"agentId,omitempty" gorm:"column:agent_id;type:uuid"`++ Trigger VerificationTrigger `json:"trigger" gorm:"column:trigger;type:text;not null"`+ Status VerificationStatus `json:"status" gorm:"column:status;type:text;not null"`++ AttemptCount int `json:"attemptCount" gorm:"column:attempt_count;type:integer;not null;default:1"`++ CreatedAt time.Time `json:"createdAt" gorm:"column:created_at"`+ StartedAt *time.Time `json:"startedAt,omitzero" gorm:"column:started_at"`+ FinishedAt *time.Time `json:"finishedAt,omitzero" gorm:"column:finished_at"`++ RestoreDurationMs *int64 `json:"restoreDurationMs,omitempty" gorm:"column:restore_duration_ms"`+ VerifyDurationMs *int64 `json:"verifyDurationMs,omitempty" gorm:"column:verify_duration_ms"`++ PgRestoreExitCode *int `json:"pgRestoreExitCode,omitempty" gorm:"column:pg_restore_exit_code"`+ DBSizeBytesAfterRestore *int64 `json:"dbSizeBytesAfterRestore,omitempty" gorm:"column:db_size_bytes_after_restore"`+ TableCount *int `json:"tableCount,omitempty" gorm:"column:table_count"`+ SchemaCount *int `json:"schemaCount,omitempty" gorm:"column:schema_count"`+ FailMessage *string `json:"failMessage,omitempty" gorm:"column:fail_message"`++ TableStats []RestoreVerificationTableStat `json:"tableStats,omitempty" gorm:"foreignKey:RestoreVerificationID;references:ID"`+}++func (RestoreVerification) TableName() string {+ return "restore_verifications"+}++type RestoreVerificationTableStat struct {+ ID uuid.UUID `json:"id" gorm:"column:id;type:uuid;primaryKey"`+ RestoreVerificationID uuid.UUID `json:"-" gorm:"column:restore_verification_id;type:uuid;not null"`+ SchemaName string `json:"schemaName" gorm:"column:schema_name;type:text;not null"`+ Name string `json:"name" gorm:"column:name;type:text;not null"`+ RowCount int64 `json:"rowCount" gorm:"column:row_count;type:bigint;not null"`+}++func (RestoreVerificationTableStat) TableName() string {+ return "restore_verification_table_stats"+}diff --git a/backend/internal/features/verification/runs/notification_test.go b/backend/internal/features/verification/runs/notification_test.gonew file mode 100644index 00000000..e5c8e616--- /dev/null+++ b/backend/internal/features/verification/runs/notification_test.go@@ -0,0 +1,386 @@+package verification_runs++import (+ "net/http"+ "sync"+ "testing"+ "time"++ "github.com/gin-gonic/gin"+ "github.com/google/uuid"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ "databasus-backend/internal/features/backups/backups/backuping"+ "databasus-backend/internal/features/databases"+ "databasus-backend/internal/features/intervals"+ "databasus-backend/internal/features/notifiers"+ "databasus-backend/internal/features/storages"+ users_enums "databasus-backend/internal/features/users/enums"+ users_testing "databasus-backend/internal/features/users/testing"+ verification_agents "databasus-backend/internal/features/verification/agents"+ verification_config "databasus-backend/internal/features/verification/config"+ workspaces_testing "databasus-backend/internal/features/workspaces/testing"+ "databasus-backend/internal/storage"+ test_utils "databasus-backend/internal/util/testing"+)++type recordedNotification struct {+ notifier *notifiers.Notifier+ title string+ message string+}++type recordingNotificationSender struct {+ mu sync.Mutex+ recorded []recordedNotification+ notifyCh chan struct{}+}++func newRecordingNotificationSender() *recordingNotificationSender {+ return &recordingNotificationSender{notifyCh: make(chan struct{}, 16)}+}++func (s *recordingNotificationSender) SendNotification(+ notifier *notifiers.Notifier,+ title string,+ message string,+) {+ s.mu.Lock()+ s.recorded = append(s.recorded, recordedNotification{notifier, title, message})+ s.mu.Unlock()++ s.notifyCh <- struct{}{}+}++func (s *recordingNotificationSender) waitForNotification(+ t *testing.T,+ timeout time.Duration,+) recordedNotification {+ t.Helper()++ select {+ case <-s.notifyCh:+ case <-time.After(timeout):+ t.Fatalf("timed out after %s waiting for notification", timeout)+ }++ s.mu.Lock()+ defer s.mu.Unlock()++ return s.recorded[len(s.recorded)-1]+}++func (s *recordingNotificationSender) count() int {+ s.mu.Lock()+ defer s.mu.Unlock()++ return len(s.recorded)+}++func installRecordingNotificationSender(t *testing.T) *recordingNotificationSender {+ t.Helper()++ recorder := newRecordingNotificationSender()+ original := verificationService.notifierService+ verificationService.notifierService = recorder++ t.Cleanup(func() { verificationService.notifierService = original })++ return recorder+}++func enableFailureNotificationsViaAPI(+ t *testing.T,+ router *gin.Engine,+ userToken string,+ databaseID uuid.UUID,+) {+ t.Helper()++ verification_config.SaveVerificationConfigViaAPI(t, router, userToken, databaseID,+ verification_config.SaveBackupVerificationConfigDTO{+ IsScheduledVerificationEnabled: false,+ ScheduleType: verification_config.VerificationScheduleInterval,+ VerificationInterval: intervals.Interval{Type: intervals.IntervalHourly},+ SendNotificationsOn: []verification_config.VerificationNotificationType{+ verification_config.NotificationVerificationFailed,+ },+ })+}++func Test_SubmitReport_WhenBackupRejected_SendsFailureNotification(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)++ enableFailureNotificationsViaAPI(t, router, owner.Token, database.ID)++ recorder := installRecordingNotificationSender(t)++ backup := backuping.SeedTestBackup(t, database.ID, testStorage.ID, 100)+ agent := verification_agents.CreateTestVerificationAgent(+ t,+ router,+ owner.Token,+ "notif-rejected-"+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},+ )++ pgRestoreExit := 1+ failMessage := "pg_restore: schema mismatch"+ test_utils.MakePostRequest(+ t, router,+ reportPathFor(agent.Agent.ID, assignment.VerificationID),+ "Bearer "+agent.Token,+ ReportRequest{+ Status: VerificationStatusFailed,+ PgRestoreExitCode: &pgRestoreExit,+ FailMessage: &failMessage,+ },+ http.StatusNoContent,+ )++ sent := recorder.waitForNotification(t, 2*time.Second)+ require.NotNil(t, sent.notifier)+ assert.Equal(t, notifier.ID, sent.notifier.ID, "must dispatch to the database's notifier")+ assert.Contains(t, sent.title, database.Name, "title must name the database")+ assert.Contains(t, sent.title, "failed", "title must convey failure")+ assert.Contains(t, sent.message, failMessage, "notification body must include the agent's diagnostic")+}++func Test_SubmitReport_WhenRestoredTooSmall_SendsFailureNotification(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)++ enableFailureNotificationsViaAPI(t, router, owner.Token, database.ID)++ recorder := installRecordingNotificationSender(t)++ backup := backuping.SeedTestBackup(t, database.ID, testStorage.ID, 100)+ agent := verification_agents.CreateTestVerificationAgent(t, router, owner.Token, "notif-tiny-"+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},+ )++ tinyRestoredSize := int64(1_000_000) // 1 MB ≪ 20% of 100 MB+ test_utils.MakePostRequest(+ t, router,+ reportPathFor(agent.Agent.ID, assignment.VerificationID),+ "Bearer "+agent.Token,+ ReportRequest{+ Status: VerificationStatusCompleted,+ PgRestoreExitCode: new(int),+ DBSizeBytesAfterRestore: &tinyRestoredSize,+ },+ http.StatusNoContent,+ )++ sent := recorder.waitForNotification(t, 2*time.Second)+ require.NotNil(t, sent.notifier)+ assert.Equal(t, notifier.ID, sent.notifier.ID)+ assert.Contains(t, sent.title, "failed", "size-guard terminal must be reported as a failure")+ assert.Contains(t, sent.message, "less than 20%", "notification body must explain why the restore was rejected")+}++func Test_SubmitReport_WhenAgentSetupFailedRepeatedly_SendsFailureNotificationOnlyAtTerminal(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)++ enableFailureNotificationsViaAPI(t, router, owner.Token, database.ID)++ recorder := installRecordingNotificationSender(t)++ backup := backuping.SeedTestBackup(t, database.ID, testStorage.ID, 100)+ agent := verification_agents.CreateTestVerificationAgent(t, router, owner.Token, "notif-setup-"+uuid.New().String())+ defer verification_agents.RemoveTestVerificationAgent(t, router, owner.Token, agent.Agent.ID)++ enqueued := EnqueueManualVerificationViaAPI(t, router, owner.Token, backup.ID)++ for attempt := range MaxAgentSideAttempts {+ claim := ClaimVerificationViaAPI(+ t, router, agent.Agent.ID, agent.Token,+ AgentCapacity{MaxCPU: 4, MaxRAMMb: 4096, MaxDiskGb: 50, MaxConcurrentJobs: 2},+ )+ require.Equal(+ t,+ enqueued.ID,+ claim.VerificationID,+ "requeued row must be the same verification (attempt %d)",+ attempt+1,+ )++ failMessage := "agent setup failed"+ test_utils.MakePostRequest(+ t, router,+ reportPathFor(agent.Agent.ID, claim.VerificationID),+ "Bearer "+agent.Token,+ ReportRequest{Status: VerificationStatusFailed, FailMessage: &failMessage},+ http.StatusNoContent,+ )++ if attempt < MaxAgentSideAttempts-1 {+ // Mid-retry: confirm no notification was sent. Give goroutines a beat+ // to misfire before asserting the recorder is still empty.+ time.Sleep(50 * time.Millisecond)+ assert.Equal(t, 0, recorder.count(),+ "must not notify between retries (attempt %d)", attempt+1)+ }+ }++ sent := recorder.waitForNotification(t, 2*time.Second)+ assert.Equal(t, notifier.ID, sent.notifier.ID)+ assert.Contains(t, sent.title, "failed")+ assert.Equal(t, 1, recorder.count(), "exactly one notification on terminal — not one per attempt")+}++func Test_ReapStaleRuns_WhenAgentLostContact_SendsFailureNotificationOnlyAtTerminal(t *testing.T) {+ shrinkThresholds(t, 1*time.Hour, 1*time.Millisecond)++ 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)++ enableFailureNotificationsViaAPI(t, router, owner.Token, database.ID)++ recorder := installRecordingNotificationSender(t)++ backup := backuping.SeedTestBackup(t, database.ID, testStorage.ID, 100)+ agent := verification_agents.CreateTestVerificationAgent(+ t,+ router,+ owner.Token,+ "notif-silent-"+uuid.New().String(),+ )+ defer verification_agents.RemoveTestVerificationAgent(t, router, owner.Token, agent.Agent.ID)++ enqueued := EnqueueManualVerificationViaAPI(t, router, owner.Token, backup.ID)++ for attempt := range MaxAgentSideAttempts {+ ClaimVerificationViaAPI(+ t, router, agent.Agent.ID, agent.Token,+ AgentCapacity{MaxCPU: 4, MaxRAMMb: 4096, MaxDiskGb: 50, MaxConcurrentJobs: 2},+ )++ require.NoError(t, storage.GetDb().+ Model(&verification_agents.Agent{}).+ Where("id = ?", agent.Agent.ID).+ Update("last_seen_at", time.Now().UTC().Add(-1*time.Hour)).Error)++ require.NoError(t, GetVerificationScheduler().reapStaleRuns())++ if attempt < MaxAgentSideAttempts-1 {+ time.Sleep(50 * time.Millisecond)+ assert.Equal(t, 0, recorder.count(),+ "must not notify between reaper-driven retries (attempt %d)", attempt+1)+ }+ }++ sent := recorder.waitForNotification(t, 2*time.Second)+ assert.Equal(t, notifier.ID, sent.notifier.ID)+ assert.Contains(t, sent.title, "failed")+ assert.Contains(t, sent.message, "agent went silent")++ final := GetVerificationByIDViaAPI(t, router, owner.Token, enqueued.ID)+ assert.Equal(t, VerificationStatusFailed, final.Status)+}++func Test_SubmitReport_WhenFailureNotificationsDisabled_DoesNotSend(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)++ // Default config has IsScheduledVerificationEnabled=false and no notification types.+ // Do not call enableFailureNotificationsViaAPI — failure notification must NOT fire.++ recorder := installRecordingNotificationSender(t)++ backup := backuping.SeedTestBackup(t, database.ID, testStorage.ID, 100)+ agent := verification_agents.CreateTestVerificationAgent(t, router, owner.Token, "notif-off-"+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},+ )++ pgRestoreExit := 1+ failMessage := "pg_restore: schema mismatch"+ test_utils.MakePostRequest(+ t, router,+ reportPathFor(agent.Agent.ID, assignment.VerificationID),+ "Bearer "+agent.Token,+ ReportRequest{+ Status: VerificationStatusFailed,+ PgRestoreExitCode: &pgRestoreExit,+ FailMessage: &failMessage,+ },+ http.StatusNoContent,+ )++ time.Sleep(100 * time.Millisecond) // let any goroutine misfire surface+ assert.Equal(t, 0, recorder.count(), "no failure notification type configured → no send")+}diff --git a/backend/internal/features/verification/runs/repository.go b/backend/internal/features/verification/runs/repository.gonew file mode 100644index 00000000..406250c8--- /dev/null+++ b/backend/internal/features/verification/runs/repository.go@@ -0,0 +1,404 @@+package verification_runs++import (+ "errors"+ "maps"+ "time"++ "github.com/google/uuid"+ "gorm.io/gorm"+ "gorm.io/gorm/clause"++ backups_core "databasus-backend/internal/features/backups/backups/core"+ "databasus-backend/internal/storage"+)++type VerificationRepository struct{}++func (r *VerificationRepository) Create(verification *RestoreVerification) error {+ if verification.ID == uuid.Nil {+ verification.ID = uuid.New()+ }++ return storage.GetDb().Create(verification).Error+}++func (r *VerificationRepository) FindByID(id uuid.UUID) (*RestoreVerification, error) {+ var verification RestoreVerification++ err := storage.GetDb().+ Preload("TableStats").+ Where("id = ?", id).+ First(&verification).Error+ if err != nil {+ if errors.Is(err, gorm.ErrRecordNotFound) {+ return nil, nil+ }++ return nil, err+ }++ return &verification, nil+}++func (r *VerificationRepository) FindByDatabaseID(+ databaseID uuid.UUID,+) ([]*RestoreVerification, error) {+ verifications := make([]*RestoreVerification, 0)++ err := storage.GetDb().+ Where("database_id = ?", databaseID).+ Order("created_at DESC").+ Find(&verifications).Error++ return verifications, err+}++func (r *VerificationRepository) FindByDatabaseIDWithPagination(+ databaseID uuid.UUID,+ limit, offset int,+) ([]*RestoreVerification, error) {+ verifications := make([]*RestoreVerification, 0)++ err := storage.GetDb().+ Where("database_id = ?", databaseID).+ Order("created_at DESC").+ Limit(limit).+ Offset(offset).+ Find(&verifications).Error++ return verifications, err+}++func (r *VerificationRepository) CountByDatabaseID(databaseID uuid.UUID) (int64, error) {+ var count int64++ err := storage.GetDb().+ Model(&RestoreVerification{}).+ Where("database_id = ?", databaseID).+ Count(&count).Error++ return count, err+}++func (r *VerificationRepository) ListRunningBackupsByAgentID(+ agentID uuid.UUID,+) ([]*backups_core.Backup, error) {+ backups := make([]*backups_core.Backup, 0)++ err := storage.GetDb().+ Table("backups b").+ Select("b.*").+ Joins("JOIN restore_verifications v ON v.backup_id = b.id").+ Where("v.agent_id = ? AND v.status = ?", agentID, VerificationStatusRunning).+ Scan(&backups).Error++ return backups, err+}++// ClaimCandidate pairs a PENDING verification with its backup so the service can run+// the disk-fit check in Go without re-fetching the backup row.+type ClaimCandidate struct {+ Verification *RestoreVerification+ Backup *backups_core.Backup+}++// FindOldestPendingClaimablesTop100 locks up to 100 oldest PENDING verification rows+// with SKIP LOCKED and returns each one paired with its backup. The service iterates+// these in order and picks the first that fits the agent's budget — see+// DoesVerificationFit. Locks held for the rest are released when the caller's tx+// commits or rolls back; SKIP LOCKED ensures concurrent agents don't queue on them.+func (r *VerificationRepository) FindOldestPendingClaimablesTop100(+ tx *gorm.DB,+) ([]ClaimCandidate, error) {+ var verifications []*RestoreVerification++ err := tx.+ Where("status = ?", VerificationStatusPending).+ Order("created_at").+ Clauses(clause.Locking{Strength: "UPDATE", Options: "SKIP LOCKED"}).+ Limit(100).+ Find(&verifications).Error+ if err != nil {+ return nil, err+ }++ if len(verifications) == 0 {+ return nil, nil+ }++ backupIDs := make([]uuid.UUID, len(verifications))+ for i, verification := range verifications {+ backupIDs[i] = verification.BackupID+ }++ var backups []*backups_core.Backup+ if err := tx.Where("id IN ?", backupIDs).Find(&backups).Error; err != nil {+ return nil, err+ }++ backupByID := make(map[uuid.UUID]*backups_core.Backup, len(backups))+ for _, backup := range backups {+ backupByID[backup.ID] = backup+ }++ candidates := make([]ClaimCandidate, 0, len(verifications))+ for _, verification := range verifications {+ backup, ok := backupByID[verification.BackupID]+ if !ok {+ continue+ }++ candidates = append(candidates, ClaimCandidate{+ Verification: verification,+ Backup: backup,+ })+ }++ return candidates, nil+}++func (r *VerificationRepository) UpdateClaim(+ tx *gorm.DB,+ verificationID, agentID uuid.UUID,+ startedAt time.Time,+) error {+ result := tx.Model(&RestoreVerification{}).+ Where("id = ? AND status = ? AND agent_id IS NULL", verificationID, VerificationStatusPending).+ Updates(map[string]any{+ "status": VerificationStatusRunning,+ "agent_id": agentID,+ "started_at": startedAt,+ })+ if result.Error != nil {+ return result.Error+ }++ if result.RowsAffected == 0 {+ return errors.New("verification claim failed: row no longer PENDING")+ }++ return nil+}++// WriteSuccessReport atomically applies a COMPLETED agent report: CAS-updates the+// verification row (still RUNNING and owned by this agent) and inserts its table+// stats in the same transaction. Returns errVerificationGone when the CAS sees zero+// rows updated — the controller maps that to 410.+func (r *VerificationRepository) WriteSuccessReport(+ verificationID, agentID uuid.UUID,+ report *ReportRequest,+) error {+ return storage.GetDb().Transaction(func(tx *gorm.DB) error {+ fields := map[string]any{+ "status": VerificationStatusCompleted,+ "finished_at": time.Now().UTC(),+ "pg_restore_exit_code": report.PgRestoreExitCode,+ "restore_duration_ms": report.RestoreDurationMs,+ "verify_duration_ms": report.VerifyDurationMs,+ "db_size_bytes_after_restore": report.DBSizeBytesAfterRestore,+ "table_count": report.TableCount,+ "schema_count": report.SchemaCount,+ "fail_message": nil,+ }++ result := tx.Model(&RestoreVerification{}).+ Where(+ "id = ? AND agent_id = ? AND status = ?",+ verificationID, agentID, VerificationStatusRunning,+ ).+ Updates(fields)+ if result.Error != nil {+ return result.Error+ }++ if result.RowsAffected == 0 {+ return errors.New("verification gone")+ }++ return r.insertTableStats(tx, verificationID, report.TableStats)+ })+}++func (r *VerificationRepository) FindNonTerminalForDatabase(+ tx *gorm.DB,+ databaseID uuid.UUID,+) ([]*RestoreVerification, error) {+ verifications := make([]*RestoreVerification, 0)++ err := tx.+ Where(+ "database_id = ? AND status IN ?",+ databaseID,+ []VerificationStatus{VerificationStatusPending, VerificationStatusRunning},+ ).+ Clauses(clause.Locking{Strength: "UPDATE"}).+ Find(&verifications).Error++ return verifications, err+}++func (r *VerificationRepository) FindStalePending(+ threshold time.Time,+) ([]*RestoreVerification, error) {+ verifications := make([]*RestoreVerification, 0)++ err := storage.GetDb().+ Where("status = ? AND created_at < ?", VerificationStatusPending, threshold).+ Find(&verifications).Error++ return verifications, err+}++func (r *VerificationRepository) FindAllRunning() ([]*RestoreVerification, error) {+ verifications := make([]*RestoreVerification, 0)++ err := storage.GetDb().+ Where("status = ?", VerificationStatusRunning).+ Find(&verifications).Error++ return verifications, err+}++func (r *VerificationRepository) FindRunningByAgent(+ agentID uuid.UUID,+) ([]*RestoreVerification, error) {+ verifications := make([]*RestoreVerification, 0)++ err := storage.GetDb().+ Where("status = ? AND agent_id = ?", VerificationStatusRunning, agentID).+ Find(&verifications).Error++ return verifications, err+}++func (r *VerificationRepository) FindNonTerminalForDisabledConfigs() ([]*RestoreVerification, error) {+ verifications := make([]*RestoreVerification, 0)++ err := storage.GetDb().+ Table("restore_verifications v").+ Select("v.*").+ Joins("JOIN backup_verification_configs c ON c.database_id = v.database_id").+ Where(+ "c.is_scheduled_verification_enabled = ? AND v.status IN ?",+ false,+ []VerificationStatus{VerificationStatusPending, VerificationStatusRunning},+ ).+ Scan(&verifications).Error++ return verifications, err+}++func (r *VerificationRepository) FindLatestFinishedAt(+ databaseID uuid.UUID,+) (*time.Time, error) {+ var verification RestoreVerification++ err := storage.GetDb().+ Where(+ "database_id = ? AND status IN ? AND finished_at IS NOT NULL",+ databaseID,+ []VerificationStatus{+ VerificationStatusCompleted,+ VerificationStatusFailed,+ VerificationStatusCanceled,+ },+ ).+ Order("finished_at DESC").+ First(&verification).Error+ if err != nil {+ if errors.Is(err, gorm.ErrRecordNotFound) {+ return nil, nil+ }++ return nil, err+ }++ return verification.FinishedAt, nil+}++// Requeue resets created_at so each requeue gets a fresh PENDING-too-long window.+func (r *VerificationRepository) Requeue(tx *gorm.DB, verificationID uuid.UUID) error {+ db := tx+ if db == nil {+ db = storage.GetDb()+ }++ now := time.Now().UTC()++ result := db.Model(&RestoreVerification{}).+ Where("id = ?", verificationID).+ Updates(map[string]any{+ "status": VerificationStatusPending,+ "agent_id": nil,+ "started_at": nil,+ "finished_at": nil,+ "created_at": now,+ "attempt_count": gorm.Expr("attempt_count + 1"),+ "fail_message": nil,+ })+ if result.Error != nil {+ return result.Error+ }++ if result.RowsAffected == 0 {+ return errors.New("requeue failed: verification not found")+ }++ return nil+}++// MarkTerminal runs inside tx when non-nil to avoid deadlock against the caller's+// own row lock (e.g. displacement during EnqueueManualVerification).+func (r *VerificationRepository) MarkTerminal(+ tx *gorm.DB,+ verificationID uuid.UUID,+ status VerificationStatus,+ fields map[string]any,+) error {+ db := tx+ if db == nil {+ db = storage.GetDb()+ }++ updates := make(map[string]any, len(fields)+2)+ maps.Copy(updates, fields)+ updates["status"] = status+ updates["finished_at"] = time.Now().UTC()++ result := db.Model(&RestoreVerification{}).+ Where("id = ?", verificationID).+ Updates(updates)+ if result.Error != nil {+ return result.Error+ }++ if result.RowsAffected == 0 {+ return errors.New("mark terminal failed: verification not found")+ }++ return nil+}++func (r *VerificationRepository) insertTableStats(+ tx *gorm.DB,+ verificationID uuid.UUID,+ stats []ReportTableStat,+) error {+ if len(stats) == 0 {+ return nil+ }++ rows := make([]RestoreVerificationTableStat, len(stats))+ for i, stat := range stats {+ rows[i] = RestoreVerificationTableStat{+ ID: uuid.New(),+ RestoreVerificationID: verificationID,+ SchemaName: stat.SchemaName,+ Name: stat.Name,+ RowCount: stat.RowCount,+ }+ }++ return tx.Create(&rows).Error+}diff --git a/backend/internal/features/verification/runs/scheduler.go b/backend/internal/features/verification/runs/scheduler.gonew file mode 100644index 00000000..1368bd86--- /dev/null+++ b/backend/internal/features/verification/runs/scheduler.go@@ -0,0 +1,254 @@+package verification_runs++import (+ "context"+ "fmt"+ "log/slog"+ "sync/atomic"+ "time"++ "github.com/google/uuid"++ backups_services "databasus-backend/internal/features/backups/backups/services"+ "databasus-backend/internal/features/databases"+ verification_agents "databasus-backend/internal/features/verification/agents"+ verification_config "databasus-backend/internal/features/verification/config"+)++const jobName = "verification_scheduler"++var (+ schedulerTickInterval = 15 * time.Second+ maxPendingDuration = 24 * time.Hour+)++type VerificationScheduler struct {+ repo *VerificationRepository+ service *VerificationService+ verificaionConfigService *verification_config.VerificationConfigService+ agentService *verification_agents.AgentService+ backupService *backups_services.BackupService+ databaseService *databases.DatabaseService+ logger *slog.Logger++ hasRun atomic.Bool+}++func (s *VerificationScheduler) Run(ctx context.Context) {+ if s.hasRun.Swap(true) {+ panic(fmt.Sprintf("%T.Run() called multiple times", s))+ }++ ticker := time.NewTicker(schedulerTickInterval)+ defer ticker.Stop()++ for {+ select {+ case <-ctx.Done():+ return+ case <-ticker.C:+ tickLogger := s.logger.With("job_id", uuid.New(), "job_name", jobName)++ if err := s.createScheduledRuns(); err != nil {+ tickLogger.Error("createScheduledRuns failed", "error", err)+ }++ if err := s.reapStaleRuns(); err != nil {+ tickLogger.Error("reapStaleRuns failed", "error", err)+ }++ if err := s.sweepCanceledByDisabledConfig(); err != nil {+ tickLogger.Error("sweepCanceledByDisabledConfig failed", "error", err)+ }+ }+ }+}++func (s *VerificationScheduler) createScheduledRuns() error {+ configsWithEnabledVerifications, err := s.verificaionConfigService.ListEnabled()+ if err != nil {+ return err+ }++ now := time.Now().UTC()++ for _, config := range configsWithEnabledVerifications {+ if err := s.createScheduledRunForConfig(config, now); err != nil {+ s.logger.Error(+ "failed to evaluate scheduled run for database",+ "error", err,+ "database_id", config.DatabaseID,+ )+ }+ }++ return nil+}++func (s *VerificationScheduler) createScheduledRunForConfig(+ config *verification_config.BackupVerificationConfig,+ now time.Time,+) error {+ // After-backup configs are driven by the backup-completion listener+ if config.ScheduleType == verification_config.VerificationScheduleAfterBackup {+ return nil+ }++ existing, err := s.repo.FindByDatabaseID(config.DatabaseID)+ if err != nil {+ return err+ }++ for _, row := range existing {+ if row.Trigger != VerificationTriggerScheduled {+ continue+ }++ if row.Status == VerificationStatusPending || row.Status == VerificationStatusRunning {+ return nil+ }+ }++ lastFinishedAt, err := s.repo.FindLatestFinishedAt(config.DatabaseID)+ if err != nil {+ return err+ }++ if !config.VerificationInterval.ShouldTriggerBackup(now, lastFinishedAt) {+ return nil+ }++ backup, err := s.backupService.GetLatestVerifiableBackup(config.DatabaseID)+ if err != nil {+ return err+ }++ if backup == nil {+ s.logger.Info(+ "skipping scheduled verification: no verifiable backup yet",+ "database_id", config.DatabaseID,+ )++ return nil+ }++ database, err := s.databaseService.GetDatabaseByID(config.DatabaseID)+ if err != nil {+ return err+ }++ if err := validateDatabaseIsVerifiable(database); err != nil {+ s.logger.Warn(+ "skipping scheduled verification: database not verifiable",+ "database_id", config.DatabaseID,+ "error", err,+ )++ return nil+ }++ verification := &RestoreVerification{+ ID: uuid.New(),+ DatabaseID: database.ID,+ BackupID: backup.ID,+ Trigger: VerificationTriggerScheduled,+ Status: VerificationStatusPending,+ AttemptCount: 1,+ CreatedAt: now,+ }++ return s.repo.Create(verification)+}++func (s *VerificationScheduler) reapStaleRuns() error {+ runningRows, err := s.repo.FindAllRunning()+ if err != nil {+ return err+ }++ now := time.Now().UTC()+ staleBefore := now.Add(-StaleAgentThreshold)++ for _, row := range runningRows {+ if row.AgentID == nil {+ continue+ }++ agent, lookupErr := s.agentService.GetAgentByID(*row.AgentID)+ if lookupErr != nil {+ s.logger.Error(+ "failed to load agent during reap",+ "error", lookupErr,+ "verification_id", row.ID,+ "agent_id", row.AgentID,+ )++ continue+ }++ if agent == nil || agent.IsDeleted() {+ // The owning agent is gone, but Requeue clears agent_id so a+ // different agent can pick the run up. If none does, the stale+ // PENDING reaper retires it after maxPendingDuration.+ if failErr := s.service.RequeueOrFail(row, FailureReasonAgentRemoved, nil); failErr != nil {+ s.logger.Error(+ "failed to requeue or fail RUNNING verification for removed agent",+ "error", failErr,+ "verification_id", row.ID,+ )+ }++ continue+ }++ if agent.LastSeenAt == nil || agent.LastSeenAt.Before(staleBefore) {+ if failErr := s.service.RequeueOrFail(row, FailureReasonAgentLostContact, nil); failErr != nil {+ s.logger.Error(+ "failed to requeue or fail stale RUNNING verification",+ "error", failErr,+ "verification_id", row.ID,+ )+ }+ }+ }++ stalePendingBefore := now.Add(-maxPendingDuration)++ stalePending, err := s.repo.FindStalePending(stalePendingBefore)+ if err != nil {+ return err+ }++ for _, row := range stalePending {+ if failErr := s.service.RequeueOrFail(row, FailureReasonUnclaimedTooLong, nil); failErr != nil {+ s.logger.Error(+ "failed to fail stale PENDING verification",+ "error", failErr,+ "verification_id", row.ID,+ )+ }+ }++ return nil+}++// sweepCanceledByDisabledConfig sends no notification+// — disable is user-initiated, not a failure.+func (s *VerificationScheduler) sweepCanceledByDisabledConfig() error {+ rows, err := s.repo.FindNonTerminalForDisabledConfigs()+ if err != nil {+ return err+ }++ for _, row := range rows {+ if cancelErr := s.repo.MarkTerminal(nil, row.ID, VerificationStatusCanceled, nil); cancelErr != nil {+ s.logger.Error(+ "failed to mark verification CANCELED",+ "error", cancelErr,+ "verification_id", row.ID,+ )+ }+ }++ return nil+}diff --git a/backend/internal/features/verification/runs/scheduler_test.go b/backend/internal/features/verification/runs/scheduler_test.gonew file mode 100644index 00000000..ebe44fb8--- /dev/null+++ b/backend/internal/features/verification/runs/scheduler_test.go@@ -0,0 +1,466 @@+package verification_runs++import (+ "net/http"+ "testing"+ "time"++ "github.com/gin-gonic/gin"+ "github.com/google/uuid"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ "databasus-backend/internal/features/backups/backups/backuping"+ "databasus-backend/internal/features/databases"+ "databasus-backend/internal/features/intervals"+ "databasus-backend/internal/features/notifiers"+ "databasus-backend/internal/features/storages"+ users_enums "databasus-backend/internal/features/users/enums"+ users_testing "databasus-backend/internal/features/users/testing"+ verification_agents "databasus-backend/internal/features/verification/agents"+ verification_config "databasus-backend/internal/features/verification/config"+ workspaces_testing "databasus-backend/internal/features/workspaces/testing"+ "databasus-backend/internal/storage"+ test_utils "databasus-backend/internal/util/testing"+)++func shrinkThresholds(t *testing.T, pendingMax, staleAgent time.Duration) {+ t.Helper()++ originalPending := maxPendingDuration+ originalStale := StaleAgentThreshold++ maxPendingDuration = pendingMax+ StaleAgentThreshold = staleAgent++ t.Cleanup(func() {+ maxPendingDuration = originalPending+ StaleAgentThreshold = originalStale+ })+}++func enableHourlyVerificationViaAPI(+ t *testing.T,+ router *gin.Engine,+ userToken string,+ databaseID uuid.UUID,+) {+ t.Helper()++ verification_config.SaveVerificationConfigViaAPI(t, router, userToken, databaseID,+ verification_config.SaveBackupVerificationConfigDTO{+ IsScheduledVerificationEnabled: true,+ ScheduleType: verification_config.VerificationScheduleInterval,+ VerificationInterval: intervals.Interval{Type: intervals.IntervalHourly},+ })+}++func Test_CreateScheduledRuns_WhenMultipleBackupsExist_PicksLatestForVerification(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)++ older := backuping.SeedTestBackup(t, database.ID, testStorage.ID, 50)+ older.CreatedAt = time.Now().UTC().Add(-2 * time.Hour)+ require.NoError(t, storage.GetDb().Save(older).Error)++ latestBackup := backuping.SeedTestBackup(t, database.ID, testStorage.ID, 100)++ enableHourlyVerificationViaAPI(t, router, owner.Token, database.ID)++ scheduler := GetVerificationScheduler()+ require.NoError(t, scheduler.createScheduledRuns())++ rows := ListVerificationsByDatabaseViaAPI(t, router, owner.Token, database.ID)+ require.Len(t, rows, 1)+ assert.Equal(t, VerificationStatusPending, rows[0].Status)+ assert.Equal(t, VerificationTriggerScheduled, rows[0].Trigger)+ assert.Equal(t, latestBackup.ID, rows[0].BackupID)+}++func Test_CreateScheduledRuns_WhenScheduledPendingAlreadyExists_DoesNotInsertNewRun(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)++ backuping.SeedTestBackup(t, database.ID, testStorage.ID, 100)++ enableHourlyVerificationViaAPI(t, router, owner.Token, database.ID)++ scheduler := GetVerificationScheduler()+ require.NoError(t, scheduler.createScheduledRuns())+ require.NoError(t, scheduler.createScheduledRuns())++ rows := ListVerificationsByDatabaseViaAPI(t, router, owner.Token, database.ID)+ assert.Len(t, rows, 1, "second tick must not insert a second row while a SCHEDULED PENDING exists")+}++func Test_CreateScheduledRuns_WhenManualPendingExists_StillCreatesScheduledRun(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.SeedTestBackup(t, database.ID, testStorage.ID, 100)++ EnqueueManualVerificationViaAPI(t, router, owner.Token, backup.ID)++ enableHourlyVerificationViaAPI(t, router, owner.Token, database.ID)++ scheduler := GetVerificationScheduler()+ require.NoError(t, scheduler.createScheduledRuns())++ rows := ListVerificationsByDatabaseViaAPI(t, router, owner.Token, database.ID)+ require.Len(t, rows, 2, "manual non-terminal row must not block scheduled creation")++ var manualCount, scheduledCount int+ for _, row := range rows {+ switch row.Trigger {+ case VerificationTriggerManual:+ manualCount+++ assert.Equal(t, VerificationStatusPending, row.Status, "manual row must remain untouched")+ case VerificationTriggerScheduled:+ scheduledCount+++ assert.Equal(t, VerificationStatusPending, row.Status)+ }+ }+ assert.Equal(t, 1, manualCount)+ assert.Equal(t, 1, scheduledCount)+}++func Test_ReapStaleRuns_WhenPendingExceedsMaxDuration_MarksFailedWithoutRetry(t *testing.T) {+ shrinkThresholds(t, 5*time.Millisecond, 5*time.Second)++ 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.SeedTestBackup(t, database.ID, testStorage.ID, 100)++ stalePending := EnqueueManualVerificationViaAPI(t, router, owner.Token, backup.ID)+ require.NoError(t, storage.GetDb().+ Model(&RestoreVerification{}).+ Where("id = ?", stalePending.ID).+ Update("created_at", time.Now().UTC().Add(-1*time.Hour)).Error)++ scheduler := GetVerificationScheduler()+ require.NoError(t, scheduler.reapStaleRuns())++ final := GetVerificationByIDViaAPI(t, router, owner.Token, stalePending.ID)+ assert.Equal(t, VerificationStatusFailed, final.Status)+ require.NotNil(t, final.FailMessage)+ assert.Contains(t, *final.FailMessage, "not picked up")+}++func Test_ReapStaleRuns_WhenOwningAgentRemoved_RequeuesThenRetiresIfUnclaimed(t *testing.T) {+ shrinkThresholds(t, 5*time.Millisecond, 1*time.Millisecond)++ 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.SeedTestBackup(t, database.ID, testStorage.ID, 100)+ agent := verification_agents.CreateTestVerificationAgent(t, router, owner.Token, "soft-del-"+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},+ )++ test_utils.MakeDeleteRequest(+ t, router,+ "/api/v1/verification/agents/"+agent.Agent.ID.String(),+ "Bearer "+owner.Token,+ http.StatusNoContent,+ )++ scheduler := GetVerificationScheduler()+ require.NoError(t, scheduler.reapStaleRuns())++ requeued := GetVerificationByIDViaAPI(t, router, owner.Token, assignment.VerificationID)+ assert.Equal(+ t,+ VerificationStatusPending,+ requeued.Status,+ "owning agent gone → requeue so another agent can claim it, not terminal",+ )+ assert.Equal(t, 2, requeued.AttemptCount)+ assert.Nil(t, requeued.AgentID)+ assert.Nil(t, requeued.FailMessage)++ // No agent ever claims it: backdating created_at past the (shrunk)+ // maxPendingDuration drives the stale-PENDING reaper, which retires it.+ require.NoError(t, storage.GetDb().+ Model(&RestoreVerification{}).+ Where("id = ?", assignment.VerificationID).+ Update("created_at", time.Now().UTC().Add(-1*time.Hour)).Error)+ require.NoError(t, scheduler.reapStaleRuns())++ final := GetVerificationByIDViaAPI(t, router, owner.Token, assignment.VerificationID)+ assert.Equal(t, VerificationStatusFailed, final.Status)+ require.NotNil(t, final.FailMessage)+ assert.Contains(t, *final.FailMessage, "not picked up")+}++func Test_ReapStaleRuns_WhenAgentLostContactWithRetriesRemaining_RequeuesVerification(t *testing.T) {+ shrinkThresholds(t, 1*time.Hour, 1*time.Millisecond)++ 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)++ enableHourlyVerificationViaAPI(t, router, owner.Token, database.ID)++ backup := backuping.SeedTestBackup(t, database.ID, testStorage.ID, 100)+ agent := verification_agents.CreateTestVerificationAgent(+ t,+ router,+ owner.Token,+ "silent-retry-"+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},+ )++ require.NoError(t, storage.GetDb().+ Model(&verification_agents.Agent{}).+ Where("id = ?", agent.Agent.ID).+ Update("last_seen_at", time.Now().UTC().Add(-1*time.Hour)).Error)++ require.NoError(t, GetVerificationScheduler().reapStaleRuns())++ requeued := GetVerificationByIDViaAPI(t, router, owner.Token, assignment.VerificationID)+ assert.Equal(t, VerificationStatusPending, requeued.Status, "must requeue, not go terminal — retries left")+ assert.Equal(t, 2, requeued.AttemptCount)+ assert.Nil(t, requeued.AgentID)+ assert.Nil(t, requeued.FailMessage)+}++func Test_ReapStaleRuns_WhenPendingExceedsMaxDuration_MarksTerminalRegardlessOfPolicy(t *testing.T) {+ shrinkThresholds(t, 5*time.Millisecond, 5*time.Second)++ 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)++ enableHourlyVerificationViaAPI(t, router, owner.Token, database.ID)++ backup := backuping.SeedTestBackup(t, database.ID, testStorage.ID, 100)+ stalePending := EnqueueManualVerificationViaAPI(t, router, owner.Token, backup.ID)+ require.NoError(t, storage.GetDb().+ Model(&RestoreVerification{}).+ Where("id = ?", stalePending.ID).+ Update("created_at", time.Now().UTC().Add(-1*time.Hour)).Error)++ require.NoError(t, GetVerificationScheduler().reapStaleRuns())++ final := GetVerificationByIDViaAPI(t, router, owner.Token, stalePending.ID)+ assert.Equal(t, VerificationStatusFailed, final.Status,+ "unclaimed-too-long always goes terminal — agent-side retry policy does not apply to fleet-side failures")+ assert.Equal(t, 1, final.AttemptCount, "no retry → attempt counter must NOT advance")+ require.NotNil(t, final.FailMessage)+ assert.Contains(t, *final.FailMessage, "not picked up")+}++func Test_SweepCanceledByDisabledConfig_WhenScheduledVerificationDisabled_CancelsNonTerminalRows(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)++ backuping.SeedTestBackup(t, database.ID, testStorage.ID, 100)++ enableHourlyVerificationViaAPI(t, router, owner.Token, database.ID)++ scheduler := GetVerificationScheduler()+ require.NoError(t, scheduler.createScheduledRuns())++ rows := ListVerificationsByDatabaseViaAPI(t, router, owner.Token, database.ID)+ require.Len(t, rows, 1)+ scheduledRowID := rows[0].ID++ verification_config.SaveVerificationConfigViaAPI(t, router, owner.Token, database.ID,+ verification_config.SaveBackupVerificationConfigDTO{+ IsScheduledVerificationEnabled: false,+ ScheduleType: verification_config.VerificationScheduleInterval,+ VerificationInterval: intervals.Interval{Type: intervals.IntervalHourly},+ })++ require.NoError(t, scheduler.sweepCanceledByDisabledConfig())++ final := GetVerificationByIDViaAPI(t, router, owner.Token, scheduledRowID)+ assert.Equal(t, VerificationStatusCanceled, final.Status)+}++func Test_CreateScheduledRuns_AfterUserCancel_DoesNotImmediatelyRecreate(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)++ backuping.SeedTestBackup(t, database.ID, testStorage.ID, 100)++ enableHourlyVerificationViaAPI(t, router, owner.Token, database.ID)++ scheduler := GetVerificationScheduler()+ require.NoError(t, scheduler.createScheduledRuns())++ rows := ListVerificationsByDatabaseViaAPI(t, router, owner.Token, database.ID)+ require.Len(t, rows, 1)+ scheduledRowID := rows[0].ID++ CancelVerificationViaAPI(t, router, owner.Token, scheduledRowID)++ require.NoError(t, scheduler.createScheduledRuns())++ rowsAfter := ListVerificationsByDatabaseViaAPI(t, router, owner.Token, database.ID)+ assert.Len(+ t,+ rowsAfter,+ 1,+ "scheduler must not recreate a SCHEDULED row right after a user cancel within the interval window",+ )+ assert.Equal(t, VerificationStatusCanceled, rowsAfter[0].Status)+}++func Test_CreateScheduledRuns_AfterUserCancel_DoesNotRequeueOrRestart(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)++ backuping.SeedTestBackup(t, database.ID, testStorage.ID, 100)++ enableHourlyVerificationViaAPI(t, router, owner.Token, database.ID)++ scheduler := GetVerificationScheduler()+ require.NoError(t, scheduler.createScheduledRuns())++ rows := ListVerificationsByDatabaseViaAPI(t, router, owner.Token, database.ID)+ require.Len(t, rows, 1)+ scheduledRowID := rows[0].ID++ CancelVerificationViaAPI(t, router, owner.Token, scheduledRowID)++ cancelled := GetVerificationByIDViaAPI(t, router, owner.Token, scheduledRowID)+ require.Equal(t, VerificationStatusCanceled, cancelled.Status)+ require.NotNil(t, cancelled.FinishedAt)+ cancelledFinishedAt := *cancelled.FinishedAt+ cancelledAttemptCount := cancelled.AttemptCount++ require.NoError(t, scheduler.createScheduledRuns())+ require.NoError(t, scheduler.reapStaleRuns())+ require.NoError(t, scheduler.sweepCanceledByDisabledConfig())++ final := GetVerificationByIDViaAPI(t, router, owner.Token, scheduledRowID)+ assert.Equal(t, VerificationStatusCanceled, final.Status)+ require.NotNil(t, final.FinishedAt)+ assert.True(+ t,+ final.FinishedAt.Equal(cancelledFinishedAt),+ "finished_at must not be rewritten after a row is CANCELED",+ )+ assert.Equal(t, cancelledAttemptCount, final.AttemptCount, "attempt_count must not advance after CANCELED")+}diff --git a/backend/internal/features/verification/runs/service.go b/backend/internal/features/verification/runs/service.gonew file mode 100644index 00000000..ec290776--- /dev/null+++ b/backend/internal/features/verification/runs/service.go@@ -0,0 +1,846 @@+package verification_runs++import (+ "errors"+ "fmt"+ "io"+ "log/slog"+ "slices"+ "time"++ "github.com/google/uuid"+ "gorm.io/gorm"++ "databasus-backend/internal/features/audit_logs"+ backups_core "databasus-backend/internal/features/backups/backups/core"+ backups_services "databasus-backend/internal/features/backups/backups/services"+ "databasus-backend/internal/features/databases"+ "databasus-backend/internal/features/databases/databases/postgresql"+ users_models "databasus-backend/internal/features/users/models"+ verification_agents "databasus-backend/internal/features/verification/agents"+ verification_config "databasus-backend/internal/features/verification/config"+ workspaces_services "databasus-backend/internal/features/workspaces/services"+ "databasus-backend/internal/storage"+)++type VerificationService struct {+ verificationRepository *VerificationRepository+ databaseService *databases.DatabaseService+ backupService *backups_services.BackupService+ configService *verification_config.VerificationConfigService+ notifierService NotificationSender+ workspaceService *workspaces_services.WorkspaceService+ auditLogService *audit_logs.AuditLogService+ logger *slog.Logger+}++func (s *VerificationService) EnqueueManualVerification(+ user *users_models.User,+ backupID uuid.UUID,+) (*RestoreVerification, error) {+ backup, err := s.backupService.GetBackup(backupID)+ if err != nil {+ return nil, err+ }++ if backup == nil {+ return nil, errors.New("backup not found")+ }++ database, err := s.databaseService.GetDatabaseByID(backup.DatabaseID)+ if err != nil {+ return nil, err+ }++ if database.WorkspaceID == nil {+ return nil, errors.New("cannot verify backup for database without workspace")+ }++ canManage, err := s.workspaceService.CanUserManageDBs(*database.WorkspaceID, user)+ if err != nil {+ return nil, err+ }+ if !canManage {+ return nil, errors.New("insufficient permissions to trigger verification for this database")+ }++ if err := s.guardBackupIsVerifiable(backup, database); err != nil {+ return nil, err+ }++ var created *RestoreVerification++ err = storage.GetDb().Transaction(func(tx *gorm.DB) error {+ existing, txErr := s.verificationRepository.FindNonTerminalForDatabase(tx, backup.DatabaseID)+ if txErr != nil {+ return txErr+ }++ for _, row := range existing {+ if row.Trigger == VerificationTriggerManual {+ return errors.New(+ "a manual verification is already scheduled for this database, please cancel it first",+ )+ }+ }++ verification := &RestoreVerification{+ ID: uuid.New(),+ DatabaseID: backup.DatabaseID,+ BackupID: backup.ID,+ Trigger: VerificationTriggerManual,+ Status: VerificationStatusPending,+ AttemptCount: 1,+ CreatedAt: time.Now().UTC(),+ }++ if createErr := tx.Create(verification).Error; createErr != nil {+ return createErr+ }++ created = verification+ return nil+ })+ if err != nil {+ return nil, err+ }++ s.auditLogService.WriteAuditLog(+ fmt.Sprintf("manual backup verification enqueued for database %q", database.Name),+ &user.ID,+ database.WorkspaceID,+ )++ return created, nil+}++func (s *VerificationService) OnBackupCompleted(backupID uuid.UUID) {+ s.scheduleVerificationForCompletedBackup(backupID)+}++func (s *VerificationService) CancelVerification(+ user *users_models.User,+ verificationID uuid.UUID,+) error {+ verification, err := s.verificationRepository.FindByID(verificationID)+ if err != nil {+ return err+ }++ if verification == nil {+ return errors.New("verification not found")+ }++ database, err := s.databaseService.GetDatabaseByID(verification.DatabaseID)+ if err != nil {+ return err+ }++ if database.WorkspaceID == nil {+ return errors.New("cannot cancel verification for database without workspace")+ }++ canManage, err := s.workspaceService.CanUserManageDBs(*database.WorkspaceID, user)+ if err != nil {+ return err+ }+ if !canManage {+ return errors.New("insufficient permissions to cancel verification for this database")+ }++ if verification.Status != VerificationStatusPending && verification.Status != VerificationStatusRunning {+ return fmt.Errorf("verification is not cancellable (status: %s)", verification.Status)+ }++ if err := s.verificationRepository.MarkTerminal(nil, verificationID, VerificationStatusCanceled, nil); err != nil {+ return err+ }++ s.auditLogService.WriteAuditLog(+ fmt.Sprintf("backup verification canceled for database %q", database.Name),+ &user.ID,+ database.WorkspaceID,+ )++ return nil+}++func (s *VerificationService) GetVerificationsByDatabaseID(+ user *users_models.User,+ databaseID uuid.UUID,+ limit, offset int,+) (*GetVerificationsResponse, error) {+ database, err := s.databaseService.GetDatabaseByID(databaseID)+ if err != nil {+ return nil, err+ }++ if database.WorkspaceID == nil {+ return nil, errors.New("cannot list verifications for database without workspace")+ }++ canAccess, _, err := s.workspaceService.CanUserAccessWorkspace(*database.WorkspaceID, user)+ if err != nil {+ return nil, err+ }+ if !canAccess {+ return nil, errors.New("insufficient permissions to view verifications for this database")+ }++ if limit <= 0 {+ limit = 10+ }+ if offset < 0 {+ offset = 0+ }++ verifications, err := s.verificationRepository.FindByDatabaseIDWithPagination(databaseID, limit, offset)+ if err != nil {+ return nil, err+ }++ total, err := s.verificationRepository.CountByDatabaseID(databaseID)+ if err != nil {+ return nil, err+ }++ return &GetVerificationsResponse{+ Verifications: verifications,+ Total: total,+ Limit: limit,+ Offset: offset,+ }, nil+}++func (s *VerificationService) GetVerificationByID(+ user *users_models.User,+ verificationID uuid.UUID,+) (*RestoreVerification, error) {+ verification, err := s.verificationRepository.FindByID(verificationID)+ if err != nil {+ return nil, err+ }++ if verification == nil {+ return nil, errors.New("verification not found")+ }++ database, err := s.databaseService.GetDatabaseByID(verification.DatabaseID)+ if err != nil {+ return nil, err+ }++ if database.WorkspaceID == nil {+ return nil, errors.New("cannot view verification for database without workspace")+ }++ canAccess, _, err := s.workspaceService.CanUserAccessWorkspace(*database.WorkspaceID, user)+ if err != nil {+ return nil, err+ }+ if !canAccess {+ return nil, errors.New("insufficient permissions to view this verification")+ }++ return verification, nil+}++func (s *VerificationService) ClaimVerification(+ agent *verification_agents.Agent,+ req *ClaimRequest,+) (*JobAssignment, error) {+ runningBackups, err := s.verificationRepository.ListRunningBackupsByAgentID(agent.ID)+ if err != nil {+ return nil, err+ }++ var assignment *JobAssignment++ err = storage.GetDb().Transaction(func(tx *gorm.DB) error {+ candidates, txErr := s.verificationRepository.FindOldestPendingClaimablesTop100(tx)+ if txErr != nil {+ return txErr+ }++ for _, candidate := range candidates {+ if !IsVerificationFitWithinRemainedDiskCapacity(req.Capacity, runningBackups, candidate.Backup) {+ continue+ }++ database, dbErr := s.databaseService.GetDatabaseByID(candidate.Verification.DatabaseID)+ if dbErr != nil {+ return dbErr+ }++ if validateErr := validateDatabaseIsVerifiable(database); validateErr != nil {+ s.logger.Warn(+ "skipping claim: database not verifiable",+ "verification_id", candidate.Verification.ID,+ "database_id", candidate.Verification.DatabaseID,+ "error", validateErr,+ )++ continue+ }++ now := time.Now().UTC()+ if claimErr := s.verificationRepository.UpdateClaim(+ tx,+ candidate.Verification.ID,+ agent.ID,+ now,+ ); claimErr != nil {+ return claimErr+ }++ assignment = &JobAssignment{+ VerificationID: candidate.Verification.ID,+ BackupID: candidate.Verification.BackupID,+ BackupSizeMb: candidate.Backup.BackupSizeMb,+ MaxContainerDiskMb: float64(EstimateRequiredForRestoreDiskMb(candidate.Backup)),+ Database: sanitizeDatabaseForAgent(database),+ }++ return nil+ }++ return nil+ })+ if err != nil {+ return nil, err+ }++ return assignment, nil+}++func (s *VerificationService) OnAgentHeartbeated(+ agent *verification_agents.Agent,+ currentVerificationIDs []uuid.UUID,+) ([]uuid.UUID, error) {+ ownedRunning, err := s.verificationRepository.FindRunningByAgent(agent.ID)+ if err != nil {+ return nil, err+ }++ reportedVerifications := make(map[uuid.UUID]struct{}, len(currentVerificationIDs))+ for _, id := range currentVerificationIDs {+ reportedVerifications[id] = struct{}{}+ }++ ownedVerifications := make(map[uuid.UUID]struct{}, len(ownedRunning))+ for _, row := range ownedRunning {+ ownedVerifications[row.ID] = struct{}{}+ }++ // An ID the agent reports that the backend no longer owns as RUNNING was+ // hard-deleted (config cascade) or flipped terminal/CANCELED by the reaper:+ // tell the agent to abort it.+ verificationsToAbort := make([]uuid.UUID, 0)+ for _, id := range currentVerificationIDs {+ if _, stillOwned := ownedVerifications[id]; !stillOwned {+ verificationsToAbort = append(verificationsToAbort, id)+ }+ }++ s.reclaimDroppedRunningJobs(agent, ownedRunning, reportedVerifications)++ return verificationsToAbort, nil+}++func (s *VerificationService) GetBackupFile(+ agent *verification_agents.Agent,+ verificationID uuid.UUID,+) (io.ReadCloser, error) {+ verification, err := s.verificationRepository.FindByID(verificationID)+ if err != nil {+ return nil, err+ }++ if verification == nil {+ return nil, errors.New("verification not found")+ }++ if verification.Status != VerificationStatusRunning {+ return nil, errors.New("verification is not in RUNNING state")+ }++ if verification.AgentID == nil || *verification.AgentID != agent.ID {+ return nil, errors.New("verification is not owned by this agent")+ }++ reader, _, _, err := s.backupService.GetBackupFileWithoutAuth(verification.BackupID)+ if err != nil {+ return nil, err+ }++ return reader, nil+}++func (s *VerificationService) SubmitReport(+ agent *verification_agents.Agent,+ verificationID uuid.UUID,+ req *ReportRequest,+) error {+ verification, err := s.verificationRepository.FindByID(verificationID)+ if err != nil {+ return err+ }++ if verification == nil {+ return errors.New("verification gone")+ }++ if req.Status == VerificationStatusFailed {+ return s.RequeueOrFail(verification, classifyAgentReport(req), req.FailMessage)+ }++ if restoredDbTooSmall, sizeMessage := s.isRestoredTooSmall(verification, req); restoredDbTooSmall {+ return s.RequeueOrFail(verification, FailureReasonRestoredTooSmall, &sizeMessage)+ }++ if err := s.verificationRepository.WriteSuccessReport(verificationID, agent.ID, req); err != nil {+ return err+ }++ s.syncBackupVerificationStatus(verification, VerificationStatusCompleted)+ s.notifyTerminal(verification, VerificationStatusCompleted, nil)++ return nil+}++func (s *VerificationService) RequeueOrFail(+ row *RestoreVerification,+ reason FailureReason,+ agentMessage *string,+) error {+ if shouldRequeueAgentSide(reason, row.AttemptCount) {+ return s.verificationRepository.Requeue(nil, row.ID)+ }++ failMessage := failureMessageFor(reason, agentMessage)++ if err := s.verificationRepository.MarkTerminal(nil, row.ID, VerificationStatusFailed, map[string]any{+ "fail_message": failMessage,+ }); err != nil {+ return err+ }++ // Re-read so the notification body reflects the row's freshly stamped finished_at.+ updated, err := s.verificationRepository.FindByID(row.ID)+ if err == nil && updated != nil {+ row = updated+ }++ s.syncBackupVerificationStatus(row, VerificationStatusFailed)+ s.notifyTerminal(row, VerificationStatusFailed, &failMessage)+ return nil+}++// reclaimDroppedRunningJobs requeues (or, once attempts are exhausted, fails)+// every RUNNING job this still-online agent owns that its heartbeat no longer+// lists — the agent dropped it (report given up after the retry budget, or the+// agent restarted mid-run). Rows younger than agentJobReclaimGrace are skipped:+// the claim stamps started_at before the owner has had a heartbeat cycle to+// report the job, so a just-claimed row is legitimately unreported for one+// cycle. Best-effort: it logs its own errors and never fails the heartbeat.+func (s *VerificationService) reclaimDroppedRunningJobs(+ agent *verification_agents.Agent,+ ownedRunning []*RestoreVerification,+ reported map[uuid.UUID]struct{},+) {+ reclaimEligibleBefore := time.Now().UTC().Add(-agentJobReclaimGrace)++ for _, row := range ownedRunning {+ if _, stillReported := reported[row.ID]; stillReported {+ continue+ }++ if row.StartedAt == nil || !row.StartedAt.Before(reclaimEligibleBefore) {+ continue+ }++ logger := s.logger.With("verification_id", row.ID, "agent_id", agent.ID)+ logger.Info("reclaiming dropped verification")++ if err := s.RequeueOrFail(row, FailureReasonAgentDroppedJob, nil); err != nil {+ logger.Error("failed to reclaim dropped verification", "error", err)+ }+ }+}++func (s *VerificationService) scheduleVerificationForCompletedBackup(backupID uuid.UUID) {+ logger := s.logger.With("backup_id", backupID)++ backup, err := s.backupService.GetBackup(backupID)+ if err != nil || backup == nil {+ return+ }++ databaseID := backup.DatabaseID+ logger = logger.With("database_id", databaseID)++ config, err := s.configService.GetByDatabaseIDNoAuth(databaseID)+ if err != nil {+ logger.Error("failed to load verification config on backup completion", "error", err)+ return+ }++ if config == nil ||+ !config.IsScheduledVerificationEnabled ||+ config.ScheduleType != verification_config.VerificationScheduleAfterBackup {+ return+ }++ verifiableBackup, err := s.backupService.GetLatestVerifiableBackup(databaseID)+ if err != nil {+ logger.Error("failed to load latest verifiable backup", "error", err)+ return+ }++ if verifiableBackup == nil {+ logger.Info("skipping after-backup verification: no verifiable backup yet")+ return+ }++ database, err := s.databaseService.GetDatabaseByID(databaseID)+ if err != nil {+ logger.Error("failed to load database for after-backup verification", "error", err)+ return+ }++ if err := validateDatabaseIsVerifiable(database); err != nil {+ logger.Warn("skipping after-backup verification: database not verifiable", "error", err)+ return+ }++ err = storage.GetDb().Transaction(func(tx *gorm.DB) error {+ if cancelErr := s.cancelPendingAutoScheduledVerificationsByDatabaseID(tx, databaseID); cancelErr != nil {+ return cancelErr+ }++ return tx.Create(&RestoreVerification{+ ID: uuid.New(),+ DatabaseID: databaseID,+ BackupID: verifiableBackup.ID,+ Trigger: VerificationTriggerAfterBackup,+ Status: VerificationStatusPending,+ AttemptCount: 1,+ CreatedAt: time.Now().UTC(),+ }).Error+ })+ if err != nil {+ logger.Error("failed to enqueue after-backup verification", "error", err)+ }+}++func (s *VerificationService) cancelPendingAutoScheduledVerificationsByDatabaseID(+ tx *gorm.DB,+ databaseID uuid.UUID,+) error {+ existing, err := s.verificationRepository.FindNonTerminalForDatabase(tx, databaseID)+ if err != nil {+ return err+ }++ for _, row := range existing {+ if row.Trigger == VerificationTriggerManual {+ continue+ }++ if row.Status == VerificationStatusPending {+ if cancelErr := s.verificationRepository.MarkTerminal(+ tx, row.ID, VerificationStatusCanceled, nil,+ ); cancelErr != nil {+ return cancelErr+ }+ }+ }++ return nil+}++func isAgentSideFailure(reason FailureReason) bool {+ return reason == FailureReasonAgentLostContact ||+ reason == FailureReasonAgentRemoved ||+ reason == FailureReasonAgentSetupFailed ||+ reason == FailureReasonAgentDroppedJob+}++// shouldRequeueAgentSide is the single retry-vs-terminal policy: an agent-side+// failure with attempts left is requeued; everything else goes terminal+func shouldRequeueAgentSide(reason FailureReason, attemptCount int) bool {+ return isAgentSideFailure(reason) && attemptCount < MaxAgentSideAttempts+}++func classifyAgentReport(req *ReportRequest) FailureReason {+ if req.FailureKind != nil && *req.FailureKind == string(FailureReasonDiskLimitExceeded) {+ return FailureReasonDiskLimitExceeded+ }++ if req.PgRestoreExitCode != nil {+ return FailureReasonBackupRejected+ }++ return FailureReasonAgentSetupFailed+}++func (s *VerificationService) isRestoredTooSmall(+ verification *RestoreVerification,+ req *ReportRequest,+) (bool, string) {+ if req.DBSizeBytesAfterRestore == nil {+ return false, ""+ }++ backup, err := s.backupService.GetBackup(verification.BackupID)+ if err != nil || backup == nil || backup.BackupRawDbSizeMb <= 0 {+ return false, ""+ }++ rawDbSizeBytes := int64(backup.BackupRawDbSizeMb * 1024 * 1024)+ minAcceptableBytes := int64(float64(rawDbSizeBytes) * minRestoredSizeRatio)++ if *req.DBSizeBytesAfterRestore >= minAcceptableBytes {+ return false, ""+ }++ message := fmt.Sprintf(+ "restored database is %d bytes, which is less than %.0f%% of the original size (%d bytes)",+ *req.DBSizeBytesAfterRestore, minRestoredSizeRatio*100, rawDbSizeBytes,+ )++ return true, message+}++func (s *VerificationService) syncBackupVerificationStatus(+ verification *RestoreVerification,+ terminalStatus VerificationStatus,+) {+ var status backups_core.RestoreVerificationStatus++ switch terminalStatus {+ case VerificationStatusCompleted:+ status = backups_core.RestoreVerificationStatusVerifiedSuccessful+ case VerificationStatusFailed:+ status = backups_core.RestoreVerificationStatusVerificationFailed+ default:+ return+ }++ if err := s.backupService.SetRestoreVerificationStatus(verification.BackupID, status); err != nil {+ s.logger.Error(+ "failed to sync backup restore-verification status",+ "error", err,+ "verification_id", verification.ID,+ "backup_id", verification.BackupID,+ )+ }+}++func (s *VerificationService) notifyTerminal(+ verification *RestoreVerification,+ terminalStatus VerificationStatus,+ failMessage *string,+) {+ if terminalStatus == VerificationStatusCanceled {+ return+ }++ config, err := s.configService.GetByDatabaseIDNoAuth(verification.DatabaseID)+ if err != nil {+ s.logger.Error(+ "failed to load verification config for notification",+ "error", err,+ "verification_id", verification.ID,+ )++ return+ }++ if config == nil {+ return+ }++ wantedType := verification_config.NotificationVerificationSuccess+ if terminalStatus == VerificationStatusFailed {+ wantedType = verification_config.NotificationVerificationFailed+ }++ if !slices.Contains(config.SendNotificationsOn, wantedType) {+ return+ }++ database, err := s.databaseService.GetDatabaseByID(verification.DatabaseID)+ if err != nil {+ s.logger.Error(+ "failed to load database for notification",+ "error", err,+ "verification_id", verification.ID,+ )++ return+ }++ if database.WorkspaceID == nil {+ return+ }++ title, body := buildNotificationCopy(verification, database, terminalStatus, failMessage)++ for i := range database.Notifiers {+ notifier := database.Notifiers[i]+ go s.notifierService.SendNotification(¬ifier, title, body)+ }+}++func (s *VerificationService) guardBackupIsVerifiable(+ backup *backups_core.Backup,+ database *databases.Database,+) error {+ if backup.Status != backups_core.BackupStatusCompleted {+ return errors.New("only COMPLETED backups can be verified")+ }++ if backup.PgWalBackupType != nil {+ return errors.New("WAL segments cannot be verified standalone; only PG_DUMP backups are supported")+ }++ if database.Postgresql != nil &&+ database.Postgresql.BackupType == postgresql.PostgresBackupTypeWalV1 {+ return errors.New("verification is not supported for WAL-based databases")+ }++ return nil+}++// validateDatabaseIsVerifiable rejects databases the agent cannot restore yet:+// non-postgres engines (no agent support today) and postgres rows missing a+// version (so the agent would have no client binary to pick). The scheduler+// uses this to skip enqueueing; the claim path uses it to skip handing a+// no-op job to an agent.+func validateDatabaseIsVerifiable(database *databases.Database) error {+ switch database.Type {+ case databases.DatabaseTypePostgres:+ if database.Postgresql == nil || database.Postgresql.Version == "" {+ return errors.New("postgresql sub-row missing or version empty")+ }++ return nil+ default:+ return fmt.Errorf("database type %q not supported for verification yet", database.Type)+ }+}++// sanitizeDatabaseForAgent strips every field the agent has no business seeing+// before the row goes over the wire: engine-specific credentials via the+// existing HideSensitiveData contract, notifier secrets (webhook URLs, SMTP+// creds), and the agent token. Mutates the passed row in place — gorm doesn't+// auto-save, and the caller owns the row from GetDatabaseByID.+func sanitizeDatabaseForAgent(database *databases.Database) *databases.Database {+ database.HideSensitiveData()+ database.Notifiers = nil+ database.AgentToken = nil++ return database+}++func failureMessageFor(reason FailureReason, agentMessage *string) string {+ hasAgentMessage := agentMessage != nil && *agentMessage != ""++ switch reason {+ case FailureReasonAgentSetupFailed:+ if hasAgentMessage {+ return *agentMessage+ }++ return "agent failed before pg_restore ran (download, container, or OOM) without diagnostic detail"+ case FailureReasonBackupRejected:+ if hasAgentMessage {+ return *agentMessage+ }++ return "pg_restore rejected the backup without diagnostic detail"+ case FailureReasonDiskLimitExceeded:+ if hasAgentMessage {+ return *agentMessage+ }++ return "restore exceeded the per-job disk budget"+ case FailureReasonRestoredTooSmall:+ if hasAgentMessage {+ return *agentMessage+ }++ return "restored database is smaller than expected vs the original raw size"+ case FailureReasonAgentLostContact:+ return "verification stalled: agent went silent"+ case FailureReasonAgentRemoved:+ return "verification failed: the owning agent was removed before the run finished"+ case FailureReasonAgentDroppedJob:+ return "verification was dropped by its still-online agent before it reported a result (likely a report-delivery failure or an agent restart mid-run)"+ case FailureReasonUnclaimedTooLong:+ return "verification was not picked up by any agent in time"+ default:+ return "verification failed"+ }+}++func buildNotificationCopy(+ verification *RestoreVerification,+ database *databases.Database,+ terminalStatus VerificationStatus,+ failMessage *string,+) (title, body string) {+ workspaceLabel := ""+ if database.WorkspaceID != nil {+ workspaceLabel = fmt.Sprintf(" (workspace %q)", database.WorkspaceID.String())+ }++ if terminalStatus == VerificationStatusCompleted {+ title = fmt.Sprintf("backup verification passed for %q%s", database.Name, workspaceLabel)+ } else {+ title = fmt.Sprintf(+ "backup verification failed after %d attempts for %q%s",+ verification.AttemptCount, database.Name, workspaceLabel,+ )+ }++ bodyParts := []string{+ fmt.Sprintf("verification id: %s", verification.ID),+ fmt.Sprintf("backup id: %s", verification.BackupID),+ fmt.Sprintf("attempt: %d", verification.AttemptCount),+ }++ if verification.RestoreDurationMs != nil {+ bodyParts = append(bodyParts, fmt.Sprintf("restore duration: %d ms", *verification.RestoreDurationMs))+ }+ if verification.VerifyDurationMs != nil {+ bodyParts = append(bodyParts, fmt.Sprintf("verify duration: %d ms", *verification.VerifyDurationMs))+ }+ if verification.DBSizeBytesAfterRestore != nil {+ bodyParts = append(bodyParts, fmt.Sprintf("db size: %d bytes", *verification.DBSizeBytesAfterRestore))+ }+ if verification.TableCount != nil {+ bodyParts = append(bodyParts, fmt.Sprintf("table count: %d", *verification.TableCount))+ }++ if failMessage != nil && *failMessage != "" {+ messageRunes := []rune(*failMessage)+ if len(messageRunes) > 2000 {+ messageRunes = messageRunes[:2000]+ }++ bodyParts = append(bodyParts, fmt.Sprintf("error: %s", string(messageRunes)))+ }++ body = ""+ for i, part := range bodyParts {+ if i > 0 {+ body += "\n"+ }++ body += part+ }++ return title, body+}diff --git a/backend/internal/features/verification/runs/testing.go b/backend/internal/features/verification/runs/testing.gonew file mode 100644index 00000000..71dd9e4a--- /dev/null+++ b/backend/internal/features/verification/runs/testing.go@@ -0,0 +1,147 @@+package verification_runs++import (+ "net/http"+ "testing"++ "github.com/gin-gonic/gin"+ "github.com/google/uuid"++ backups_core "databasus-backend/internal/features/backups/backups/core"+ backups_dto "databasus-backend/internal/features/backups/backups/dto"+ test_utils "databasus-backend/internal/util/testing"+)++func EnqueueManualVerificationViaAPI(+ t *testing.T,+ router *gin.Engine,+ userToken string,+ backupID uuid.UUID,+) *RestoreVerification {+ t.Helper()++ var response RestoreVerification+ test_utils.MakePostRequestAndUnmarshal(+ t,+ router,+ "/api/v1/verifications/enqueue",+ "Bearer "+userToken,+ EnqueueManualRequest{BackupID: backupID},+ http.StatusOK,+ &response,+ )++ return &response+}++func CancelVerificationViaAPI(+ t *testing.T,+ router *gin.Engine,+ userToken string,+ verificationID uuid.UUID,+) {+ t.Helper()++ test_utils.MakePostRequest(+ t,+ router,+ "/api/v1/verifications/"+verificationID.String()+"/cancel",+ "Bearer "+userToken,+ nil,+ http.StatusNoContent,+ )+}++func GetVerificationByIDViaAPI(+ t *testing.T,+ router *gin.Engine,+ userToken string,+ verificationID uuid.UUID,+) *RestoreVerification {+ t.Helper()++ var response RestoreVerification+ test_utils.MakeGetRequestAndUnmarshal(+ t,+ router,+ "/api/v1/verifications/"+verificationID.String(),+ "Bearer "+userToken,+ http.StatusOK,+ &response,+ )++ return &response+}++func ClaimVerificationViaAPI(+ t *testing.T,+ router *gin.Engine,+ agentID uuid.UUID,+ agentToken string,+ capacity AgentCapacity,+) *JobAssignment {+ t.Helper()++ var response JobAssignment+ test_utils.MakePostRequestAndUnmarshal(+ t,+ router,+ "/api/v1/agent/verifications/"+agentID.String()+"/claim",+ "Bearer "+agentToken,+ ClaimRequest{Capacity: capacity},+ http.StatusOK,+ &response,+ )++ return &response+}++func GetBackupViaAPI(+ t *testing.T,+ router *gin.Engine,+ userToken string,+ databaseID, backupID uuid.UUID,+) *backups_core.Backup {+ t.Helper()++ var response backups_dto.GetBackupsResponse+ test_utils.MakeGetRequestAndUnmarshal(+ t,+ router,+ "/api/v1/backups?database_id="+databaseID.String()+"&limit=1000",+ "Bearer "+userToken,+ http.StatusOK,+ &response,+ )++ for _, backup := range response.Backups {+ if backup.ID == backupID {+ return backup+ }+ }++ t.Fatalf("backup %s not found for database %s", backupID, databaseID)++ return nil+}++func ListVerificationsByDatabaseViaAPI(+ t *testing.T,+ router *gin.Engine,+ userToken string,+ databaseID uuid.UUID,+) []*RestoreVerification {+ t.Helper()++ var response GetVerificationsResponse+ test_utils.MakeGetRequestAndUnmarshal(+ t,+ router,+ "/api/v1/verifications/by-database/"+databaseID.String()+"?limit=1000",+ "Bearer "+userToken,+ http.StatusOK,+ &response,+ )++ return response.Verifications+}diff --git a/backend/migrations/20260520120000_add_restore_verification.sql b/backend/migrations/20260520120000_add_restore_verification.sqlnew file mode 100644index 00000000..1f06adaa--- /dev/null+++ b/backend/migrations/20260520120000_add_restore_verification.sql@@ -0,0 +1,202 @@+-- +goose Up+-- +goose StatementBegin++CREATE TABLE verification_agents (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ name TEXT NOT NULL,+ token_hash TEXT NOT NULL,+ max_cpu INTEGER NOT NULL DEFAULT 0,+ max_ram_gb INTEGER NOT NULL DEFAULT 0,+ max_disk_gb INTEGER NOT NULL DEFAULT 0,+ max_concurrent_jobs INTEGER NOT NULL DEFAULT 0,+ last_seen_at TIMESTAMPTZ,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ deleted_at TIMESTAMPTZ+);++CREATE UNIQUE INDEX idx_verification_agents_token_hash+ ON verification_agents (token_hash);++ALTER TABLE backup_configs+ ADD COLUMN interval_type TEXT,+ ADD COLUMN time_of_day TEXT,+ ADD COLUMN weekday INTEGER,+ ADD COLUMN day_of_month INTEGER,+ ADD COLUMN cron_expression TEXT;++UPDATE backup_configs bc+SET interval_type = i.interval,+ time_of_day = i.time_of_day,+ weekday = i.weekday,+ day_of_month = i.day_of_month,+ cron_expression = i.cron_expression+FROM intervals i+WHERE bc.backup_interval_id = i.id;++UPDATE backup_configs+SET interval_type = 'DAILY',+ time_of_day = '04:00'+WHERE interval_type IS NULL;++ALTER TABLE backup_configs+ ALTER COLUMN interval_type SET NOT NULL;++ALTER TABLE backup_configs+ DROP CONSTRAINT IF EXISTS fk_backup_config_backup_interval_id;++ALTER TABLE backup_configs+ DROP COLUMN backup_interval_id;++DROP TABLE intervals;++CREATE TABLE backup_verification_configs (+ database_id UUID PRIMARY KEY,++ is_scheduled_verification_enabled BOOLEAN NOT NULL DEFAULT FALSE,++ interval_type TEXT NOT NULL DEFAULT 'WEEKLY',+ time_of_day TEXT,+ weekday INTEGER,+ day_of_month INTEGER,+ cron_expression TEXT,++ send_notifications_on TEXT NOT NULL DEFAULT '',+ schedule_type TEXT NOT NULL DEFAULT 'AFTER_BACKUP',++ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()+);++ALTER TABLE backup_verification_configs+ ADD CONSTRAINT fk_backup_verification_configs_database+ FOREIGN KEY (database_id)+ REFERENCES databases (id)+ ON DELETE CASCADE;++CREATE TABLE restore_verifications (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ database_id UUID NOT NULL,+ backup_id UUID NOT NULL,+ agent_id UUID,++ trigger TEXT NOT NULL,+ status TEXT NOT NULL DEFAULT 'PENDING',++ attempt_count INTEGER NOT NULL DEFAULT 1,++ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ started_at TIMESTAMPTZ,+ finished_at TIMESTAMPTZ,++ restore_duration_ms BIGINT,+ verify_duration_ms BIGINT,++ pg_restore_exit_code INTEGER,+ db_size_bytes_after_restore BIGINT,+ table_count INTEGER,+ schema_count INTEGER,+ fail_message TEXT+);++ALTER TABLE restore_verifications+ ADD CONSTRAINT fk_restore_verifications_database+ FOREIGN KEY (database_id)+ REFERENCES databases (id)+ ON DELETE CASCADE;++ALTER TABLE restore_verifications+ ADD CONSTRAINT fk_restore_verifications_backup+ FOREIGN KEY (backup_id)+ REFERENCES backups (id)+ ON DELETE CASCADE;++ALTER TABLE restore_verifications+ ADD CONSTRAINT fk_restore_verifications_agent+ FOREIGN KEY (agent_id)+ REFERENCES verification_agents (id)+ ON DELETE SET NULL;++CREATE INDEX idx_restore_verifications_database_created+ ON restore_verifications (database_id, created_at);++CREATE INDEX idx_restore_verifications_status_created+ ON restore_verifications (status, created_at);++CREATE INDEX idx_restore_verifications_agent_status+ ON restore_verifications (agent_id, status);++CREATE TABLE restore_verification_table_stats (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ restore_verification_id UUID NOT NULL,+ schema_name TEXT NOT NULL,+ name TEXT NOT NULL,+ row_count BIGINT NOT NULL+);++ALTER TABLE restore_verification_table_stats+ ADD CONSTRAINT fk_restore_verification_table_stats_verification+ FOREIGN KEY (restore_verification_id)+ REFERENCES restore_verifications (id)+ ON DELETE CASCADE;++CREATE INDEX idx_restore_verification_table_stats_verification+ ON restore_verification_table_stats (restore_verification_id);++ALTER TABLE backups+ ADD COLUMN restore_verification_status TEXT NOT NULL DEFAULT 'NOT_VERIFIED';++-- +goose StatementEnd++-- +goose Down+-- +goose StatementBegin++ALTER TABLE backups+ DROP COLUMN restore_verification_status;++DROP TABLE restore_verification_table_stats;+DROP TABLE restore_verifications;+DROP TABLE backup_verification_configs;+DROP TABLE verification_agents;++CREATE TABLE intervals (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ interval TEXT NOT NULL,+ time_of_day TEXT,+ weekday INTEGER,+ day_of_month INTEGER,+ cron_expression TEXT+);++ALTER TABLE backup_configs ADD COLUMN backup_interval_id UUID;++DO $$+DECLARE+ bc RECORD;+ new_id UUID;+BEGIN+ FOR bc IN SELECT database_id, interval_type, time_of_day, weekday, day_of_month, cron_expression+ FROM backup_configs WHERE backup_interval_id IS NULL+ LOOP+ INSERT INTO intervals (id, interval, time_of_day, weekday, day_of_month, cron_expression)+ VALUES (gen_random_uuid(), bc.interval_type, bc.time_of_day, bc.weekday, bc.day_of_month, bc.cron_expression)+ RETURNING id INTO new_id;++ UPDATE backup_configs SET backup_interval_id = new_id WHERE database_id = bc.database_id;+ END LOOP;+END $$;++ALTER TABLE backup_configs ALTER COLUMN backup_interval_id SET NOT NULL;++ALTER TABLE backup_configs+ ADD CONSTRAINT fk_backup_config_backup_interval_id+ FOREIGN KEY (backup_interval_id)+ REFERENCES intervals (id);++ALTER TABLE backup_configs+ DROP COLUMN interval_type,+ DROP COLUMN time_of_day,+ DROP COLUMN weekday,+ DROP COLUMN day_of_month,+ DROP COLUMN cron_expression;++-- +goose StatementEnddiff --git a/frontend/CLAUDE.md b/frontend/CLAUDE.mdindex 184a9f17..38e8eb07 100644--- a/frontend/CLAUDE.md+++ b/frontend/CLAUDE.md@@ -9,6 +9,7 @@ For project-wide engineering philosophy, see the root `CLAUDE.md`.- [UI kit and icons](#ui-kit-and-icons)- [React component structure](#react-component-structure)+- [Vertical spacing](#vertical-spacing)- [Clipboard operations](#clipboard-operations)- [Forms](#forms)- [User-facing copy](#user-facing-copy)@@ -64,11 +65,19 @@ export const ReactComponent = ({ someValue }: Props): JSX.Element => {2. **Helper functions** (outside component) — Pure utility functions3. **Component declaration**- **States** — `useState` declarations- - **Functions** — Event handlers and async operations- - **Hooks** — `useEffect`, `useMemo`, `useCallback`, etc.- - **Calculated values** — Derived data from props/state+ - **Plain functions** — Event handlers, async operations, in-component formatters. Anything that does _not_ call a React hook.+ - **Hooks** — `useRef` + ref mutation, `useCallback`, `useMemo`, `useEffect`. A function wrapped in `useCallback` is a hook — it lives here, not in the functions section.+ - **Calculated values** — Derived data computed inline (e.g. an AntD `columns` array).- **Return** — JSX markup+**All hooks (including every `useEffect`) come below every plain function definition.** If a `useEffect` reads a handler, the handler must be defined above it — don't reorder by putting handlers below the effects.++---++## Vertical spacing++- Structure function bodies with vertical rhythm. Put a blank line between logically distinct steps (setup / main work / return, independent branches, before and after a guard). Do not leave blank lines at the start or end of a body, never stack two in a row. Do not insert blanks inside a tight expression, a single statement split across lines, or a short (≤ 5-line) function. If blank lines alone aren't enough to navigate a body, extract — don't add comments.+---## Clipboard operations@@ -159,6 +168,15 @@ import { Button } from '@/shared/ui/Button';// ✅ model/user.ts, model/backup.ts, api/fetch-database.ts```4. **No business logic in `shared/`.** Shared holds only infrastructure. Domain calculations live in `entities/` or higher.+5. **One type per file in `model/` / DTOs.** Each `interface`, `class`, or `enum` that represents a domain entity, DTO, request body, or response shape gets its own file in `model/` (or `models/`), named after the type. Don't co-locate sibling types like `Foo` + `FooStatus` + `FooResponse` in a single `Foo.ts` — split them. Re-export each from the slice `index.ts` so consumers still import from the slice's public API.+ ```text+ // ❌ model/RestoreVerification.ts — enums + table-stat + main interface all in one file+ // ✅ model/RestoreVerification.ts — interface RestoreVerification+ // ✅ model/RestoreVerificationTableStat.ts — interface RestoreVerificationTableStat+ // ✅ model/VerificationStatus.ts — enum VerificationStatus+ // ✅ model/VerificationTrigger.ts — enum VerificationTrigger+ ```+ Tiny shape-only helper types tightly coupled to a parent type (a literal-union alias, a `Pick<>`) may stay in the parent's file. Splitting applies to anything with its own identity — anything you'd reasonably import on its own elsewhere.### Segments inside a slicediff --git a/frontend/src/entity/backups/index.ts b/frontend/src/entity/backups/index.tsindex 0a1e2627..6db307a3 100644--- a/frontend/src/entity/backups/index.ts+++ b/frontend/src/entity/backups/index.ts@@ -6,5 +6,6 @@ export type { BackupConfig } from './model/BackupConfig';export { BackupNotificationType } from './model/BackupNotificationType';export { BackupEncryption } from './model/BackupEncryption';export { PgWalBackupType } from './model/PgWalBackupType';+export { RestoreVerificationStatus } from './model/RestoreVerificationStatus';export { RetentionPolicyType } from './model/RetentionPolicyType';export type { TransferDatabaseRequest } from './model/TransferDatabaseRequest';diff --git a/frontend/src/entity/backups/model/Backup.ts b/frontend/src/entity/backups/model/Backup.tsindex b3c29e9c..0327892c 100644--- a/frontend/src/entity/backups/model/Backup.ts+++ b/frontend/src/entity/backups/model/Backup.ts@@ -3,6 +3,7 @@ import type { Storage } from '../../storages';import { BackupEncryption } from './BackupEncryption';import { BackupStatus } from './BackupStatus';import type { PgWalBackupType } from './PgWalBackupType';+import { RestoreVerificationStatus } from './RestoreVerificationStatus';export interface Backup {id: string;@@ -15,5 +16,6 @@ export interface Backup {backupDurationMs: number;encryption: BackupEncryption;pgWalBackupType?: PgWalBackupType;+ restoreVerificationStatus?: RestoreVerificationStatus;createdAt: Date;}diff --git a/frontend/src/entity/backups/model/RestoreVerificationStatus.ts b/frontend/src/entity/backups/model/RestoreVerificationStatus.tsnew file mode 100644index 00000000..5c9aca29--- /dev/null+++ b/frontend/src/entity/backups/model/RestoreVerificationStatus.ts@@ -0,0 +1,5 @@+export enum RestoreVerificationStatus {+ NOT_VERIFIED = 'NOT_VERIFIED',+ VERIFIED_SUCCESSFUL = 'VERIFIED_SUCCESSFUL',+ VERIFICATION_FAILED = 'VERIFICATION_FAILED',+}diff --git a/frontend/src/entity/intervals/model/Interval.ts b/frontend/src/entity/intervals/model/Interval.tsindex 9293b5bf..b483a957 100644--- a/frontend/src/entity/intervals/model/Interval.ts+++ b/frontend/src/entity/intervals/model/Interval.ts@@ -1,13 +1,9 @@import type { IntervalType } from './IntervalType';export interface Interval {- id: string;- interval: IntervalType;+ type: IntervalType;timeOfDay: string;- // only for WEEKLYweekday?: number;- // only for MONTHLYdayOfMonth?: number;- // only for CRONcronExpression?: string;}diff --git a/frontend/src/entity/verification/agents/api/verificationAgentApi.ts b/frontend/src/entity/verification/agents/api/verificationAgentApi.tsnew file mode 100644index 00000000..94781f2c--- /dev/null+++ b/frontend/src/entity/verification/agents/api/verificationAgentApi.ts@@ -0,0 +1,55 @@+import { getApplicationServer } from '../../../../constants';+import RequestOptions from '../../../../shared/api/RequestOptions';+import { apiHelper } from '../../../../shared/api/apiHelper';+import type {+ CreatedAgentResponse,+ RotateTokenResponse,+ VerificationAgent,+ VerificationAgentAvailability,+} from '../models/VerificationAgent';++export const verificationAgentApi = {+ async listAgents() {+ const requestOptions: RequestOptions = new RequestOptions();+ return apiHelper.fetchGetJson<VerificationAgent[]>(+ `${getApplicationServer()}/api/v1/verification/agents`,+ requestOptions,+ true,+ );+ },++ async getAvailability() {+ const requestOptions: RequestOptions = new RequestOptions();+ return apiHelper.fetchGetJson<VerificationAgentAvailability>(+ `${getApplicationServer()}/api/v1/verification/agents/availability`,+ requestOptions,+ true,+ );+ },++ async createAgent(name: string) {+ const requestOptions: RequestOptions = new RequestOptions();+ requestOptions.setBody(JSON.stringify({ name }));+ return apiHelper.fetchPostJson<CreatedAgentResponse>(+ `${getApplicationServer()}/api/v1/verification/agents`,+ requestOptions,+ );+ },++ async rotateToken(id: string) {+ const requestOptions: RequestOptions = new RequestOptions();+ requestOptions.setBody(JSON.stringify({}));+ return apiHelper.fetchPostJson<RotateTokenResponse>(+ `${getApplicationServer()}/api/v1/verification/agents/${id}/rotate-token`,+ requestOptions,+ );+ },++ async deleteAgent(id: string) {+ const requestOptions: RequestOptions = new RequestOptions();+ return apiHelper.fetchDeleteJson(+ `${getApplicationServer()}/api/v1/verification/agents/${id}`,+ requestOptions,+ );+ },+};diff --git a/frontend/src/entity/verification/agents/index.ts b/frontend/src/entity/verification/agents/index.tsnew file mode 100644index 00000000..64ad6a4c--- /dev/null+++ b/frontend/src/entity/verification/agents/index.ts@@ -0,0 +1,7 @@+export { verificationAgentApi } from './api/verificationAgentApi';+export type {+ CreatedAgentResponse,+ RotateTokenResponse,+ VerificationAgent,+ VerificationAgentAvailability,+} from './models/VerificationAgent';diff --git a/frontend/src/entity/verification/agents/models/VerificationAgent.ts b/frontend/src/entity/verification/agents/models/VerificationAgent.tsnew file mode 100644index 00000000..e3c1bec0--- /dev/null+++ b/frontend/src/entity/verification/agents/models/VerificationAgent.ts@@ -0,0 +1,24 @@+export interface VerificationAgent {+ id: string;+ name: string;+ maxCpu: number;+ maxRamGb: number;+ maxDiskGb: number;+ maxConcurrentJobs: number;+ lastSeenAt?: string;+ createdAt: string;+}++export interface CreatedAgentResponse {+ agent: VerificationAgent;+ token: string;+}++export interface RotateTokenResponse {+ token: string;+}++export interface VerificationAgentAvailability {+ count: number;+ hasAgents: boolean;+}diff --git a/frontend/src/entity/verification/config/api/verificationConfigApi.ts b/frontend/src/entity/verification/config/api/verificationConfigApi.tsnew file mode 100644index 00000000..9a6a83ef--- /dev/null+++ b/frontend/src/entity/verification/config/api/verificationConfigApi.ts@@ -0,0 +1,24 @@+import { getApplicationServer } from '../../../../constants';+import RequestOptions from '../../../../shared/api/RequestOptions';+import { apiHelper } from '../../../../shared/api/apiHelper';+import type { BackupVerificationConfig } from '../models/BackupVerificationConfig';++export const verificationConfigApi = {+ async getByDatabaseId(databaseId: string) {+ const requestOptions: RequestOptions = new RequestOptions();+ return apiHelper.fetchGetJson<BackupVerificationConfig>(+ `${getApplicationServer()}/api/v1/verification-config/${databaseId}`,+ requestOptions,+ true,+ );+ },++ async save(databaseId: string, config: BackupVerificationConfig) {+ const requestOptions: RequestOptions = new RequestOptions();+ requestOptions.setBody(JSON.stringify(config));+ return apiHelper.fetchPutJson<BackupVerificationConfig>(+ `${getApplicationServer()}/api/v1/verification-config/${databaseId}`,+ requestOptions,+ );+ },+};diff --git a/frontend/src/entity/verification/config/index.ts b/frontend/src/entity/verification/config/index.tsnew file mode 100644index 00000000..617563f3--- /dev/null+++ b/frontend/src/entity/verification/config/index.ts@@ -0,0 +1,4 @@+export { verificationConfigApi } from './api/verificationConfigApi';+export type { BackupVerificationConfig } from './models/BackupVerificationConfig';+export { VerificationNotificationType } from './models/VerificationNotificationType';+export { VerificationScheduleType } from './models/VerificationScheduleType';diff --git a/frontend/src/entity/verification/config/models/BackupVerificationConfig.ts b/frontend/src/entity/verification/config/models/BackupVerificationConfig.tsnew file mode 100644index 00000000..032009aa--- /dev/null+++ b/frontend/src/entity/verification/config/models/BackupVerificationConfig.ts@@ -0,0 +1,13 @@+import type { Interval } from '../../../intervals';+import type { VerificationNotificationType } from './VerificationNotificationType';+import type { VerificationScheduleType } from './VerificationScheduleType';++export interface BackupVerificationConfig {+ databaseId: string;+ isScheduledVerificationEnabled: boolean;+ scheduleType: VerificationScheduleType;+ verificationInterval: Interval;+ sendNotificationsOn: VerificationNotificationType[];+ createdAt: string;+ updatedAt: string;+}diff --git a/frontend/src/entity/verification/config/models/VerificationNotificationType.ts b/frontend/src/entity/verification/config/models/VerificationNotificationType.tsnew file mode 100644index 00000000..a7a94467--- /dev/null+++ b/frontend/src/entity/verification/config/models/VerificationNotificationType.ts@@ -0,0 +1,4 @@+export enum VerificationNotificationType {+ VerificationSuccess = 'VERIFICATION_SUCCESS',+ VerificationFailed = 'VERIFICATION_FAILED',+}diff --git a/frontend/src/entity/verification/config/models/VerificationScheduleType.ts b/frontend/src/entity/verification/config/models/VerificationScheduleType.tsnew file mode 100644index 00000000..6dd7f18f--- /dev/null+++ b/frontend/src/entity/verification/config/models/VerificationScheduleType.ts@@ -0,0 +1,4 @@+export enum VerificationScheduleType {+ INTERVAL = 'INTERVAL',+ AFTER_BACKUP = 'AFTER_BACKUP',+}diff --git a/frontend/src/entity/verification/runs/api/verificationRunsApi.ts b/frontend/src/entity/verification/runs/api/verificationRunsApi.tsnew file mode 100644index 00000000..cc6a3322--- /dev/null+++ b/frontend/src/entity/verification/runs/api/verificationRunsApi.ts@@ -0,0 +1,42 @@+import { getApplicationServer } from '../../../../constants';+import RequestOptions from '../../../../shared/api/RequestOptions';+import { apiHelper } from '../../../../shared/api/apiHelper';+import type { GetVerificationsResponse } from '../models/GetVerificationsResponse';+import type { RestoreVerification } from '../models/RestoreVerification';++export const verificationRunsApi = {+ async listByDatabase(databaseId: string, limit?: number, offset?: number) {+ const params = new URLSearchParams();+ if (limit !== undefined) params.append('limit', limit.toString());+ if (offset !== undefined) params.append('offset', offset.toString());++ const query = params.toString();+ return apiHelper.fetchGetJson<GetVerificationsResponse>(+ `${getApplicationServer()}/api/v1/verifications/by-database/${databaseId}${query ? `?${query}` : ''}`,+ undefined,+ true,+ );+ },++ async getById(id: string) {+ const requestOptions: RequestOptions = new RequestOptions();+ return apiHelper.fetchGetJson<RestoreVerification>(+ `${getApplicationServer()}/api/v1/verifications/${id}`,+ requestOptions,+ true,+ );+ },++ async enqueue(backupId: string) {+ const requestOptions: RequestOptions = new RequestOptions();+ requestOptions.setBody(JSON.stringify({ backupId }));+ return apiHelper.fetchPostJson<RestoreVerification>(+ `${getApplicationServer()}/api/v1/verifications/enqueue`,+ requestOptions,+ );+ },++ async cancel(id: string) {+ return apiHelper.fetchPostRaw(`${getApplicationServer()}/api/v1/verifications/${id}/cancel`);+ },+};diff --git a/frontend/src/entity/verification/runs/index.ts b/frontend/src/entity/verification/runs/index.tsnew file mode 100644index 00000000..962adf37--- /dev/null+++ b/frontend/src/entity/verification/runs/index.ts@@ -0,0 +1,6 @@+export { verificationRunsApi } from './api/verificationRunsApi';+export type { GetVerificationsResponse } from './models/GetVerificationsResponse';+export type { RestoreVerification } from './models/RestoreVerification';+export type { RestoreVerificationTableStat } from './models/RestoreVerificationTableStat';+export { VerificationStatus } from './models/VerificationStatus';+export { VerificationTrigger } from './models/VerificationTrigger';diff --git a/frontend/src/entity/verification/runs/models/GetVerificationsResponse.ts b/frontend/src/entity/verification/runs/models/GetVerificationsResponse.tsnew file mode 100644index 00000000..dede288a--- /dev/null+++ b/frontend/src/entity/verification/runs/models/GetVerificationsResponse.ts@@ -0,0 +1,8 @@+import type { RestoreVerification } from './RestoreVerification';++export interface GetVerificationsResponse {+ verifications: RestoreVerification[];+ total: number;+ limit: number;+ offset: number;+}diff --git a/frontend/src/entity/verification/runs/models/RestoreVerification.ts b/frontend/src/entity/verification/runs/models/RestoreVerification.tsnew file mode 100644index 00000000..665ac4e6--- /dev/null+++ b/frontend/src/entity/verification/runs/models/RestoreVerification.ts@@ -0,0 +1,24 @@+import type { RestoreVerificationTableStat } from './RestoreVerificationTableStat';+import type { VerificationStatus } from './VerificationStatus';+import type { VerificationTrigger } from './VerificationTrigger';++export interface RestoreVerification {+ id: string;+ databaseId: string;+ backupId: string;+ agentId?: string;+ trigger: VerificationTrigger;+ status: VerificationStatus;+ attemptCount: number;+ createdAt: string;+ startedAt?: string;+ finishedAt?: string;+ restoreDurationMs?: number;+ verifyDurationMs?: number;+ pgRestoreExitCode?: number;+ dbSizeBytesAfterRestore?: number;+ tableCount?: number;+ schemaCount?: number;+ failMessage?: string;+ tableStats?: RestoreVerificationTableStat[];+}diff --git a/frontend/src/entity/verification/runs/models/RestoreVerificationTableStat.ts b/frontend/src/entity/verification/runs/models/RestoreVerificationTableStat.tsnew file mode 100644index 00000000..7c1b3f42--- /dev/null+++ b/frontend/src/entity/verification/runs/models/RestoreVerificationTableStat.ts@@ -0,0 +1,6 @@+export interface RestoreVerificationTableStat {+ id: string;+ schemaName: string;+ name: string;+ rowCount: number;+}diff --git a/frontend/src/entity/verification/runs/models/VerificationStatus.ts b/frontend/src/entity/verification/runs/models/VerificationStatus.tsnew file mode 100644index 00000000..4332e034--- /dev/null+++ b/frontend/src/entity/verification/runs/models/VerificationStatus.ts@@ -0,0 +1,7 @@+export enum VerificationStatus {+ PENDING = 'PENDING',+ RUNNING = 'RUNNING',+ COMPLETED = 'COMPLETED',+ FAILED = 'FAILED',+ CANCELED = 'CANCELED',+}diff --git a/frontend/src/entity/verification/runs/models/VerificationTrigger.ts b/frontend/src/entity/verification/runs/models/VerificationTrigger.tsnew file mode 100644index 00000000..1d164283--- /dev/null+++ b/frontend/src/entity/verification/runs/models/VerificationTrigger.ts@@ -0,0 +1,4 @@+export enum VerificationTrigger {+ MANUAL = 'MANUAL',+ SCHEDULED = 'SCHEDULED',+}diff --git a/frontend/src/features/backups/model/restoreVerificationStatus.ts b/frontend/src/features/backups/model/restoreVerificationStatus.tsnew file mode 100644index 00000000..e68237b7--- /dev/null+++ b/frontend/src/features/backups/model/restoreVerificationStatus.ts@@ -0,0 +1,17 @@+import { RestoreVerificationStatus } from '../../../entity/backups';++// NOT_VERIFIED is intentionally absent: a lookup miss is how the UI decides to+// render no tag at all for backups that were never restore-verified.+export const RESTORE_VERIFICATION_STATUS_COLORS: Partial<+ Record<RestoreVerificationStatus, string>+> = {+ [RestoreVerificationStatus.VERIFIED_SUCCESSFUL]: 'green',+ [RestoreVerificationStatus.VERIFICATION_FAILED]: 'red',+};++export const RESTORE_VERIFICATION_STATUS_LABELS: Partial<+ Record<RestoreVerificationStatus, string>+> = {+ [RestoreVerificationStatus.VERIFIED_SUCCESSFUL]: 'Verified',+ [RestoreVerificationStatus.VERIFICATION_FAILED]: 'Verification failed',+};diff --git a/frontend/src/features/backups/ui/BackupsComponent.tsx b/frontend/src/features/backups/ui/BackupsComponent.tsxindex 73011bb9..3268e1cf 100644--- a/frontend/src/features/backups/ui/BackupsComponent.tsx+++ b/frontend/src/features/backups/ui/BackupsComponent.tsx@@ -9,12 +9,13 @@ import {FilterOutlined,InfoCircleOutlined,LockOutlined,+ SafetyOutlined,SyncOutlined,} from '@ant-design/icons';-import { Button, Modal, Spin, Table, Tooltip } from 'antd';+import { App, Button, Modal, Spin, Table, Tag, Tooltip } from 'antd';import type { ColumnsType } from 'antd/es/table';import dayjs from 'dayjs';-import { useEffect, useRef, useState } from 'react';+import { type JSX, useEffect, useRef, useState } from 'react';import { IS_CLOUD } from '../../../constants';import {@@ -23,14 +24,20 @@ import {BackupEncryption,BackupStatus,PgWalBackupType,+ RestoreVerificationStatus,backupConfigApi,backupsApi,} from '../../../entity/backups';import type { BackupsFilters } from '../../../entity/backups/api/backupsApi';import { type Database, DatabaseType, PostgresBackupType } from '../../../entity/databases';+import { verificationRunsApi } from '../../../entity/verification/runs';import { getUserTimeFormat } from '../../../shared/time';import { ConfirmationComponent } from '../../../shared/ui';import { RestoresComponent } from '../../restores';+import {+ RESTORE_VERIFICATION_STATUS_COLORS,+ RESTORE_VERIFICATION_STATUS_LABELS,+} from '../model/restoreVerificationStatus';import { AgentRestoreComponent } from './AgentRestoreComponent';import { BackupsBillingBannerComponent } from './BackupsBillingBannerComponent';import { BackupsFiltersPanelComponent } from './BackupsFiltersPanelComponent';@@ -43,15 +50,38 @@ interface Props {isDirectlyUnderTab?: boolean;scrollContainerRef?: React.RefObject<HTMLDivElement | null>;onNavigateToBilling?: () => void;+ onNavigateToVerifications?: () => void;}+const renderRestoreVerificationTag = (+ status: RestoreVerificationStatus | undefined,+): JSX.Element | null => {+ if (!status || status === RestoreVerificationStatus.NOT_VERIFIED) {+ return null;+ }++ const color = RESTORE_VERIFICATION_STATUS_COLORS[status];+ const label = RESTORE_VERIFICATION_STATUS_LABELS[status];+ if (!color || !label) {+ return null;+ }++ return (+ <Tag color={color} className="ml-2">+ {label}+ </Tag>+ );+};+export const BackupsComponent = ({database,isCanManageDBs,isDirectlyUnderTab,scrollContainerRef,onNavigateToBilling,+ onNavigateToVerifications,}: Props) => {+ const { message, modal } = App.useApp();const [isBackupsLoading, setIsBackupsLoading] = useState(false);const [backups, setBackups] = useState<Backup[]>([]);@@ -77,6 +107,7 @@ export const BackupsComponent = ({const [downloadingBackupId, setDownloadingBackupId] = useState<string | undefined>();const [cancellingBackupId, setCancellingBackupId] = useState<string | undefined>();+ const [verifyingBackupId, setVerifyingBackupId] = useState<string | undefined>();const [isFilterPanelVisible, setIsFilterPanelVisible] = useState(false);const [filters, setFilters] = useState<BackupsFilters>({});@@ -198,6 +229,45 @@ export const BackupsComponent = ({setCancellingBackupId(undefined);};+ const enqueueVerifyRestore = async (backupId: string) => {+ setVerifyingBackupId(backupId);++ try {+ await verificationRunsApi.enqueue(backupId);+ message.success('Restore check queued');+ onNavigateToVerifications?.();+ } catch (e) {+ message.error((e as Error).message);+ } finally {+ setVerifyingBackupId(undefined);+ }+ };++ const confirmVerifyRestore = (backupId: string) => {+ modal.confirm({+ title: 'Verify restore?',+ icon: <InfoCircleOutlined className="!text-blue-600" />,+ content: (+ <span>+ An agent will restore this backup to a temporary database and report row counts. This may+ take a while depending on backup size.{' '}+ <a+ href="https://databasus.com/restore-verification"+ target="_blank"+ rel="noopener noreferrer"+ >+ How it works?+ </a>+ </span>+ ),+ okText: 'Queue check',+ okType: 'primary',+ okButtonProps: { type: 'primary', danger: false },+ cancelText: 'Cancel',+ onOk: () => enqueueVerifyRestore(backupId),+ });+ };+useEffect(() => {setIsBackupConfigLoading(true);setCurrentLimit(BACKUPS_PAGE_SIZE);@@ -255,7 +325,7 @@ export const BackupsComponent = ({return () => container.removeEventListener('scroll', handleScroll);}, [hasMore, isLoadingMore, currentLimit, scrollContainerRef]);- const renderStatus = (status: BackupStatus, record: Backup) => {+ const renderBackupStatusLabel = (status: BackupStatus, record: Backup) => {if (status === BackupStatus.FAILED) {return (<Tooltip title="Click to see error details">@@ -314,6 +384,20 @@ export const BackupsComponent = ({return <span className="font-bold">{status}</span>;};+ const renderStatus = (status: BackupStatus, record: Backup) => {+ const verificationTag = renderRestoreVerificationTag(record.restoreVerificationStatus);+ if (!verificationTag) {+ return renderBackupStatusLabel(status, record);+ }++ return (+ <div className="flex items-center">+ {renderBackupStatusLabel(status, record)}+ {verificationTag}+ </div>+ );+ };+const renderActions = (record: Backup) => {return (<div className="flex gap-2 text-lg">@@ -357,6 +441,27 @@ export const BackupsComponent = ({</Tooltip>)}+ {isCanManageDBs &&+ database.postgresql?.backupType !== PostgresBackupType.WAL_V1 &&+ database.type === DatabaseType.POSTGRES &&+ (verifyingBackupId === record.id ? (+ <SyncOutlined spin style={{ color: '#155dfc' }} />+ ) : (+ <Tooltip title="Verify restore - queue an agent to restore this backup to a temporary database and report row counts">+ <SafetyOutlined+ className="cursor-pointer"+ onClick={() => {+ if (verifyingBackupId) return;+ confirmVerifyRestore(record.id);+ }}+ style={{+ color: '#155dfc',+ opacity: verifyingBackupId ? 0.2 : 1,+ }}+ />+ </Tooltip>+ ))}+<Tooltip title="Restore from backup"><CloudUploadOutlinedclassName="cursor-pointer"diff --git a/frontend/src/features/backups/ui/EditBackupConfigComponent.tsx b/frontend/src/features/backups/ui/EditBackupConfigComponent.tsxindex f0be2f5f..c92e8c66 100644--- a/frontend/src/features/backups/ui/EditBackupConfigComponent.tsx+++ b/frontend/src/features/backups/ui/EditBackupConfigComponent.tsx@@ -1,4 +1,4 @@-import { DownOutlined, InfoCircleOutlined, UpOutlined } from '@ant-design/icons';+import { DownOutlined, InfoCircleOutlined, UpOutlined } from '@ant-design/icons';import {Button,Checkbox,@@ -120,10 +120,6 @@ export const EditBackupConfigComponent = ({const updatedBackupInterval = { ...(prev.backupInterval ?? {}), ...patch };- if (!updatedBackupInterval.id && prev.backupInterval?.id) {- updatedBackupInterval.id = prev.backupInterval.id;- }-return { ...prev, backupInterval: updatedBackupInterval as Interval };});@@ -178,8 +174,7 @@ export const EditBackupConfigComponent = ({databaseId: database.id,isBackupsEnabled: true,backupInterval: {- id: undefined as unknown as string,- interval: IntervalType.DAILY,+ type: IntervalType.DAILY,timeOfDay: '00:00',},storage: undefined,@@ -229,14 +224,14 @@ export const EditBackupConfigComponent = ({: undefined;const displayedWeekday: number | undefined =- backupInterval?.interval === IntervalType.WEEKLY &&+ backupInterval?.type === IntervalType.WEEKLY &&backupInterval.weekday &&backupInterval.timeOfDay? getLocalWeekday(backupInterval.weekday, backupInterval.timeOfDay): backupInterval?.weekday;const displayedDayOfMonth: number | undefined =- backupInterval?.interval === IntervalType.MONTHLY &&+ backupInterval?.type === IntervalType.MONTHLY &&backupInterval.dayOfMonth &&backupInterval.timeOfDay? getLocalDayOfMonth(backupInterval.dayOfMonth, backupInterval.timeOfDay)@@ -245,8 +240,7 @@ export const EditBackupConfigComponent = ({const retentionPolicyType = backupConfig.retentionPolicyType ?? RetentionPolicyType.TimePeriod;const isShowGfsHours =- backupInterval?.interval === IntervalType.HOURLY ||- backupInterval?.interval === IntervalType.CRON;+ backupInterval?.type === IntervalType.HOURLY || backupInterval?.type === IntervalType.CRON;const isRetentionValid = (() => {switch (retentionPolicyType) {@@ -269,11 +263,11 @@ export const EditBackupConfigComponent = ({(isRetentionValid &&Boolean(backupConfig.storage?.id) &&Boolean(backupConfig.encryption) &&- Boolean(backupInterval?.interval) &&+ Boolean(backupInterval?.type) &&(!backupInterval ||- ((backupInterval.interval !== IntervalType.WEEKLY || displayedWeekday) &&- (backupInterval.interval !== IntervalType.MONTHLY || displayedDayOfMonth) &&- (backupInterval.interval !== IntervalType.CRON || backupInterval.cronExpression))));+ ((backupInterval.type !== IntervalType.WEEKLY || displayedWeekday) &&+ (backupInterval.type !== IntervalType.MONTHLY || displayedDayOfMonth) &&+ (backupInterval.type !== IntervalType.CRON || backupInterval.cronExpression))));return (<div>@@ -295,9 +289,9 @@ export const EditBackupConfigComponent = ({<div className="mt-4 mb-1 flex w-full flex-col items-start sm:flex-row sm:items-center"><div className="mb-1 min-w-[150px] sm:mb-0">Backup interval</div><Select- value={backupInterval?.interval}+ value={backupInterval?.type}onChange={(v) => {- saveInterval({ interval: v });+ saveInterval({ type: v });const isDailyOrMore =v === IntervalType.DAILY ||@@ -320,7 +314,7 @@ export const EditBackupConfigComponent = ({/></div>- {backupInterval?.interval === IntervalType.WEEKLY && (+ {backupInterval?.type === IntervalType.WEEKLY && (<div className="mb-1 flex w-full flex-col items-start sm:flex-row sm:items-center"><div className="mb-1 min-w-[150px] sm:mb-0">Backup weekday</div><Select@@ -337,7 +331,7 @@ export const EditBackupConfigComponent = ({</div>)}- {backupInterval?.interval === IntervalType.MONTHLY && (+ {backupInterval?.type === IntervalType.MONTHLY && (<div className="mb-1 flex w-full flex-col items-start sm:flex-row sm:items-center"><div className="mb-1 min-w-[150px] sm:mb-0">Backup day of month</div><InputNumber@@ -355,7 +349,7 @@ export const EditBackupConfigComponent = ({</div>)}- {backupInterval?.interval === IntervalType.CRON && (+ {backupInterval?.type === IntervalType.CRON && (<><div className="mb-1 flex w-full flex-col items-start sm:flex-row sm:items-center"><div className="mb-1 min-w-[150px] sm:mb-0">Cron expression (UTC)</div>@@ -414,8 +408,8 @@ export const EditBackupConfigComponent = ({</>)}- {backupInterval?.interval !== IntervalType.HOURLY &&- backupInterval?.interval !== IntervalType.CRON && (+ {backupInterval?.type !== IntervalType.HOURLY &&+ backupInterval?.type !== IntervalType.CRON && (<div className="mb-1 flex w-full flex-col items-start sm:flex-row sm:items-center"><div className="mb-1 min-w-[150px] sm:mb-0">Backup time of day</div><TimePicker@@ -429,10 +423,10 @@ export const EditBackupConfigComponent = ({if (!t) return;const patch: Partial<Interval> = { timeOfDay: t.utc().format('HH:mm') };- if (backupInterval?.interval === IntervalType.WEEKLY && displayedWeekday) {+ if (backupInterval?.type === IntervalType.WEEKLY && displayedWeekday) {patch.weekday = getUtcWeekday(displayedWeekday, t);}- if (backupInterval?.interval === IntervalType.MONTHLY && displayedDayOfMonth) {+ if (backupInterval?.type === IntervalType.MONTHLY && displayedDayOfMonth) {patch.dayOfMonth = getUtcDayOfMonth(displayedDayOfMonth, t);}diff --git a/frontend/src/features/backups/ui/ShowBackupConfigComponent.tsx b/frontend/src/features/backups/ui/ShowBackupConfigComponent.tsxindex 70d179dc..548d7582 100644--- a/frontend/src/features/backups/ui/ShowBackupConfigComponent.tsx+++ b/frontend/src/features/backups/ui/ShowBackupConfigComponent.tsx@@ -1,4 +1,4 @@-import { InfoCircleOutlined } from '@ant-design/icons';+import { InfoCircleOutlined } from '@ant-design/icons';import { Tooltip } from 'antd';import { CronExpressionParser } from 'cron-parser';import dayjs from 'dayjs';@@ -109,14 +109,14 @@ export const ShowBackupConfigComponent = ({ database }: Props) => {const formattedTime = localTime ? localTime.format(timeFormat.format) : '';const displayedWeekday: number | undefined =- backupInterval?.interval === IntervalType.WEEKLY &&+ backupInterval?.type === IntervalType.WEEKLY &&backupInterval.weekday &&backupInterval.timeOfDay? getLocalWeekday(backupInterval.weekday, backupInterval.timeOfDay): backupInterval?.weekday;const displayedDayOfMonth: number | undefined =- backupInterval?.interval === IntervalType.MONTHLY &&+ backupInterval?.type === IntervalType.MONTHLY &&backupInterval.dayOfMonth &&backupInterval.timeOfDay? getLocalDayOfMonth(backupInterval.dayOfMonth, backupInterval.timeOfDay)@@ -137,10 +137,10 @@ export const ShowBackupConfigComponent = ({ database }: Props) => {<><div className="mt-4 mb-1 flex w-full items-center"><div className="min-w-[150px]">Backup interval</div>- <div>{backupInterval?.interval ? intervalLabels[backupInterval.interval] : ''}</div>+ <div>{backupInterval?.type ? intervalLabels[backupInterval.type] : ''}</div></div>- {backupInterval?.interval === IntervalType.WEEKLY && (+ {backupInterval?.type === IntervalType.WEEKLY && (<div className="mb-1 flex w-full items-center"><div className="min-w-[150px]">Backup weekday</div><div>@@ -151,14 +151,14 @@ export const ShowBackupConfigComponent = ({ database }: Props) => {</div>)}- {backupInterval?.interval === IntervalType.MONTHLY && (+ {backupInterval?.type === IntervalType.MONTHLY && (<div className="mb-1 flex w-full items-center"><div className="min-w-[150px]">Backup day of month</div><div>{displayedDayOfMonth || ''}</div></div>)}- {backupInterval?.interval === IntervalType.CRON && (+ {backupInterval?.type === IntervalType.CRON && (<><div className="mb-1 flex w-full items-center"><div className="min-w-[150px]">Cron expression (UTC)</div>@@ -189,8 +189,8 @@ export const ShowBackupConfigComponent = ({ database }: Props) => {</>)}- {backupInterval?.interval !== IntervalType.HOURLY &&- backupInterval?.interval !== IntervalType.CRON && (+ {backupInterval?.type !== IntervalType.HOURLY &&+ backupInterval?.type !== IntervalType.CRON && (<div className="mb-1 flex w-full items-center"><div className="min-w-[150px]">Backup time of day</div><div>{formattedTime}</div>diff --git a/frontend/src/features/databases/ui/DatabaseComponent.tsx b/frontend/src/features/databases/ui/DatabaseComponent.tsxindex 8123c329..f43b8f23 100644--- a/frontend/src/features/databases/ui/DatabaseComponent.tsx+++ b/frontend/src/features/databases/ui/DatabaseComponent.tsx@@ -4,11 +4,17 @@ import { useEffect } from 'react';import { IS_CLOUD } from '../../../constants';import { backupsApi } from '../../../entity/backups';-import { type Database, PostgresBackupType, databaseApi } from '../../../entity/databases';+import {+ type Database,+ DatabaseType,+ PostgresBackupType,+ databaseApi,+} from '../../../entity/databases';import type { UserProfile } from '../../../entity/users';import { BackupsComponent } from '../../backups';import { BillingComponent } from '../../billing';import { HealthckeckAttemptsComponent } from '../../healthcheck';+import { VerificationsComponent } from '../../verification/runs';import { AgentInstallationComponent } from './AgentInstallationComponent';import { DatabaseConfigComponent } from './DatabaseConfigComponent';@@ -29,9 +35,9 @@ export const DatabaseComponent = ({onDatabaseDeleted,isCanManageDBs,}: Props) => {- const [currentTab, setCurrentTab] = useState<'config' | 'backups' | 'installation' | 'billing'>(- 'backups',- );+ const [currentTab, setCurrentTab] = useState<+ 'config' | 'backups' | 'verifications' | 'installation' | 'billing'+ >('backups');const [database, setDatabase] = useState<Database | undefined>();const [editDatabase, setEditDatabase] = useState<Database | undefined>();@@ -45,6 +51,9 @@ export const DatabaseComponent = ({};const isWalDatabase = database?.postgresql?.backupType === PostgresBackupType.WAL_V1;+ const isPostgresLogicalDatabase =+ database?.type === DatabaseType.POSTGRES &&+ database?.postgresql?.backupType !== PostgresBackupType.WAL_V1;const loadSettings = () => {setDatabase(undefined);@@ -59,6 +68,10 @@ export const DatabaseComponent = ({useEffect(() => {if (!database) return;+ if (!isPostgresLogicalDatabase) {+ setCurrentTab((prev) => (prev === 'verifications' ? 'backups' : prev));+ }+if (!isWalDatabase) {setCurrentTab((prev) => (prev === 'installation' ? 'backups' : prev));return;@@ -96,6 +109,15 @@ export const DatabaseComponent = ({Backups</div>+ {isPostgresLogicalDatabase && (+ <div+ className={`mr-2 cursor-pointer rounded-tl-md rounded-tr-md px-6 py-2 ${currentTab === 'verifications' ? 'bg-white dark:bg-gray-800' : 'bg-gray-200 dark:bg-gray-700'}`}+ onClick={() => setCurrentTab('verifications')}+ >+ Verifications+ </div>+ )}+{isWalDatabase && (<divclassName={`mr-2 cursor-pointer rounded-tl-md rounded-tr-md px-6 py-2 ${currentTab === 'installation' ? 'bg-white dark:bg-gray-800' : 'bg-gray-200 dark:bg-gray-700'}`}@@ -142,10 +164,20 @@ export const DatabaseComponent = ({isDirectlyUnderTab={isWalDatabase || !isHealthcheckVisible}scrollContainerRef={scrollContainerRef}onNavigateToBilling={() => setCurrentTab('billing')}+ onNavigateToVerifications={() => setCurrentTab('verifications')}/></>)}+ {currentTab === 'verifications' && isPostgresLogicalDatabase && (+ <VerificationsComponent+ database={database}+ isCanManageDBs={isCanManageDBs}+ isDirectlyUnderTab={true}+ scrollContainerRef={scrollContainerRef}+ />+ )}+{currentTab === 'installation' && isWalDatabase && (<AgentInstallationComponent database={database} onTokenGenerated={loadSettings} />)}diff --git a/frontend/src/features/databases/ui/DatabaseConfigComponent.tsx b/frontend/src/features/databases/ui/DatabaseConfigComponent.tsxindex a3a3e8f2..c15574d8 100644--- a/frontend/src/features/databases/ui/DatabaseConfigComponent.tsx+++ b/frontend/src/features/databases/ui/DatabaseConfigComponent.tsx@@ -9,12 +9,21 @@ import { Button, Input } from 'antd';import { useEffect, useState } from 'react';import { backupConfigApi } from '../../../entity/backups';-import { type Database, PostgresBackupType, databaseApi } from '../../../entity/databases';+import {+ type Database,+ DatabaseType,+ PostgresBackupType,+ databaseApi,+} from '../../../entity/databases';import type { UserProfile } from '../../../entity/users';import { ToastHelper } from '../../../shared/toast';import { ConfirmationComponent } from '../../../shared/ui';import { EditBackupConfigComponent, ShowBackupConfigComponent } from '../../backups';import { EditHealthcheckConfigComponent, ShowHealthcheckConfigComponent } from '../../healthcheck';+import {+ EditBackupVerificationConfigComponent,+ ShowBackupVerificationConfigComponent,+} from '../../verification/config';import { DatabaseTransferDialogComponent } from './DatabaseTransferDialogComponent';import { EditDatabaseNotifiersComponent } from './edit/EditDatabaseNotifiersComponent';import { EditDatabaseSpecificDataComponent } from './edit/EditDatabaseSpecificDataComponent';@@ -49,6 +58,7 @@ export const DatabaseConfigComponent = ({const [isEditBackupConfig, setIsEditBackupConfig] = useState(false);const [isEditNotifiersSettings, setIsEditNotifiersSettings] = useState(false);const [isEditHealthcheckSettings, setIsEditHealthcheckSettings] = useState(false);+ const [isEditVerificationConfig, setIsEditVerificationConfig] = useState(false);const [isNameUnsaved, setIsNameUnsaved] = useState(false);const [isSaving, setIsSaving] = useState(false);@@ -139,13 +149,22 @@ export const DatabaseConfigComponent = ({});};- const startEdit = (type: 'name' | 'database' | 'backup-config' | 'notifiers' | 'healthcheck') => {+ const startEdit = (+ type:+ | 'name'+ | 'database'+ | 'backup-config'+ | 'notifiers'+ | 'healthcheck'+ | 'verification-config',+ ) => {setEditDatabase(JSON.parse(JSON.stringify(database)));setIsEditName(type === 'name');setIsEditDatabaseSpecificDataSettings(type === 'database');setIsEditBackupConfig(type === 'backup-config');setIsEditNotifiersSettings(type === 'notifiers');setIsEditHealthcheckSettings(type === 'healthcheck');+ setIsEditVerificationConfig(type === 'verification-config');setIsNameUnsaved(false);};@@ -169,6 +188,9 @@ export const DatabaseConfigComponent = ({};const isWalDatabase = database.postgresql?.backupType === PostgresBackupType.WAL_V1;+ const isPostgresLogicalDatabase =+ database.type === DatabaseType.POSTGRES &&+ database.postgresql?.backupType !== PostgresBackupType.WAL_V1;return (<div className="relative w-full rounded-tr-md rounded-br-md rounded-bl-md bg-white p-3 shadow sm:p-5 dark:bg-gray-800">@@ -369,6 +391,39 @@ export const DatabaseConfigComponent = ({</div>)}+ {isPostgresLogicalDatabase && (+ <div className="w-full lg:w-[400px]">+ <div className="mt-5 flex items-center font-bold">+ <div>Restore verification</div>++ {!isEditVerificationConfig && isCanManageDBs ? (+ <div+ className="ml-2 h-4 w-4 cursor-pointer"+ onClick={() => startEdit('verification-config')}+ >+ <img src="/icons/pen-gray.svg" />+ </div>+ ) : (+ <div />+ )}+ </div>++ <div className="mt-1 text-sm">+ {isEditVerificationConfig ? (+ <EditBackupVerificationConfigComponent+ databaseId={database.id}+ onClose={() => {+ setIsEditVerificationConfig(false);+ loadSettings();+ }}+ />+ ) : (+ <ShowBackupVerificationConfigComponent databaseId={database.id} />+ )}+ </div>+ </div>+ )}+<div className="w-full lg:w-[400px]"><div className="mt-5 flex items-center font-bold"><div>Notifiers settings</div>diff --git a/frontend/src/features/settings/ui/SettingsComponent.tsx b/frontend/src/features/settings/ui/SettingsComponent.tsxindex 8ba67b1b..8a4d9f1d 100644--- a/frontend/src/features/settings/ui/SettingsComponent.tsx+++ b/frontend/src/features/settings/ui/SettingsComponent.tsx@@ -6,6 +6,7 @@ import { IS_CLOUD, getApplicationServer } from '../../../constants';import { settingsApi } from '../../../entity/users/api/settingsApi';import type { UsersSettings } from '../../../entity/users/model/UsersSettings';import { ClipboardHelper } from '../../../shared/lib/ClipboardHelper';+import { VerificationAgentsComponent } from '../../verification/agents';import { AuditLogsComponent } from './AuditLogsComponent';interface Props {@@ -263,6 +264,8 @@ export function SettingsComponent({ contentHeight }: Props) {</div></div>+ <VerificationAgentsComponent />+<AuditLogsComponent scrollContainerRef={scrollContainerRef} /></div></div>diff --git a/frontend/src/features/users/ui/AuthNavbarComponent.tsx b/frontend/src/features/users/ui/AuthNavbarComponent.tsxindex 40d5dbbf..e95aff9b 100644--- a/frontend/src/features/users/ui/AuthNavbarComponent.tsx+++ b/frontend/src/features/users/ui/AuthNavbarComponent.tsx@@ -25,15 +25,6 @@ export function AuthNavbarComponent() {</div><div className="mr-3 ml-auto hidden items-center gap-5 sm:flex">- <a- className="!text-black hover:opacity-80 dark:!text-gray-200"- href="https://t.me/databasus_community"- target="_blank"- rel="noreferrer"- >- Community- </a>-{!IS_CLOUD && (<Tooltip title="99.9% uptime, 2x backup copies"><a@@ -51,6 +42,35 @@ export function AuthNavbarComponent() {</Tooltip>)}+ {!IS_CLOUD && (+ <a+ className="!text-black hover:opacity-80 dark:!text-gray-200"+ href="https://databasus.com/labs"+ target="_blank"+ rel="noreferrer"+ >+ Labs+ </a>+ )}++ <a+ className="!text-black hover:opacity-80 dark:!text-gray-200"+ href="https://databasus.com/installation"+ target="_blank"+ rel="noreferrer"+ >+ Docs+ </a>++ <a+ className="!text-black hover:opacity-80 dark:!text-gray-200"+ href="https://t.me/databasus_community"+ target="_blank"+ rel="noreferrer"+ >+ Community+ </a>+<div className="flex items-center gap-2"><StarButtonComponent />diff --git a/frontend/src/features/verification/agents/index.ts b/frontend/src/features/verification/agents/index.tsnew file mode 100644index 00000000..f6c412fa--- /dev/null+++ b/frontend/src/features/verification/agents/index.ts@@ -0,0 +1 @@+export { VerificationAgentsComponent } from './ui/VerificationAgentsComponent';diff --git a/frontend/src/features/verification/agents/model/agentStatus.ts b/frontend/src/features/verification/agents/model/agentStatus.tsnew file mode 100644index 00000000..b7f4dea3--- /dev/null+++ b/frontend/src/features/verification/agents/model/agentStatus.ts@@ -0,0 +1,33 @@+// Thresholds for translating last_seen_at into a status badge.+// Agents are expected to heartbeat every 30 seconds; the 15-second list poll on+// the page gives a snappy transition between Online and Stale.+const ONLINE_WINDOW_MS = 90 * 1000;+const STALE_WINDOW_MS = 5 * 60 * 1000;++export type AgentStatus = 'never-seen' | 'online' | 'stale' | 'offline';++export const getAgentStatus = (+ lastSeenAt: string | undefined,+ now: number = Date.now(),+): AgentStatus => {+ if (!lastSeenAt) return 'never-seen';++ const diff = now - new Date(lastSeenAt).getTime();+ if (diff <= ONLINE_WINDOW_MS) return 'online';+ if (diff <= STALE_WINDOW_MS) return 'stale';+ return 'offline';+};++export const AGENT_STATUS_COLORS: Record<AgentStatus, string> = {+ 'never-seen': 'default',+ online: 'green',+ stale: 'orange',+ offline: 'red',+};++export const AGENT_STATUS_LABELS: Record<AgentStatus, string> = {+ 'never-seen': 'Never seen',+ online: 'Online',+ stale: 'Stale',+ offline: 'Offline',+};diff --git a/frontend/src/features/verification/agents/ui/VerificationAgentsComponent.tsx b/frontend/src/features/verification/agents/ui/VerificationAgentsComponent.tsxnew file mode 100644index 00000000..323845c5--- /dev/null+++ b/frontend/src/features/verification/agents/ui/VerificationAgentsComponent.tsx@@ -0,0 +1,542 @@+import {+ CopyOutlined,+ DeleteOutlined,+ EyeOutlined,+ LoadingOutlined,+ PlusOutlined,+ ReloadOutlined,+} from '@ant-design/icons';+import { App, Button, Input, Modal, Popconfirm, Spin, Table, Tag, Tooltip } from 'antd';+import type { ColumnsType } from 'antd/es/table';+import dayjs from 'dayjs';+import { useCallback, useEffect, useRef, useState } from 'react';++import { IS_CLOUD } from '../../../../constants';+import {+ type VerificationAgent,+ verificationAgentApi,+} from '../../../../entity/verification/agents';+import { ClipboardHelper } from '../../../../shared/lib/ClipboardHelper';+import { AGENT_STATUS_COLORS, AGENT_STATUS_LABELS, getAgentStatus } from '../model/agentStatus';++const LIST_REFRESH_MS = 15_000;+const MUTED_TEXT_CLASS = 'text-gray-400 dark:text-gray-500';++type AgentArchitecture = 'amd64' | 'arm64';++const formatCapacity = (agent: VerificationAgent): string => {+ if (+ agent.maxCpu <= 0 &&+ agent.maxRamGb <= 0 &&+ agent.maxDiskGb <= 0 &&+ agent.maxConcurrentJobs <= 0+ ) {+ return '';+ }++ const parts: string[] = [];+ if (agent.maxCpu > 0) parts.push(`${agent.maxCpu} CPU`);+ if (agent.maxRamGb > 0) parts.push(`${agent.maxRamGb} GB RAM`);+ if (agent.maxDiskGb > 0) parts.push(`${agent.maxDiskGb} GB disk`);+ if (agent.maxConcurrentJobs > 0) parts.push(`${agent.maxConcurrentJobs} jobs`);+ return parts.join(' · ');+};++const TOKEN_PLACEHOLDER = '<YOUR_AGENT_TOKEN>';++const buildInstallCommand = (arch: AgentArchitecture): string => {+ const host = window.location.origin;+ return `curl -L -o verification-agent "${host}/api/v1/system/verification-agent?arch=${arch}" && chmod +x verification-agent`;+};++const buildLaunchCommand = (agentId: string, token: string): string => {+ const host = window.location.origin;++ return [+ './verification-agent start \\',+ ` --databasus-host=${host} \\`,+ ` --agent-id=${agentId} \\`,+ ` --token=${token} \\`,+ ' --max-cpu=2 \\',+ ' --max-ram-mb=2048 \\',+ ' --max-disk-gb=20 \\',+ ' --max-concurrent-jobs=1',+ ].join('\n');+};++export const VerificationAgentsComponent = () => {+ const { message } = App.useApp();++ const [agents, setAgents] = useState<VerificationAgent[]>([]);+ const [isLoading, setIsLoading] = useState(true);++ const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);+ const [newAgentName, setNewAgentName] = useState('');+ const [isCreating, setIsCreating] = useState(false);++ const [revealedToken, setRevealedToken] = useState<string | null>(null);+ const [revealedTokenAgentName, setRevealedTokenAgentName] = useState<string>('');+ const [revealedTokenAgentId, setRevealedTokenAgentId] = useState<string>('');+ const [selectedArch, setSelectedArch] = useState<AgentArchitecture>('amd64');++ const [rotatingAgent, setRotatingAgent] = useState<VerificationAgent | null>(null);+ const [isRotating, setIsRotating] = useState(false);++ const [viewingInstallAgent, setViewingInstallAgent] = useState<VerificationAgent | null>(null);++ const [deletingAgentId, setDeletingAgentId] = useState<string | null>(null);+ const [currentTimeMs, setCurrentTimeMs] = useState<number>(Date.now());++ const copyToClipboard = async (text: string) => {+ try {+ await ClipboardHelper.copyToClipboard(text);+ message.success('Copied to clipboard');+ } catch {+ message.error('Failed to copy');+ }+ };++ const closeRevealedTokenModal = () => {+ setRevealedToken(null);+ setRevealedTokenAgentName('');+ setRevealedTokenAgentId('');+ };++ const renderCodeBlock = (code: string) => (+ <div className="relative mt-2">+ <pre className="rounded-md bg-gray-900 p-4 pr-10 font-mono text-sm break-all whitespace-pre-wrap text-gray-100">+ {code}+ </pre>+ <Tooltip title="Copy">+ <button+ className="absolute top-2 right-2 cursor-pointer rounded p-1 text-gray-400 hover:text-white"+ onClick={() => copyToClipboard(code)}+ >+ <CopyOutlined />+ </button>+ </Tooltip>+ </div>+ );++ const renderArchButton = (arch: AgentArchitecture) => (+ <Button+ type="primary"+ ghost={selectedArch !== arch}+ onClick={() => setSelectedArch(arch)}+ className="mr-2"+ >+ {arch}+ </Button>+ );++ const renderAgentIdRow = (agentId: string) => (+ <div className="mt-3 flex items-center text-sm text-gray-500 dark:text-gray-400">+ <span className="mr-1">Agent ID:</span>+ <code className="rounded bg-gray-100 px-2 py-0.5 text-xs dark:bg-gray-700">{agentId}</code>+ <Tooltip title="Copy">+ <button+ className="ml-1 cursor-pointer rounded p-1 text-gray-400 hover:text-gray-700 dark:hover:text-white"+ onClick={() => copyToClipboard(agentId)}+ >+ <CopyOutlined style={{ fontSize: 12 }} />+ </button>+ </Tooltip>+ </div>+ );++ const renderArchitecturePicker = () => (+ <div className="mt-4">+ <div className="mb-1 text-sm font-medium text-gray-700 dark:text-gray-300">Architecture</div>+ <div className="flex">+ {renderArchButton('amd64')}+ {renderArchButton('arm64')}+ </div>+ </div>+ );++ const renderInstallAndLaunchSteps = (agentId: string, token: string) => (+ <>+ <div className="mt-4 font-semibold dark:text-white">Step 1 - Install</div>+ {renderCodeBlock(buildInstallCommand(selectedArch))}++ <div className="mt-4 font-semibold dark:text-white">Step 2 - Launch</div>+ <p className="mt-1 text-sm text-gray-600 dark:text-gray-400">+ The capacity values below are starting defaults - tune <code>--max-cpu</code>,{' '}+ <code>--max-ram-mb</code>, <code>--max-disk-gb</code> and <code>--max-concurrent-jobs</code>{' '}+ to the machine running the agent.+ </p>+ {renderCodeBlock(buildLaunchCommand(agentId, token))}++ <div className="mt-4 font-semibold dark:text-white">After installation</div>+ <ul className="mt-1 list-disc space-y-1 pl-5 text-sm text-gray-600 dark:text-gray-400">+ <li>+ The agent runs in the background after <code>start</code>+ </li>+ <li>+ Check status: <code>./verification-agent status</code>+ </li>+ <li>+ View logs: <code>databasus-verification.log</code> in the working directory+ </li>+ <li>+ Stop the agent: <code>./verification-agent stop</code>+ </li>+ </ul>+ </>+ );++ const closeViewingInstallModal = () => {+ setViewingInstallAgent(null);+ };++ const handleCreate = async () => {+ const name = newAgentName.trim();+ if (!name) {+ message.error('Name is required');+ return;+ }++ setIsCreating(true);++ try {+ const response = await verificationAgentApi.createAgent(name);+ setAgents((prev) => [response.agent, ...prev]);+ setRevealedToken(response.token);+ setRevealedTokenAgentName(response.agent.name);+ setRevealedTokenAgentId(response.agent.id);+ setIsCreateModalOpen(false);+ setNewAgentName('');+ } catch (e) {+ message.error((e as Error).message);+ } finally {+ setIsCreating(false);+ }+ };++ const handleConfirmRotate = async () => {+ if (!rotatingAgent) return;++ setIsRotating(true);++ try {+ const response = await verificationAgentApi.rotateToken(rotatingAgent.id);+ setRevealedToken(response.token);+ setRevealedTokenAgentName(rotatingAgent.name);+ setRevealedTokenAgentId(rotatingAgent.id);+ setRotatingAgent(null);+ } catch (e) {+ message.error((e as Error).message);+ } finally {+ setIsRotating(false);+ }+ };++ const handleDelete = async (agent: VerificationAgent) => {+ setDeletingAgentId(agent.id);++ try {+ await verificationAgentApi.deleteAgent(agent.id);+ setAgents((prev) => prev.filter((a) => a.id !== agent.id));+ message.success(`Agent "${agent.name}" deleted`);+ } catch (e) {+ message.error((e as Error).message);+ } finally {+ setDeletingAgentId(null);+ }+ };++ // Pause background polling while any modal is open so it doesn't trample state.+ const hasOpenModal = useRef(false);+ hasOpenModal.current =+ isCreateModalOpen ||+ revealedToken !== null ||+ rotatingAgent !== null ||+ viewingInstallAgent !== null;++ const loadAgents = useCallback(async () => {+ try {+ const list = await verificationAgentApi.listAgents();+ setAgents(list);+ } catch (e) {+ message.error((e as Error).message);+ }+ }, [message]);++ useEffect(() => {+ setIsLoading(true);+ loadAgents().finally(() => setIsLoading(false));+ }, [loadAgents]);++ useEffect(() => {+ const interval = window.setInterval(() => {+ setCurrentTimeMs(Date.now());++ if (!hasOpenModal.current) {+ loadAgents();+ }+ }, LIST_REFRESH_MS);++ return () => window.clearInterval(interval);+ }, [loadAgents]);++ const columns: ColumnsType<VerificationAgent> = [+ {+ title: 'Name',+ dataIndex: 'name',+ key: 'name',+ render: (name: string) => (+ <span className="font-medium text-gray-900 dark:text-white">{name}</span>+ ),+ },+ {+ title: 'Status',+ key: 'status',+ width: 220,+ render: (_, record) => {+ const status = getAgentStatus(record.lastSeenAt, currentTimeMs);+ return (+ <div className="flex items-center gap-2">+ <Tag color={AGENT_STATUS_COLORS[status]} className="!m-0">+ {AGENT_STATUS_LABELS[status]}+ </Tag>+ {record.lastSeenAt && (+ <span className={`text-xs ${MUTED_TEXT_CLASS}`}>+ {dayjs(record.lastSeenAt).fromNow()}+ </span>+ )}+ </div>+ );+ },+ },+ {+ title: 'Capacity',+ key: 'capacity',+ render: (_, record) => {+ const capacity = formatCapacity(record);+ return capacity ? (+ <span className="text-xs text-gray-700 dark:text-gray-300">{capacity}</span>+ ) : (+ <span className={`text-xs ${MUTED_TEXT_CLASS}`}>not yet reported</span>+ );+ },+ },+ {+ title: 'Created',+ dataIndex: 'createdAt',+ key: 'createdAt',+ width: 140,+ render: (createdAt: string) => (+ <span className={`text-xs ${MUTED_TEXT_CLASS}`}>{dayjs(createdAt).fromNow()}</span>+ ),+ },+ {+ title: '',+ key: 'actions',+ width: 110,+ align: 'right',+ render: (_, record) => (+ <div className="flex items-center justify-end gap-1">+ <Tooltip title="View install commands">+ <Button+ type="text"+ size="small"+ icon={<EyeOutlined />}+ onClick={() => setViewingInstallAgent(record)}+ />+ </Tooltip>++ <Tooltip title="Rotate token">+ <Button+ type="text"+ size="small"+ icon={<ReloadOutlined />}+ onClick={() => setRotatingAgent(record)}+ />+ </Tooltip>++ <Popconfirm+ title="Delete this agent?"+ okText="Delete"+ okButtonProps={{ danger: true, loading: deletingAgentId === record.id }}+ cancelText="Cancel"+ onConfirm={() => handleDelete(record)}+ >+ <Tooltip title="Delete">+ <Button type="text" size="small" danger icon={<DeleteOutlined />} />+ </Tooltip>+ </Popconfirm>+ </div>+ ),+ },+ ];++ return (+ <section className="my-8 max-w-[800px]">+ <div className="mb-3 flex items-center justify-between">+ <div className="flex items-baseline gap-3">+ <h2 className="text-xl font-bold dark:text-white">Verification agents</h2>+ </div>++ <div className="flex items-center gap-2">+ {!IS_CLOUD && (+ <Button+ size="small"+ href="https://databasus.com/cloud"+ target="_blank"+ rel="noopener noreferrer"+ className="!border-green-600 !bg-transparent !text-green-600 hover:!border-green-700 hover:!text-green-700 dark:!border-green-500 dark:!text-green-400 dark:hover:!border-green-400 dark:hover:!text-green-300"+ >+ Use in cloud+ </Button>+ )}++ <Button+ type="primary"+ size="small"+ icon={<PlusOutlined />}+ onClick={() => setIsCreateModalOpen(true)}+ >+ Create+ </Button>+ </div>+ </div>++ <p className="mb-4 max-w-2xl text-sm text-gray-500 dark:text-gray-400">+ Agents that run restore verifications to confirm a backup is restorable (+ <a+ href="https://databasus.com/restore-verification"+ target="_blank"+ rel="noopener noreferrer"+ >+ read more+ </a>+ )+ </p>++ {isLoading ? (+ <div className="py-4">+ <Spin indicator={<LoadingOutlined spin />} />+ </div>+ ) : agents.length === 0 ? (+ <p className="text-sm text-gray-500 dark:text-gray-400">No agents registered yet.</p>+ ) : (+ <Table columns={columns} dataSource={agents} pagination={false} rowKey="id" size="small" />+ )}++ <Modal+ title="Create verification agent"+ open={isCreateModalOpen}+ onCancel={() => {+ setIsCreateModalOpen(false);+ setNewAgentName('');+ }}+ footer={[+ <Button+ key="cancel"+ onClick={() => {+ setIsCreateModalOpen(false);+ setNewAgentName('');+ }}+ >+ Cancel+ </Button>,+ <Button key="create" type="primary" loading={isCreating} onClick={handleCreate}>+ Create+ </Button>,+ ]}+ >+ <p className="mb-2 text-sm text-gray-500 dark:text-gray-400">+ A token will be generated and shown exactly once on the next screen.+ </p>+ <Input+ placeholder="Agent name"+ value={newAgentName}+ onChange={(e) => setNewAgentName(e.target.value)}+ onPressEnter={handleCreate}+ maxLength={200}+ autoFocus+ />+ </Modal>++ <Modal+ title="Rotate token"+ open={rotatingAgent !== null}+ onCancel={() => setRotatingAgent(null)}+ footer={[+ <Button key="cancel" onClick={() => setRotatingAgent(null)}>+ Cancel+ </Button>,+ <Button+ key="rotate"+ type="primary"+ danger+ loading={isRotating}+ onClick={handleConfirmRotate}+ >+ Rotate token+ </Button>,+ ]}+ >+ <p className="text-sm text-gray-700 dark:text-gray-300">+ Rotating the token for <strong>{rotatingAgent?.name}</strong> invalidates the existing+ token immediately. Any worker still using the old token will be rejected on its next+ heartbeat.+ </p>+ </Modal>++ <Modal+ title="Agent token"+ open={revealedToken !== null}+ onCancel={closeRevealedTokenModal}+ width={640}+ footer={+ <Button type="primary" onClick={closeRevealedTokenModal}>+ I've saved the token+ </Button>+ }+ maskClosable={false}+ >+ <p className="text-sm text-gray-700 dark:text-gray-300">+ Token for <strong>{revealedTokenAgentName}</strong>:+ </p>+ {renderCodeBlock(revealedToken ?? '')}++ {renderAgentIdRow(revealedTokenAgentId)}+ {renderArchitecturePicker()}+ {renderInstallAndLaunchSteps(revealedTokenAgentId, revealedToken ?? '')}++ <p className="mt-3 text-sm text-amber-600 dark:text-amber-400">+ Shown once. Store it securely - you won't be able to retrieve it again.+ </p>+ </Modal>++ <Modal+ title="Install commands"+ open={viewingInstallAgent !== null}+ onCancel={closeViewingInstallModal}+ width={640}+ footer={+ <Button type="primary" onClick={closeViewingInstallModal}>+ Close+ </Button>+ }+ >+ <p className="text-sm text-gray-700 dark:text-gray-300">+ Install commands for <strong>{viewingInstallAgent?.name}</strong>. Replace{' '}+ <code className="rounded bg-gray-100 px-1 text-xs dark:bg-gray-700">+ {TOKEN_PLACEHOLDER}+ </code>{' '}+ with the token you saved when you created or last rotated this agent.+ </p>++ {viewingInstallAgent && (+ <>+ {renderAgentIdRow(viewingInstallAgent.id)}+ {renderArchitecturePicker()}+ {renderInstallAndLaunchSteps(viewingInstallAgent.id, TOKEN_PLACEHOLDER)}+ </>+ )}+ </Modal>+ </section>+ );+};diff --git a/frontend/src/features/verification/config/index.ts b/frontend/src/features/verification/config/index.tsnew file mode 100644index 00000000..e765cd50--- /dev/null+++ b/frontend/src/features/verification/config/index.ts@@ -0,0 +1,2 @@+export { EditBackupVerificationConfigComponent } from './ui/EditBackupVerificationConfigComponent';+export { ShowBackupVerificationConfigComponent } from './ui/ShowBackupVerificationConfigComponent';diff --git a/frontend/src/features/verification/config/ui/EditBackupVerificationConfigComponent.tsx b/frontend/src/features/verification/config/ui/EditBackupVerificationConfigComponent.tsxnew file mode 100644index 00000000..36a3f789--- /dev/null+++ b/frontend/src/features/verification/config/ui/EditBackupVerificationConfigComponent.tsx@@ -0,0 +1,409 @@+import { InfoCircleOutlined } from '@ant-design/icons';+import {+ Button,+ Checkbox,+ Input,+ InputNumber,+ Select,+ Spin,+ Switch,+ TimePicker,+ Tooltip,+} from 'antd';+import { CronExpressionParser } from 'cron-parser';+import dayjs, { type Dayjs } from 'dayjs';+import { useEffect, useState } from 'react';++import { type Interval, IntervalType } from '../../../../entity/intervals';+import {+ type BackupVerificationConfig,+ VerificationNotificationType,+ VerificationScheduleType,+ verificationConfigApi,+} from '../../../../entity/verification/config';+import { getUserTimeFormat } from '../../../../shared/time';+import {+ getUserTimeFormat as getIs12Hour,+ getLocalDayOfMonth,+ getLocalWeekday,+ getUtcDayOfMonth,+ getUtcWeekday,+} from '../../../../shared/time/utils';++interface Props {+ databaseId: string;+ onClose: () => void;+}++const weekdayOptions = [+ { value: 1, label: 'Mon' },+ { value: 2, label: 'Tue' },+ { value: 3, label: 'Wed' },+ { value: 4, label: 'Thu' },+ { value: 5, label: 'Fri' },+ { value: 6, label: 'Sat' },+ { value: 7, label: 'Sun' },+];++export const EditBackupVerificationConfigComponent = ({ databaseId, onClose }: Props) => {+ const [config, setConfig] = useState<BackupVerificationConfig>();+ const [isLoading, setIsLoading] = useState(true);+ const [isSaving, setIsSaving] = useState(false);+ const [isUnsaved, setIsUnsaved] = useState(false);++ const updateConfig = (patch: Partial<BackupVerificationConfig>) => {+ setConfig((prev) => (prev ? { ...prev, ...patch } : prev));+ setIsUnsaved(true);+ };++ const saveInterval = (patch: Partial<Interval>) => {+ setConfig((prev) => {+ if (!prev) return prev;++ const updatedInterval = { ...prev.verificationInterval, ...patch } as Interval;+ return { ...prev, verificationInterval: updatedInterval };+ });+ setIsUnsaved(true);+ };++ const selectSchedule = (value: string) => {+ if (value === VerificationScheduleType.AFTER_BACKUP) {+ updateConfig({ scheduleType: VerificationScheduleType.AFTER_BACKUP });+ return;+ }++ setConfig((prev) =>+ prev+ ? {+ ...prev,+ scheduleType: VerificationScheduleType.INTERVAL,+ verificationInterval: { ...prev.verificationInterval, type: value as IntervalType },+ }+ : prev,+ );+ setIsUnsaved(true);+ };++ const toggleNotification = (type: VerificationNotificationType, checked: boolean) => {+ if (!config) return;++ const notifications = [...config.sendNotificationsOn];+ const index = notifications.indexOf(type);++ if (checked && index === -1) {+ notifications.push(type);+ } else if (!checked && index > -1) {+ notifications.splice(index, 1);+ }++ updateConfig({ sendNotificationsOn: notifications });+ };++ const handleSave = async () => {+ if (!config) return;++ setIsSaving(true);++ try {+ await verificationConfigApi.save(databaseId, config);+ setIsUnsaved(false);+ onClose();+ } catch (e) {+ alert((e as Error).message);+ }++ setIsSaving(false);+ };++ useEffect(() => {+ setIsLoading(true);+ verificationConfigApi+ .getByDatabaseId(databaseId)+ .then(setConfig)+ .catch((error: Error) => alert(error.message))+ .finally(() => setIsLoading(false));+ }, [databaseId]);++ if (isLoading) {+ return <Spin size="small" />;+ }++ if (!config) return <div />;++ const is12Hour = getIs12Hour();+ const timeFormat = { use12Hours: is12Hour, format: is12Hour ? 'h:mm A' : 'HH:mm' };+ const dateTimeFormat = getUserTimeFormat();++ const { verificationInterval } = config;++ const localTime: Dayjs | undefined = verificationInterval?.timeOfDay+ ? dayjs.utc(verificationInterval.timeOfDay, 'HH:mm').local()+ : undefined;++ const displayedWeekday: number | undefined =+ verificationInterval?.type === IntervalType.WEEKLY &&+ verificationInterval.weekday &&+ verificationInterval.timeOfDay+ ? getLocalWeekday(verificationInterval.weekday, verificationInterval.timeOfDay)+ : verificationInterval?.weekday;++ const displayedDayOfMonth: number | undefined =+ verificationInterval?.type === IntervalType.MONTHLY &&+ verificationInterval.dayOfMonth &&+ verificationInterval.timeOfDay+ ? getLocalDayOfMonth(verificationInterval.dayOfMonth, verificationInterval.timeOfDay)+ : verificationInterval?.dayOfMonth;++ const isAfterBackup = config.scheduleType === VerificationScheduleType.AFTER_BACKUP;++ const isIntervalValid =+ !config.isScheduledVerificationEnabled ||+ isAfterBackup ||+ (Boolean(verificationInterval?.type) &&+ (verificationInterval.type !== IntervalType.WEEKLY || displayedWeekday) &&+ (verificationInterval.type !== IntervalType.MONTHLY || displayedDayOfMonth) &&+ (verificationInterval.type !== IntervalType.CRON || verificationInterval.cronExpression));++ const isAllFieldsFilled = isIntervalValid;++ return (+ <div className="space-y-3">+ <div className="mb-1 flex w-full flex-col items-start sm:flex-row sm:items-center">+ <div className="mb-1 min-w-[180px] sm:mb-0">Scheduled verification</div>+ <Switch+ checked={config.isScheduledVerificationEnabled}+ onChange={(checked) => updateConfig({ isScheduledVerificationEnabled: checked })}+ size="small"+ />+ <Tooltip+ className="cursor-pointer"+ title={+ <>+ Periodically restore the latest backup into an ephemeral Postgres container to verify+ it is restorable.{' '}+ <a+ href="https://databasus.com/restore-verification"+ target="_blank"+ rel="noopener noreferrer"+ className="underline"+ >+ Read here how it works+ </a>+ </>+ }+ >+ <InfoCircleOutlined className="ml-2" style={{ color: 'gray' }} />+ </Tooltip>+ </div>++ {config.isScheduledVerificationEnabled && (+ <>+ <div className="mt-5 mb-1 flex w-full flex-col items-start sm:flex-row sm:items-center">+ <div className="mb-1 min-w-[180px] sm:mb-0">Verification interval</div>+ <Select+ value={+ isAfterBackup ? VerificationScheduleType.AFTER_BACKUP : verificationInterval?.type+ }+ onChange={selectSchedule}+ size="small"+ className="w-full max-w-[200px] grow"+ options={[+ { label: 'After backup', value: VerificationScheduleType.AFTER_BACKUP },+ { label: 'Hourly', value: IntervalType.HOURLY },+ { label: 'Daily', value: IntervalType.DAILY },+ { label: 'Weekly', value: IntervalType.WEEKLY },+ { label: 'Monthly', value: IntervalType.MONTHLY },+ { label: 'Cron', value: IntervalType.CRON },+ ]}+ />+ </div>++ {isAfterBackup && (+ <div className="mb-1 flex w-full flex-col items-start text-xs text-gray-600 sm:flex-row sm:items-center dark:text-gray-400">+ <div className="mb-1 min-w-[180px] sm:mb-0" />+ <div>+ Runs automatically after each successful backup. If there are pending in the queue,+ they are canceled to not cause infinite queue when backups are faster than+ verifications.+ </div>+ </div>+ )}++ {!isAfterBackup && verificationInterval?.type === IntervalType.WEEKLY && (+ <div className="mb-1 flex w-full flex-col items-start sm:flex-row sm:items-center">+ <div className="mb-1 min-w-[180px] sm:mb-0">Verification weekday</div>+ <Select+ value={displayedWeekday}+ onChange={(localWeekday) => {+ if (!localWeekday) return;+ const ref = localTime ?? dayjs();+ saveInterval({ weekday: getUtcWeekday(localWeekday, ref) });+ }}+ size="small"+ className="w-full max-w-[200px] grow"+ options={weekdayOptions}+ />+ </div>+ )}++ {!isAfterBackup && verificationInterval?.type === IntervalType.MONTHLY && (+ <div className="mb-1 flex w-full flex-col items-start sm:flex-row sm:items-center">+ <div className="mb-1 min-w-[180px] sm:mb-0">Verification day of month</div>+ <InputNumber+ min={1}+ max={31}+ value={displayedDayOfMonth}+ onChange={(localDom) => {+ if (!localDom) return;+ const ref = localTime ?? dayjs();+ saveInterval({ dayOfMonth: getUtcDayOfMonth(localDom, ref) });+ }}+ size="small"+ className="w-full max-w-[200px] grow"+ />+ </div>+ )}++ {!isAfterBackup && verificationInterval?.type === IntervalType.CRON && (+ <>+ <div className="mb-1 flex w-full flex-col items-start sm:flex-row sm:items-center">+ <div className="mb-1 min-w-[180px] sm:mb-0">Cron expression (UTC)</div>+ <div className="flex items-center">+ <Input+ value={verificationInterval?.cronExpression || ''}+ onChange={(e) => saveInterval({ cronExpression: e.target.value })}+ placeholder="0 4 * * 0"+ size="small"+ className="w-full max-w-[200px] grow"+ />+ <Tooltip+ className="cursor-pointer"+ title={+ <div>+ <div className="font-bold">+ Cron format: minute hour day month weekday (UTC)+ </div>+ <div className="mt-1">Examples:</div>+ <div>- 0 4 * * 0 - Every Sunday at 4:00 AM UTC</div>+ <div>- 0 */6 * * * - Every 6 hours</div>+ </div>+ }+ >+ <InfoCircleOutlined className="ml-2" style={{ color: 'gray' }} />+ </Tooltip>+ </div>+ </div>+ {verificationInterval?.cronExpression &&+ (() => {+ try {+ const interval = CronExpressionParser.parse(+ verificationInterval.cronExpression,+ {+ tz: 'UTC',+ },+ );+ const nextRun = interval.next().toDate();+ return (+ <div className="mb-1 flex w-full flex-col items-start text-xs text-gray-600 sm:flex-row sm:items-center dark:text-gray-400">+ <div className="mb-1 min-w-[180px] sm:mb-0" />+ <div className="text-gray-600 dark:text-gray-400">+ Next run {dayjs(nextRun).local().format(dateTimeFormat.format)}+ <br />({dayjs(nextRun).fromNow()})+ </div>+ </div>+ );+ } catch {+ return (+ <div className="mb-1 flex w-full flex-col items-start text-red-500 sm:flex-row sm:items-center">+ <div className="mb-1 min-w-[180px] sm:mb-0" />+ <div className="text-red-500">Invalid cron expression</div>+ </div>+ );+ }+ })()}+ </>+ )}++ {!isAfterBackup &&+ verificationInterval?.type !== IntervalType.HOURLY &&+ verificationInterval?.type !== IntervalType.CRON && (+ <div className="mb-1 flex w-full flex-col items-start sm:flex-row sm:items-center">+ <div className="mb-1 min-w-[180px] sm:mb-0">Verification time of day</div>+ <TimePicker+ value={localTime}+ format={timeFormat.format}+ use12Hours={timeFormat.use12Hours}+ allowClear={false}+ size="small"+ className="w-full max-w-[200px] grow"+ onChange={(t) => {+ if (!t) return;+ const patch: Partial<Interval> = { timeOfDay: t.utc().format('HH:mm') };++ if (verificationInterval?.type === IntervalType.WEEKLY && displayedWeekday) {+ patch.weekday = getUtcWeekday(displayedWeekday, t);+ }+ if (+ verificationInterval?.type === IntervalType.MONTHLY &&+ displayedDayOfMonth+ ) {+ patch.dayOfMonth = getUtcDayOfMonth(displayedDayOfMonth, t);+ }++ saveInterval(patch);+ }}+ />+ </div>+ )}++ <div className="mt-5 mb-1 flex w-full flex-col items-start sm:flex-row sm:items-start">+ <div className="mt-0 mb-1 min-w-[180px] sm:mt-1 sm:mb-0">Notifications</div>+ <div className="flex flex-col space-y-2">+ <Checkbox+ checked={config.sendNotificationsOn.includes(+ VerificationNotificationType.VerificationSuccess,+ )}+ onChange={(e) =>+ toggleNotification(+ VerificationNotificationType.VerificationSuccess,+ e.target.checked,+ )+ }+ >+ Verification success+ </Checkbox>+ <Checkbox+ checked={config.sendNotificationsOn.includes(+ VerificationNotificationType.VerificationFailed,+ )}+ onChange={(e) =>+ toggleNotification(+ VerificationNotificationType.VerificationFailed,+ e.target.checked,+ )+ }+ >+ Verification failed+ </Checkbox>+ </div>+ </div>+ </>+ )}++ <div className="mt-6 flex justify-end space-x-2">+ <Button onClick={onClose} disabled={isSaving}>+ Cancel+ </Button>++ <Button+ type="primary"+ onClick={handleSave}+ loading={isSaving}+ disabled={!isUnsaved || !isAllFieldsFilled}+ >+ Save+ </Button>+ </div>+ </div>+ );+};diff --git a/frontend/src/features/verification/config/ui/ShowBackupVerificationConfigComponent.tsx b/frontend/src/features/verification/config/ui/ShowBackupVerificationConfigComponent.tsxnew file mode 100644index 00000000..46f149dd--- /dev/null+++ b/frontend/src/features/verification/config/ui/ShowBackupVerificationConfigComponent.tsx@@ -0,0 +1,185 @@+import { Spin } from 'antd';+import { CronExpressionParser } from 'cron-parser';+import dayjs from 'dayjs';+import { useEffect, useState } from 'react';++import { IntervalType } from '../../../../entity/intervals';+import {+ type BackupVerificationConfig,+ VerificationNotificationType,+ VerificationScheduleType,+ verificationConfigApi,+} from '../../../../entity/verification/config';+import { getUserTimeFormat } from '../../../../shared/time';+import {+ getUserTimeFormat as getIs12Hour,+ getLocalDayOfMonth,+ getLocalWeekday,+} from '../../../../shared/time/utils';++interface Props {+ databaseId: string;+}++const weekdayLabels: Record<number, string> = {+ 1: 'Mon',+ 2: 'Tue',+ 3: 'Wed',+ 4: 'Thu',+ 5: 'Fri',+ 6: 'Sat',+ 7: 'Sun',+};++const intervalLabels: Record<IntervalType, string> = {+ [IntervalType.HOURLY]: 'Hourly',+ [IntervalType.DAILY]: 'Daily',+ [IntervalType.WEEKLY]: 'Weekly',+ [IntervalType.MONTHLY]: 'Monthly',+ [IntervalType.CRON]: 'Cron',+};++const notificationLabels: Record<VerificationNotificationType, string> = {+ [VerificationNotificationType.VerificationSuccess]: 'Verification success',+ [VerificationNotificationType.VerificationFailed]: 'Verification failed',+};++export const ShowBackupVerificationConfigComponent = ({ databaseId }: Props) => {+ const [config, setConfig] = useState<BackupVerificationConfig>();+ const [isLoading, setIsLoading] = useState(true);++ useEffect(() => {+ setIsLoading(true);+ verificationConfigApi+ .getByDatabaseId(databaseId)+ .then(setConfig)+ .catch((error: Error) => alert(error.message))+ .finally(() => setIsLoading(false));+ }, [databaseId]);++ if (isLoading) {+ return <Spin size="small" />;+ }++ if (!config) return <div />;++ const is12Hour = getIs12Hour();+ const timeFormat = { use12Hours: is12Hour, format: is12Hour ? 'h:mm A' : 'HH:mm' };+ const dateTimeFormat = getUserTimeFormat();++ const { verificationInterval } = config;++ const localTime = verificationInterval?.timeOfDay+ ? dayjs.utc(verificationInterval.timeOfDay, 'HH:mm').local()+ : undefined;++ const formattedTime = localTime ? localTime.format(timeFormat.format) : '';++ const displayedWeekday: number | undefined =+ verificationInterval?.type === IntervalType.WEEKLY &&+ verificationInterval.weekday &&+ verificationInterval.timeOfDay+ ? getLocalWeekday(verificationInterval.weekday, verificationInterval.timeOfDay)+ : verificationInterval?.weekday;++ const displayedDayOfMonth: number | undefined =+ verificationInterval?.type === IntervalType.MONTHLY &&+ verificationInterval.dayOfMonth &&+ verificationInterval.timeOfDay+ ? getLocalDayOfMonth(verificationInterval.dayOfMonth, verificationInterval.timeOfDay)+ : verificationInterval?.dayOfMonth;++ const isAfterBackup = config.scheduleType === VerificationScheduleType.AFTER_BACKUP;++ return (+ <div>+ <div className="mb-1 flex w-full items-center">+ <div className="min-w-[180px]">Scheduled verification</div>+ <div className={config.isScheduledVerificationEnabled ? '' : 'text-gray-500'}>+ {config.isScheduledVerificationEnabled ? 'Yes' : 'No'}+ </div>+ </div>++ {config.isScheduledVerificationEnabled && (+ <>+ <div className="mt-5 mb-1 flex w-full items-center">+ <div className="min-w-[180px]">Verification interval</div>+ <div>+ {isAfterBackup+ ? 'After backup'+ : verificationInterval?.type+ ? intervalLabels[verificationInterval.type]+ : ''}+ </div>+ </div>++ {!isAfterBackup && verificationInterval?.type === IntervalType.WEEKLY && (+ <div className="mb-1 flex w-full items-center">+ <div className="min-w-[180px]">Verification weekday</div>+ <div>{displayedWeekday ? weekdayLabels[displayedWeekday] : ''}</div>+ </div>+ )}++ {!isAfterBackup && verificationInterval?.type === IntervalType.MONTHLY && (+ <div className="mb-1 flex w-full items-center">+ <div className="min-w-[180px]">Verification day of month</div>+ <div>{displayedDayOfMonth || ''}</div>+ </div>+ )}++ {!isAfterBackup && verificationInterval?.type === IntervalType.CRON && (+ <>+ <div className="mb-1 flex w-full items-center">+ <div className="min-w-[180px]">Cron expression (UTC)</div>+ <code className="rounded bg-gray-100 px-2 py-0.5 text-sm dark:bg-gray-700">+ {verificationInterval?.cronExpression || ''}+ </code>+ </div>+ {verificationInterval?.cronExpression &&+ (() => {+ try {+ const interval = CronExpressionParser.parse(+ verificationInterval.cronExpression,+ {+ tz: 'UTC',+ },+ );+ const nextRun = interval.next().toDate();+ return (+ <div className="mb-1 flex w-full items-center text-xs text-gray-600 dark:text-gray-400">+ <div className="min-w-[180px]" />+ <div>+ Next run {dayjs(nextRun).local().format(dateTimeFormat.format)}+ <br />({dayjs(nextRun).fromNow()})+ </div>+ </div>+ );+ } catch {+ return null;+ }+ })()}+ </>+ )}++ {!isAfterBackup &&+ verificationInterval?.type !== IntervalType.HOURLY &&+ verificationInterval?.type !== IntervalType.CRON && (+ <div className="mb-1 flex w-full items-center">+ <div className="min-w-[180px]">Verification time of day</div>+ <div>{formattedTime}</div>+ </div>+ )}++ <div className="mt-5 mb-1 flex w-full items-center">+ <div className="min-w-[180px]">Notifications</div>+ <div>+ {config.sendNotificationsOn.length > 0+ ? config.sendNotificationsOn.map((type) => notificationLabels[type]).join(', ')+ : 'None'}+ </div>+ </div>+ </>+ )}+ </div>+ );+};diff --git a/frontend/src/features/verification/runs/index.ts b/frontend/src/features/verification/runs/index.tsnew file mode 100644index 00000000..e3d8d0e4--- /dev/null+++ b/frontend/src/features/verification/runs/index.ts@@ -0,0 +1 @@+export { VerificationsComponent } from './ui/VerificationsComponent';diff --git a/frontend/src/features/verification/runs/ui/VerificationDetailDrawer.tsx b/frontend/src/features/verification/runs/ui/VerificationDetailDrawer.tsxnew file mode 100644index 00000000..e2c2ec2b--- /dev/null+++ b/frontend/src/features/verification/runs/ui/VerificationDetailDrawer.tsx@@ -0,0 +1,248 @@+import { Button, Drawer, Skeleton, Table, Tag } from 'antd';+import type { ColumnsType } from 'antd/es/table';+import dayjs from 'dayjs';+import { useEffect, useMemo, useState } from 'react';++import {+ type RestoreVerification,+ type RestoreVerificationTableStat,+ VerificationStatus,+ VerificationTrigger,+ verificationRunsApi,+} from '../../../../entity/verification/runs';+import { getUserTimeFormat } from '../../../../shared/time';++interface Props {+ verificationId: string;+ onClose: () => void;+}++const formatDurationMs = (durationMs?: number) => {+ if (durationMs === undefined || durationMs === null) {+ return '-';+ }++ const totalSeconds = Math.floor(durationMs / 1000);++ if (totalSeconds < 60) {+ return `${totalSeconds}s`;+ }++ const minutes = Math.floor(totalSeconds / 60);+ const seconds = totalSeconds % 60;++ return `${minutes}m ${seconds}s`;+};++const formatSizeBytes = (sizeBytes?: number) => {+ if (sizeBytes === undefined || sizeBytes === null || sizeBytes <= 0) {+ return '-';+ }++ const sizeMb = sizeBytes / (1024 * 1024);++ if (sizeMb >= 1024) {+ return `${Number((sizeMb / 1024).toFixed(2)).toLocaleString()} GB`;+ }++ return `${Number(sizeMb.toFixed(2)).toLocaleString()} MB`;+};++const renderStatusTag = (status: VerificationStatus) => {+ if (status === VerificationStatus.COMPLETED) {+ return <Tag color="green">Successful</Tag>;+ }++ if (status === VerificationStatus.FAILED) {+ return <Tag color="red">Failed</Tag>;+ }++ if (status === VerificationStatus.RUNNING) {+ return <Tag color="blue">Running</Tag>;+ }++ if (status === VerificationStatus.PENDING) {+ return <Tag>Pending</Tag>;+ }++ if (status === VerificationStatus.CANCELED) {+ return <Tag color="default">Canceled</Tag>;+ }++ return <Tag>{status}</Tag>;+};++const renderTriggerTag = (trigger: VerificationTrigger) => {+ if (trigger === VerificationTrigger.MANUAL) {+ return <Tag color="blue">Manual</Tag>;+ }++ return <Tag color="purple">Scheduled</Tag>;+};++const renderInfoRow = (label: string, value: React.ReactNode) => (+ <div className="flex items-baseline justify-between border-b border-gray-100 py-1 last:border-b-0 dark:border-gray-700">+ <span className="text-xs text-gray-500 dark:text-gray-400">{label}</span>+ <span className="text-sm text-gray-800 dark:text-gray-200">{value}</span>+ </div>+);++const renderSection = (title: string, children: React.ReactNode) => (+ <div className="mb-4">+ <div className="mb-1 text-xs font-semibold tracking-wide text-gray-400 uppercase dark:text-gray-500">+ {title}+ </div>+ {children}+ </div>+);++export const VerificationDetailDrawer = ({ verificationId, onClose }: Props) => {+ const [verification, setVerification] = useState<RestoreVerification | undefined>();+ const [isLoading, setIsLoading] = useState(true);+ const [loadError, setLoadError] = useState<string | undefined>();++ const loadVerification = () => {+ setIsLoading(true);+ setLoadError(undefined);++ verificationRunsApi+ .getById(verificationId)+ .then(setVerification)+ .catch((e: Error) => {+ alert(e.message);+ setLoadError(e.message);+ })+ .finally(() => setIsLoading(false));+ };++ useEffect(() => {+ loadVerification();+ }, [verificationId]);++ const sortedStats = useMemo(+ () => [...(verification?.tableStats ?? [])].sort((a, b) => b.rowCount - a.rowCount),+ [verification],+ );++ const tableStatColumns: ColumnsType<RestoreVerificationTableStat> = [+ {+ title: 'Schema',+ dataIndex: 'schemaName',+ key: 'schemaName',+ width: 140,+ render: (schemaName: string) => <span className="font-mono text-xs">{schemaName}</span>,+ },+ {+ title: 'Table',+ dataIndex: 'name',+ key: 'name',+ render: (name: string) => <span className="font-mono text-xs">{name}</span>,+ },+ {+ title: 'Rows',+ dataIndex: 'rowCount',+ key: 'rowCount',+ width: 120,+ align: 'right',+ render: (rowCount: number) => (+ <span className="tabular-nums">{rowCount.toLocaleString()}</span>+ ),+ sorter: (a, b) => a.rowCount - b.rowCount,+ },+ ];++ return (+ <Drawer+ title="Restore check details"+ placement="right"+ width={620}+ onClose={onClose}+ open={true}+ maskClosable={true}+ >+ {isLoading ? (+ <Skeleton active paragraph={{ rows: 10 }} />+ ) : loadError || !verification ? (+ <div className="flex flex-col items-center gap-3 py-12 text-center">+ <div className="text-sm text-gray-500 dark:text-gray-400">+ Could not load restore check details.+ </div>+ <Button onClick={loadVerification}>Retry</Button>+ </div>+ ) : (+ <div>+ {verification.failMessage && (+ <div className="mb-4 rounded-md border border-red-200 bg-red-50 p-3 text-sm text-red-700 dark:border-red-900 dark:bg-red-950 dark:text-red-300">+ <div className="mb-1 font-semibold">Failure</div>+ <div className="break-words whitespace-pre-wrap">{verification.failMessage}</div>+ </div>+ )}++ {renderSection(+ 'Status',+ <>+ {renderInfoRow('Status', renderStatusTag(verification.status))}+ {renderInfoRow('Trigger', renderTriggerTag(verification.trigger))}+ {renderInfoRow('Attempt', verification.attemptCount)}+ </>,+ )}++ {renderSection(+ 'Timeline',+ <>+ {renderInfoRow(+ 'Created at',+ dayjs.utc(verification.createdAt).local().format(getUserTimeFormat().format),+ )}+ {verification.startedAt &&+ renderInfoRow(+ 'Started at',+ dayjs.utc(verification.startedAt).local().format(getUserTimeFormat().format),+ )}+ {verification.finishedAt &&+ renderInfoRow(+ 'Finished at',+ dayjs.utc(verification.finishedAt).local().format(getUserTimeFormat().format),+ )}+ </>,+ )}++ {renderSection(+ 'Results & diagnostics',+ <>+ {renderInfoRow('Restore duration', formatDurationMs(verification.restoreDurationMs))}+ {renderInfoRow('Verify duration', formatDurationMs(verification.verifyDurationMs))}+ {renderInfoRow(+ 'Restored DB size',+ formatSizeBytes(verification.dbSizeBytesAfterRestore),+ )}+ {renderInfoRow('Schemas', verification.schemaCount ?? '-')}+ {renderInfoRow('Tables', verification.tableCount ?? '-')}+ {verification.pgRestoreExitCode !== undefined &&+ verification.pgRestoreExitCode !== null &&+ renderInfoRow('pg_restore exit code', verification.pgRestoreExitCode)}+ </>,+ )}++ <h3 className="mt-2 mb-2 text-base font-semibold dark:text-white">+ Per-table row counts+ </h3>+ {sortedStats.length === 0 ? (+ <div className="text-sm text-gray-500 dark:text-gray-400">+ No per-table stats reported.+ </div>+ ) : (+ <Table+ bordered+ size="small"+ columns={tableStatColumns}+ dataSource={sortedStats}+ rowKey="id"+ pagination={false}+ />+ )}+ </div>+ )}+ </Drawer>+ );+};diff --git a/frontend/src/features/verification/runs/ui/VerificationsComponent.tsx b/frontend/src/features/verification/runs/ui/VerificationsComponent.tsxnew file mode 100644index 00000000..f6ef262c--- /dev/null+++ b/frontend/src/features/verification/runs/ui/VerificationsComponent.tsx@@ -0,0 +1,492 @@+import {+ CheckCircleOutlined,+ ClockCircleOutlined,+ CloseCircleOutlined,+ ExclamationCircleOutlined,+ EyeOutlined,+ PauseCircleOutlined,+ SyncOutlined,+} from '@ant-design/icons';+import { Spin, Table, Tag, Tooltip } from 'antd';+import type { ColumnsType } from 'antd/es/table';+import dayjs from 'dayjs';+import { useEffect, useRef, useState } from 'react';++import type { Database } from '../../../../entity/databases';+import { verificationAgentApi } from '../../../../entity/verification/agents';+import {+ type RestoreVerification,+ VerificationStatus,+ VerificationTrigger,+ verificationRunsApi,+} from '../../../../entity/verification/runs';+import { getUserTimeFormat } from '../../../../shared/time';+import { VerificationDetailDrawer } from './VerificationDetailDrawer';++interface Props {+ database: Database;+ isCanManageDBs: boolean;+ isDirectlyUnderTab?: boolean;+ scrollContainerRef?: React.RefObject<HTMLDivElement | null>;+}++const AGENT_AVAILABILITY_REFRESH_MS = 5_000;+const VERIFICATIONS_REFRESH_MS = 1_000;+const VERIFICATIONS_PAGE_SIZE = 50;++const formatDurationMs = (durationMs?: number) => {+ if (durationMs === undefined || durationMs === null) {+ return '-';+ }++ const totalSeconds = Math.floor(durationMs / 1000);+ const hours = Math.floor(totalSeconds / 3600);+ const minutes = Math.floor((totalSeconds % 3600) / 60);+ const seconds = totalSeconds % 60;++ if (hours > 0) {+ return `${hours}h ${minutes}m ${seconds}s`;+ }++ if (minutes > 0) {+ return `${minutes}m ${seconds}s`;+ }++ return `${seconds}s`;+};++const renderStatus = (status: VerificationStatus) => {+ if (status === VerificationStatus.COMPLETED) {+ return (+ <div className="flex items-center text-green-600">+ <CheckCircleOutlined className="mr-2" style={{ fontSize: 16 }} />+ <span>Successful</span>+ </div>+ );+ }++ if (status === VerificationStatus.FAILED) {+ return (+ <div className="flex items-center text-red-600">+ <ExclamationCircleOutlined className="mr-2" style={{ fontSize: 16 }} />+ <span>Failed</span>+ </div>+ );+ }++ if (status === VerificationStatus.RUNNING) {+ return (+ <div className="flex items-center font-bold text-blue-600">+ <SyncOutlined spin />+ <span className="ml-2">Running</span>+ </div>+ );+ }++ if (status === VerificationStatus.PENDING) {+ return (+ <div className="flex items-center text-gray-600">+ <ClockCircleOutlined className="mr-2" style={{ fontSize: 16 }} />+ <span>Pending</span>+ </div>+ );+ }++ if (status === VerificationStatus.CANCELED) {+ return (+ <div className="flex items-center text-gray-500">+ <CloseCircleOutlined className="mr-2" style={{ fontSize: 16 }} />+ <span>Canceled</span>+ </div>+ );+ }++ return (+ <div className="flex items-center">+ <PauseCircleOutlined className="mr-2" style={{ fontSize: 16 }} />+ <span>{status}</span>+ </div>+ );+};++const renderTrigger = (trigger: VerificationTrigger) => {+ if (trigger === VerificationTrigger.MANUAL) {+ return <Tag color="blue">Manual</Tag>;+ }++ return <Tag color="purple">Scheduled</Tag>;+};++export const VerificationsComponent = ({+ database,+ isCanManageDBs,+ isDirectlyUnderTab,+ scrollContainerRef,+}: Props) => {+ const [verifications, setVerifications] = useState<RestoreVerification[]>([]);+ const [isLoading, setIsLoading] = useState(true);+ const [selectedVerificationId, setSelectedVerificationId] = useState<string | undefined>();+ const [hasAgents, setHasAgents] = useState<boolean | undefined>();+ const [cancellingVerificationId, setCancellingVerificationId] = useState<string | undefined>();++ const [totalVerifications, setTotalVerifications] = useState(0);+ const [currentLimit, setCurrentLimit] = useState(VERIFICATIONS_PAGE_SIZE);+ const [isLoadingMore, setIsLoadingMore] = useState(false);+ const [hasMore, setHasMore] = useState(true);++ const isVerificationsRequestInFlightRef = useRef(false);++ const loadVerifications = async (limit?: number) => {+ if (isVerificationsRequestInFlightRef.current) {+ return;+ }++ isVerificationsRequestInFlightRef.current = true;+ const loadLimit = limit ?? currentLimit;++ try {+ const response = await verificationRunsApi.listByDatabase(database.id, loadLimit, 0);+ setVerifications(response.verifications);+ setTotalVerifications(response.total);+ setHasMore(response.verifications.length < response.total);+ } catch (e) {+ alert((e as Error).message);+ } finally {+ isVerificationsRequestInFlightRef.current = false;+ }+ };++ const loadMoreVerifications = async () => {+ if (isLoadingMore || !hasMore) {+ return;+ }++ setIsLoadingMore(true);++ const newLimit = currentLimit + VERIFICATIONS_PAGE_SIZE;+ setCurrentLimit(newLimit);++ await loadVerifications(newLimit);++ setIsLoadingMore(false);+ };++ const cancelVerification = async (id: string) => {+ setCancellingVerificationId(id);++ try {+ await verificationRunsApi.cancel(id);+ await loadVerifications();+ } catch (e) {+ alert((e as Error).message);+ } finally {+ setCancellingVerificationId(undefined);+ }+ };++ const renderActions = (record: RestoreVerification) => {+ if (+ record.status === VerificationStatus.PENDING ||+ record.status === VerificationStatus.RUNNING+ ) {+ if (!isCanManageDBs) {+ return <span className="text-xs text-gray-400">-</span>;+ }++ const isCancelling = cancellingVerificationId === record.id;++ return (+ <div className="flex gap-2 text-lg">+ {isCancelling ? (+ <SyncOutlined spin />+ ) : (+ <Tooltip title="Cancel verification">+ <CloseCircleOutlined+ className="cursor-pointer"+ onClick={() => {+ if (cancellingVerificationId) return;+ cancelVerification(record.id);+ }}+ style={{ color: '#ff0000', opacity: cancellingVerificationId ? 0.2 : 1 }}+ />+ </Tooltip>+ )}+ </div>+ );+ }++ if (+ record.status === VerificationStatus.COMPLETED ||+ record.status === VerificationStatus.FAILED+ ) {+ return (+ <div className="flex gap-2 text-lg">+ <Tooltip title="View details">+ <EyeOutlined+ className="cursor-pointer"+ onClick={() => setSelectedVerificationId(record.id)}+ style={{ color: '#155dfc' }}+ />+ </Tooltip>+ </div>+ );+ }++ return <span className="text-xs text-gray-400">-</span>;+ };++ useEffect(() => {+ setCurrentLimit(VERIFICATIONS_PAGE_SIZE);+ setHasMore(true);+ setIsLoading(true);+ loadVerifications(VERIFICATIONS_PAGE_SIZE).then(() => setIsLoading(false));+ }, [database.id]);++ useEffect(() => {+ const intervalId = setInterval(() => {+ loadVerifications();+ }, VERIFICATIONS_REFRESH_MS);++ return () => clearInterval(intervalId);+ }, [currentLimit]);++ useEffect(() => {+ let isCancelled = false;++ const loadAvailability = () => {+ verificationAgentApi+ .getAvailability()+ .then((availability) => {+ if (isCancelled) return;+ setHasAgents(availability.hasAgents);+ })+ .catch(() => {+ if (isCancelled) return;+ setHasAgents(undefined);+ });+ };++ loadAvailability();+ const intervalId = setInterval(loadAvailability, AGENT_AVAILABILITY_REFRESH_MS);++ return () => {+ isCancelled = true;+ clearInterval(intervalId);+ };+ }, []);++ useEffect(() => {+ if (!scrollContainerRef?.current) {+ return;+ }++ const handleScroll = () => {+ if (!scrollContainerRef.current) return;++ const { scrollTop, scrollHeight, clientHeight } = scrollContainerRef.current;++ if (scrollHeight - scrollTop <= clientHeight + 100 && hasMore && !isLoadingMore) {+ loadMoreVerifications();+ }+ };++ const container = scrollContainerRef.current;+ container.addEventListener('scroll', handleScroll);+ return () => container.removeEventListener('scroll', handleScroll);+ }, [hasMore, isLoadingMore, currentLimit, scrollContainerRef]);++ const columns: ColumnsType<RestoreVerification> = [+ {+ title: 'Created at',+ dataIndex: 'createdAt',+ key: 'createdAt',+ width: 220,+ render: (createdAt: string) => (+ <div>+ {dayjs.utc(createdAt).local().format(getUserTimeFormat().format)} <br />+ <span className="text-gray-500 dark:text-gray-400">+ ({dayjs.utc(createdAt).local().fromNow()})+ </span>+ </div>+ ),+ },+ {+ title: 'Status',+ dataIndex: 'status',+ key: 'status',+ width: 160,+ render: (status: VerificationStatus) => renderStatus(status),+ },+ {+ title: 'Trigger',+ dataIndex: 'trigger',+ key: 'trigger',+ width: 110,+ render: (trigger: VerificationTrigger) => renderTrigger(trigger),+ },+ {+ title: (+ <div className="flex items-center">+ Duration+ <Tooltip className="ml-1" title="Restore + verify time reported by the agent.">+ <ExclamationCircleOutlined />+ </Tooltip>+ </div>+ ),+ key: 'duration',+ width: 130,+ render: (_, record: RestoreVerification) => {+ const restoreMs = record.restoreDurationMs ?? 0;+ const verifyMs = record.verifyDurationMs ?? 0;+ const total = restoreMs + verifyMs;++ if (total === 0) {+ return '-';+ }++ return (+ <div className="text-sm">+ <div>{formatDurationMs(total)}</div>+ <div className="text-xs text-gray-500 dark:text-gray-400">+ restore {formatDurationMs(restoreMs)}+ </div>+ </div>+ );+ },+ },+ {+ title: 'Actions',+ key: 'actions',+ width: 120,+ render: (_, record: RestoreVerification) => renderActions(record),+ },+ ];++ return (+ <div+ className={`w-full bg-white p-3 shadow md:p-5 dark:bg-gray-800 ${isDirectlyUnderTab ? 'rounded-tr-md rounded-br-md rounded-bl-md' : 'rounded-md'}`}+ >+ <h2 className="text-lg font-bold md:text-xl dark:text-white">Restore verifications</h2>++ <p className="mt-2 max-w-2xl text-sm text-gray-500 dark:text-gray-400">+ Each row is one attempt to restore a backup of this database into a temporary copy+ </p>++ {hasAgents === false && (+ <div className="mt-3 flex max-w-2xl max-w-[400px] items-center gap-2 rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-900 dark:border-amber-900/50 dark:bg-amber-950/40 dark:text-amber-200">+ <ExclamationCircleOutlined className="shrink-0" />+ <span>+ No verification agents registered - please add it in Databasus settings tab in+ "Verification agents" section.{' '}+ <a+ href="https://databasus.com/restore-verification"+ target="_blank"+ rel="noopener noreferrer"+ className="underline hover:no-underline"+ >+ Learn more+ </a>+ </span>+ </div>+ )}++ <div className="mt-5 w-full md:max-w-[900px]">+ {/* Desktop table */}+ <div className="hidden md:block">+ <Table+ bordered+ columns={columns}+ dataSource={verifications}+ rowKey="id"+ loading={isLoading}+ size="small"+ pagination={false}+ />+ {!isLoading && verifications.length === 0 && (+ <div className="mt-3 text-center text-sm text-gray-500 dark:text-gray-400">+ No restore checks yet+ </div>+ )}+ {isLoadingMore && (+ <div className="mt-2 flex justify-center">+ <Spin />+ </div>+ )}+ {!hasMore && verifications.length > 0 && (+ <div className="mt-2 text-center text-gray-500 dark:text-gray-400">+ All restore checks loaded ({totalVerifications} total)+ </div>+ )}+ </div>++ {/* Mobile card list */}+ <div className="md:hidden">+ {isLoading ? (+ <div className="flex justify-center py-8">+ <Spin />+ </div>+ ) : verifications.length === 0 ? (+ <div className="py-8 text-center text-gray-500 dark:text-gray-400">+ No restore checks yet+ </div>+ ) : (+ verifications.map((verification) => (+ <div+ key={verification.id}+ className="mb-2 rounded-lg border border-gray-200 bg-white p-4 shadow-sm dark:border-gray-700 dark:bg-gray-800"+ >+ <div className="flex items-start justify-between">+ <div>+ <div className="text-xs text-gray-500 dark:text-gray-400">Created at</div>+ <div className="text-sm font-medium">+ {dayjs.utc(verification.createdAt).local().format(getUserTimeFormat().format)}+ </div>+ <div className="text-xs text-gray-500 dark:text-gray-400">+ ({dayjs.utc(verification.createdAt).local().fromNow()})+ </div>+ </div>+ <div>{renderStatus(verification.status)}</div>+ </div>++ <div className="mt-3 flex items-center gap-2">+ {renderTrigger(verification.trigger)}+ {verification.attemptCount > 1 && (+ <span className="text-xs text-gray-500">+ attempt {verification.attemptCount}+ </span>+ )}+ </div>++ {verification.failMessage && (+ <div className="mt-2 text-xs text-red-600">{verification.failMessage}</div>+ )}++ <div className="mt-3 flex items-center justify-end border-t border-gray-200 pt-3 dark:border-gray-700">+ {renderActions(verification)}+ </div>+ </div>+ ))+ )}++ {isLoadingMore && (+ <div className="mt-3 flex justify-center">+ <Spin />+ </div>+ )}+ {!hasMore && verifications.length > 0 && (+ <div className="mt-3 text-center text-sm text-gray-500 dark:text-gray-400">+ All restore checks loaded ({totalVerifications} total)+ </div>+ )}+ </div>+ </div>++ {selectedVerificationId && (+ <VerificationDetailDrawer+ verificationId={selectedVerificationId}+ onClose={() => setSelectedVerificationId(undefined)}+ />+ )}+ </div>+ );+};diff --git a/frontend/src/shared/api/apiHelper.ts b/frontend/src/shared/api/apiHelper.tsindex f3f277b4..860a0d30 100644--- a/frontend/src/shared/api/apiHelper.ts+++ b/frontend/src/shared/api/apiHelper.ts@@ -238,7 +238,12 @@ export const apiHelper = {isRetryOnError ? 0 : REPEAT_TRIES_COUNT,);- return response.json();+ if (response.status === 204) {+ return undefined as T;+ }++ const text = await response.text();+ return (text ? JSON.parse(text) : undefined) as T;},fetchDeleteRaw: async (diff --git a/frontend/src/widgets/main/MainScreenComponent.tsx b/frontend/src/widgets/main/MainScreenComponent.tsxindex 6f5d0d5b..55f70a10 100644--- a/frontend/src/widgets/main/MainScreenComponent.tsx+++ b/frontend/src/widgets/main/MainScreenComponent.tsx@@ -212,6 +212,34 @@ export const MainScreenComponent = () => {</div><div className="ml-auto hidden items-center gap-5 md:flex">+ {!IS_CLOUD && (+ <Tooltip title="99.9% uptime, 2x backup copies">+ <a+ className="flex items-center gap-2 !text-black hover:opacity-80 dark:!text-gray-200"+ href="https://databasus.com/cloud"+ target="_blank"+ rel="noreferrer"+ >+ Cloud+ <span className="relative flex h-2 w-2" aria-label="99.9% uptime, 2 backup copies">+ <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-green-500 opacity-75" />+ <span className="relative inline-flex h-2 w-2 rounded-full bg-green-500" />+ </span>+ </a>+ </Tooltip>+ )}++ {!IS_CLOUD && (+ <a+ className="!text-black hover:opacity-80 dark:!text-gray-200"+ href="https://databasus.com/labs"+ target="_blank"+ rel="noreferrer"+ >+ Labs+ </a>+ )}+<aclassName="!text-black hover:opacity-80 dark:!text-gray-200"href="https://databasus.com/installation"@@ -230,23 +258,6 @@ export const MainScreenComponent = () => {Community</a>- {!IS_CLOUD && (- <Tooltip title="99.9% uptime, 2x backup copies">- <a- className="flex items-center gap-2 !text-black hover:opacity-80 dark:!text-gray-200"- href="https://databasus.com/cloud"- target="_blank"- rel="noreferrer"- >- Cloud- <span className="relative flex h-2 w-2" aria-label="99.9% uptime, 2 backup copies">- <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-green-500 opacity-75" />- <span className="relative inline-flex h-2 w-2 rounded-full bg-green-500" />- </span>- </a>- </Tooltip>- )}-{isUsedMoreThan85Percent && (<Tooltip title="To make backups locally and restore them, you need to have enough space on your disk. For restore, you need to have same amount of space that the backup size."><div