PostgreSQL backup tool with Point-In-Time-Recovery and restore verification
TypeScript backupbackupsdatabasedatabase-backupdevopsdockergolangkubernetesmariadbmongodbmysqlpgpostgrespostgresqls3self-hostedsystem-administrationtoolsweb-ui
1. Establish the pending deletion model
- 1.1 Add the
storage_pending_deletionsmigration withnot_before,generation,attempt_count,last_error, the unique(storage_id, file_name)constraint, theON DELETE CASCADEstorage foreign key and one index onnot_before; verifymake migration-up-testapplies it andmake migration-downreverses it. The plan gaveattempt_countboth meanings and the first implementation followed it, which made every deletion request count as a failed attempt: a file requested a few times began its first real attempt near the retry cap. A follow-up migration splits the compare-and-swap value intogenerationand leavesattempt_countcounting attempts. - 1.2 Add
StoredFileReference,WriteReceiptand the narrowFileWriter,FileRemoverandStorageLocatorcontracts plusPendingDeletionRepositoryunderbackend/internal/features/storages/filesaspackage storage_files, split acrossdoc.go,store.go,repository.go,worker.go,model.go,dto.go,errors.goandtimings.goso the background loop and the transport types do not share a file with the store; verify withmake testand confirm by inspection that the package imports neither its parentstoragespackage nor any backup repository. - 1.3 Implement the repository operations: insert-if-absent, insert-or-take, generation-conditional completion, generation-conditional reschedule and a skip-locked batch claim excluding a caller-supplied set of live IDs; verify rollback, an insert that conflicts with an existing row, duplicate request, stale-generation and empty-batch cases with repository tests, and that a claim skips rows locked by an uncommitted deletion request instead of waiting for it.
- 1.4 Add the package timing constants for the commit window, the attempt lease, the retry base and maximum delay and the worker tick, with a test constructor that shrinks them; verify the shrunk values reach every consumer so no test waits on production timings.
2. Route writes through the file store
- 2.1 Implement
storage_files.Store.WriteFileso it joins the in-process live-write set before inserting the pending deletion row, inserts it ineligible by one commit window, calls the provider and then updatesnot_beforeconditionally on the unchanged generation before leaving the set. Verify that a write whose name already carries a pending deletion fails without sending bytes and reports that the name is already registered rather than guessing which caller registered it, that provider failure leaves the file eligible exactly when its writer is gone, that success returns a receipt carrying the generation, that a write whose file was taken for deletion returns an error instead of a receipt and that the row leaves the live set in every branch including panic. - 2.2 Implement
ConfirmFileWrites(ctx, tx, receipts)andRequestFileDeletions(ctx, tx, references)as transaction-bound state changes without remote calls, while the registration insert insideWriteFilecommits on its own connection so a caller rollback cannot take the obligation with it, where confirmation fails unless every receipt matches exactly one row at its generation; verify commit, rollback, repeated calls, mixed receipt batches and a receipt invalidated by a concurrent deletion request. - 2.3 Make
RequestFileDeletionssucceed against every state, inserting a missing row atnot_before = now()and taking an existing one by settingnot_beforeto now and incrementing the generation; verify it never returns an error for a running writer and that the writer's own completion cannot extend a file that was taken from it. - 2.4 Wire
storage_files.Store, its repository, storage locator and background worker through the existing storage dependency setup while keeping reads on the currentStorageService; verify application construction and shutdown with the relevant dependency-injection tests.
3. Make deletion durable and terminating
- 3.1 Implement one deletion-worker pass that takes the live-write mutex, reads the set under it and holds it until its claim statement returns, so no writer can join in between; that statement claims a bounded batch of due rows with skip-locked row selection ordered by
not_before, excludes the set and increments the generation, commits the claim and only then performs remote I/O; verify a live write is never claimed even when it runs longer than the scan interval or when a cascading deletion request pulls its row forward to now, a file inherited from a stopped process is claimed on the first pass, a claim invalidates an outstanding receipt and an open deletion request does not block the batch. - 3.2 Complete a successful deletion by removing the row and reschedule a failed one with capped exponential backoff, jitter, the incremented attempt count and a sanitized error, both conditional on the generation it claimed; verify transient failure, process restart, an attempt that outlived its lease, an attempt whose row and storage were both removed by a storage deletion while it ran, and eventual success. Since
not_beforeis compared against the database clock, drive these tests with the shrunk constants from task 1.4, a deterministic jitter source and fixtures that writenot_beforedirectly, not with a Go-side clock. - 3.3 Persist only bounded, sanitized deletion errors and emit attempt, retry and success logs carrying
job_name, a freshjob_id,storage_id,file_nameanderroras key-value pairs, with the attempt count and the next retry time in the message text and the per-pass pending count, overdue count and oldest-obligation age in the summary message, following the value-in-message rule inbackend/AGENTS.md; verify centralized redaction and truncation preserve these fields while removing credentials, storage configuration and signed URLs. - 3.4 Add a non-overlapping
Runguard and a single-pass execution seam, then register graceful startup and shutdown with the application lifecycle inbackend/cmd/main.go; verify a secondRunpanics, that overlapping ticks are skipped and that a cancelled context ends the loop only after the pass in flight has finished its provider call. The worker is started with a barego, the same as every other background service incmd/main.go, so nothing joins it at shutdown.
4. Enforce the provider cleanup contract
- 4.1 Make local storage deletion remove the exact final file and any staging or partial file for the same operation, while treating only confirmed absence as success; verify failure-after-write and repeated-deletion cases with filesystem tests.
- 4.2 Make S3-compatible deletion remove the base object, manifest, exact numbered chunks and incomplete multipart uploads even when the manifest was never published, without deleting prefix-neighbor objects; verify all cases against the repository MinIO test container, including repeated deletion and an injected mid-upload failure.
- 4.3 Make Azure deletion cover committed objects and uncommitted blocks for the exact operation. Guard the block-discarding step on blob existence rather than on a non-empty committed block list, because a blob written with one Put Blob has no committed blocks and committing an empty list over it would truncate real content. The step assumes Azure answers Get Block List for a blob that was never committed, which Azurite does; if Azure answers 404 instead, the step becomes a silent no-op that nothing in this repository can detect. Azurite cannot verify this end to end, because its
DeleteBlobsucceeds on a blob holding only uncommitted blocks and drops them, while Azure returns 404 and keeps charging for the blocks for a week; verify the block-discarding step directly instead, that a committed blob is not emptied by it and thatDeleteFilestill removes a committed blob and tolerates an absent one. - 4.4 Make Google Drive treat a missing
databasus_backupsfolder as a confirmed absence rather than an error, since cleanup would otherwise retry that obligation for as long as the storage exists, and leave rclone unchanged because it already resolves one exact object and returns any lookup error that is not a confirmed absence.deleteByNamealready lists every file with the exact name in the backups folder and deletes each, which covers a duplicate left by an interrupted attempt. Verify rclone against a local remote for the exact-path, similarly-prefixed, sidecar, absent and repeated cases. Google Drive has no test double or container in this repository and needs live OAuth, so it stays covered by inspection. - 4.5 Tighten FTP, SFTP and NAS deletion so only an explicit not-found result is acknowledged as success and connectivity, permission and ambiguous failures are retried. Each one drops its stat probe and classifies the removal reply instead, because the probe was where any error became a silent success. Verify with provider tests that a stored file is gone after deletion and that an absent one still succeeds, and unit test the FTP reply classifier. Cover the refusal branch for SFTP and NAS by deleting a non-empty directory, in each provider's own package, where the test can reach the connection helper that creates it;
SaveFilecannot, because it does not create parent directories. Absence is covered by the existing provider table, except on NAS, where the configured path is a directory that never exists and so also covers a removal whose parent is missing. FTP has no equivalent, because 550 is its answer to both a missing file and a refused one, so its classifier is unit tested instead.
5. Integrate logical backups
- 5.1 Change logical database writers to accept the file store and return write receipts for every uploaded artifact, including metadata, without exposing a raw writable
Storage; verify MySQL, PostgreSQL, MariaDB and MongoDB use-case tests compile and exercise the new contract. - 5.2 Confirm all logical receipts in the same database transaction that publishes a successful backup, and leave the pending deletions in place on every failure and cancellation path; verify transaction rollback leaves files recoverable for cleanup and no remote deletion occurs inside the transaction.
- 5.3 Rename the PostgreSQL reproduction test
Test_MakeBackup_WhenUsecaseStoresArtifactThenFails_LeavesArtifacttoTest_MakeBackup_WhenUsecaseStoresArtifactThenFails_ArtifactRemovedand convert it, then cover cancellation after a stored artifact and metadata that cannot be restored from. These cases live at the backuper rather than once per engine, because every engine now reaches storage through the same file store and the discard logic they exercise is one code path; the engine use cases keep their own tests for producing bytes. Run the worker until idle and assert the catalog state plus actual absence of the base file and its metadata sidecar. - 5.4 Cover a process restart after upload but before logical backup publication; verify the unpublished file is eventually deleted while a transaction-confirmed file is retained.
6. Integrate physical full and incremental backups
- 6.1 Route full and incremental stream uploads and their sidecars through the file store and return receipts only after writer goroutines are joined. Give
buildObjectName(.../executor.go:152) an attempt UUID, since its four current inputs are constant across the codec fallback loop, and split it instead intobuildBackupLabel, which keeps the four inputs it already had, andbuildObjectName(label, attemptID). That satisfies the rule the struct was there to protect without a struct: neither function grows a fifth positional value, and neither takes two adjacentuuid.UUIDvalues. HavestreamWithCodecFallback(.../executor.go:50) mint each name through amintAndSaveAttemptNamecallback its two callers supply, named for both of its effects, because the loop holds neither the naming inputs nor the repository that persistsfile_name, and move that function's stream inputs into astreamAttemptSpecstruct rather than growing an already eight-value positional list. The callback becomes the only producer of object names: the pre-loopbuildObjectNamecall and itsSave(create_full_uc.go:40with its assignment andSaveat:42and:43,create_incremental_uc.go:76with its own at:78and:80) stop minting the object key and keep only the stable pg_basebackup label, whichnewPgBasebackupCommandtakes atpg_basebackup.go:50and which names the backup rather than the object. Return the settled attempt's name and take every consumer from that result rather than the caller's variable:runStreamParams(.../executor.go:79) so the upload-time manifest atstream.go:317follows it, the chain-broken removal and the reportedFileName(create_full_uc.go:84,:92),streamResult.FileName(create_full_uc.go:113), the incremental equivalent (create_incremental_uc.go:116) and the metadata sidecar (metadata.go:123). Correct the two comments that state the old shape,executor.go:45("every attempt streams to the same object key") and thebuildObjectNamecomment about uniqueness coming from the trailing backup ID, and moveexecutor_test.goonto the new shape, renaming the table fieldexpected(declared at:19, set at:25and:31, read at:39) toobjectNameand updating its values for the attempt UUID; verify stream success, a zstd rejection that downgrades to gzip and then completes without the second attempt being refused for a name already in use and with the manifest landing under the settled name, pg_basebackup failure after partial output, cancellation and provider failure with focused tests, renamingTest_RunStream_WhenPgBasebackupWritesBytesThenFails_LeavesUploadedArtifactto..._LeavesNoReceiptToPublishand asserting the outcome carries no receipts.runStreamsits below the layer that owns cleanup and its tests drive a fake store, so removal cannot be observed there; task 6.3 covers it against a real store. - 6.2 Confirm physical receipts in the same transaction that publishes the backup and leave pending deletions in place on terminal failure paths, including manifest, metadata and incremental-chain failures; verify rollback and restart behavior with service and scheduler tests. A superseded attempt, whose row a later attempt already moved out of
IN_PROGRESS, hands its files back in that same transaction, and a codec attempt the fallback rejects hands its own back immediately rather than waiting out the commit window. - 6.3 Convert the physical reproduction tests into passing cleanup tests, run the worker until idle and assert that the artifact, its manifest and its metadata are absent after an ordinary error, a cancellation and a supersession. Skip the MinIO variant: the S3 chunk, manifest and multipart representations are covered at the provider level by
s3_cleanup_test.go, which is mutation-verified, and the physical path names no provider, so running it against MinIO would re-test the provider through a slower route. The backups feature has no MinIO fixture today, so adding one would be new test infrastructure for coverage that already exists. - 6.4 Rewrite restart recovery so it no longer assumes a missing backup file name means no object exists, replacing the stale premise recorded at
scheduler.go:710, and request deletion for a claimlessIN_PROGRESSrow that carries a file name in the same transaction that records its terminal state, gated on that conditionalIN_PROGRESStransition affecting one row so a late completion that already wrote a terminal status keeps its file; verify withTest_RecoverInFlightOnRestart_WhenFullHasNamedArtifact_LeavesArtifactrenamed toTest_RecoverInFlightOnRestart_WhenFullHasNamedArtifact_ArtifactRemovedand rewritten to assert eventual absence, and that recovery neither deletes a confirmed successful backup nor duplicates an existing pending deletion.
7. Integrate WAL and backup history artifacts
- 7.1 Give each WAL and history write attempt an immutable operation-specific object name while preserving the logical restore ordering metadata. Move
walSegmentObjectNameonto awalObjectNameSpecstruct rather than taking it to four positional values with a second adjacentuuid.UUID, mint the WAL name once per upload attempt where the artifact name is built (wal_upload.go:232) and pass it to the sidecar, sowal_upload.go:380stops callingwalSegmentObjectNamea second time; do the same for history, whose key is built attimeline.go:231and whose sidecar appends.metadatato it at:246, using thehistoryFileIDalready minted attimeline.go:230. If either sidecar keeps rebuilding the key, artifact and sidecar get different UUIDs and every consumer that readsfile_nameoff the row and appends.metadatamisses. Replace the doc comment onwalSegmentObjectName(.../wal_upload.go:439), which currently argues that the insert-first claim model makes a UUID unnecessary; verify two retries cannot address the same remote object and restore selection remains correct. - 7.2 Confirm WAL artifacts and their sidecars in the same transaction that marks the WAL row uploaded, and confirm history files in the transaction that publishes their catalog row, including the history insert failure that currently strands both artifact and sidecar; verify commit failure and restart leave unconfirmed files eligible for cleanup while the locally queued segment file remains available for retry.
- 7.3 Replace the synchronous orphan cleanup inside WAL upload: the
!committedbranch atwal_upload.go:275deletes the object directly because the claim row is already gone, and its helperdeleteObject(wal_upload.go:391) is reached from three other branches (:247,:255,:262) and twice inside this one, for the artifact at:282and its sidecar at:283. Route all of them through the file store, delete the comment at:276that explains why the cleaner cannot see those bytes, and confirm task 8.6's guard finds nothing left in this file; verify the cascade-versus-upload case still ends with no object and no row. - 7.4 Request deletion transactionally for failed, superseded and retention-expired WAL and history artifacts, and correct the doc comment on
PhysicalWalSegmentRepository.DeleteAbandonedClaims(core/physical/repositories/wal_segment_repository.go:122), which claims a NULLfile_nameproves no object exists; task 6.4 owns the scheduler comment that cites it as shared reasoning, so this task changes only the repository file, by deleting both that premise and the sentences restating what the name and the signature already say, keeping only what a reader cannot derive from them; verify the worker removes the exact remote objects without affecting adjacent WAL segments or valid history files, and that an abandoned claim whose upload did reach the provider still loses its object.
8. Replace synchronous cleanup paths
- 8.1 Change the logical backup cleaner to request deletion in the same transaction that removes the catalog row, eliminating the current delete-error-and-continue split; verify the record and the row commit or roll back together.
- 8.2 Change physical backup, WAL, history and metadata cleanup,
removeUploadedArtifactsAfterChainBroken(create_full_uc.go:192and:198, whose manifest name also comes from the pre-loop file name, and whose doc comment at:179restates its name and promises thatDeleteFileis idempotent on not-found, which stops being what the call does, so delete both claims and keep only what survives),DeleteChainDependentsKeepFull,DeleteOrphanWalSegmentsInSpan,deleteOrphanedHistoryFilesand retention paths to request exact references transactionally, removing both the fail-open and fail-closed remote deletion behavior and the remote calls that currently run inside the cascade transaction; verify cascade and partial-batch rollback cases, including that a rolled-back cascade leaves every object intact. - 8.3 Add clear-path tests that create real local and MinIO artifacts, invoke each cleaner, run the deletion worker until idle and assert both catalog removal and physical absence; include one transient deletion failure to prove the catalog may disappear before eventual remote cleanup succeeds.
- 8.4 Keep the
OnBeforeDatabaseRemovesignature and add a physical implementation instead. The contract change was meant to make database removal record every reference atomically. Nothing recorded them at all for the physical family: every physical table cascades ondatabases.id, so removing a database dropped the only record of its object names.PhysicalBackupServicenow implements the listener and records the references for its full, incremental, WAL and history rows in a transaction of its own, which is the same shape the logical cleaner already used. Passing the caller's transaction instead would hold one transaction across every backup of a database, which the design's own risk entry names as a cost, so each listener keeps its own. - 8.5 Nothing to move:
DeleteForTestruns the same listener chain as production deletion, and with task 8.4 dropped that chain keeps its signature. The fixture therefore records the same obligations as the controller path already. - 8.6 Add a production-code guard that fails tests if backup workflows call provider
SaveFileorDeleteFiledirectly, once sections 5 through 8 have removed the last of those calls. Scope it to non-test files underbackend/internal/features/backups, so it flags neither the storages feature's ownStoragemethods, its provider tests and the--test-storageprobe inbackend/cmd/storage_command.go, nor the backup test fixtures that legitimately create and remove provider objects, such as theSaveFilecall incore/physical/service/service_test.go; verify the guard by planting aDeleteFilecall underbackend/internal/features/backupsand confirming the guard fails on it, then removing it and confirming the guard stays silent for the provider calls that live outside its scope.
9. Guard and drain the storage lifecycle
- 9.1 Refuse storage deletion while backup rows still reference the storage, returning an actionable conflict instead of a silent logical cascade or a raw foreign-key error, by adding a second registration,
AddStorageBackupCounter, beside the existingAddStorageDatabaseCounter. One interface carrying both questions would have made the config services answer for tables the backup services own, which meant reading those tables by name across a feature boundary; each feature counts its own rows instead; verify controller responses for logical and physical references and that deletion succeeds once the backups are gone. - 9.2 Make storage deletion run one drain of that storage's pending deletions first, bounded by a row count and a wall-clock budget and claiming through the same live-write exclusion the worker uses, then write one audit-log entry and a warning naming the storage, how many pending deletion rows are still present for it after the drain and their names up to a fixed limit, counting rows the drain failed on, skipped as locked, never saw because the worker had claimed them or never reached before the budget expired; verify a reachable provider leaves nothing behind, an unreachable one still deletes the storage within the budget and reports each remaining file once, that the entry stays bounded for a storage with thousands of obligations and that the remaining rows disappear with the storage row.
- 9.3 Give the storage workspace-deletion listener at
storages/service.go:73the same drain and reporting path instead of deleting storage rows straight through its repository, leavingOnBeforeWorkspaceDeletionas it is and giving the drain a background context. The signature change would have kept the request ID on the drain's audit entry, but it touches three implementations for one log field on a path that already runs after the request that started it; verify workspace deletion succeeds with an unreachable provider, records what it left behind and keeps the existing refusal for a workspace that still contains databases.
10. Keep the existing suite and the module rules current
- 10.1 Give object-absence assertions a worker drain seam and apply it to the existing cascade coverage, starting with
Test_DeleteFull_WithDependents_CascadesEntireChainAndObjects; verify no test waits on a ticker or a sleep to observe cleanup. - 10.2 Make WAL tests read object names from catalog rows instead of rebuilding them at
wal_upload_test.go:74,wal_upload_test.go:212,wal_watch_dir_test.go:51,wal_watch_dir_test.go:71andwal_stream_test.go:444; verify they pass with per-attempt names.Test_WalUpload_DeleteCascadesIntoNullClaim_UploadCompletes_DeleteFileCleansOrphanalso asserts the orphan is already absent, so it takes the worker drain seam from task 10.1 and a name that no longer promises synchronous removal. - 10.3 Re-check the storage and backup-config controller tests that delete a storage, including
Test_DeleteStorage_StorageNotReturnedViaGet,Test_DeleteStorageWithAttachedDatabases_CannotDeleteandTest_DeleteStorageWithAttachedPhysicalConfig_CannotDelete, against the new reference refusal; verify each one still asserts the outcome it was written for and confirm the shared teardown fixtures need no change because pending deletions cascade with their storage row. - 10.4 Record the new conventions in
backend/AGENTS.md: backup code writes and deletes through the file store rather than a provider, a stored file is kept only when a committed transaction claims it, and a providerDeleteFileowes every representation derived from the logical name; verify each of the three rules appears in the storage section of that file and that the file store is named in the list of feature boundaries backup code goes through.
11. Final verification
- 11.1 Run focused logical, physical, WAL, cleaner, storage lifecycle and provider cleanup tests, including the MinIO integration suite, and confirm no test depends on timing sleeps instead of controllable worker passes.
- 11.2 Run
make lintand the repository backend test command (make testin the dev container ormake test-fedoraon supported Fedora), then resolve every failure without weakening security or cleanup assertions. 62 of 63 packages pass;internal/features/tests/logical/mariadbfails on a clean tree too, on a container this environment cannot bring up healthily, so it is not this change's regression. - 11.3 Run
openspec validate ensure-storage-file-cleanup --strictand resolve every validation error. - 11.4 Request the mandatory final reviewer audit against the root and backend agent rules, resolve every
CHANGES REQUIREDfinding and rerun the affected linters and tests.